]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r271309:
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/types.h>
51 #include <sys/kthread.h>
52 #include <sys/bio.h>
53 #include <sys/fcntl.h>
54 #include <sys/lock.h>
55 #include <sys/module.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/malloc.h>
59 #include <sys/conf.h>
60 #include <sys/ioccom.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/endian.h>
65 #include <sys/sysctl.h>
66
67 #include <cam/cam.h>
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_da.h>
70 #include <cam/ctl/ctl_io.h>
71 #include <cam/ctl/ctl.h>
72 #include <cam/ctl/ctl_frontend.h>
73 #include <cam/ctl/ctl_frontend_internal.h>
74 #include <cam/ctl/ctl_util.h>
75 #include <cam/ctl/ctl_backend.h>
76 #include <cam/ctl/ctl_ioctl.h>
77 #include <cam/ctl/ctl_ha.h>
78 #include <cam/ctl/ctl_private.h>
79 #include <cam/ctl/ctl_debug.h>
80 #include <cam/ctl/ctl_scsi_all.h>
81 #include <cam/ctl/ctl_error.h>
82
83 struct ctl_softc *control_softc = NULL;
84
85 /*
86  * Size and alignment macros needed for Copan-specific HA hardware.  These
87  * can go away when the HA code is re-written, and uses busdma for any
88  * hardware.
89  */
90 #define CTL_ALIGN_8B(target, source, type)                              \
91         if (((uint32_t)source & 0x7) != 0)                              \
92                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93         else                                                            \
94                 target = (type)source;
95
96 #define CTL_SIZE_8B(target, size)                                       \
97         if ((size & 0x7) != 0)                                          \
98                 target = size + (0x8 - (size & 0x7));                   \
99         else                                                            \
100                 target = size;
101
102 #define CTL_ALIGN_8B_MARGIN     16
103
104 /*
105  * Template mode pages.
106  */
107
108 /*
109  * Note that these are default values only.  The actual values will be
110  * filled in when the user does a mode sense.
111  */
112 static struct copan_power_subpage power_page_default = {
113         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114         /*subpage*/ PWR_SUBPAGE_CODE,
115         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117         /*page_version*/ PWR_VERSION,
118         /* total_luns */ 26,
119         /* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122                       0, 0, 0, 0, 0, 0}
123 };
124
125 static struct copan_power_subpage power_page_changeable = {
126         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127         /*subpage*/ PWR_SUBPAGE_CODE,
128         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130         /*page_version*/ 0,
131         /* total_luns */ 0,
132         /* max_active_luns*/ 0,
133         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135                       0, 0, 0, 0, 0, 0}
136 };
137
138 static struct copan_aps_subpage aps_page_default = {
139         APS_PAGE_CODE | SMPH_SPF, //page_code
140         APS_SUBPAGE_CODE, //subpage
141         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143         APS_VERSION, //page_version
144         0, //lock_active
145         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147         0, 0, 0, 0, 0} //reserved
148 };
149
150 static struct copan_aps_subpage aps_page_changeable = {
151         APS_PAGE_CODE | SMPH_SPF, //page_code
152         APS_SUBPAGE_CODE, //subpage
153         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155         0, //page_version
156         0, //lock_active
157         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159         0, 0, 0, 0, 0} //reserved
160 };
161
162 static struct copan_debugconf_subpage debugconf_page_default = {
163         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
164         DBGCNF_SUBPAGE_CODE,            /* subpage */
165         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167         DBGCNF_VERSION,                 /* page_version */
168         {CTL_TIME_IO_DEFAULT_SECS>>8,
169          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
170 };
171
172 static struct copan_debugconf_subpage debugconf_page_changeable = {
173         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
174         DBGCNF_SUBPAGE_CODE,            /* subpage */
175         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177         0,                              /* page_version */
178         {0xff,0xff},                    /* ctl_time_io_secs */
179 };
180
181 static struct scsi_format_page format_page_default = {
182         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
183         /*page_length*/sizeof(struct scsi_format_page) - 2,
184         /*tracks_per_zone*/ {0, 0},
185         /*alt_sectors_per_zone*/ {0, 0},
186         /*alt_tracks_per_zone*/ {0, 0},
187         /*alt_tracks_per_lun*/ {0, 0},
188         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190         /*bytes_per_sector*/ {0, 0},
191         /*interleave*/ {0, 0},
192         /*track_skew*/ {0, 0},
193         /*cylinder_skew*/ {0, 0},
194         /*flags*/ SFP_HSEC,
195         /*reserved*/ {0, 0, 0}
196 };
197
198 static struct scsi_format_page format_page_changeable = {
199         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
200         /*page_length*/sizeof(struct scsi_format_page) - 2,
201         /*tracks_per_zone*/ {0, 0},
202         /*alt_sectors_per_zone*/ {0, 0},
203         /*alt_tracks_per_zone*/ {0, 0},
204         /*alt_tracks_per_lun*/ {0, 0},
205         /*sectors_per_track*/ {0, 0},
206         /*bytes_per_sector*/ {0, 0},
207         /*interleave*/ {0, 0},
208         /*track_skew*/ {0, 0},
209         /*cylinder_skew*/ {0, 0},
210         /*flags*/ 0,
211         /*reserved*/ {0, 0, 0}
212 };
213
214 static struct scsi_rigid_disk_page rigid_disk_page_default = {
215         /*page_code*/SMS_RIGID_DISK_PAGE,
216         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217         /*cylinders*/ {0, 0, 0},
218         /*heads*/ CTL_DEFAULT_HEADS,
219         /*start_write_precomp*/ {0, 0, 0},
220         /*start_reduced_current*/ {0, 0, 0},
221         /*step_rate*/ {0, 0},
222         /*landing_zone_cylinder*/ {0, 0, 0},
223         /*rpl*/ SRDP_RPL_DISABLED,
224         /*rotational_offset*/ 0,
225         /*reserved1*/ 0,
226         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227                            CTL_DEFAULT_ROTATION_RATE & 0xff},
228         /*reserved2*/ {0, 0}
229 };
230
231 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232         /*page_code*/SMS_RIGID_DISK_PAGE,
233         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234         /*cylinders*/ {0, 0, 0},
235         /*heads*/ 0,
236         /*start_write_precomp*/ {0, 0, 0},
237         /*start_reduced_current*/ {0, 0, 0},
238         /*step_rate*/ {0, 0},
239         /*landing_zone_cylinder*/ {0, 0, 0},
240         /*rpl*/ 0,
241         /*rotational_offset*/ 0,
242         /*reserved1*/ 0,
243         /*rotation_rate*/ {0, 0},
244         /*reserved2*/ {0, 0}
245 };
246
247 static struct scsi_caching_page caching_page_default = {
248         /*page_code*/SMS_CACHING_PAGE,
249         /*page_length*/sizeof(struct scsi_caching_page) - 2,
250         /*flags1*/ SCP_DISC | SCP_WCE,
251         /*ret_priority*/ 0,
252         /*disable_pf_transfer_len*/ {0xff, 0xff},
253         /*min_prefetch*/ {0, 0},
254         /*max_prefetch*/ {0xff, 0xff},
255         /*max_pf_ceiling*/ {0xff, 0xff},
256         /*flags2*/ 0,
257         /*cache_segments*/ 0,
258         /*cache_seg_size*/ {0, 0},
259         /*reserved*/ 0,
260         /*non_cache_seg_size*/ {0, 0, 0}
261 };
262
263 static struct scsi_caching_page caching_page_changeable = {
264         /*page_code*/SMS_CACHING_PAGE,
265         /*page_length*/sizeof(struct scsi_caching_page) - 2,
266         /*flags1*/ SCP_WCE | SCP_RCD,
267         /*ret_priority*/ 0,
268         /*disable_pf_transfer_len*/ {0, 0},
269         /*min_prefetch*/ {0, 0},
270         /*max_prefetch*/ {0, 0},
271         /*max_pf_ceiling*/ {0, 0},
272         /*flags2*/ 0,
273         /*cache_segments*/ 0,
274         /*cache_seg_size*/ {0, 0},
275         /*reserved*/ 0,
276         /*non_cache_seg_size*/ {0, 0, 0}
277 };
278
279 static struct scsi_control_page control_page_default = {
280         /*page_code*/SMS_CONTROL_MODE_PAGE,
281         /*page_length*/sizeof(struct scsi_control_page) - 2,
282         /*rlec*/0,
283         /*queue_flags*/0,
284         /*eca_and_aen*/0,
285         /*flags4*/SCP_TAS,
286         /*aen_holdoff_period*/{0, 0},
287         /*busy_timeout_period*/{0, 0},
288         /*extended_selftest_completion_time*/{0, 0}
289 };
290
291 static struct scsi_control_page control_page_changeable = {
292         /*page_code*/SMS_CONTROL_MODE_PAGE,
293         /*page_length*/sizeof(struct scsi_control_page) - 2,
294         /*rlec*/SCP_DSENSE,
295         /*queue_flags*/0,
296         /*eca_and_aen*/0,
297         /*flags4*/0,
298         /*aen_holdoff_period*/{0, 0},
299         /*busy_timeout_period*/{0, 0},
300         /*extended_selftest_completion_time*/{0, 0}
301 };
302
303
304 /*
305  * XXX KDM move these into the softc.
306  */
307 static int rcv_sync_msg;
308 static int persis_offset;
309 static uint8_t ctl_pause_rtr;
310 static int     ctl_is_single = 1;
311 static int     index_to_aps_page;
312
313 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314 static int worker_threads = -1;
315 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
316 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
317     &worker_threads, 1, "Number of worker threads");
318 static int verbose = 0;
319 TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
320 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
321     &verbose, 0, "Show SCSI errors returned to initiator");
322
323 /*
324  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
325  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
326  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
327  */
328 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   8
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 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
355 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
356 #ifdef unused
357 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
358                                    uint32_t targ_target, uint32_t targ_lun,
359                                    int can_wait);
360 static void ctl_kfree_io(union ctl_io *io);
361 #endif /* unused */
362 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
363                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
364 static int ctl_free_lun(struct ctl_lun *lun);
365 static void ctl_create_lun(struct ctl_be_lun *be_lun);
366 /**
367 static void ctl_failover_change_pages(struct ctl_softc *softc,
368                                       struct ctl_scsiio *ctsio, int master);
369 **/
370
371 static int ctl_do_mode_select(union ctl_io *io);
372 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
373                            uint64_t res_key, uint64_t sa_res_key,
374                            uint8_t type, uint32_t residx,
375                            struct ctl_scsiio *ctsio,
376                            struct scsi_per_res_out *cdb,
377                            struct scsi_per_res_out_parms* param);
378 static void ctl_pro_preempt_other(struct ctl_lun *lun,
379                                   union ctl_ha_msg *msg);
380 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
381 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
382 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
383 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
384 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
385                                          int alloc_len);
386 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
387                                          int alloc_len);
388 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
389 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
390 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
391 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
392 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
393 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
394 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
395                                          union ctl_io *ooa_io);
396 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
397                                 union ctl_io *starting_io);
398 static int ctl_check_blocked(struct ctl_lun *lun);
399 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
400                                 struct ctl_lun *lun,
401                                 const struct ctl_cmd_entry *entry,
402                                 struct ctl_scsiio *ctsio);
403 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
404 static void ctl_failover(void);
405 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
406                                struct ctl_scsiio *ctsio);
407 static int ctl_scsiio(struct ctl_scsiio *ctsio);
408
409 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
410 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
411                             ctl_ua_type ua_type);
412 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
413                          ctl_ua_type ua_type);
414 static int ctl_abort_task(union ctl_io *io);
415 static int ctl_abort_task_set(union ctl_io *io);
416 static int ctl_i_t_nexus_reset(union ctl_io *io);
417 static void ctl_run_task(union ctl_io *io);
418 #ifdef CTL_IO_DELAY
419 static void ctl_datamove_timer_wakeup(void *arg);
420 static void ctl_done_timer_wakeup(void *arg);
421 #endif /* CTL_IO_DELAY */
422
423 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
424 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
425 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
426 static void ctl_datamove_remote_write(union ctl_io *io);
427 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
428 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
429 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
430 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
431                                     ctl_ha_dt_cb callback);
432 static void ctl_datamove_remote_read(union ctl_io *io);
433 static void ctl_datamove_remote(union ctl_io *io);
434 static int ctl_process_done(union ctl_io *io);
435 static void ctl_lun_thread(void *arg);
436 static void ctl_work_thread(void *arg);
437 static void ctl_enqueue_incoming(union ctl_io *io);
438 static void ctl_enqueue_rtr(union ctl_io *io);
439 static void ctl_enqueue_done(union ctl_io *io);
440 static void ctl_enqueue_isc(union ctl_io *io);
441 static const struct ctl_cmd_entry *
442     ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
443 static const struct ctl_cmd_entry *
444     ctl_validate_command(struct ctl_scsiio *ctsio);
445 static int ctl_cmd_applicable(uint8_t lun_type,
446     const struct ctl_cmd_entry *entry);
447
448 /*
449  * Load the serialization table.  This isn't very pretty, but is probably
450  * the easiest way to do it.
451  */
452 #include "ctl_ser_table.c"
453
454 /*
455  * We only need to define open, close and ioctl routines for this driver.
456  */
457 static struct cdevsw ctl_cdevsw = {
458         .d_version =    D_VERSION,
459         .d_flags =      0,
460         .d_open =       ctl_open,
461         .d_close =      ctl_close,
462         .d_ioctl =      ctl_ioctl,
463         .d_name =       "ctl",
464 };
465
466
467 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
468 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
469
470 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
471
472 static moduledata_t ctl_moduledata = {
473         "ctl",
474         ctl_module_event_handler,
475         NULL
476 };
477
478 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
479 MODULE_VERSION(ctl, 1);
480
481 static struct ctl_frontend ioctl_frontend =
482 {
483         .name = "ioctl",
484 };
485
486 static void
487 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
488                             union ctl_ha_msg *msg_info)
489 {
490         struct ctl_scsiio *ctsio;
491
492         if (msg_info->hdr.original_sc == NULL) {
493                 printf("%s: original_sc == NULL!\n", __func__);
494                 /* XXX KDM now what? */
495                 return;
496         }
497
498         ctsio = &msg_info->hdr.original_sc->scsiio;
499         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
500         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
501         ctsio->io_hdr.status = msg_info->hdr.status;
502         ctsio->scsi_status = msg_info->scsi.scsi_status;
503         ctsio->sense_len = msg_info->scsi.sense_len;
504         ctsio->sense_residual = msg_info->scsi.sense_residual;
505         ctsio->residual = msg_info->scsi.residual;
506         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
507                sizeof(ctsio->sense_data));
508         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
509                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
510         ctl_enqueue_isc((union ctl_io *)ctsio);
511 }
512
513 static void
514 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
515                                 union ctl_ha_msg *msg_info)
516 {
517         struct ctl_scsiio *ctsio;
518
519         if (msg_info->hdr.serializing_sc == NULL) {
520                 printf("%s: serializing_sc == NULL!\n", __func__);
521                 /* XXX KDM now what? */
522                 return;
523         }
524
525         ctsio = &msg_info->hdr.serializing_sc->scsiio;
526 #if 0
527         /*
528          * Attempt to catch the situation where an I/O has
529          * been freed, and we're using it again.
530          */
531         if (ctsio->io_hdr.io_type == 0xff) {
532                 union ctl_io *tmp_io;
533                 tmp_io = (union ctl_io *)ctsio;
534                 printf("%s: %p use after free!\n", __func__,
535                        ctsio);
536                 printf("%s: type %d msg %d cdb %x iptl: "
537                        "%d:%d:%d:%d tag 0x%04x "
538                        "flag %#x status %x\n",
539                         __func__,
540                         tmp_io->io_hdr.io_type,
541                         tmp_io->io_hdr.msg_type,
542                         tmp_io->scsiio.cdb[0],
543                         tmp_io->io_hdr.nexus.initid.id,
544                         tmp_io->io_hdr.nexus.targ_port,
545                         tmp_io->io_hdr.nexus.targ_target.id,
546                         tmp_io->io_hdr.nexus.targ_lun,
547                         (tmp_io->io_hdr.io_type ==
548                         CTL_IO_TASK) ?
549                         tmp_io->taskio.tag_num :
550                         tmp_io->scsiio.tag_num,
551                         tmp_io->io_hdr.flags,
552                         tmp_io->io_hdr.status);
553         }
554 #endif
555         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
556         ctl_enqueue_isc((union ctl_io *)ctsio);
557 }
558
559 /*
560  * ISC (Inter Shelf Communication) event handler.  Events from the HA
561  * subsystem come in here.
562  */
563 static void
564 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
565 {
566         struct ctl_softc *ctl_softc;
567         union ctl_io *io;
568         struct ctl_prio *presio;
569         ctl_ha_status isc_status;
570
571         ctl_softc = control_softc;
572         io = NULL;
573
574
575 #if 0
576         printf("CTL: Isc Msg event %d\n", event);
577 #endif
578         if (event == CTL_HA_EVT_MSG_RECV) {
579                 union ctl_ha_msg msg_info;
580
581                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
582                                              sizeof(msg_info), /*wait*/ 0);
583 #if 0
584                 printf("CTL: msg_type %d\n", msg_info.msg_type);
585 #endif
586                 if (isc_status != 0) {
587                         printf("Error receiving message, status = %d\n",
588                                isc_status);
589                         return;
590                 }
591
592                 switch (msg_info.hdr.msg_type) {
593                 case CTL_MSG_SERIALIZE:
594 #if 0
595                         printf("Serialize\n");
596 #endif
597                         io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
598                         if (io == NULL) {
599                                 printf("ctl_isc_event_handler: can't allocate "
600                                        "ctl_io!\n");
601                                 /* Bad Juju */
602                                 /* Need to set busy and send msg back */
603                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
604                                 msg_info.hdr.status = CTL_SCSI_ERROR;
605                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
606                                 msg_info.scsi.sense_len = 0;
607                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
608                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
609                                 }
610                                 goto bailout;
611                         }
612                         ctl_zero_io(io);
613                         // populate ctsio from msg_info
614                         io->io_hdr.io_type = CTL_IO_SCSI;
615                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
616                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
617 #if 0
618                         printf("pOrig %x\n", (int)msg_info.original_sc);
619 #endif
620                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
621                                             CTL_FLAG_IO_ACTIVE;
622                         /*
623                          * If we're in serialization-only mode, we don't
624                          * want to go through full done processing.  Thus
625                          * the COPY flag.
626                          *
627                          * XXX KDM add another flag that is more specific.
628                          */
629                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
630                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
631                         io->io_hdr.nexus = msg_info.hdr.nexus;
632 #if 0
633                         printf("targ %d, port %d, iid %d, lun %d\n",
634                                io->io_hdr.nexus.targ_target.id,
635                                io->io_hdr.nexus.targ_port,
636                                io->io_hdr.nexus.initid.id,
637                                io->io_hdr.nexus.targ_lun);
638 #endif
639                         io->scsiio.tag_num = msg_info.scsi.tag_num;
640                         io->scsiio.tag_type = msg_info.scsi.tag_type;
641                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
642                                CTL_MAX_CDBLEN);
643                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
644                                 const struct ctl_cmd_entry *entry;
645
646                                 entry = ctl_get_cmd_entry(&io->scsiio);
647                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
648                                 io->io_hdr.flags |=
649                                         entry->flags & CTL_FLAG_DATA_MASK;
650                         }
651                         ctl_enqueue_isc(io);
652                         break;
653
654                 /* Performed on the Originating SC, XFER mode only */
655                 case CTL_MSG_DATAMOVE: {
656                         struct ctl_sg_entry *sgl;
657                         int i, j;
658
659                         io = msg_info.hdr.original_sc;
660                         if (io == NULL) {
661                                 printf("%s: original_sc == NULL!\n", __func__);
662                                 /* XXX KDM do something here */
663                                 break;
664                         }
665                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
666                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
667                         /*
668                          * Keep track of this, we need to send it back over
669                          * when the datamove is complete.
670                          */
671                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
672
673                         if (msg_info.dt.sg_sequence == 0) {
674                                 /*
675                                  * XXX KDM we use the preallocated S/G list
676                                  * here, but we'll need to change this to
677                                  * dynamic allocation if we need larger S/G
678                                  * lists.
679                                  */
680                                 if (msg_info.dt.kern_sg_entries >
681                                     sizeof(io->io_hdr.remote_sglist) /
682                                     sizeof(io->io_hdr.remote_sglist[0])) {
683                                         printf("%s: number of S/G entries "
684                                             "needed %u > allocated num %zd\n",
685                                             __func__,
686                                             msg_info.dt.kern_sg_entries,
687                                             sizeof(io->io_hdr.remote_sglist)/
688                                             sizeof(io->io_hdr.remote_sglist[0]));
689                                 
690                                         /*
691                                          * XXX KDM send a message back to
692                                          * the other side to shut down the
693                                          * DMA.  The error will come back
694                                          * through via the normal channel.
695                                          */
696                                         break;
697                                 }
698                                 sgl = io->io_hdr.remote_sglist;
699                                 memset(sgl, 0,
700                                        sizeof(io->io_hdr.remote_sglist));
701
702                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
703
704                                 io->scsiio.kern_sg_entries =
705                                         msg_info.dt.kern_sg_entries;
706                                 io->scsiio.rem_sg_entries =
707                                         msg_info.dt.kern_sg_entries;
708                                 io->scsiio.kern_data_len =
709                                         msg_info.dt.kern_data_len;
710                                 io->scsiio.kern_total_len =
711                                         msg_info.dt.kern_total_len;
712                                 io->scsiio.kern_data_resid =
713                                         msg_info.dt.kern_data_resid;
714                                 io->scsiio.kern_rel_offset =
715                                         msg_info.dt.kern_rel_offset;
716                                 /*
717                                  * Clear out per-DMA flags.
718                                  */
719                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
720                                 /*
721                                  * Add per-DMA flags that are set for this
722                                  * particular DMA request.
723                                  */
724                                 io->io_hdr.flags |= msg_info.dt.flags &
725                                                     CTL_FLAG_RDMA_MASK;
726                         } else
727                                 sgl = (struct ctl_sg_entry *)
728                                         io->scsiio.kern_data_ptr;
729
730                         for (i = msg_info.dt.sent_sg_entries, j = 0;
731                              i < (msg_info.dt.sent_sg_entries +
732                              msg_info.dt.cur_sg_entries); i++, j++) {
733                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
734                                 sgl[i].len = msg_info.dt.sg_list[j].len;
735
736 #if 0
737                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
738                                        __func__,
739                                        msg_info.dt.sg_list[j].addr,
740                                        msg_info.dt.sg_list[j].len,
741                                        sgl[i].addr, sgl[i].len, j, i);
742 #endif
743                         }
744 #if 0
745                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
746                                msg_info.dt.sg_list,
747                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
748 #endif
749
750                         /*
751                          * If this is the last piece of the I/O, we've got
752                          * the full S/G list.  Queue processing in the thread.
753                          * Otherwise wait for the next piece.
754                          */
755                         if (msg_info.dt.sg_last != 0)
756                                 ctl_enqueue_isc(io);
757                         break;
758                 }
759                 /* Performed on the Serializing (primary) SC, XFER mode only */
760                 case CTL_MSG_DATAMOVE_DONE: {
761                         if (msg_info.hdr.serializing_sc == NULL) {
762                                 printf("%s: serializing_sc == NULL!\n",
763                                        __func__);
764                                 /* XXX KDM now what? */
765                                 break;
766                         }
767                         /*
768                          * We grab the sense information here in case
769                          * there was a failure, so we can return status
770                          * back to the initiator.
771                          */
772                         io = msg_info.hdr.serializing_sc;
773                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
774                         io->io_hdr.status = msg_info.hdr.status;
775                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
776                         io->scsiio.sense_len = msg_info.scsi.sense_len;
777                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
778                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
779                         io->scsiio.residual = msg_info.scsi.residual;
780                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
781                                sizeof(io->scsiio.sense_data));
782                         ctl_enqueue_isc(io);
783                         break;
784                 }
785
786                 /* Preformed on Originating SC, SER_ONLY mode */
787                 case CTL_MSG_R2R:
788                         io = msg_info.hdr.original_sc;
789                         if (io == NULL) {
790                                 printf("%s: Major Bummer\n", __func__);
791                                 return;
792                         } else {
793 #if 0
794                                 printf("pOrig %x\n",(int) ctsio);
795 #endif
796                         }
797                         io->io_hdr.msg_type = CTL_MSG_R2R;
798                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
799                         ctl_enqueue_isc(io);
800                         break;
801
802                 /*
803                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
804                  * mode.
805                  * Performed on the Originating (i.e. secondary) SC in XFER
806                  * mode
807                  */
808                 case CTL_MSG_FINISH_IO:
809                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
810                                 ctl_isc_handler_finish_xfer(ctl_softc,
811                                                             &msg_info);
812                         else
813                                 ctl_isc_handler_finish_ser_only(ctl_softc,
814                                                                 &msg_info);
815                         break;
816
817                 /* Preformed on Originating SC */
818                 case CTL_MSG_BAD_JUJU:
819                         io = msg_info.hdr.original_sc;
820                         if (io == NULL) {
821                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
822                                        __func__);
823                                 break;
824                         }
825                         ctl_copy_sense_data(&msg_info, io);
826                         /*
827                          * IO should have already been cleaned up on other
828                          * SC so clear this flag so we won't send a message
829                          * back to finish the IO there.
830                          */
831                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
832                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
833
834                         /* io = msg_info.hdr.serializing_sc; */
835                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
836                         ctl_enqueue_isc(io);
837                         break;
838
839                 /* Handle resets sent from the other side */
840                 case CTL_MSG_MANAGE_TASKS: {
841                         struct ctl_taskio *taskio;
842                         taskio = (struct ctl_taskio *)ctl_alloc_io(
843                                 (void *)ctl_softc->othersc_pool);
844                         if (taskio == NULL) {
845                                 printf("ctl_isc_event_handler: can't allocate "
846                                        "ctl_io!\n");
847                                 /* Bad Juju */
848                                 /* should I just call the proper reset func
849                                    here??? */
850                                 goto bailout;
851                         }
852                         ctl_zero_io((union ctl_io *)taskio);
853                         taskio->io_hdr.io_type = CTL_IO_TASK;
854                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
855                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
856                         taskio->task_action = msg_info.task.task_action;
857                         taskio->tag_num = msg_info.task.tag_num;
858                         taskio->tag_type = msg_info.task.tag_type;
859 #ifdef CTL_TIME_IO
860                         taskio->io_hdr.start_time = time_uptime;
861                         getbintime(&taskio->io_hdr.start_bt);
862 #if 0
863                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
864 #endif
865 #endif /* CTL_TIME_IO */
866                         ctl_run_task((union ctl_io *)taskio);
867                         break;
868                 }
869                 /* Persistent Reserve action which needs attention */
870                 case CTL_MSG_PERS_ACTION:
871                         presio = (struct ctl_prio *)ctl_alloc_io(
872                                 (void *)ctl_softc->othersc_pool);
873                         if (presio == NULL) {
874                                 printf("ctl_isc_event_handler: can't allocate "
875                                        "ctl_io!\n");
876                                 /* Bad Juju */
877                                 /* Need to set busy and send msg back */
878                                 goto bailout;
879                         }
880                         ctl_zero_io((union ctl_io *)presio);
881                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
882                         presio->pr_msg = msg_info.pr;
883                         ctl_enqueue_isc((union ctl_io *)presio);
884                         break;
885                 case CTL_MSG_SYNC_FE:
886                         rcv_sync_msg = 1;
887                         break;
888                 case CTL_MSG_APS_LOCK: {
889                         // It's quicker to execute this then to
890                         // queue it.
891                         struct ctl_lun *lun;
892                         struct ctl_page_index *page_index;
893                         struct copan_aps_subpage *current_sp;
894                         uint32_t targ_lun;
895
896                         targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
897                         lun = ctl_softc->ctl_luns[targ_lun];
898                         mtx_lock(&lun->lun_lock);
899                         page_index = &lun->mode_pages.index[index_to_aps_page];
900                         current_sp = (struct copan_aps_subpage *)
901                                      (page_index->page_data +
902                                      (page_index->page_len * CTL_PAGE_CURRENT));
903
904                         current_sp->lock_active = msg_info.aps.lock_flag;
905                         mtx_unlock(&lun->lun_lock);
906                         break;
907                 }
908                 default:
909                         printf("How did I get here?\n");
910                 }
911         } else if (event == CTL_HA_EVT_MSG_SENT) {
912                 if (param != CTL_HA_STATUS_SUCCESS) {
913                         printf("Bad status from ctl_ha_msg_send status %d\n",
914                                param);
915                 }
916                 return;
917         } else if (event == CTL_HA_EVT_DISCONNECT) {
918                 printf("CTL: Got a disconnect from Isc\n");
919                 return;
920         } else {
921                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
922                 return;
923         }
924
925 bailout:
926         return;
927 }
928
929 static void
930 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
931 {
932         struct scsi_sense_data *sense;
933
934         sense = &dest->scsiio.sense_data;
935         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
936         dest->scsiio.scsi_status = src->scsi.scsi_status;
937         dest->scsiio.sense_len = src->scsi.sense_len;
938         dest->io_hdr.status = src->hdr.status;
939 }
940
941 static int
942 ctl_init(void)
943 {
944         struct ctl_softc *softc;
945         struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
946         struct ctl_port *port;
947         uint8_t sc_id =0;
948         int i, error, retval;
949         //int isc_retval;
950
951         retval = 0;
952         ctl_pause_rtr = 0;
953         rcv_sync_msg = 0;
954
955         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
956                                M_WAITOK | M_ZERO);
957         softc = control_softc;
958
959         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
960                               "cam/ctl");
961
962         softc->dev->si_drv1 = softc;
963
964         /*
965          * By default, return a "bad LUN" peripheral qualifier for unknown
966          * LUNs.  The user can override this default using the tunable or
967          * sysctl.  See the comment in ctl_inquiry_std() for more details.
968          */
969         softc->inquiry_pq_no_lun = 1;
970         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
971                           &softc->inquiry_pq_no_lun);
972         sysctl_ctx_init(&softc->sysctl_ctx);
973         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
974                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
975                 CTLFLAG_RD, 0, "CAM Target Layer");
976
977         if (softc->sysctl_tree == NULL) {
978                 printf("%s: unable to allocate sysctl tree\n", __func__);
979                 destroy_dev(softc->dev);
980                 free(control_softc, M_DEVBUF);
981                 control_softc = NULL;
982                 return (ENOMEM);
983         }
984
985         SYSCTL_ADD_INT(&softc->sysctl_ctx,
986                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
987                        "inquiry_pq_no_lun", CTLFLAG_RW,
988                        &softc->inquiry_pq_no_lun, 0,
989                        "Report no lun possible for invalid LUNs");
990
991         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
992         mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
993         softc->open_count = 0;
994
995         /*
996          * Default to actually sending a SYNCHRONIZE CACHE command down to
997          * the drive.
998          */
999         softc->flags = CTL_FLAG_REAL_SYNC;
1000
1001         /*
1002          * In Copan's HA scheme, the "master" and "slave" roles are
1003          * figured out through the slot the controller is in.  Although it
1004          * is an active/active system, someone has to be in charge.
1005          */
1006 #ifdef NEEDTOPORT
1007         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1008 #endif
1009
1010         if (sc_id == 0) {
1011                 softc->flags |= CTL_FLAG_MASTER_SHELF;
1012                 persis_offset = 0;
1013         } else
1014                 persis_offset = CTL_MAX_INITIATORS;
1015
1016         /*
1017          * XXX KDM need to figure out where we want to get our target ID
1018          * and WWID.  Is it different on each port?
1019          */
1020         softc->target.id = 0;
1021         softc->target.wwid[0] = 0x12345678;
1022         softc->target.wwid[1] = 0x87654321;
1023         STAILQ_INIT(&softc->lun_list);
1024         STAILQ_INIT(&softc->pending_lun_queue);
1025         STAILQ_INIT(&softc->fe_list);
1026         STAILQ_INIT(&softc->port_list);
1027         STAILQ_INIT(&softc->be_list);
1028         STAILQ_INIT(&softc->io_pools);
1029         ctl_tpc_init(softc);
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         ctl_tpc_shutdown(softc);
1178         mtx_destroy(&softc->pool_lock);
1179         mtx_destroy(&softc->ctl_lock);
1180
1181         destroy_dev(softc->dev);
1182
1183         sysctl_ctx_free(&softc->sysctl_ctx);
1184
1185         free(control_softc, M_DEVBUF);
1186         control_softc = NULL;
1187
1188         if (bootverbose)
1189                 printf("ctl: CAM Target Layer unloaded\n");
1190 }
1191
1192 static int
1193 ctl_module_event_handler(module_t mod, int what, void *arg)
1194 {
1195
1196         switch (what) {
1197         case MOD_LOAD:
1198                 return (ctl_init());
1199         case MOD_UNLOAD:
1200                 return (EBUSY);
1201         default:
1202                 return (EOPNOTSUPP);
1203         }
1204 }
1205
1206 /*
1207  * XXX KDM should we do some access checks here?  Bump a reference count to
1208  * prevent a CTL module from being unloaded while someone has it open?
1209  */
1210 static int
1211 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1212 {
1213         return (0);
1214 }
1215
1216 static int
1217 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1218 {
1219         return (0);
1220 }
1221
1222 int
1223 ctl_port_enable(ctl_port_type port_type)
1224 {
1225         struct ctl_softc *softc;
1226         struct ctl_port *port;
1227
1228         if (ctl_is_single == 0) {
1229                 union ctl_ha_msg msg_info;
1230                 int isc_retval;
1231
1232 #if 0
1233                 printf("%s: HA mode, synchronizing frontend enable\n",
1234                         __func__);
1235 #endif
1236                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1237                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1238                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1239                         printf("Sync msg send error retval %d\n", isc_retval);
1240                 }
1241                 if (!rcv_sync_msg) {
1242                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1243                                 sizeof(msg_info), 1);
1244                 }
1245 #if 0
1246                 printf("CTL:Frontend Enable\n");
1247         } else {
1248                 printf("%s: single mode, skipping frontend synchronization\n",
1249                         __func__);
1250 #endif
1251         }
1252
1253         softc = control_softc;
1254
1255         STAILQ_FOREACH(port, &softc->port_list, links) {
1256                 if (port_type & port->port_type)
1257                 {
1258 #if 0
1259                         printf("port %d\n", port->targ_port);
1260 #endif
1261                         ctl_port_online(port);
1262                 }
1263         }
1264
1265         return (0);
1266 }
1267
1268 int
1269 ctl_port_disable(ctl_port_type port_type)
1270 {
1271         struct ctl_softc *softc;
1272         struct ctl_port *port;
1273
1274         softc = control_softc;
1275
1276         STAILQ_FOREACH(port, &softc->port_list, links) {
1277                 if (port_type & port->port_type)
1278                         ctl_port_offline(port);
1279         }
1280
1281         return (0);
1282 }
1283
1284 /*
1285  * Returns 0 for success, 1 for failure.
1286  * Currently the only failure mode is if there aren't enough entries
1287  * allocated.  So, in case of a failure, look at num_entries_dropped,
1288  * reallocate and try again.
1289  */
1290 int
1291 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1292               int *num_entries_filled, int *num_entries_dropped,
1293               ctl_port_type port_type, int no_virtual)
1294 {
1295         struct ctl_softc *softc;
1296         struct ctl_port *port;
1297         int entries_dropped, entries_filled;
1298         int retval;
1299         int i;
1300
1301         softc = control_softc;
1302
1303         retval = 0;
1304         entries_filled = 0;
1305         entries_dropped = 0;
1306
1307         i = 0;
1308         mtx_lock(&softc->ctl_lock);
1309         STAILQ_FOREACH(port, &softc->port_list, links) {
1310                 struct ctl_port_entry *entry;
1311
1312                 if ((port->port_type & port_type) == 0)
1313                         continue;
1314
1315                 if ((no_virtual != 0)
1316                  && (port->virtual_port != 0))
1317                         continue;
1318
1319                 if (entries_filled >= num_entries_alloced) {
1320                         entries_dropped++;
1321                         continue;
1322                 }
1323                 entry = &entries[i];
1324
1325                 entry->port_type = port->port_type;
1326                 strlcpy(entry->port_name, port->port_name,
1327                         sizeof(entry->port_name));
1328                 entry->physical_port = port->physical_port;
1329                 entry->virtual_port = port->virtual_port;
1330                 entry->wwnn = port->wwnn;
1331                 entry->wwpn = port->wwpn;
1332
1333                 i++;
1334                 entries_filled++;
1335         }
1336
1337         mtx_unlock(&softc->ctl_lock);
1338
1339         if (entries_dropped > 0)
1340                 retval = 1;
1341
1342         *num_entries_dropped = entries_dropped;
1343         *num_entries_filled = entries_filled;
1344
1345         return (retval);
1346 }
1347
1348 static void
1349 ctl_ioctl_online(void *arg)
1350 {
1351         struct ctl_ioctl_info *ioctl_info;
1352
1353         ioctl_info = (struct ctl_ioctl_info *)arg;
1354
1355         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1356 }
1357
1358 static void
1359 ctl_ioctl_offline(void *arg)
1360 {
1361         struct ctl_ioctl_info *ioctl_info;
1362
1363         ioctl_info = (struct ctl_ioctl_info *)arg;
1364
1365         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1366 }
1367
1368 /*
1369  * Remove an initiator by port number and initiator ID.
1370  * Returns 0 for success, -1 for failure.
1371  */
1372 int
1373 ctl_remove_initiator(struct ctl_port *port, int iid)
1374 {
1375         struct ctl_softc *softc = control_softc;
1376
1377         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1378
1379         if (iid > CTL_MAX_INIT_PER_PORT) {
1380                 printf("%s: initiator ID %u > maximun %u!\n",
1381                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1382                 return (-1);
1383         }
1384
1385         mtx_lock(&softc->ctl_lock);
1386         port->wwpn_iid[iid].in_use--;
1387         port->wwpn_iid[iid].last_use = time_uptime;
1388         mtx_unlock(&softc->ctl_lock);
1389
1390         return (0);
1391 }
1392
1393 /*
1394  * Add an initiator to the initiator map.
1395  * Returns iid for success, < 0 for failure.
1396  */
1397 int
1398 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1399 {
1400         struct ctl_softc *softc = control_softc;
1401         time_t best_time;
1402         int i, best;
1403
1404         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1405
1406         if (iid >= CTL_MAX_INIT_PER_PORT) {
1407                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1408                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1409                 free(name, M_CTL);
1410                 return (-1);
1411         }
1412
1413         mtx_lock(&softc->ctl_lock);
1414
1415         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1416                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1417                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1418                                 iid = i;
1419                                 break;
1420                         }
1421                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1422                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1423                                 iid = i;
1424                                 break;
1425                         }
1426                 }
1427         }
1428
1429         if (iid < 0) {
1430                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1431                         if (port->wwpn_iid[i].in_use == 0 &&
1432                             port->wwpn_iid[i].wwpn == 0 &&
1433                             port->wwpn_iid[i].name == NULL) {
1434                                 iid = i;
1435                                 break;
1436                         }
1437                 }
1438         }
1439
1440         if (iid < 0) {
1441                 best = -1;
1442                 best_time = INT32_MAX;
1443                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1444                         if (port->wwpn_iid[i].in_use == 0) {
1445                                 if (port->wwpn_iid[i].last_use < best_time) {
1446                                         best = i;
1447                                         best_time = port->wwpn_iid[i].last_use;
1448                                 }
1449                         }
1450                 }
1451                 iid = best;
1452         }
1453
1454         if (iid < 0) {
1455                 mtx_unlock(&softc->ctl_lock);
1456                 free(name, M_CTL);
1457                 return (-2);
1458         }
1459
1460         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1461                 /*
1462                  * This is not an error yet.
1463                  */
1464                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1465 #if 0
1466                         printf("%s: port %d iid %u WWPN %#jx arrived"
1467                             " again\n", __func__, port->targ_port,
1468                             iid, (uintmax_t)wwpn);
1469 #endif
1470                         goto take;
1471                 }
1472                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1473                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1474 #if 0
1475                         printf("%s: port %d iid %u name '%s' arrived"
1476                             " again\n", __func__, port->targ_port,
1477                             iid, name);
1478 #endif
1479                         goto take;
1480                 }
1481
1482                 /*
1483                  * This is an error, but what do we do about it?  The
1484                  * driver is telling us we have a new WWPN for this
1485                  * initiator ID, so we pretty much need to use it.
1486                  */
1487                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1488                     " but WWPN %#jx '%s' is still at that address\n",
1489                     __func__, port->targ_port, iid, wwpn, name,
1490                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1491                     port->wwpn_iid[iid].name);
1492
1493                 /*
1494                  * XXX KDM clear have_ca and ua_pending on each LUN for
1495                  * this initiator.
1496                  */
1497         }
1498 take:
1499         free(port->wwpn_iid[iid].name, M_CTL);
1500         port->wwpn_iid[iid].name = name;
1501         port->wwpn_iid[iid].wwpn = wwpn;
1502         port->wwpn_iid[iid].in_use++;
1503         mtx_unlock(&softc->ctl_lock);
1504
1505         return (iid);
1506 }
1507
1508 static int
1509 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1510 {
1511         int len;
1512
1513         switch (port->port_type) {
1514         case CTL_PORT_FC:
1515         {
1516                 struct scsi_transportid_fcp *id =
1517                     (struct scsi_transportid_fcp *)buf;
1518                 if (port->wwpn_iid[iid].wwpn == 0)
1519                         return (0);
1520                 memset(id, 0, sizeof(*id));
1521                 id->format_protocol = SCSI_PROTO_FC;
1522                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1523                 return (sizeof(*id));
1524         }
1525         case CTL_PORT_ISCSI:
1526         {
1527                 struct scsi_transportid_iscsi_port *id =
1528                     (struct scsi_transportid_iscsi_port *)buf;
1529                 if (port->wwpn_iid[iid].name == NULL)
1530                         return (0);
1531                 memset(id, 0, 256);
1532                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1533                     SCSI_PROTO_ISCSI;
1534                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1535                 len = roundup2(min(len, 252), 4);
1536                 scsi_ulto2b(len, id->additional_length);
1537                 return (sizeof(*id) + len);
1538         }
1539         case CTL_PORT_SAS:
1540         {
1541                 struct scsi_transportid_sas *id =
1542                     (struct scsi_transportid_sas *)buf;
1543                 if (port->wwpn_iid[iid].wwpn == 0)
1544                         return (0);
1545                 memset(id, 0, sizeof(*id));
1546                 id->format_protocol = SCSI_PROTO_SAS;
1547                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1548                 return (sizeof(*id));
1549         }
1550         default:
1551         {
1552                 struct scsi_transportid_spi *id =
1553                     (struct scsi_transportid_spi *)buf;
1554                 memset(id, 0, sizeof(*id));
1555                 id->format_protocol = SCSI_PROTO_SPI;
1556                 scsi_ulto2b(iid, id->scsi_addr);
1557                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1558                 return (sizeof(*id));
1559         }
1560         }
1561 }
1562
1563 static int
1564 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1565 {
1566         return (0);
1567 }
1568
1569 static int
1570 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1571 {
1572         return (0);
1573 }
1574
1575 /*
1576  * Data movement routine for the CTL ioctl frontend port.
1577  */
1578 static int
1579 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1580 {
1581         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1582         struct ctl_sg_entry ext_entry, kern_entry;
1583         int ext_sglen, ext_sg_entries, kern_sg_entries;
1584         int ext_sg_start, ext_offset;
1585         int len_to_copy, len_copied;
1586         int kern_watermark, ext_watermark;
1587         int ext_sglist_malloced;
1588         int i, j;
1589
1590         ext_sglist_malloced = 0;
1591         ext_sg_start = 0;
1592         ext_offset = 0;
1593
1594         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1595
1596         /*
1597          * If this flag is set, fake the data transfer.
1598          */
1599         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1600                 ctsio->ext_data_filled = ctsio->ext_data_len;
1601                 goto bailout;
1602         }
1603
1604         /*
1605          * To simplify things here, if we have a single buffer, stick it in
1606          * a S/G entry and just make it a single entry S/G list.
1607          */
1608         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1609                 int len_seen;
1610
1611                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1612
1613                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1614                                                            M_WAITOK);
1615                 ext_sglist_malloced = 1;
1616                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1617                                    ext_sglen) != 0) {
1618                         ctl_set_internal_failure(ctsio,
1619                                                  /*sks_valid*/ 0,
1620                                                  /*retry_count*/ 0);
1621                         goto bailout;
1622                 }
1623                 ext_sg_entries = ctsio->ext_sg_entries;
1624                 len_seen = 0;
1625                 for (i = 0; i < ext_sg_entries; i++) {
1626                         if ((len_seen + ext_sglist[i].len) >=
1627                              ctsio->ext_data_filled) {
1628                                 ext_sg_start = i;
1629                                 ext_offset = ctsio->ext_data_filled - len_seen;
1630                                 break;
1631                         }
1632                         len_seen += ext_sglist[i].len;
1633                 }
1634         } else {
1635                 ext_sglist = &ext_entry;
1636                 ext_sglist->addr = ctsio->ext_data_ptr;
1637                 ext_sglist->len = ctsio->ext_data_len;
1638                 ext_sg_entries = 1;
1639                 ext_sg_start = 0;
1640                 ext_offset = ctsio->ext_data_filled;
1641         }
1642
1643         if (ctsio->kern_sg_entries > 0) {
1644                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1645                 kern_sg_entries = ctsio->kern_sg_entries;
1646         } else {
1647                 kern_sglist = &kern_entry;
1648                 kern_sglist->addr = ctsio->kern_data_ptr;
1649                 kern_sglist->len = ctsio->kern_data_len;
1650                 kern_sg_entries = 1;
1651         }
1652
1653
1654         kern_watermark = 0;
1655         ext_watermark = ext_offset;
1656         len_copied = 0;
1657         for (i = ext_sg_start, j = 0;
1658              i < ext_sg_entries && j < kern_sg_entries;) {
1659                 uint8_t *ext_ptr, *kern_ptr;
1660
1661                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1662                                       kern_sglist[j].len - kern_watermark);
1663
1664                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1665                 ext_ptr = ext_ptr + ext_watermark;
1666                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1667                         /*
1668                          * XXX KDM fix this!
1669                          */
1670                         panic("need to implement bus address support");
1671 #if 0
1672                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1673 #endif
1674                 } else
1675                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1676                 kern_ptr = kern_ptr + kern_watermark;
1677
1678                 kern_watermark += len_to_copy;
1679                 ext_watermark += len_to_copy;
1680
1681                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1682                      CTL_FLAG_DATA_IN) {
1683                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1684                                          "bytes to user\n", len_to_copy));
1685                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1686                                          "to %p\n", kern_ptr, ext_ptr));
1687                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1688                                 ctl_set_internal_failure(ctsio,
1689                                                          /*sks_valid*/ 0,
1690                                                          /*retry_count*/ 0);
1691                                 goto bailout;
1692                         }
1693                 } else {
1694                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1695                                          "bytes from user\n", len_to_copy));
1696                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1697                                          "to %p\n", ext_ptr, kern_ptr));
1698                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1699                                 ctl_set_internal_failure(ctsio,
1700                                                          /*sks_valid*/ 0,
1701                                                          /*retry_count*/0);
1702                                 goto bailout;
1703                         }
1704                 }
1705
1706                 len_copied += len_to_copy;
1707
1708                 if (ext_sglist[i].len == ext_watermark) {
1709                         i++;
1710                         ext_watermark = 0;
1711                 }
1712
1713                 if (kern_sglist[j].len == kern_watermark) {
1714                         j++;
1715                         kern_watermark = 0;
1716                 }
1717         }
1718
1719         ctsio->ext_data_filled += len_copied;
1720
1721         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1722                          "kern_sg_entries: %d\n", ext_sg_entries,
1723                          kern_sg_entries));
1724         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1725                          "kern_data_len = %d\n", ctsio->ext_data_len,
1726                          ctsio->kern_data_len));
1727
1728
1729         /* XXX KDM set residual?? */
1730 bailout:
1731
1732         if (ext_sglist_malloced != 0)
1733                 free(ext_sglist, M_CTL);
1734
1735         return (CTL_RETVAL_COMPLETE);
1736 }
1737
1738 /*
1739  * Serialize a command that went down the "wrong" side, and so was sent to
1740  * this controller for execution.  The logic is a little different than the
1741  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1742  * sent back to the other side, but in the success case, we execute the
1743  * command on this side (XFER mode) or tell the other side to execute it
1744  * (SER_ONLY mode).
1745  */
1746 static int
1747 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1748 {
1749         struct ctl_softc *ctl_softc;
1750         union ctl_ha_msg msg_info;
1751         struct ctl_lun *lun;
1752         int retval = 0;
1753         uint32_t targ_lun;
1754
1755         ctl_softc = control_softc;
1756
1757         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1758         lun = ctl_softc->ctl_luns[targ_lun];
1759         if (lun==NULL)
1760         {
1761                 /*
1762                  * Why isn't LUN defined? The other side wouldn't
1763                  * send a cmd if the LUN is undefined.
1764                  */
1765                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1766
1767                 /* "Logical unit not supported" */
1768                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1769                                    lun,
1770                                    /*sense_format*/SSD_TYPE_NONE,
1771                                    /*current_error*/ 1,
1772                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1773                                    /*asc*/ 0x25,
1774                                    /*ascq*/ 0x00,
1775                                    SSD_ELEM_NONE);
1776
1777                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1778                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1779                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1780                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1781                 msg_info.hdr.serializing_sc = NULL;
1782                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1783                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1784                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1785                 }
1786                 return(1);
1787
1788         }
1789
1790         mtx_lock(&lun->lun_lock);
1791         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1792
1793         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1794                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1795                  ooa_links))) {
1796         case CTL_ACTION_BLOCK:
1797                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1798                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1799                                   blocked_links);
1800                 break;
1801         case CTL_ACTION_PASS:
1802         case CTL_ACTION_SKIP:
1803                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1804                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1805                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1806                 } else {
1807
1808                         /* send msg back to other side */
1809                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1810                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1811                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1812 #if 0
1813                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1814 #endif
1815                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1816                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1817                         }
1818                 }
1819                 break;
1820         case CTL_ACTION_OVERLAP:
1821                 /* OVERLAPPED COMMANDS ATTEMPTED */
1822                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1823                                    lun,
1824                                    /*sense_format*/SSD_TYPE_NONE,
1825                                    /*current_error*/ 1,
1826                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1827                                    /*asc*/ 0x4E,
1828                                    /*ascq*/ 0x00,
1829                                    SSD_ELEM_NONE);
1830
1831                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1832                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1833                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1834                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1835                 msg_info.hdr.serializing_sc = NULL;
1836                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1837 #if 0
1838                 printf("BAD JUJU:Major Bummer Overlap\n");
1839 #endif
1840                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1841                 retval = 1;
1842                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1843                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1844                 }
1845                 break;
1846         case CTL_ACTION_OVERLAP_TAG:
1847                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1848                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1849                                    lun,
1850                                    /*sense_format*/SSD_TYPE_NONE,
1851                                    /*current_error*/ 1,
1852                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1853                                    /*asc*/ 0x4D,
1854                                    /*ascq*/ ctsio->tag_num & 0xff,
1855                                    SSD_ELEM_NONE);
1856
1857                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1858                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1859                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1860                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1861                 msg_info.hdr.serializing_sc = NULL;
1862                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1863 #if 0
1864                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1865 #endif
1866                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1867                 retval = 1;
1868                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1869                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1870                 }
1871                 break;
1872         case CTL_ACTION_ERROR:
1873         default:
1874                 /* "Internal target failure" */
1875                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1876                                    lun,
1877                                    /*sense_format*/SSD_TYPE_NONE,
1878                                    /*current_error*/ 1,
1879                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1880                                    /*asc*/ 0x44,
1881                                    /*ascq*/ 0x00,
1882                                    SSD_ELEM_NONE);
1883
1884                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1885                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1886                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1887                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1888                 msg_info.hdr.serializing_sc = NULL;
1889                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1890 #if 0
1891                 printf("BAD JUJU:Major Bummer HW Error\n");
1892 #endif
1893                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1894                 retval = 1;
1895                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1896                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1897                 }
1898                 break;
1899         }
1900         mtx_unlock(&lun->lun_lock);
1901         return (retval);
1902 }
1903
1904 static int
1905 ctl_ioctl_submit_wait(union ctl_io *io)
1906 {
1907         struct ctl_fe_ioctl_params params;
1908         ctl_fe_ioctl_state last_state;
1909         int done, retval;
1910
1911         retval = 0;
1912
1913         bzero(&params, sizeof(params));
1914
1915         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1916         cv_init(&params.sem, "ctlioccv");
1917         params.state = CTL_IOCTL_INPROG;
1918         last_state = params.state;
1919
1920         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1921
1922         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1923
1924         /* This shouldn't happen */
1925         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1926                 return (retval);
1927
1928         done = 0;
1929
1930         do {
1931                 mtx_lock(&params.ioctl_mtx);
1932                 /*
1933                  * Check the state here, and don't sleep if the state has
1934                  * already changed (i.e. wakeup has already occured, but we
1935                  * weren't waiting yet).
1936                  */
1937                 if (params.state == last_state) {
1938                         /* XXX KDM cv_wait_sig instead? */
1939                         cv_wait(&params.sem, &params.ioctl_mtx);
1940                 }
1941                 last_state = params.state;
1942
1943                 switch (params.state) {
1944                 case CTL_IOCTL_INPROG:
1945                         /* Why did we wake up? */
1946                         /* XXX KDM error here? */
1947                         mtx_unlock(&params.ioctl_mtx);
1948                         break;
1949                 case CTL_IOCTL_DATAMOVE:
1950                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1951
1952                         /*
1953                          * change last_state back to INPROG to avoid
1954                          * deadlock on subsequent data moves.
1955                          */
1956                         params.state = last_state = CTL_IOCTL_INPROG;
1957
1958                         mtx_unlock(&params.ioctl_mtx);
1959                         ctl_ioctl_do_datamove(&io->scsiio);
1960                         /*
1961                          * Note that in some cases, most notably writes,
1962                          * this will queue the I/O and call us back later.
1963                          * In other cases, generally reads, this routine
1964                          * will immediately call back and wake us up,
1965                          * probably using our own context.
1966                          */
1967                         io->scsiio.be_move_done(io);
1968                         break;
1969                 case CTL_IOCTL_DONE:
1970                         mtx_unlock(&params.ioctl_mtx);
1971                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1972                         done = 1;
1973                         break;
1974                 default:
1975                         mtx_unlock(&params.ioctl_mtx);
1976                         /* XXX KDM error here? */
1977                         break;
1978                 }
1979         } while (done == 0);
1980
1981         mtx_destroy(&params.ioctl_mtx);
1982         cv_destroy(&params.sem);
1983
1984         return (CTL_RETVAL_COMPLETE);
1985 }
1986
1987 static void
1988 ctl_ioctl_datamove(union ctl_io *io)
1989 {
1990         struct ctl_fe_ioctl_params *params;
1991
1992         params = (struct ctl_fe_ioctl_params *)
1993                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1994
1995         mtx_lock(&params->ioctl_mtx);
1996         params->state = CTL_IOCTL_DATAMOVE;
1997         cv_broadcast(&params->sem);
1998         mtx_unlock(&params->ioctl_mtx);
1999 }
2000
2001 static void
2002 ctl_ioctl_done(union ctl_io *io)
2003 {
2004         struct ctl_fe_ioctl_params *params;
2005
2006         params = (struct ctl_fe_ioctl_params *)
2007                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2008
2009         mtx_lock(&params->ioctl_mtx);
2010         params->state = CTL_IOCTL_DONE;
2011         cv_broadcast(&params->sem);
2012         mtx_unlock(&params->ioctl_mtx);
2013 }
2014
2015 static void
2016 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2017 {
2018         struct ctl_fe_ioctl_startstop_info *sd_info;
2019
2020         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2021
2022         sd_info->hs_info.status = metatask->status;
2023         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2024         sd_info->hs_info.luns_complete =
2025                 metatask->taskinfo.startstop.luns_complete;
2026         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2027
2028         cv_broadcast(&sd_info->sem);
2029 }
2030
2031 static void
2032 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2033 {
2034         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2035
2036         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2037
2038         mtx_lock(fe_bbr_info->lock);
2039         fe_bbr_info->bbr_info->status = metatask->status;
2040         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2041         fe_bbr_info->wakeup_done = 1;
2042         mtx_unlock(fe_bbr_info->lock);
2043
2044         cv_broadcast(&fe_bbr_info->sem);
2045 }
2046
2047 /*
2048  * Returns 0 for success, errno for failure.
2049  */
2050 static int
2051 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2052                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2053 {
2054         union ctl_io *io;
2055         int retval;
2056
2057         retval = 0;
2058
2059         mtx_lock(&lun->lun_lock);
2060         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2061              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2062              ooa_links)) {
2063                 struct ctl_ooa_entry *entry;
2064
2065                 /*
2066                  * If we've got more than we can fit, just count the
2067                  * remaining entries.
2068                  */
2069                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2070                         continue;
2071
2072                 entry = &kern_entries[*cur_fill_num];
2073
2074                 entry->tag_num = io->scsiio.tag_num;
2075                 entry->lun_num = lun->lun;
2076 #ifdef CTL_TIME_IO
2077                 entry->start_bt = io->io_hdr.start_bt;
2078 #endif
2079                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2080                 entry->cdb_len = io->scsiio.cdb_len;
2081                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2082                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2083
2084                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2085                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2086
2087                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2088                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2089
2090                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2091                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2092
2093                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2094                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2095         }
2096         mtx_unlock(&lun->lun_lock);
2097
2098         return (retval);
2099 }
2100
2101 static void *
2102 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2103                  size_t error_str_len)
2104 {
2105         void *kptr;
2106
2107         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2108
2109         if (copyin(user_addr, kptr, len) != 0) {
2110                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2111                          "from user address %p to kernel address %p", len,
2112                          user_addr, kptr);
2113                 free(kptr, M_CTL);
2114                 return (NULL);
2115         }
2116
2117         return (kptr);
2118 }
2119
2120 static void
2121 ctl_free_args(int num_args, struct ctl_be_arg *args)
2122 {
2123         int i;
2124
2125         if (args == NULL)
2126                 return;
2127
2128         for (i = 0; i < num_args; i++) {
2129                 free(args[i].kname, M_CTL);
2130                 free(args[i].kvalue, M_CTL);
2131         }
2132
2133         free(args, M_CTL);
2134 }
2135
2136 static struct ctl_be_arg *
2137 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2138                 char *error_str, size_t error_str_len)
2139 {
2140         struct ctl_be_arg *args;
2141         int i;
2142
2143         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2144                                 error_str, error_str_len);
2145
2146         if (args == NULL)
2147                 goto bailout;
2148
2149         for (i = 0; i < num_args; i++) {
2150                 args[i].kname = NULL;
2151                 args[i].kvalue = NULL;
2152         }
2153
2154         for (i = 0; i < num_args; i++) {
2155                 uint8_t *tmpptr;
2156
2157                 args[i].kname = ctl_copyin_alloc(args[i].name,
2158                         args[i].namelen, error_str, error_str_len);
2159                 if (args[i].kname == NULL)
2160                         goto bailout;
2161
2162                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2163                         snprintf(error_str, error_str_len, "Argument %d "
2164                                  "name is not NUL-terminated", i);
2165                         goto bailout;
2166                 }
2167
2168                 if (args[i].flags & CTL_BEARG_RD) {
2169                         tmpptr = ctl_copyin_alloc(args[i].value,
2170                                 args[i].vallen, error_str, error_str_len);
2171                         if (tmpptr == NULL)
2172                                 goto bailout;
2173                         if ((args[i].flags & CTL_BEARG_ASCII)
2174                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2175                                 snprintf(error_str, error_str_len, "Argument "
2176                                     "%d value is not NUL-terminated", i);
2177                                 goto bailout;
2178                         }
2179                         args[i].kvalue = tmpptr;
2180                 } else {
2181                         args[i].kvalue = malloc(args[i].vallen,
2182                             M_CTL, M_WAITOK | M_ZERO);
2183                 }
2184         }
2185
2186         return (args);
2187 bailout:
2188
2189         ctl_free_args(num_args, args);
2190
2191         return (NULL);
2192 }
2193
2194 static void
2195 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2196 {
2197         int i;
2198
2199         for (i = 0; i < num_args; i++) {
2200                 if (args[i].flags & CTL_BEARG_WR)
2201                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2202         }
2203 }
2204
2205 /*
2206  * Escape characters that are illegal or not recommended in XML.
2207  */
2208 int
2209 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2210 {
2211         int retval;
2212
2213         retval = 0;
2214
2215         for (; *str; str++) {
2216                 switch (*str) {
2217                 case '&':
2218                         retval = sbuf_printf(sb, "&amp;");
2219                         break;
2220                 case '>':
2221                         retval = sbuf_printf(sb, "&gt;");
2222                         break;
2223                 case '<':
2224                         retval = sbuf_printf(sb, "&lt;");
2225                         break;
2226                 default:
2227                         retval = sbuf_putc(sb, *str);
2228                         break;
2229                 }
2230
2231                 if (retval != 0)
2232                         break;
2233
2234         }
2235
2236         return (retval);
2237 }
2238
2239 static int
2240 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2241           struct thread *td)
2242 {
2243         struct ctl_softc *softc;
2244         int retval;
2245
2246         softc = control_softc;
2247
2248         retval = 0;
2249
2250         switch (cmd) {
2251         case CTL_IO: {
2252                 union ctl_io *io;
2253                 void *pool_tmp;
2254
2255                 /*
2256                  * If we haven't been "enabled", don't allow any SCSI I/O
2257                  * to this FETD.
2258                  */
2259                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2260                         retval = EPERM;
2261                         break;
2262                 }
2263
2264                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2265                 if (io == NULL) {
2266                         printf("ctl_ioctl: can't allocate ctl_io!\n");
2267                         retval = ENOSPC;
2268                         break;
2269                 }
2270
2271                 /*
2272                  * Need to save the pool reference so it doesn't get
2273                  * spammed by the user's ctl_io.
2274                  */
2275                 pool_tmp = io->io_hdr.pool;
2276
2277                 memcpy(io, (void *)addr, sizeof(*io));
2278
2279                 io->io_hdr.pool = pool_tmp;
2280                 /*
2281                  * No status yet, so make sure the status is set properly.
2282                  */
2283                 io->io_hdr.status = CTL_STATUS_NONE;
2284
2285                 /*
2286                  * The user sets the initiator ID, target and LUN IDs.
2287                  */
2288                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2289                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2290                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2291                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2292                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2293
2294                 retval = ctl_ioctl_submit_wait(io);
2295
2296                 if (retval != 0) {
2297                         ctl_free_io(io);
2298                         break;
2299                 }
2300
2301                 memcpy((void *)addr, io, sizeof(*io));
2302
2303                 /* return this to our pool */
2304                 ctl_free_io(io);
2305
2306                 break;
2307         }
2308         case CTL_ENABLE_PORT:
2309         case CTL_DISABLE_PORT:
2310         case CTL_SET_PORT_WWNS: {
2311                 struct ctl_port *port;
2312                 struct ctl_port_entry *entry;
2313
2314                 entry = (struct ctl_port_entry *)addr;
2315                 
2316                 mtx_lock(&softc->ctl_lock);
2317                 STAILQ_FOREACH(port, &softc->port_list, links) {
2318                         int action, done;
2319
2320                         action = 0;
2321                         done = 0;
2322
2323                         if ((entry->port_type == CTL_PORT_NONE)
2324                          && (entry->targ_port == port->targ_port)) {
2325                                 /*
2326                                  * If the user only wants to enable or
2327                                  * disable or set WWNs on a specific port,
2328                                  * do the operation and we're done.
2329                                  */
2330                                 action = 1;
2331                                 done = 1;
2332                         } else if (entry->port_type & port->port_type) {
2333                                 /*
2334                                  * Compare the user's type mask with the
2335                                  * particular frontend type to see if we
2336                                  * have a match.
2337                                  */
2338                                 action = 1;
2339                                 done = 0;
2340
2341                                 /*
2342                                  * Make sure the user isn't trying to set
2343                                  * WWNs on multiple ports at the same time.
2344                                  */
2345                                 if (cmd == CTL_SET_PORT_WWNS) {
2346                                         printf("%s: Can't set WWNs on "
2347                                                "multiple ports\n", __func__);
2348                                         retval = EINVAL;
2349                                         break;
2350                                 }
2351                         }
2352                         if (action != 0) {
2353                                 /*
2354                                  * XXX KDM we have to drop the lock here,
2355                                  * because the online/offline operations
2356                                  * can potentially block.  We need to
2357                                  * reference count the frontends so they
2358                                  * can't go away,
2359                                  */
2360                                 mtx_unlock(&softc->ctl_lock);
2361
2362                                 if (cmd == CTL_ENABLE_PORT) {
2363                                         struct ctl_lun *lun;
2364
2365                                         STAILQ_FOREACH(lun, &softc->lun_list,
2366                                                        links) {
2367                                                 port->lun_enable(port->targ_lun_arg,
2368                                                     lun->target,
2369                                                     lun->lun);
2370                                         }
2371
2372                                         ctl_port_online(port);
2373                                 } else if (cmd == CTL_DISABLE_PORT) {
2374                                         struct ctl_lun *lun;
2375
2376                                         ctl_port_offline(port);
2377
2378                                         STAILQ_FOREACH(lun, &softc->lun_list,
2379                                                        links) {
2380                                                 port->lun_disable(
2381                                                     port->targ_lun_arg,
2382                                                     lun->target,
2383                                                     lun->lun);
2384                                         }
2385                                 }
2386
2387                                 mtx_lock(&softc->ctl_lock);
2388
2389                                 if (cmd == CTL_SET_PORT_WWNS)
2390                                         ctl_port_set_wwns(port,
2391                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2392                                             1 : 0, entry->wwnn,
2393                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2394                                             1 : 0, entry->wwpn);
2395                         }
2396                         if (done != 0)
2397                                 break;
2398                 }
2399                 mtx_unlock(&softc->ctl_lock);
2400                 break;
2401         }
2402         case CTL_GET_PORT_LIST: {
2403                 struct ctl_port *port;
2404                 struct ctl_port_list *list;
2405                 int i;
2406
2407                 list = (struct ctl_port_list *)addr;
2408
2409                 if (list->alloc_len != (list->alloc_num *
2410                     sizeof(struct ctl_port_entry))) {
2411                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2412                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2413                                "%zu\n", __func__, list->alloc_len,
2414                                list->alloc_num, sizeof(struct ctl_port_entry));
2415                         retval = EINVAL;
2416                         break;
2417                 }
2418                 list->fill_len = 0;
2419                 list->fill_num = 0;
2420                 list->dropped_num = 0;
2421                 i = 0;
2422                 mtx_lock(&softc->ctl_lock);
2423                 STAILQ_FOREACH(port, &softc->port_list, links) {
2424                         struct ctl_port_entry entry, *list_entry;
2425
2426                         if (list->fill_num >= list->alloc_num) {
2427                                 list->dropped_num++;
2428                                 continue;
2429                         }
2430
2431                         entry.port_type = port->port_type;
2432                         strlcpy(entry.port_name, port->port_name,
2433                                 sizeof(entry.port_name));
2434                         entry.targ_port = port->targ_port;
2435                         entry.physical_port = port->physical_port;
2436                         entry.virtual_port = port->virtual_port;
2437                         entry.wwnn = port->wwnn;
2438                         entry.wwpn = port->wwpn;
2439                         if (port->status & CTL_PORT_STATUS_ONLINE)
2440                                 entry.online = 1;
2441                         else
2442                                 entry.online = 0;
2443
2444                         list_entry = &list->entries[i];
2445
2446                         retval = copyout(&entry, list_entry, sizeof(entry));
2447                         if (retval != 0) {
2448                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2449                                        "returned %d\n", __func__, retval);
2450                                 break;
2451                         }
2452                         i++;
2453                         list->fill_num++;
2454                         list->fill_len += sizeof(entry);
2455                 }
2456                 mtx_unlock(&softc->ctl_lock);
2457
2458                 /*
2459                  * If this is non-zero, we had a copyout fault, so there's
2460                  * probably no point in attempting to set the status inside
2461                  * the structure.
2462                  */
2463                 if (retval != 0)
2464                         break;
2465
2466                 if (list->dropped_num > 0)
2467                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2468                 else
2469                         list->status = CTL_PORT_LIST_OK;
2470                 break;
2471         }
2472         case CTL_DUMP_OOA: {
2473                 struct ctl_lun *lun;
2474                 union ctl_io *io;
2475                 char printbuf[128];
2476                 struct sbuf sb;
2477
2478                 mtx_lock(&softc->ctl_lock);
2479                 printf("Dumping OOA queues:\n");
2480                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2481                         mtx_lock(&lun->lun_lock);
2482                         for (io = (union ctl_io *)TAILQ_FIRST(
2483                              &lun->ooa_queue); io != NULL;
2484                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2485                              ooa_links)) {
2486                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2487                                          SBUF_FIXEDLEN);
2488                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2489                                             (intmax_t)lun->lun,
2490                                             io->scsiio.tag_num,
2491                                             (io->io_hdr.flags &
2492                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2493                                             (io->io_hdr.flags &
2494                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2495                                             (io->io_hdr.flags &
2496                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2497                                             (io->io_hdr.flags &
2498                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2499                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2500                                 sbuf_finish(&sb);
2501                                 printf("%s\n", sbuf_data(&sb));
2502                         }
2503                         mtx_unlock(&lun->lun_lock);
2504                 }
2505                 printf("OOA queues dump done\n");
2506                 mtx_unlock(&softc->ctl_lock);
2507                 break;
2508         }
2509         case CTL_GET_OOA: {
2510                 struct ctl_lun *lun;
2511                 struct ctl_ooa *ooa_hdr;
2512                 struct ctl_ooa_entry *entries;
2513                 uint32_t cur_fill_num;
2514
2515                 ooa_hdr = (struct ctl_ooa *)addr;
2516
2517                 if ((ooa_hdr->alloc_len == 0)
2518                  || (ooa_hdr->alloc_num == 0)) {
2519                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2520                                "must be non-zero\n", __func__,
2521                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2522                         retval = EINVAL;
2523                         break;
2524                 }
2525
2526                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2527                     sizeof(struct ctl_ooa_entry))) {
2528                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2529                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2530                                __func__, ooa_hdr->alloc_len,
2531                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2532                         retval = EINVAL;
2533                         break;
2534                 }
2535
2536                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2537                 if (entries == NULL) {
2538                         printf("%s: could not allocate %d bytes for OOA "
2539                                "dump\n", __func__, ooa_hdr->alloc_len);
2540                         retval = ENOMEM;
2541                         break;
2542                 }
2543
2544                 mtx_lock(&softc->ctl_lock);
2545                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2546                  && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2547                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2548                         mtx_unlock(&softc->ctl_lock);
2549                         free(entries, M_CTL);
2550                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2551                                __func__, (uintmax_t)ooa_hdr->lun_num);
2552                         retval = EINVAL;
2553                         break;
2554                 }
2555
2556                 cur_fill_num = 0;
2557
2558                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2559                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2560                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2561                                         ooa_hdr, entries);
2562                                 if (retval != 0)
2563                                         break;
2564                         }
2565                         if (retval != 0) {
2566                                 mtx_unlock(&softc->ctl_lock);
2567                                 free(entries, M_CTL);
2568                                 break;
2569                         }
2570                 } else {
2571                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2572
2573                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2574                                                     entries);
2575                 }
2576                 mtx_unlock(&softc->ctl_lock);
2577
2578                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2579                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2580                         sizeof(struct ctl_ooa_entry);
2581                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2582                 if (retval != 0) {
2583                         printf("%s: error copying out %d bytes for OOA dump\n", 
2584                                __func__, ooa_hdr->fill_len);
2585                 }
2586
2587                 getbintime(&ooa_hdr->cur_bt);
2588
2589                 if (cur_fill_num > ooa_hdr->alloc_num) {
2590                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2591                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2592                 } else {
2593                         ooa_hdr->dropped_num = 0;
2594                         ooa_hdr->status = CTL_OOA_OK;
2595                 }
2596
2597                 free(entries, M_CTL);
2598                 break;
2599         }
2600         case CTL_CHECK_OOA: {
2601                 union ctl_io *io;
2602                 struct ctl_lun *lun;
2603                 struct ctl_ooa_info *ooa_info;
2604
2605
2606                 ooa_info = (struct ctl_ooa_info *)addr;
2607
2608                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2609                         ooa_info->status = CTL_OOA_INVALID_LUN;
2610                         break;
2611                 }
2612                 mtx_lock(&softc->ctl_lock);
2613                 lun = softc->ctl_luns[ooa_info->lun_id];
2614                 if (lun == NULL) {
2615                         mtx_unlock(&softc->ctl_lock);
2616                         ooa_info->status = CTL_OOA_INVALID_LUN;
2617                         break;
2618                 }
2619                 mtx_lock(&lun->lun_lock);
2620                 mtx_unlock(&softc->ctl_lock);
2621                 ooa_info->num_entries = 0;
2622                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2623                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2624                      &io->io_hdr, ooa_links)) {
2625                         ooa_info->num_entries++;
2626                 }
2627                 mtx_unlock(&lun->lun_lock);
2628
2629                 ooa_info->status = CTL_OOA_SUCCESS;
2630
2631                 break;
2632         }
2633         case CTL_HARD_START:
2634         case CTL_HARD_STOP: {
2635                 struct ctl_fe_ioctl_startstop_info ss_info;
2636                 struct cfi_metatask *metatask;
2637                 struct mtx hs_mtx;
2638
2639                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2640
2641                 cv_init(&ss_info.sem, "hard start/stop cv" );
2642
2643                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2644                 if (metatask == NULL) {
2645                         retval = ENOMEM;
2646                         mtx_destroy(&hs_mtx);
2647                         break;
2648                 }
2649
2650                 if (cmd == CTL_HARD_START)
2651                         metatask->tasktype = CFI_TASK_STARTUP;
2652                 else
2653                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2654
2655                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2656                 metatask->callback_arg = &ss_info;
2657
2658                 cfi_action(metatask);
2659
2660                 /* Wait for the callback */
2661                 mtx_lock(&hs_mtx);
2662                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2663                 mtx_unlock(&hs_mtx);
2664
2665                 /*
2666                  * All information has been copied from the metatask by the
2667                  * time cv_broadcast() is called, so we free the metatask here.
2668                  */
2669                 cfi_free_metatask(metatask);
2670
2671                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2672
2673                 mtx_destroy(&hs_mtx);
2674                 break;
2675         }
2676         case CTL_BBRREAD: {
2677                 struct ctl_bbrread_info *bbr_info;
2678                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2679                 struct mtx bbr_mtx;
2680                 struct cfi_metatask *metatask;
2681
2682                 bbr_info = (struct ctl_bbrread_info *)addr;
2683
2684                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2685
2686                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2687                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2688
2689                 fe_bbr_info.bbr_info = bbr_info;
2690                 fe_bbr_info.lock = &bbr_mtx;
2691
2692                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2693                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2694
2695                 if (metatask == NULL) {
2696                         mtx_destroy(&bbr_mtx);
2697                         cv_destroy(&fe_bbr_info.sem);
2698                         retval = ENOMEM;
2699                         break;
2700                 }
2701                 metatask->tasktype = CFI_TASK_BBRREAD;
2702                 metatask->callback = ctl_ioctl_bbrread_callback;
2703                 metatask->callback_arg = &fe_bbr_info;
2704                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2705                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2706                 metatask->taskinfo.bbrread.len = bbr_info->len;
2707
2708                 cfi_action(metatask);
2709
2710                 mtx_lock(&bbr_mtx);
2711                 while (fe_bbr_info.wakeup_done == 0)
2712                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2713                 mtx_unlock(&bbr_mtx);
2714
2715                 bbr_info->status = metatask->status;
2716                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2717                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2718                 memcpy(&bbr_info->sense_data,
2719                        &metatask->taskinfo.bbrread.sense_data,
2720                        ctl_min(sizeof(bbr_info->sense_data),
2721                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2722
2723                 cfi_free_metatask(metatask);
2724
2725                 mtx_destroy(&bbr_mtx);
2726                 cv_destroy(&fe_bbr_info.sem);
2727
2728                 break;
2729         }
2730         case CTL_DELAY_IO: {
2731                 struct ctl_io_delay_info *delay_info;
2732 #ifdef CTL_IO_DELAY
2733                 struct ctl_lun *lun;
2734 #endif /* CTL_IO_DELAY */
2735
2736                 delay_info = (struct ctl_io_delay_info *)addr;
2737
2738 #ifdef CTL_IO_DELAY
2739                 mtx_lock(&softc->ctl_lock);
2740
2741                 if ((delay_info->lun_id > CTL_MAX_LUNS)
2742                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2743                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2744                 } else {
2745                         lun = softc->ctl_luns[delay_info->lun_id];
2746                         mtx_lock(&lun->lun_lock);
2747
2748                         delay_info->status = CTL_DELAY_STATUS_OK;
2749
2750                         switch (delay_info->delay_type) {
2751                         case CTL_DELAY_TYPE_CONT:
2752                                 break;
2753                         case CTL_DELAY_TYPE_ONESHOT:
2754                                 break;
2755                         default:
2756                                 delay_info->status =
2757                                         CTL_DELAY_STATUS_INVALID_TYPE;
2758                                 break;
2759                         }
2760
2761                         switch (delay_info->delay_loc) {
2762                         case CTL_DELAY_LOC_DATAMOVE:
2763                                 lun->delay_info.datamove_type =
2764                                         delay_info->delay_type;
2765                                 lun->delay_info.datamove_delay =
2766                                         delay_info->delay_secs;
2767                                 break;
2768                         case CTL_DELAY_LOC_DONE:
2769                                 lun->delay_info.done_type =
2770                                         delay_info->delay_type;
2771                                 lun->delay_info.done_delay =
2772                                         delay_info->delay_secs;
2773                                 break;
2774                         default:
2775                                 delay_info->status =
2776                                         CTL_DELAY_STATUS_INVALID_LOC;
2777                                 break;
2778                         }
2779                         mtx_unlock(&lun->lun_lock);
2780                 }
2781
2782                 mtx_unlock(&softc->ctl_lock);
2783 #else
2784                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2785 #endif /* CTL_IO_DELAY */
2786                 break;
2787         }
2788         case CTL_REALSYNC_SET: {
2789                 int *syncstate;
2790
2791                 syncstate = (int *)addr;
2792
2793                 mtx_lock(&softc->ctl_lock);
2794                 switch (*syncstate) {
2795                 case 0:
2796                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2797                         break;
2798                 case 1:
2799                         softc->flags |= CTL_FLAG_REAL_SYNC;
2800                         break;
2801                 default:
2802                         retval = EINVAL;
2803                         break;
2804                 }
2805                 mtx_unlock(&softc->ctl_lock);
2806                 break;
2807         }
2808         case CTL_REALSYNC_GET: {
2809                 int *syncstate;
2810
2811                 syncstate = (int*)addr;
2812
2813                 mtx_lock(&softc->ctl_lock);
2814                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2815                         *syncstate = 1;
2816                 else
2817                         *syncstate = 0;
2818                 mtx_unlock(&softc->ctl_lock);
2819
2820                 break;
2821         }
2822         case CTL_SETSYNC:
2823         case CTL_GETSYNC: {
2824                 struct ctl_sync_info *sync_info;
2825                 struct ctl_lun *lun;
2826
2827                 sync_info = (struct ctl_sync_info *)addr;
2828
2829                 mtx_lock(&softc->ctl_lock);
2830                 lun = softc->ctl_luns[sync_info->lun_id];
2831                 if (lun == NULL) {
2832                         mtx_unlock(&softc->ctl_lock);
2833                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2834                 }
2835                 /*
2836                  * Get or set the sync interval.  We're not bounds checking
2837                  * in the set case, hopefully the user won't do something
2838                  * silly.
2839                  */
2840                 mtx_lock(&lun->lun_lock);
2841                 mtx_unlock(&softc->ctl_lock);
2842                 if (cmd == CTL_GETSYNC)
2843                         sync_info->sync_interval = lun->sync_interval;
2844                 else
2845                         lun->sync_interval = sync_info->sync_interval;
2846                 mtx_unlock(&lun->lun_lock);
2847
2848                 sync_info->status = CTL_GS_SYNC_OK;
2849
2850                 break;
2851         }
2852         case CTL_GETSTATS: {
2853                 struct ctl_stats *stats;
2854                 struct ctl_lun *lun;
2855                 int i;
2856
2857                 stats = (struct ctl_stats *)addr;
2858
2859                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2860                      stats->alloc_len) {
2861                         stats->status = CTL_SS_NEED_MORE_SPACE;
2862                         stats->num_luns = softc->num_luns;
2863                         break;
2864                 }
2865                 /*
2866                  * XXX KDM no locking here.  If the LUN list changes,
2867                  * things can blow up.
2868                  */
2869                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2870                      i++, lun = STAILQ_NEXT(lun, links)) {
2871                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2872                                          sizeof(lun->stats));
2873                         if (retval != 0)
2874                                 break;
2875                 }
2876                 stats->num_luns = softc->num_luns;
2877                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2878                                  softc->num_luns;
2879                 stats->status = CTL_SS_OK;
2880 #ifdef CTL_TIME_IO
2881                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2882 #else
2883                 stats->flags = CTL_STATS_FLAG_NONE;
2884 #endif
2885                 getnanouptime(&stats->timestamp);
2886                 break;
2887         }
2888         case CTL_ERROR_INJECT: {
2889                 struct ctl_error_desc *err_desc, *new_err_desc;
2890                 struct ctl_lun *lun;
2891
2892                 err_desc = (struct ctl_error_desc *)addr;
2893
2894                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2895                                       M_WAITOK | M_ZERO);
2896                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2897
2898                 mtx_lock(&softc->ctl_lock);
2899                 lun = softc->ctl_luns[err_desc->lun_id];
2900                 if (lun == NULL) {
2901                         mtx_unlock(&softc->ctl_lock);
2902                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2903                                __func__, (uintmax_t)err_desc->lun_id);
2904                         retval = EINVAL;
2905                         break;
2906                 }
2907                 mtx_lock(&lun->lun_lock);
2908                 mtx_unlock(&softc->ctl_lock);
2909
2910                 /*
2911                  * We could do some checking here to verify the validity
2912                  * of the request, but given the complexity of error
2913                  * injection requests, the checking logic would be fairly
2914                  * complex.
2915                  *
2916                  * For now, if the request is invalid, it just won't get
2917                  * executed and might get deleted.
2918                  */
2919                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2920
2921                 /*
2922                  * XXX KDM check to make sure the serial number is unique,
2923                  * in case we somehow manage to wrap.  That shouldn't
2924                  * happen for a very long time, but it's the right thing to
2925                  * do.
2926                  */
2927                 new_err_desc->serial = lun->error_serial;
2928                 err_desc->serial = lun->error_serial;
2929                 lun->error_serial++;
2930
2931                 mtx_unlock(&lun->lun_lock);
2932                 break;
2933         }
2934         case CTL_ERROR_INJECT_DELETE: {
2935                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2936                 struct ctl_lun *lun;
2937                 int delete_done;
2938
2939                 delete_desc = (struct ctl_error_desc *)addr;
2940                 delete_done = 0;
2941
2942                 mtx_lock(&softc->ctl_lock);
2943                 lun = softc->ctl_luns[delete_desc->lun_id];
2944                 if (lun == NULL) {
2945                         mtx_unlock(&softc->ctl_lock);
2946                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2947                                __func__, (uintmax_t)delete_desc->lun_id);
2948                         retval = EINVAL;
2949                         break;
2950                 }
2951                 mtx_lock(&lun->lun_lock);
2952                 mtx_unlock(&softc->ctl_lock);
2953                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2954                         if (desc->serial != delete_desc->serial)
2955                                 continue;
2956
2957                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2958                                       links);
2959                         free(desc, M_CTL);
2960                         delete_done = 1;
2961                 }
2962                 mtx_unlock(&lun->lun_lock);
2963                 if (delete_done == 0) {
2964                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2965                                "error serial %ju on LUN %u\n", __func__, 
2966                                delete_desc->serial, delete_desc->lun_id);
2967                         retval = EINVAL;
2968                         break;
2969                 }
2970                 break;
2971         }
2972         case CTL_DUMP_STRUCTS: {
2973                 int i, j, k, idx;
2974                 struct ctl_port *port;
2975                 struct ctl_frontend *fe;
2976
2977                 mtx_lock(&softc->ctl_lock);
2978                 printf("CTL Persistent Reservation information start:\n");
2979                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2980                         struct ctl_lun *lun;
2981
2982                         lun = softc->ctl_luns[i];
2983
2984                         if ((lun == NULL)
2985                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2986                                 continue;
2987
2988                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2989                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2990                                         idx = j * CTL_MAX_INIT_PER_PORT + k;
2991                                         if (lun->per_res[idx].registered == 0)
2992                                                 continue;
2993                                         printf("  LUN %d port %d iid %d key "
2994                                                "%#jx\n", i, j, k,
2995                                                (uintmax_t)scsi_8btou64(
2996                                                lun->per_res[idx].res_key.key));
2997                                 }
2998                         }
2999                 }
3000                 printf("CTL Persistent Reservation information end\n");
3001                 printf("CTL Ports:\n");
3002                 STAILQ_FOREACH(port, &softc->port_list, links) {
3003                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3004                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3005                                port->frontend->name, port->port_type,
3006                                port->physical_port, port->virtual_port,
3007                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3008                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3009                                 if (port->wwpn_iid[j].in_use == 0 &&
3010                                     port->wwpn_iid[j].wwpn == 0 &&
3011                                     port->wwpn_iid[j].name == NULL)
3012                                         continue;
3013
3014                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3015                                     j, port->wwpn_iid[j].in_use,
3016                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3017                                     port->wwpn_iid[j].name);
3018                         }
3019                 }
3020                 printf("CTL Port information end\n");
3021                 mtx_unlock(&softc->ctl_lock);
3022                 /*
3023                  * XXX KDM calling this without a lock.  We'd likely want
3024                  * to drop the lock before calling the frontend's dump
3025                  * routine anyway.
3026                  */
3027                 printf("CTL Frontends:\n");
3028                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3029                         printf("  Frontend '%s'\n", fe->name);
3030                         if (fe->fe_dump != NULL)
3031                                 fe->fe_dump();
3032                 }
3033                 printf("CTL Frontend information end\n");
3034                 break;
3035         }
3036         case CTL_LUN_REQ: {
3037                 struct ctl_lun_req *lun_req;
3038                 struct ctl_backend_driver *backend;
3039
3040                 lun_req = (struct ctl_lun_req *)addr;
3041
3042                 backend = ctl_backend_find(lun_req->backend);
3043                 if (backend == NULL) {
3044                         lun_req->status = CTL_LUN_ERROR;
3045                         snprintf(lun_req->error_str,
3046                                  sizeof(lun_req->error_str),
3047                                  "Backend \"%s\" not found.",
3048                                  lun_req->backend);
3049                         break;
3050                 }
3051                 if (lun_req->num_be_args > 0) {
3052                         lun_req->kern_be_args = ctl_copyin_args(
3053                                 lun_req->num_be_args,
3054                                 lun_req->be_args,
3055                                 lun_req->error_str,
3056                                 sizeof(lun_req->error_str));
3057                         if (lun_req->kern_be_args == NULL) {
3058                                 lun_req->status = CTL_LUN_ERROR;
3059                                 break;
3060                         }
3061                 }
3062
3063                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3064
3065                 if (lun_req->num_be_args > 0) {
3066                         ctl_copyout_args(lun_req->num_be_args,
3067                                       lun_req->kern_be_args);
3068                         ctl_free_args(lun_req->num_be_args,
3069                                       lun_req->kern_be_args);
3070                 }
3071                 break;
3072         }
3073         case CTL_LUN_LIST: {
3074                 struct sbuf *sb;
3075                 struct ctl_lun *lun;
3076                 struct ctl_lun_list *list;
3077                 struct ctl_option *opt;
3078
3079                 list = (struct ctl_lun_list *)addr;
3080
3081                 /*
3082                  * Allocate a fixed length sbuf here, based on the length
3083                  * of the user's buffer.  We could allocate an auto-extending
3084                  * buffer, and then tell the user how much larger our
3085                  * amount of data is than his buffer, but that presents
3086                  * some problems:
3087                  *
3088                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3089                  *     we can't hold a lock while calling them with an
3090                  *     auto-extending buffer.
3091                  *
3092                  * 2.  There is not currently a LUN reference counting
3093                  *     mechanism, outside of outstanding transactions on
3094                  *     the LUN's OOA queue.  So a LUN could go away on us
3095                  *     while we're getting the LUN number, backend-specific
3096                  *     information, etc.  Thus, given the way things
3097                  *     currently work, we need to hold the CTL lock while
3098                  *     grabbing LUN information.
3099                  *
3100                  * So, from the user's standpoint, the best thing to do is
3101                  * allocate what he thinks is a reasonable buffer length,
3102                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3103                  * double the buffer length and try again.  (And repeat
3104                  * that until he succeeds.)
3105                  */
3106                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3107                 if (sb == NULL) {
3108                         list->status = CTL_LUN_LIST_ERROR;
3109                         snprintf(list->error_str, sizeof(list->error_str),
3110                                  "Unable to allocate %d bytes for LUN list",
3111                                  list->alloc_len);
3112                         break;
3113                 }
3114
3115                 sbuf_printf(sb, "<ctllunlist>\n");
3116
3117                 mtx_lock(&softc->ctl_lock);
3118                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3119                         mtx_lock(&lun->lun_lock);
3120                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3121                                              (uintmax_t)lun->lun);
3122
3123                         /*
3124                          * Bail out as soon as we see that we've overfilled
3125                          * the buffer.
3126                          */
3127                         if (retval != 0)
3128                                 break;
3129
3130                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3131                                              "</backend_type>\n",
3132                                              (lun->backend == NULL) ?  "none" :
3133                                              lun->backend->name);
3134
3135                         if (retval != 0)
3136                                 break;
3137
3138                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3139                                              lun->be_lun->lun_type);
3140
3141                         if (retval != 0)
3142                                 break;
3143
3144                         if (lun->backend == NULL) {
3145                                 retval = sbuf_printf(sb, "</lun>\n");
3146                                 if (retval != 0)
3147                                         break;
3148                                 continue;
3149                         }
3150
3151                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3152                                              (lun->be_lun->maxlba > 0) ?
3153                                              lun->be_lun->maxlba + 1 : 0);
3154
3155                         if (retval != 0)
3156                                 break;
3157
3158                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3159                                              lun->be_lun->blocksize);
3160
3161                         if (retval != 0)
3162                                 break;
3163
3164                         retval = sbuf_printf(sb, "\t<serial_number>");
3165
3166                         if (retval != 0)
3167                                 break;
3168
3169                         retval = ctl_sbuf_printf_esc(sb,
3170                                                      lun->be_lun->serial_num);
3171
3172                         if (retval != 0)
3173                                 break;
3174
3175                         retval = sbuf_printf(sb, "</serial_number>\n");
3176                 
3177                         if (retval != 0)
3178                                 break;
3179
3180                         retval = sbuf_printf(sb, "\t<device_id>");
3181
3182                         if (retval != 0)
3183                                 break;
3184
3185                         retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3186
3187                         if (retval != 0)
3188                                 break;
3189
3190                         retval = sbuf_printf(sb, "</device_id>\n");
3191
3192                         if (retval != 0)
3193                                 break;
3194
3195                         if (lun->backend->lun_info != NULL) {
3196                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3197                                 if (retval != 0)
3198                                         break;
3199                         }
3200                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3201                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3202                                     opt->name, opt->value, opt->name);
3203                                 if (retval != 0)
3204                                         break;
3205                         }
3206
3207                         retval = sbuf_printf(sb, "</lun>\n");
3208
3209                         if (retval != 0)
3210                                 break;
3211                         mtx_unlock(&lun->lun_lock);
3212                 }
3213                 if (lun != NULL)
3214                         mtx_unlock(&lun->lun_lock);
3215                 mtx_unlock(&softc->ctl_lock);
3216
3217                 if ((retval != 0)
3218                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3219                         retval = 0;
3220                         sbuf_delete(sb);
3221                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3222                         snprintf(list->error_str, sizeof(list->error_str),
3223                                  "Out of space, %d bytes is too small",
3224                                  list->alloc_len);
3225                         break;
3226                 }
3227
3228                 sbuf_finish(sb);
3229
3230                 retval = copyout(sbuf_data(sb), list->lun_xml,
3231                                  sbuf_len(sb) + 1);
3232
3233                 list->fill_len = sbuf_len(sb) + 1;
3234                 list->status = CTL_LUN_LIST_OK;
3235                 sbuf_delete(sb);
3236                 break;
3237         }
3238         case CTL_ISCSI: {
3239                 struct ctl_iscsi *ci;
3240                 struct ctl_frontend *fe;
3241
3242                 ci = (struct ctl_iscsi *)addr;
3243
3244                 fe = ctl_frontend_find("iscsi");
3245                 if (fe == NULL) {
3246                         ci->status = CTL_ISCSI_ERROR;
3247                         snprintf(ci->error_str, sizeof(ci->error_str),
3248                             "Frontend \"iscsi\" not found.");
3249                         break;
3250                 }
3251
3252                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3253                 break;
3254         }
3255         case CTL_PORT_REQ: {
3256                 struct ctl_req *req;
3257                 struct ctl_frontend *fe;
3258
3259                 req = (struct ctl_req *)addr;
3260
3261                 fe = ctl_frontend_find(req->driver);
3262                 if (fe == NULL) {
3263                         req->status = CTL_LUN_ERROR;
3264                         snprintf(req->error_str, sizeof(req->error_str),
3265                             "Frontend \"%s\" not found.", req->driver);
3266                         break;
3267                 }
3268                 if (req->num_args > 0) {
3269                         req->kern_args = ctl_copyin_args(req->num_args,
3270                             req->args, req->error_str, sizeof(req->error_str));
3271                         if (req->kern_args == NULL) {
3272                                 req->status = CTL_LUN_ERROR;
3273                                 break;
3274                         }
3275                 }
3276
3277                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3278
3279                 if (req->num_args > 0) {
3280                         ctl_copyout_args(req->num_args, req->kern_args);
3281                         ctl_free_args(req->num_args, req->kern_args);
3282                 }
3283                 break;
3284         }
3285         case CTL_PORT_LIST: {
3286                 struct sbuf *sb;
3287                 struct ctl_port *port;
3288                 struct ctl_lun_list *list;
3289                 struct ctl_option *opt;
3290
3291                 list = (struct ctl_lun_list *)addr;
3292
3293                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3294                 if (sb == NULL) {
3295                         list->status = CTL_LUN_LIST_ERROR;
3296                         snprintf(list->error_str, sizeof(list->error_str),
3297                                  "Unable to allocate %d bytes for LUN list",
3298                                  list->alloc_len);
3299                         break;
3300                 }
3301
3302                 sbuf_printf(sb, "<ctlportlist>\n");
3303
3304                 mtx_lock(&softc->ctl_lock);
3305                 STAILQ_FOREACH(port, &softc->port_list, links) {
3306                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3307                                              (uintmax_t)port->targ_port);
3308
3309                         /*
3310                          * Bail out as soon as we see that we've overfilled
3311                          * the buffer.
3312                          */
3313                         if (retval != 0)
3314                                 break;
3315
3316                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3317                             "</frontend_type>\n", port->frontend->name);
3318                         if (retval != 0)
3319                                 break;
3320
3321                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3322                                              port->port_type);
3323                         if (retval != 0)
3324                                 break;
3325
3326                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3327                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3328                         if (retval != 0)
3329                                 break;
3330
3331                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3332                             port->port_name);
3333                         if (retval != 0)
3334                                 break;
3335
3336                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3337                             port->physical_port);
3338                         if (retval != 0)
3339                                 break;
3340
3341                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3342                             port->virtual_port);
3343                         if (retval != 0)
3344                                 break;
3345
3346                         retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3347                             (uintmax_t)port->wwnn);
3348                         if (retval != 0)
3349                                 break;
3350
3351                         retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3352                             (uintmax_t)port->wwpn);
3353                         if (retval != 0)
3354                                 break;
3355
3356                         if (port->port_info != NULL) {
3357                                 retval = port->port_info(port->onoff_arg, sb);
3358                                 if (retval != 0)
3359                                         break;
3360                         }
3361                         STAILQ_FOREACH(opt, &port->options, links) {
3362                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3363                                     opt->name, opt->value, opt->name);
3364                                 if (retval != 0)
3365                                         break;
3366                         }
3367
3368                         retval = sbuf_printf(sb, "</targ_port>\n");
3369                         if (retval != 0)
3370                                 break;
3371                 }
3372                 mtx_unlock(&softc->ctl_lock);
3373
3374                 if ((retval != 0)
3375                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3376                         retval = 0;
3377                         sbuf_delete(sb);
3378                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3379                         snprintf(list->error_str, sizeof(list->error_str),
3380                                  "Out of space, %d bytes is too small",
3381                                  list->alloc_len);
3382                         break;
3383                 }
3384
3385                 sbuf_finish(sb);
3386
3387                 retval = copyout(sbuf_data(sb), list->lun_xml,
3388                                  sbuf_len(sb) + 1);
3389
3390                 list->fill_len = sbuf_len(sb) + 1;
3391                 list->status = CTL_LUN_LIST_OK;
3392                 sbuf_delete(sb);
3393                 break;
3394         }
3395         default: {
3396                 /* XXX KDM should we fix this? */
3397 #if 0
3398                 struct ctl_backend_driver *backend;
3399                 unsigned int type;
3400                 int found;
3401
3402                 found = 0;
3403
3404                 /*
3405                  * We encode the backend type as the ioctl type for backend
3406                  * ioctls.  So parse it out here, and then search for a
3407                  * backend of this type.
3408                  */
3409                 type = _IOC_TYPE(cmd);
3410
3411                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3412                         if (backend->type == type) {
3413                                 found = 1;
3414                                 break;
3415                         }
3416                 }
3417                 if (found == 0) {
3418                         printf("ctl: unknown ioctl command %#lx or backend "
3419                                "%d\n", cmd, type);
3420                         retval = EINVAL;
3421                         break;
3422                 }
3423                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3424 #endif
3425                 retval = ENOTTY;
3426                 break;
3427         }
3428         }
3429         return (retval);
3430 }
3431
3432 uint32_t
3433 ctl_get_initindex(struct ctl_nexus *nexus)
3434 {
3435         if (nexus->targ_port < CTL_MAX_PORTS)
3436                 return (nexus->initid.id +
3437                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3438         else
3439                 return (nexus->initid.id +
3440                        ((nexus->targ_port - CTL_MAX_PORTS) *
3441                         CTL_MAX_INIT_PER_PORT));
3442 }
3443
3444 uint32_t
3445 ctl_get_resindex(struct ctl_nexus *nexus)
3446 {
3447         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3448 }
3449
3450 uint32_t
3451 ctl_port_idx(int port_num)
3452 {
3453         if (port_num < CTL_MAX_PORTS)
3454                 return(port_num);
3455         else
3456                 return(port_num - CTL_MAX_PORTS);
3457 }
3458
3459 static uint32_t
3460 ctl_map_lun(int port_num, uint32_t lun_id)
3461 {
3462         struct ctl_port *port;
3463
3464         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3465         if (port == NULL)
3466                 return (UINT32_MAX);
3467         if (port->lun_map == NULL)
3468                 return (lun_id);
3469         return (port->lun_map(port->targ_lun_arg, lun_id));
3470 }
3471
3472 static uint32_t
3473 ctl_map_lun_back(int port_num, uint32_t lun_id)
3474 {
3475         struct ctl_port *port;
3476         uint32_t i;
3477
3478         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3479         if (port->lun_map == NULL)
3480                 return (lun_id);
3481         for (i = 0; i < CTL_MAX_LUNS; i++) {
3482                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3483                         return (i);
3484         }
3485         return (UINT32_MAX);
3486 }
3487
3488 /*
3489  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3490  * that are a power of 2.
3491  */
3492 int
3493 ctl_ffz(uint32_t *mask, uint32_t size)
3494 {
3495         uint32_t num_chunks, num_pieces;
3496         int i, j;
3497
3498         num_chunks = (size >> 5);
3499         if (num_chunks == 0)
3500                 num_chunks++;
3501         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3502
3503         for (i = 0; i < num_chunks; i++) {
3504                 for (j = 0; j < num_pieces; j++) {
3505                         if ((mask[i] & (1 << j)) == 0)
3506                                 return ((i << 5) + j);
3507                 }
3508         }
3509
3510         return (-1);
3511 }
3512
3513 int
3514 ctl_set_mask(uint32_t *mask, uint32_t bit)
3515 {
3516         uint32_t chunk, piece;
3517
3518         chunk = bit >> 5;
3519         piece = bit % (sizeof(uint32_t) * 8);
3520
3521         if ((mask[chunk] & (1 << piece)) != 0)
3522                 return (-1);
3523         else
3524                 mask[chunk] |= (1 << piece);
3525
3526         return (0);
3527 }
3528
3529 int
3530 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3531 {
3532         uint32_t chunk, piece;
3533
3534         chunk = bit >> 5;
3535         piece = bit % (sizeof(uint32_t) * 8);
3536
3537         if ((mask[chunk] & (1 << piece)) == 0)
3538                 return (-1);
3539         else
3540                 mask[chunk] &= ~(1 << piece);
3541
3542         return (0);
3543 }
3544
3545 int
3546 ctl_is_set(uint32_t *mask, uint32_t bit)
3547 {
3548         uint32_t chunk, piece;
3549
3550         chunk = bit >> 5;
3551         piece = bit % (sizeof(uint32_t) * 8);
3552
3553         if ((mask[chunk] & (1 << piece)) == 0)
3554                 return (0);
3555         else
3556                 return (1);
3557 }
3558
3559 #ifdef unused
3560 /*
3561  * The bus, target and lun are optional, they can be filled in later.
3562  * can_wait is used to determine whether we can wait on the malloc or not.
3563  */
3564 union ctl_io*
3565 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3566               uint32_t targ_lun, int can_wait)
3567 {
3568         union ctl_io *io;
3569
3570         if (can_wait)
3571                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3572         else
3573                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3574
3575         if (io != NULL) {
3576                 io->io_hdr.io_type = io_type;
3577                 io->io_hdr.targ_port = targ_port;
3578                 /*
3579                  * XXX KDM this needs to change/go away.  We need to move
3580                  * to a preallocated pool of ctl_scsiio structures.
3581                  */
3582                 io->io_hdr.nexus.targ_target.id = targ_target;
3583                 io->io_hdr.nexus.targ_lun = targ_lun;
3584         }
3585
3586         return (io);
3587 }
3588
3589 void
3590 ctl_kfree_io(union ctl_io *io)
3591 {
3592         free(io, M_CTL);
3593 }
3594 #endif /* unused */
3595
3596 /*
3597  * ctl_softc, pool_type, total_ctl_io are passed in.
3598  * npool is passed out.
3599  */
3600 int
3601 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3602                 uint32_t total_ctl_io, struct ctl_io_pool **npool)
3603 {
3604         uint32_t i;
3605         union ctl_io *cur_io, *next_io;
3606         struct ctl_io_pool *pool;
3607         int retval;
3608
3609         retval = 0;
3610
3611         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3612                                             M_NOWAIT | M_ZERO);
3613         if (pool == NULL) {
3614                 retval = ENOMEM;
3615                 goto bailout;
3616         }
3617
3618         pool->type = pool_type;
3619         pool->ctl_softc = ctl_softc;
3620
3621         mtx_lock(&ctl_softc->pool_lock);
3622         pool->id = ctl_softc->cur_pool_id++;
3623         mtx_unlock(&ctl_softc->pool_lock);
3624
3625         pool->flags = CTL_POOL_FLAG_NONE;
3626         pool->refcount = 1;             /* Reference for validity. */
3627         STAILQ_INIT(&pool->free_queue);
3628
3629         /*
3630          * XXX KDM other options here:
3631          * - allocate a page at a time
3632          * - allocate one big chunk of memory.
3633          * Page allocation might work well, but would take a little more
3634          * tracking.
3635          */
3636         for (i = 0; i < total_ctl_io; i++) {
3637                 cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3638                                                 M_NOWAIT);
3639                 if (cur_io == NULL) {
3640                         retval = ENOMEM;
3641                         break;
3642                 }
3643                 cur_io->io_hdr.pool = pool;
3644                 STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3645                 pool->total_ctl_io++;
3646                 pool->free_ctl_io++;
3647         }
3648
3649         if (retval != 0) {
3650                 for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3651                      cur_io != NULL; cur_io = next_io) {
3652                         next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3653                                                               links);
3654                         STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3655                                       ctl_io_hdr, links);
3656                         free(cur_io, M_CTLIO);
3657                 }
3658
3659                 free(pool, M_CTL);
3660                 goto bailout;
3661         }
3662         mtx_lock(&ctl_softc->pool_lock);
3663         ctl_softc->num_pools++;
3664         STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3665         /*
3666          * Increment our usage count if this is an external consumer, so we
3667          * can't get unloaded until the external consumer (most likely a
3668          * FETD) unloads and frees his pool.
3669          *
3670          * XXX KDM will this increment the caller's module use count, or
3671          * mine?
3672          */
3673 #if 0
3674         if ((pool_type != CTL_POOL_EMERGENCY)
3675          && (pool_type != CTL_POOL_INTERNAL)
3676          && (pool_type != CTL_POOL_4OTHERSC))
3677                 MOD_INC_USE_COUNT;
3678 #endif
3679
3680         mtx_unlock(&ctl_softc->pool_lock);
3681
3682         *npool = pool;
3683
3684 bailout:
3685
3686         return (retval);
3687 }
3688
3689 static int
3690 ctl_pool_acquire(struct ctl_io_pool *pool)
3691 {
3692
3693         mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3694
3695         if (pool->flags & CTL_POOL_FLAG_INVALID)
3696                 return (EINVAL);
3697
3698         pool->refcount++;
3699
3700         return (0);
3701 }
3702
3703 static void
3704 ctl_pool_release(struct ctl_io_pool *pool)
3705 {
3706         struct ctl_softc *ctl_softc = pool->ctl_softc;
3707         union ctl_io *io;
3708
3709         mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3710
3711         if (--pool->refcount != 0)
3712                 return;
3713
3714         while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3715                 STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3716                               links);
3717                 free(io, M_CTLIO);
3718         }
3719
3720         STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3721         ctl_softc->num_pools--;
3722
3723         /*
3724          * XXX KDM will this decrement the caller's usage count or mine?
3725          */
3726 #if 0
3727         if ((pool->type != CTL_POOL_EMERGENCY)
3728          && (pool->type != CTL_POOL_INTERNAL)
3729          && (pool->type != CTL_POOL_4OTHERSC))
3730                 MOD_DEC_USE_COUNT;
3731 #endif
3732
3733         free(pool, M_CTL);
3734 }
3735
3736 void
3737 ctl_pool_free(struct ctl_io_pool *pool)
3738 {
3739         struct ctl_softc *ctl_softc;
3740
3741         if (pool == NULL)
3742                 return;
3743
3744         ctl_softc = pool->ctl_softc;
3745         mtx_lock(&ctl_softc->pool_lock);
3746         pool->flags |= CTL_POOL_FLAG_INVALID;
3747         ctl_pool_release(pool);
3748         mtx_unlock(&ctl_softc->pool_lock);
3749 }
3750
3751 /*
3752  * This routine does not block (except for spinlocks of course).
3753  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3754  * possible.
3755  */
3756 union ctl_io *
3757 ctl_alloc_io(void *pool_ref)
3758 {
3759         union ctl_io *io;
3760         struct ctl_softc *ctl_softc;
3761         struct ctl_io_pool *pool, *npool;
3762         struct ctl_io_pool *emergency_pool;
3763
3764         pool = (struct ctl_io_pool *)pool_ref;
3765
3766         if (pool == NULL) {
3767                 printf("%s: pool is NULL\n", __func__);
3768                 return (NULL);
3769         }
3770
3771         emergency_pool = NULL;
3772
3773         ctl_softc = pool->ctl_softc;
3774
3775         mtx_lock(&ctl_softc->pool_lock);
3776         /*
3777          * First, try to get the io structure from the user's pool.
3778          */
3779         if (ctl_pool_acquire(pool) == 0) {
3780                 io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3781                 if (io != NULL) {
3782                         STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3783                         pool->total_allocated++;
3784                         pool->free_ctl_io--;
3785                         mtx_unlock(&ctl_softc->pool_lock);
3786                         return (io);
3787                 } else
3788                         ctl_pool_release(pool);
3789         }
3790         /*
3791          * If he doesn't have any io structures left, search for an
3792          * emergency pool and grab one from there.
3793          */
3794         STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3795                 if (npool->type != CTL_POOL_EMERGENCY)
3796                         continue;
3797
3798                 if (ctl_pool_acquire(npool) != 0)
3799                         continue;
3800
3801                 emergency_pool = npool;
3802
3803                 io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3804                 if (io != NULL) {
3805                         STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3806                         npool->total_allocated++;
3807                         npool->free_ctl_io--;
3808                         mtx_unlock(&ctl_softc->pool_lock);
3809                         return (io);
3810                 } else
3811                         ctl_pool_release(npool);
3812         }
3813
3814         /* Drop the spinlock before we malloc */
3815         mtx_unlock(&ctl_softc->pool_lock);
3816
3817         /*
3818          * The emergency pool (if it exists) didn't have one, so try an
3819          * atomic (i.e. nonblocking) malloc and see if we get lucky.
3820          */
3821         io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3822         if (io != NULL) {
3823                 /*
3824                  * If the emergency pool exists but is empty, add this
3825                  * ctl_io to its list when it gets freed.
3826                  */
3827                 if (emergency_pool != NULL) {
3828                         mtx_lock(&ctl_softc->pool_lock);
3829                         if (ctl_pool_acquire(emergency_pool) == 0) {
3830                                 io->io_hdr.pool = emergency_pool;
3831                                 emergency_pool->total_ctl_io++;
3832                                 /*
3833                                  * Need to bump this, otherwise
3834                                  * total_allocated and total_freed won't
3835                                  * match when we no longer have anything
3836                                  * outstanding.
3837                                  */
3838                                 emergency_pool->total_allocated++;
3839                         }
3840                         mtx_unlock(&ctl_softc->pool_lock);
3841                 } else
3842                         io->io_hdr.pool = NULL;
3843         }
3844
3845         return (io);
3846 }
3847
3848 void
3849 ctl_free_io(union ctl_io *io)
3850 {
3851         if (io == NULL)
3852                 return;
3853
3854         /*
3855          * If this ctl_io has a pool, return it to that pool.
3856          */
3857         if (io->io_hdr.pool != NULL) {
3858                 struct ctl_io_pool *pool;
3859
3860                 pool = (struct ctl_io_pool *)io->io_hdr.pool;
3861                 mtx_lock(&pool->ctl_softc->pool_lock);
3862                 io->io_hdr.io_type = 0xff;
3863                 STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3864                 pool->total_freed++;
3865                 pool->free_ctl_io++;
3866                 ctl_pool_release(pool);
3867                 mtx_unlock(&pool->ctl_softc->pool_lock);
3868         } else {
3869                 /*
3870                  * Otherwise, just free it.  We probably malloced it and
3871                  * the emergency pool wasn't available.
3872                  */
3873                 free(io, M_CTLIO);
3874         }
3875
3876 }
3877
3878 void
3879 ctl_zero_io(union ctl_io *io)
3880 {
3881         void *pool_ref;
3882
3883         if (io == NULL)
3884                 return;
3885
3886         /*
3887          * May need to preserve linked list pointers at some point too.
3888          */
3889         pool_ref = io->io_hdr.pool;
3890
3891         memset(io, 0, sizeof(*io));
3892
3893         io->io_hdr.pool = pool_ref;
3894 }
3895
3896 /*
3897  * This routine is currently used for internal copies of ctl_ios that need
3898  * to persist for some reason after we've already returned status to the
3899  * FETD.  (Thus the flag set.)
3900  *
3901  * XXX XXX
3902  * Note that this makes a blind copy of all fields in the ctl_io, except
3903  * for the pool reference.  This includes any memory that has been
3904  * allocated!  That memory will no longer be valid after done has been
3905  * called, so this would be VERY DANGEROUS for command that actually does
3906  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3907  * start and stop commands, which don't transfer any data, so this is not a
3908  * problem.  If it is used for anything else, the caller would also need to
3909  * allocate data buffer space and this routine would need to be modified to
3910  * copy the data buffer(s) as well.
3911  */
3912 void
3913 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3914 {
3915         void *pool_ref;
3916
3917         if ((src == NULL)
3918          || (dest == NULL))
3919                 return;
3920
3921         /*
3922          * May need to preserve linked list pointers at some point too.
3923          */
3924         pool_ref = dest->io_hdr.pool;
3925
3926         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3927
3928         dest->io_hdr.pool = pool_ref;
3929         /*
3930          * We need to know that this is an internal copy, and doesn't need
3931          * to get passed back to the FETD that allocated it.
3932          */
3933         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3934 }
3935
3936 #ifdef NEEDTOPORT
3937 static void
3938 ctl_update_power_subpage(struct copan_power_subpage *page)
3939 {
3940         int num_luns, num_partitions, config_type;
3941         struct ctl_softc *softc;
3942         cs_BOOL_t aor_present, shelf_50pct_power;
3943         cs_raidset_personality_t rs_type;
3944         int max_active_luns;
3945
3946         softc = control_softc;
3947
3948         /* subtract out the processor LUN */
3949         num_luns = softc->num_luns - 1;
3950         /*
3951          * Default to 7 LUNs active, which was the only number we allowed
3952          * in the past.
3953          */
3954         max_active_luns = 7;
3955
3956         num_partitions = config_GetRsPartitionInfo();
3957         config_type = config_GetConfigType();
3958         shelf_50pct_power = config_GetShelfPowerMode();
3959         aor_present = config_IsAorRsPresent();
3960
3961         rs_type = ddb_GetRsRaidType(1);
3962         if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3963          && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3964                 EPRINT(0, "Unsupported RS type %d!", rs_type);
3965         }
3966
3967
3968         page->total_luns = num_luns;
3969
3970         switch (config_type) {
3971         case 40:
3972                 /*
3973                  * In a 40 drive configuration, it doesn't matter what DC
3974                  * cards we have, whether we have AOR enabled or not,
3975                  * partitioning or not, or what type of RAIDset we have.
3976                  * In that scenario, we can power up every LUN we present
3977                  * to the user.
3978                  */
3979                 max_active_luns = num_luns;
3980
3981                 break;
3982         case 64:
3983                 if (shelf_50pct_power == CS_FALSE) {
3984                         /* 25% power */
3985                         if (aor_present == CS_TRUE) {
3986                                 if (rs_type ==
3987                                      CS_RAIDSET_PERSONALITY_RAID5) {
3988                                         max_active_luns = 7;
3989                                 } else if (rs_type ==
3990                                          CS_RAIDSET_PERSONALITY_RAID1){
3991                                         max_active_luns = 14;
3992                                 } else {
3993                                         /* XXX KDM now what?? */
3994                                 }
3995                         } else {
3996                                 if (rs_type ==
3997                                      CS_RAIDSET_PERSONALITY_RAID5) {
3998                                         max_active_luns = 8;
3999                                 } else if (rs_type ==
4000                                          CS_RAIDSET_PERSONALITY_RAID1){
4001                                         max_active_luns = 16;
4002                                 } else {
4003                                         /* XXX KDM now what?? */
4004                                 }
4005                         }
4006                 } else {
4007                         /* 50% power */
4008                         /*
4009                          * With 50% power in a 64 drive configuration, we
4010                          * can power all LUNs we present.
4011                          */
4012                         max_active_luns = num_luns;
4013                 }
4014                 break;
4015         case 112:
4016                 if (shelf_50pct_power == CS_FALSE) {
4017                         /* 25% power */
4018                         if (aor_present == CS_TRUE) {
4019                                 if (rs_type ==
4020                                      CS_RAIDSET_PERSONALITY_RAID5) {
4021                                         max_active_luns = 7;
4022                                 } else if (rs_type ==
4023                                          CS_RAIDSET_PERSONALITY_RAID1){
4024                                         max_active_luns = 14;
4025                                 } else {
4026                                         /* XXX KDM now what?? */
4027                                 }
4028                         } else {
4029                                 if (rs_type ==
4030                                      CS_RAIDSET_PERSONALITY_RAID5) {
4031                                         max_active_luns = 8;
4032                                 } else if (rs_type ==
4033                                          CS_RAIDSET_PERSONALITY_RAID1){
4034                                         max_active_luns = 16;
4035                                 } else {
4036                                         /* XXX KDM now what?? */
4037                                 }
4038                         }
4039                 } else {
4040                         /* 50% power */
4041                         if (aor_present == CS_TRUE) {
4042                                 if (rs_type ==
4043                                      CS_RAIDSET_PERSONALITY_RAID5) {
4044                                         max_active_luns = 14;
4045                                 } else if (rs_type ==
4046                                          CS_RAIDSET_PERSONALITY_RAID1){
4047                                         /*
4048                                          * We're assuming here that disk
4049                                          * caching is enabled, and so we're
4050                                          * able to power up half of each
4051                                          * LUN, and cache all writes.
4052                                          */
4053                                         max_active_luns = num_luns;
4054                                 } else {
4055                                         /* XXX KDM now what?? */
4056                                 }
4057                         } else {
4058                                 if (rs_type ==
4059                                      CS_RAIDSET_PERSONALITY_RAID5) {
4060                                         max_active_luns = 15;
4061                                 } else if (rs_type ==
4062                                          CS_RAIDSET_PERSONALITY_RAID1){
4063                                         max_active_luns = 30;
4064                                 } else {
4065                                         /* XXX KDM now what?? */
4066                                 }
4067                         }
4068                 }
4069                 break;
4070         default:
4071                 /*
4072                  * In this case, we have an unknown configuration, so we
4073                  * just use the default from above.
4074                  */
4075                 break;
4076         }
4077
4078         page->max_active_luns = max_active_luns;
4079 #if 0
4080         printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4081                page->total_luns, page->max_active_luns);
4082 #endif
4083 }
4084 #endif /* NEEDTOPORT */
4085
4086 /*
4087  * This routine could be used in the future to load default and/or saved
4088  * mode page parameters for a particuar lun.
4089  */
4090 static int
4091 ctl_init_page_index(struct ctl_lun *lun)
4092 {
4093         int i;
4094         struct ctl_page_index *page_index;
4095         struct ctl_softc *softc;
4096
4097         memcpy(&lun->mode_pages.index, page_index_template,
4098                sizeof(page_index_template));
4099
4100         softc = lun->ctl_softc;
4101
4102         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4103
4104                 page_index = &lun->mode_pages.index[i];
4105                 /*
4106                  * If this is a disk-only mode page, there's no point in
4107                  * setting it up.  For some pages, we have to have some
4108                  * basic information about the disk in order to calculate the
4109                  * mode page data.
4110                  */
4111                 if ((lun->be_lun->lun_type != T_DIRECT)
4112                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4113                         continue;
4114
4115                 switch (page_index->page_code & SMPH_PC_MASK) {
4116                 case SMS_FORMAT_DEVICE_PAGE: {
4117                         struct scsi_format_page *format_page;
4118
4119                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4120                                 panic("subpage is incorrect!");
4121
4122                         /*
4123                          * Sectors per track are set above.  Bytes per
4124                          * sector need to be set here on a per-LUN basis.
4125                          */
4126                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4127                                &format_page_default,
4128                                sizeof(format_page_default));
4129                         memcpy(&lun->mode_pages.format_page[
4130                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4131                                sizeof(format_page_changeable));
4132                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4133                                &format_page_default,
4134                                sizeof(format_page_default));
4135                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4136                                &format_page_default,
4137                                sizeof(format_page_default));
4138
4139                         format_page = &lun->mode_pages.format_page[
4140                                 CTL_PAGE_CURRENT];
4141                         scsi_ulto2b(lun->be_lun->blocksize,
4142                                     format_page->bytes_per_sector);
4143
4144                         format_page = &lun->mode_pages.format_page[
4145                                 CTL_PAGE_DEFAULT];
4146                         scsi_ulto2b(lun->be_lun->blocksize,
4147                                     format_page->bytes_per_sector);
4148
4149                         format_page = &lun->mode_pages.format_page[
4150                                 CTL_PAGE_SAVED];
4151                         scsi_ulto2b(lun->be_lun->blocksize,
4152                                     format_page->bytes_per_sector);
4153
4154                         page_index->page_data =
4155                                 (uint8_t *)lun->mode_pages.format_page;
4156                         break;
4157                 }
4158                 case SMS_RIGID_DISK_PAGE: {
4159                         struct scsi_rigid_disk_page *rigid_disk_page;
4160                         uint32_t sectors_per_cylinder;
4161                         uint64_t cylinders;
4162 #ifndef __XSCALE__
4163                         int shift;
4164 #endif /* !__XSCALE__ */
4165
4166                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4167                                 panic("invalid subpage value %d",
4168                                       page_index->subpage);
4169
4170                         /*
4171                          * Rotation rate and sectors per track are set
4172                          * above.  We calculate the cylinders here based on
4173                          * capacity.  Due to the number of heads and
4174                          * sectors per track we're using, smaller arrays
4175                          * may turn out to have 0 cylinders.  Linux and
4176                          * FreeBSD don't pay attention to these mode pages
4177                          * to figure out capacity, but Solaris does.  It
4178                          * seems to deal with 0 cylinders just fine, and
4179                          * works out a fake geometry based on the capacity.
4180                          */
4181                         memcpy(&lun->mode_pages.rigid_disk_page[
4182                                CTL_PAGE_CURRENT], &rigid_disk_page_default,
4183                                sizeof(rigid_disk_page_default));
4184                         memcpy(&lun->mode_pages.rigid_disk_page[
4185                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4186                                sizeof(rigid_disk_page_changeable));
4187                         memcpy(&lun->mode_pages.rigid_disk_page[
4188                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4189                                sizeof(rigid_disk_page_default));
4190                         memcpy(&lun->mode_pages.rigid_disk_page[
4191                                CTL_PAGE_SAVED], &rigid_disk_page_default,
4192                                sizeof(rigid_disk_page_default));
4193
4194                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4195                                 CTL_DEFAULT_HEADS;
4196
4197                         /*
4198                          * The divide method here will be more accurate,
4199                          * probably, but results in floating point being
4200                          * used in the kernel on i386 (__udivdi3()).  On the
4201                          * XScale, though, __udivdi3() is implemented in
4202                          * software.
4203                          *
4204                          * The shift method for cylinder calculation is
4205                          * accurate if sectors_per_cylinder is a power of
4206                          * 2.  Otherwise it might be slightly off -- you
4207                          * might have a bit of a truncation problem.
4208                          */
4209 #ifdef  __XSCALE__
4210                         cylinders = (lun->be_lun->maxlba + 1) /
4211                                 sectors_per_cylinder;
4212 #else
4213                         for (shift = 31; shift > 0; shift--) {
4214                                 if (sectors_per_cylinder & (1 << shift))
4215                                         break;
4216                         }
4217                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4218 #endif
4219
4220                         /*
4221                          * We've basically got 3 bytes, or 24 bits for the
4222                          * cylinder size in the mode page.  If we're over,
4223                          * just round down to 2^24.
4224                          */
4225                         if (cylinders > 0xffffff)
4226                                 cylinders = 0xffffff;
4227
4228                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4229                                 CTL_PAGE_CURRENT];
4230                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4231
4232                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4233                                 CTL_PAGE_DEFAULT];
4234                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4235
4236                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4237                                 CTL_PAGE_SAVED];
4238                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4239
4240                         page_index->page_data =
4241                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4242                         break;
4243                 }
4244                 case SMS_CACHING_PAGE: {
4245
4246                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4247                                 panic("invalid subpage value %d",
4248                                       page_index->subpage);
4249                         /*
4250                          * Defaults should be okay here, no calculations
4251                          * needed.
4252                          */
4253                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4254                                &caching_page_default,
4255                                sizeof(caching_page_default));
4256                         memcpy(&lun->mode_pages.caching_page[
4257                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4258                                sizeof(caching_page_changeable));
4259                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4260                                &caching_page_default,
4261                                sizeof(caching_page_default));
4262                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4263                                &caching_page_default,
4264                                sizeof(caching_page_default));
4265                         page_index->page_data =
4266                                 (uint8_t *)lun->mode_pages.caching_page;
4267                         break;
4268                 }
4269                 case SMS_CONTROL_MODE_PAGE: {
4270
4271                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4272                                 panic("invalid subpage value %d",
4273                                       page_index->subpage);
4274
4275                         /*
4276                          * Defaults should be okay here, no calculations
4277                          * needed.
4278                          */
4279                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4280                                &control_page_default,
4281                                sizeof(control_page_default));
4282                         memcpy(&lun->mode_pages.control_page[
4283                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4284                                sizeof(control_page_changeable));
4285                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4286                                &control_page_default,
4287                                sizeof(control_page_default));
4288                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4289                                &control_page_default,
4290                                sizeof(control_page_default));
4291                         page_index->page_data =
4292                                 (uint8_t *)lun->mode_pages.control_page;
4293                         break;
4294
4295                 }
4296                 case SMS_VENDOR_SPECIFIC_PAGE:{
4297                         switch (page_index->subpage) {
4298                         case PWR_SUBPAGE_CODE: {
4299                                 struct copan_power_subpage *current_page,
4300                                                            *saved_page;
4301
4302                                 memcpy(&lun->mode_pages.power_subpage[
4303                                        CTL_PAGE_CURRENT],
4304                                        &power_page_default,
4305                                        sizeof(power_page_default));
4306                                 memcpy(&lun->mode_pages.power_subpage[
4307                                        CTL_PAGE_CHANGEABLE],
4308                                        &power_page_changeable,
4309                                        sizeof(power_page_changeable));
4310                                 memcpy(&lun->mode_pages.power_subpage[
4311                                        CTL_PAGE_DEFAULT],
4312                                        &power_page_default,
4313                                        sizeof(power_page_default));
4314                                 memcpy(&lun->mode_pages.power_subpage[
4315                                        CTL_PAGE_SAVED],
4316                                        &power_page_default,
4317                                        sizeof(power_page_default));
4318                                 page_index->page_data =
4319                                     (uint8_t *)lun->mode_pages.power_subpage;
4320
4321                                 current_page = (struct copan_power_subpage *)
4322                                         (page_index->page_data +
4323                                          (page_index->page_len *
4324                                           CTL_PAGE_CURRENT));
4325                                 saved_page = (struct copan_power_subpage *)
4326                                         (page_index->page_data +
4327                                          (page_index->page_len *
4328                                           CTL_PAGE_SAVED));
4329                                 break;
4330                         }
4331                         case APS_SUBPAGE_CODE: {
4332                                 struct copan_aps_subpage *current_page,
4333                                                          *saved_page;
4334
4335                                 // This gets set multiple times but
4336                                 // it should always be the same. It's
4337                                 // only done during init so who cares.
4338                                 index_to_aps_page = i;
4339
4340                                 memcpy(&lun->mode_pages.aps_subpage[
4341                                        CTL_PAGE_CURRENT],
4342                                        &aps_page_default,
4343                                        sizeof(aps_page_default));
4344                                 memcpy(&lun->mode_pages.aps_subpage[
4345                                        CTL_PAGE_CHANGEABLE],
4346                                        &aps_page_changeable,
4347                                        sizeof(aps_page_changeable));
4348                                 memcpy(&lun->mode_pages.aps_subpage[
4349                                        CTL_PAGE_DEFAULT],
4350                                        &aps_page_default,
4351                                        sizeof(aps_page_default));
4352                                 memcpy(&lun->mode_pages.aps_subpage[
4353                                        CTL_PAGE_SAVED],
4354                                        &aps_page_default,
4355                                        sizeof(aps_page_default));
4356                                 page_index->page_data =
4357                                         (uint8_t *)lun->mode_pages.aps_subpage;
4358
4359                                 current_page = (struct copan_aps_subpage *)
4360                                         (page_index->page_data +
4361                                          (page_index->page_len *
4362                                           CTL_PAGE_CURRENT));
4363                                 saved_page = (struct copan_aps_subpage *)
4364                                         (page_index->page_data +
4365                                          (page_index->page_len *
4366                                           CTL_PAGE_SAVED));
4367                                 break;
4368                         }
4369                         case DBGCNF_SUBPAGE_CODE: {
4370                                 struct copan_debugconf_subpage *current_page,
4371                                                                *saved_page;
4372
4373                                 memcpy(&lun->mode_pages.debugconf_subpage[
4374                                        CTL_PAGE_CURRENT],
4375                                        &debugconf_page_default,
4376                                        sizeof(debugconf_page_default));
4377                                 memcpy(&lun->mode_pages.debugconf_subpage[
4378                                        CTL_PAGE_CHANGEABLE],
4379                                        &debugconf_page_changeable,
4380                                        sizeof(debugconf_page_changeable));
4381                                 memcpy(&lun->mode_pages.debugconf_subpage[
4382                                        CTL_PAGE_DEFAULT],
4383                                        &debugconf_page_default,
4384                                        sizeof(debugconf_page_default));
4385                                 memcpy(&lun->mode_pages.debugconf_subpage[
4386                                        CTL_PAGE_SAVED],
4387                                        &debugconf_page_default,
4388                                        sizeof(debugconf_page_default));
4389                                 page_index->page_data =
4390                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4391
4392                                 current_page = (struct copan_debugconf_subpage *)
4393                                         (page_index->page_data +
4394                                          (page_index->page_len *
4395                                           CTL_PAGE_CURRENT));
4396                                 saved_page = (struct copan_debugconf_subpage *)
4397                                         (page_index->page_data +
4398                                          (page_index->page_len *
4399                                           CTL_PAGE_SAVED));
4400                                 break;
4401                         }
4402                         default:
4403                                 panic("invalid subpage value %d",
4404                                       page_index->subpage);
4405                                 break;
4406                         }
4407                         break;
4408                 }
4409                 default:
4410                         panic("invalid page value %d",
4411                               page_index->page_code & SMPH_PC_MASK);
4412                         break;
4413         }
4414         }
4415
4416         return (CTL_RETVAL_COMPLETE);
4417 }
4418
4419 /*
4420  * LUN allocation.
4421  *
4422  * Requirements:
4423  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4424  *   wants us to allocate the LUN and he can block.
4425  * - ctl_softc is always set
4426  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4427  *
4428  * Returns 0 for success, non-zero (errno) for failure.
4429  */
4430 static int
4431 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4432               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4433 {
4434         struct ctl_lun *nlun, *lun;
4435         struct ctl_port *port;
4436         struct scsi_vpd_id_descriptor *desc;
4437         struct scsi_vpd_id_t10 *t10id;
4438         const char *eui, *naa, *scsiname, *vendor;
4439         int lun_number, i, lun_malloced;
4440         int devidlen, idlen1, idlen2 = 0, len;
4441
4442         if (be_lun == NULL)
4443                 return (EINVAL);
4444
4445         /*
4446          * We currently only support Direct Access or Processor LUN types.
4447          */
4448         switch (be_lun->lun_type) {
4449         case T_DIRECT:
4450                 break;
4451         case T_PROCESSOR:
4452                 break;
4453         case T_SEQUENTIAL:
4454         case T_CHANGER:
4455         default:
4456                 be_lun->lun_config_status(be_lun->be_lun,
4457                                           CTL_LUN_CONFIG_FAILURE);
4458                 break;
4459         }
4460         if (ctl_lun == NULL) {
4461                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4462                 lun_malloced = 1;
4463         } else {
4464                 lun_malloced = 0;
4465                 lun = ctl_lun;
4466         }
4467
4468         memset(lun, 0, sizeof(*lun));
4469         if (lun_malloced)
4470                 lun->flags = CTL_LUN_MALLOCED;
4471
4472         /* Generate LUN ID. */
4473         devidlen = max(CTL_DEVID_MIN_LEN,
4474             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4475         idlen1 = sizeof(*t10id) + devidlen;
4476         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4477         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4478         if (scsiname != NULL) {
4479                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4480                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4481         }
4482         eui = ctl_get_opt(&be_lun->options, "eui");
4483         if (eui != NULL) {
4484                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4485         }
4486         naa = ctl_get_opt(&be_lun->options, "naa");
4487         if (naa != NULL) {
4488                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4489         }
4490         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4491             M_CTL, M_WAITOK | M_ZERO);
4492         lun->lun_devid->len = len;
4493         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4494         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4495         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4496         desc->length = idlen1;
4497         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4498         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4499         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4500                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4501         } else {
4502                 strncpy(t10id->vendor, vendor,
4503                     min(sizeof(t10id->vendor), strlen(vendor)));
4504         }
4505         strncpy((char *)t10id->vendor_spec_id,
4506             (char *)be_lun->device_id, devidlen);
4507         if (scsiname != NULL) {
4508                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4509                     desc->length);
4510                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4511                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4512                     SVPD_ID_TYPE_SCSI_NAME;
4513                 desc->length = idlen2;
4514                 strlcpy(desc->identifier, scsiname, idlen2);
4515         }
4516         if (eui != NULL) {
4517                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4518                     desc->length);
4519                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4520                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4521                     SVPD_ID_TYPE_EUI64;
4522                 desc->length = 8;
4523                 scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4524         }
4525         if (naa != NULL) {
4526                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4527                     desc->length);
4528                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4529                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4530                     SVPD_ID_TYPE_NAA;
4531                 desc->length = 8;
4532                 scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4533         }
4534
4535         mtx_lock(&ctl_softc->ctl_lock);
4536         /*
4537          * See if the caller requested a particular LUN number.  If so, see
4538          * if it is available.  Otherwise, allocate the first available LUN.
4539          */
4540         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4541                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4542                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4543                         mtx_unlock(&ctl_softc->ctl_lock);
4544                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4545                                 printf("ctl: requested LUN ID %d is higher "
4546                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4547                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4548                         } else {
4549                                 /*
4550                                  * XXX KDM return an error, or just assign
4551                                  * another LUN ID in this case??
4552                                  */
4553                                 printf("ctl: requested LUN ID %d is already "
4554                                        "in use\n", be_lun->req_lun_id);
4555                         }
4556                         if (lun->flags & CTL_LUN_MALLOCED)
4557                                 free(lun, M_CTL);
4558                         be_lun->lun_config_status(be_lun->be_lun,
4559                                                   CTL_LUN_CONFIG_FAILURE);
4560                         return (ENOSPC);
4561                 }
4562                 lun_number = be_lun->req_lun_id;
4563         } else {
4564                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4565                 if (lun_number == -1) {
4566                         mtx_unlock(&ctl_softc->ctl_lock);
4567                         printf("ctl: can't allocate LUN on target %ju, out of "
4568                                "LUNs\n", (uintmax_t)target_id.id);
4569                         if (lun->flags & CTL_LUN_MALLOCED)
4570                                 free(lun, M_CTL);
4571                         be_lun->lun_config_status(be_lun->be_lun,
4572                                                   CTL_LUN_CONFIG_FAILURE);
4573                         return (ENOSPC);
4574                 }
4575         }
4576         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4577
4578         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4579         lun->target = target_id;
4580         lun->lun = lun_number;
4581         lun->be_lun = be_lun;
4582         /*
4583          * The processor LUN is always enabled.  Disk LUNs come on line
4584          * disabled, and must be enabled by the backend.
4585          */
4586         lun->flags |= CTL_LUN_DISABLED;
4587         lun->backend = be_lun->be;
4588         be_lun->ctl_lun = lun;
4589         be_lun->lun_id = lun_number;
4590         atomic_add_int(&be_lun->be->num_luns, 1);
4591         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4592                 lun->flags |= CTL_LUN_STOPPED;
4593
4594         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4595                 lun->flags |= CTL_LUN_INOPERABLE;
4596
4597         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4598                 lun->flags |= CTL_LUN_PRIMARY_SC;
4599
4600         lun->ctl_softc = ctl_softc;
4601         TAILQ_INIT(&lun->ooa_queue);
4602         TAILQ_INIT(&lun->blocked_queue);
4603         STAILQ_INIT(&lun->error_list);
4604         ctl_tpc_lun_init(lun);
4605
4606         /*
4607          * Initialize the mode page index.
4608          */
4609         ctl_init_page_index(lun);
4610
4611         /*
4612          * Set the poweron UA for all initiators on this LUN only.
4613          */
4614         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4615                 lun->pending_ua[i] = CTL_UA_POWERON;
4616
4617         /*
4618          * Now, before we insert this lun on the lun list, set the lun
4619          * inventory changed UA for all other luns.
4620          */
4621         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4622                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4623                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4624                 }
4625         }
4626
4627         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4628
4629         ctl_softc->ctl_luns[lun_number] = lun;
4630
4631         ctl_softc->num_luns++;
4632
4633         /* Setup statistics gathering */
4634         lun->stats.device_type = be_lun->lun_type;
4635         lun->stats.lun_number = lun_number;
4636         if (lun->stats.device_type == T_DIRECT)
4637                 lun->stats.blocksize = be_lun->blocksize;
4638         else
4639                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4640         for (i = 0;i < CTL_MAX_PORTS;i++)
4641                 lun->stats.ports[i].targ_port = i;
4642
4643         mtx_unlock(&ctl_softc->ctl_lock);
4644
4645         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4646
4647         /*
4648          * Run through each registered FETD and bring it online if it isn't
4649          * already.  Enable the target ID if it hasn't been enabled, and
4650          * enable this particular LUN.
4651          */
4652         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4653                 int retval;
4654
4655                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4656                 if (retval != 0) {
4657                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4658                                "%d for lun_enable on target %ju lun %d\n",
4659                                port->port_name, port->targ_port, retval,
4660                                (uintmax_t)target_id.id, lun_number);
4661                 } else
4662                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4663         }
4664         return (0);
4665 }
4666
4667 /*
4668  * Delete a LUN.
4669  * Assumptions:
4670  * - LUN has already been marked invalid and any pending I/O has been taken
4671  *   care of.
4672  */
4673 static int
4674 ctl_free_lun(struct ctl_lun *lun)
4675 {
4676         struct ctl_softc *softc;
4677 #if 0
4678         struct ctl_port *port;
4679 #endif
4680         struct ctl_lun *nlun;
4681         int i;
4682
4683         softc = lun->ctl_softc;
4684
4685         mtx_assert(&softc->ctl_lock, MA_OWNED);
4686
4687         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4688
4689         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4690
4691         softc->ctl_luns[lun->lun] = NULL;
4692
4693         if (!TAILQ_EMPTY(&lun->ooa_queue))
4694                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4695
4696         softc->num_luns--;
4697
4698         /*
4699          * XXX KDM this scheme only works for a single target/multiple LUN
4700          * setup.  It needs to be revamped for a multiple target scheme.
4701          *
4702          * XXX KDM this results in port->lun_disable() getting called twice,
4703          * once when ctl_disable_lun() is called, and a second time here.
4704          * We really need to re-think the LUN disable semantics.  There
4705          * should probably be several steps/levels to LUN removal:
4706          *  - disable
4707          *  - invalidate
4708          *  - free
4709          *
4710          * Right now we only have a disable method when communicating to
4711          * the front end ports, at least for individual LUNs.
4712          */
4713 #if 0
4714         STAILQ_FOREACH(port, &softc->port_list, links) {
4715                 int retval;
4716
4717                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4718                                          lun->lun);
4719                 if (retval != 0) {
4720                         printf("ctl_free_lun: FETD %s port %d returned error "
4721                                "%d for lun_disable on target %ju lun %jd\n",
4722                                port->port_name, port->targ_port, retval,
4723                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4724                 }
4725
4726                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4727                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4728
4729                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4730                         if (retval != 0) {
4731                                 printf("ctl_free_lun: FETD %s port %d "
4732                                        "returned error %d for targ_disable on "
4733                                        "target %ju\n", port->port_name,
4734                                        port->targ_port, retval,
4735                                        (uintmax_t)lun->target.id);
4736                         } else
4737                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4738
4739                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4740                                 continue;
4741
4742 #if 0
4743                         port->port_offline(port->onoff_arg);
4744                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4745 #endif
4746                 }
4747         }
4748 #endif
4749
4750         /*
4751          * Tell the backend to free resources, if this LUN has a backend.
4752          */
4753         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4754         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4755
4756         ctl_tpc_lun_shutdown(lun);
4757         mtx_destroy(&lun->lun_lock);
4758         free(lun->lun_devid, M_CTL);
4759         if (lun->flags & CTL_LUN_MALLOCED)
4760                 free(lun, M_CTL);
4761
4762         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4763                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4764                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4765                 }
4766         }
4767
4768         return (0);
4769 }
4770
4771 static void
4772 ctl_create_lun(struct ctl_be_lun *be_lun)
4773 {
4774         struct ctl_softc *ctl_softc;
4775
4776         ctl_softc = control_softc;
4777
4778         /*
4779          * ctl_alloc_lun() should handle all potential failure cases.
4780          */
4781         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4782 }
4783
4784 int
4785 ctl_add_lun(struct ctl_be_lun *be_lun)
4786 {
4787         struct ctl_softc *ctl_softc = control_softc;
4788
4789         mtx_lock(&ctl_softc->ctl_lock);
4790         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4791         mtx_unlock(&ctl_softc->ctl_lock);
4792         wakeup(&ctl_softc->pending_lun_queue);
4793
4794         return (0);
4795 }
4796
4797 int
4798 ctl_enable_lun(struct ctl_be_lun *be_lun)
4799 {
4800         struct ctl_softc *ctl_softc;
4801         struct ctl_port *port, *nport;
4802         struct ctl_lun *lun;
4803         int retval;
4804
4805         ctl_softc = control_softc;
4806
4807         lun = (struct ctl_lun *)be_lun->ctl_lun;
4808
4809         mtx_lock(&ctl_softc->ctl_lock);
4810         mtx_lock(&lun->lun_lock);
4811         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4812                 /*
4813                  * eh?  Why did we get called if the LUN is already
4814                  * enabled?
4815                  */
4816                 mtx_unlock(&lun->lun_lock);
4817                 mtx_unlock(&ctl_softc->ctl_lock);
4818                 return (0);
4819         }
4820         lun->flags &= ~CTL_LUN_DISABLED;
4821         mtx_unlock(&lun->lun_lock);
4822
4823         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4824                 nport = STAILQ_NEXT(port, links);
4825
4826                 /*
4827                  * Drop the lock while we call the FETD's enable routine.
4828                  * This can lead to a callback into CTL (at least in the
4829                  * case of the internal initiator frontend.
4830                  */
4831                 mtx_unlock(&ctl_softc->ctl_lock);
4832                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4833                 mtx_lock(&ctl_softc->ctl_lock);
4834                 if (retval != 0) {
4835                         printf("%s: FETD %s port %d returned error "
4836                                "%d for lun_enable on target %ju lun %jd\n",
4837                                __func__, port->port_name, port->targ_port, retval,
4838                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4839                 }
4840 #if 0
4841                  else {
4842             /* NOTE:  TODO:  why does lun enable affect port status? */
4843                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4844                 }
4845 #endif
4846         }
4847
4848         mtx_unlock(&ctl_softc->ctl_lock);
4849
4850         return (0);
4851 }
4852
4853 int
4854 ctl_disable_lun(struct ctl_be_lun *be_lun)
4855 {
4856         struct ctl_softc *ctl_softc;
4857         struct ctl_port *port;
4858         struct ctl_lun *lun;
4859         int retval;
4860
4861         ctl_softc = control_softc;
4862
4863         lun = (struct ctl_lun *)be_lun->ctl_lun;
4864
4865         mtx_lock(&ctl_softc->ctl_lock);
4866         mtx_lock(&lun->lun_lock);
4867         if (lun->flags & CTL_LUN_DISABLED) {
4868                 mtx_unlock(&lun->lun_lock);
4869                 mtx_unlock(&ctl_softc->ctl_lock);
4870                 return (0);
4871         }
4872         lun->flags |= CTL_LUN_DISABLED;
4873         mtx_unlock(&lun->lun_lock);
4874
4875         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4876                 mtx_unlock(&ctl_softc->ctl_lock);
4877                 /*
4878                  * Drop the lock before we call the frontend's disable
4879                  * routine, to avoid lock order reversals.
4880                  *
4881                  * XXX KDM what happens if the frontend list changes while
4882                  * we're traversing it?  It's unlikely, but should be handled.
4883                  */
4884                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4885                                          lun->lun);
4886                 mtx_lock(&ctl_softc->ctl_lock);
4887                 if (retval != 0) {
4888                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4889                                "%d for lun_disable on target %ju lun %jd\n",
4890                                port->port_name, port->targ_port, retval,
4891                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4892                 }
4893         }
4894
4895         mtx_unlock(&ctl_softc->ctl_lock);
4896
4897         return (0);
4898 }
4899
4900 int
4901 ctl_start_lun(struct ctl_be_lun *be_lun)
4902 {
4903         struct ctl_softc *ctl_softc;
4904         struct ctl_lun *lun;
4905
4906         ctl_softc = control_softc;
4907
4908         lun = (struct ctl_lun *)be_lun->ctl_lun;
4909
4910         mtx_lock(&lun->lun_lock);
4911         lun->flags &= ~CTL_LUN_STOPPED;
4912         mtx_unlock(&lun->lun_lock);
4913
4914         return (0);
4915 }
4916
4917 int
4918 ctl_stop_lun(struct ctl_be_lun *be_lun)
4919 {
4920         struct ctl_softc *ctl_softc;
4921         struct ctl_lun *lun;
4922
4923         ctl_softc = control_softc;
4924
4925         lun = (struct ctl_lun *)be_lun->ctl_lun;
4926
4927         mtx_lock(&lun->lun_lock);
4928         lun->flags |= CTL_LUN_STOPPED;
4929         mtx_unlock(&lun->lun_lock);
4930
4931         return (0);
4932 }
4933
4934 int
4935 ctl_lun_offline(struct ctl_be_lun *be_lun)
4936 {
4937         struct ctl_softc *ctl_softc;
4938         struct ctl_lun *lun;
4939
4940         ctl_softc = control_softc;
4941
4942         lun = (struct ctl_lun *)be_lun->ctl_lun;
4943
4944         mtx_lock(&lun->lun_lock);
4945         lun->flags |= CTL_LUN_OFFLINE;
4946         mtx_unlock(&lun->lun_lock);
4947
4948         return (0);
4949 }
4950
4951 int
4952 ctl_lun_online(struct ctl_be_lun *be_lun)
4953 {
4954         struct ctl_softc *ctl_softc;
4955         struct ctl_lun *lun;
4956
4957         ctl_softc = control_softc;
4958
4959         lun = (struct ctl_lun *)be_lun->ctl_lun;
4960
4961         mtx_lock(&lun->lun_lock);
4962         lun->flags &= ~CTL_LUN_OFFLINE;
4963         mtx_unlock(&lun->lun_lock);
4964
4965         return (0);
4966 }
4967
4968 int
4969 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4970 {
4971         struct ctl_softc *ctl_softc;
4972         struct ctl_lun *lun;
4973
4974         ctl_softc = control_softc;
4975
4976         lun = (struct ctl_lun *)be_lun->ctl_lun;
4977
4978         mtx_lock(&lun->lun_lock);
4979
4980         /*
4981          * The LUN needs to be disabled before it can be marked invalid.
4982          */
4983         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4984                 mtx_unlock(&lun->lun_lock);
4985                 return (-1);
4986         }
4987         /*
4988          * Mark the LUN invalid.
4989          */
4990         lun->flags |= CTL_LUN_INVALID;
4991
4992         /*
4993          * If there is nothing in the OOA queue, go ahead and free the LUN.
4994          * If we have something in the OOA queue, we'll free it when the
4995          * last I/O completes.
4996          */
4997         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4998                 mtx_unlock(&lun->lun_lock);
4999                 mtx_lock(&ctl_softc->ctl_lock);
5000                 ctl_free_lun(lun);
5001                 mtx_unlock(&ctl_softc->ctl_lock);
5002         } else
5003                 mtx_unlock(&lun->lun_lock);
5004
5005         return (0);
5006 }
5007
5008 int
5009 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5010 {
5011         struct ctl_softc *ctl_softc;
5012         struct ctl_lun *lun;
5013
5014         ctl_softc = control_softc;
5015         lun = (struct ctl_lun *)be_lun->ctl_lun;
5016
5017         mtx_lock(&lun->lun_lock);
5018         lun->flags |= CTL_LUN_INOPERABLE;
5019         mtx_unlock(&lun->lun_lock);
5020
5021         return (0);
5022 }
5023
5024 int
5025 ctl_lun_operable(struct ctl_be_lun *be_lun)
5026 {
5027         struct ctl_softc *ctl_softc;
5028         struct ctl_lun *lun;
5029
5030         ctl_softc = control_softc;
5031         lun = (struct ctl_lun *)be_lun->ctl_lun;
5032
5033         mtx_lock(&lun->lun_lock);
5034         lun->flags &= ~CTL_LUN_INOPERABLE;
5035         mtx_unlock(&lun->lun_lock);
5036
5037         return (0);
5038 }
5039
5040 int
5041 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5042                    int lock)
5043 {
5044         struct ctl_softc *softc;
5045         struct ctl_lun *lun;
5046         struct copan_aps_subpage *current_sp;
5047         struct ctl_page_index *page_index;
5048         int i;
5049
5050         softc = control_softc;
5051
5052         mtx_lock(&softc->ctl_lock);
5053
5054         lun = (struct ctl_lun *)be_lun->ctl_lun;
5055         mtx_lock(&lun->lun_lock);
5056
5057         page_index = NULL;
5058         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5059                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5060                      APS_PAGE_CODE)
5061                         continue;
5062
5063                 if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5064                         continue;
5065                 page_index = &lun->mode_pages.index[i];
5066         }
5067
5068         if (page_index == NULL) {
5069                 mtx_unlock(&lun->lun_lock);
5070                 mtx_unlock(&softc->ctl_lock);
5071                 printf("%s: APS subpage not found for lun %ju!\n", __func__,
5072                        (uintmax_t)lun->lun);
5073                 return (1);
5074         }
5075 #if 0
5076         if ((softc->aps_locked_lun != 0)
5077          && (softc->aps_locked_lun != lun->lun)) {
5078                 printf("%s: attempt to lock LUN %llu when %llu is already "
5079                        "locked\n");
5080                 mtx_unlock(&lun->lun_lock);
5081                 mtx_unlock(&softc->ctl_lock);
5082                 return (1);
5083         }
5084 #endif
5085
5086         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5087                 (page_index->page_len * CTL_PAGE_CURRENT));
5088
5089         if (lock != 0) {
5090                 current_sp->lock_active = APS_LOCK_ACTIVE;
5091                 softc->aps_locked_lun = lun->lun;
5092         } else {
5093                 current_sp->lock_active = 0;
5094                 softc->aps_locked_lun = 0;
5095         }
5096
5097
5098         /*
5099          * If we're in HA mode, try to send the lock message to the other
5100          * side.
5101          */
5102         if (ctl_is_single == 0) {
5103                 int isc_retval;
5104                 union ctl_ha_msg lock_msg;
5105
5106                 lock_msg.hdr.nexus = *nexus;
5107                 lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5108                 if (lock != 0)
5109                         lock_msg.aps.lock_flag = 1;
5110                 else
5111                         lock_msg.aps.lock_flag = 0;
5112                 isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5113                                          sizeof(lock_msg), 0);
5114                 if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5115                         printf("%s: APS (lock=%d) error returned from "
5116                                "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5117                         mtx_unlock(&lun->lun_lock);
5118                         mtx_unlock(&softc->ctl_lock);
5119                         return (1);
5120                 }
5121         }
5122
5123         mtx_unlock(&lun->lun_lock);
5124         mtx_unlock(&softc->ctl_lock);
5125
5126         return (0);
5127 }
5128
5129 void
5130 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5131 {
5132         struct ctl_lun *lun;
5133         struct ctl_softc *softc;
5134         int i;
5135
5136         softc = control_softc;
5137
5138         lun = (struct ctl_lun *)be_lun->ctl_lun;
5139
5140         mtx_lock(&lun->lun_lock);
5141
5142         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5143                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5144
5145         mtx_unlock(&lun->lun_lock);
5146 }
5147
5148 /*
5149  * Backend "memory move is complete" callback for requests that never
5150  * make it down to say RAIDCore's configuration code.
5151  */
5152 int
5153 ctl_config_move_done(union ctl_io *io)
5154 {
5155         int retval;
5156
5157         retval = CTL_RETVAL_COMPLETE;
5158
5159
5160         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5161         /*
5162          * XXX KDM this shouldn't happen, but what if it does?
5163          */
5164         if (io->io_hdr.io_type != CTL_IO_SCSI)
5165                 panic("I/O type isn't CTL_IO_SCSI!");
5166
5167         if ((io->io_hdr.port_status == 0)
5168          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5169          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5170                 io->io_hdr.status = CTL_SUCCESS;
5171         else if ((io->io_hdr.port_status != 0)
5172               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5173               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5174                 /*
5175                  * For hardware error sense keys, the sense key
5176                  * specific value is defined to be a retry count,
5177                  * but we use it to pass back an internal FETD
5178                  * error code.  XXX KDM  Hopefully the FETD is only
5179                  * using 16 bits for an error code, since that's
5180                  * all the space we have in the sks field.
5181                  */
5182                 ctl_set_internal_failure(&io->scsiio,
5183                                          /*sks_valid*/ 1,
5184                                          /*retry_count*/
5185                                          io->io_hdr.port_status);
5186                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5187                         free(io->scsiio.kern_data_ptr, M_CTL);
5188                 ctl_done(io);
5189                 goto bailout;
5190         }
5191
5192         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5193          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5194          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5195                 /*
5196                  * XXX KDM just assuming a single pointer here, and not a
5197                  * S/G list.  If we start using S/G lists for config data,
5198                  * we'll need to know how to clean them up here as well.
5199                  */
5200                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5201                         free(io->scsiio.kern_data_ptr, M_CTL);
5202                 /* Hopefully the user has already set the status... */
5203                 ctl_done(io);
5204         } else {
5205                 /*
5206                  * XXX KDM now we need to continue data movement.  Some
5207                  * options:
5208                  * - call ctl_scsiio() again?  We don't do this for data
5209                  *   writes, because for those at least we know ahead of
5210                  *   time where the write will go and how long it is.  For
5211                  *   config writes, though, that information is largely
5212                  *   contained within the write itself, thus we need to
5213                  *   parse out the data again.
5214                  *
5215                  * - Call some other function once the data is in?
5216                  */
5217
5218                 /*
5219                  * XXX KDM call ctl_scsiio() again for now, and check flag
5220                  * bits to see whether we're allocated or not.
5221                  */
5222                 retval = ctl_scsiio(&io->scsiio);
5223         }
5224 bailout:
5225         return (retval);
5226 }
5227
5228 /*
5229  * This gets called by a backend driver when it is done with a
5230  * data_submit method.
5231  */
5232 void
5233 ctl_data_submit_done(union ctl_io *io)
5234 {
5235         /*
5236          * If the IO_CONT flag is set, we need to call the supplied
5237          * function to continue processing the I/O, instead of completing
5238          * the I/O just yet.
5239          *
5240          * If there is an error, though, we don't want to keep processing.
5241          * Instead, just send status back to the initiator.
5242          */
5243         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5244             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5245             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5246              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5247                 io->scsiio.io_cont(io);
5248                 return;
5249         }
5250         ctl_done(io);
5251 }
5252
5253 /*
5254  * This gets called by a backend driver when it is done with a
5255  * configuration write.
5256  */
5257 void
5258 ctl_config_write_done(union ctl_io *io)
5259 {
5260         /*
5261          * If the IO_CONT flag is set, we need to call the supplied
5262          * function to continue processing the I/O, instead of completing
5263          * the I/O just yet.
5264          *
5265          * If there is an error, though, we don't want to keep processing.
5266          * Instead, just send status back to the initiator.
5267          */
5268         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5269          && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5270           || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5271                 io->scsiio.io_cont(io);
5272                 return;
5273         }
5274         /*
5275          * Since a configuration write can be done for commands that actually
5276          * have data allocated, like write buffer, and commands that have
5277          * no data, like start/stop unit, we need to check here.
5278          */
5279         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5280                 free(io->scsiio.kern_data_ptr, M_CTL);
5281         ctl_done(io);
5282 }
5283
5284 /*
5285  * SCSI release command.
5286  */
5287 int
5288 ctl_scsi_release(struct ctl_scsiio *ctsio)
5289 {
5290         int length, longid, thirdparty_id, resv_id;
5291         struct ctl_softc *ctl_softc;
5292         struct ctl_lun *lun;
5293
5294         length = 0;
5295         resv_id = 0;
5296
5297         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5298
5299         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5300         ctl_softc = control_softc;
5301
5302         switch (ctsio->cdb[0]) {
5303         case RELEASE_10: {
5304                 struct scsi_release_10 *cdb;
5305
5306                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5307
5308                 if (cdb->byte2 & SR10_LONGID)
5309                         longid = 1;
5310                 else
5311                         thirdparty_id = cdb->thirdparty_id;
5312
5313                 resv_id = cdb->resv_id;
5314                 length = scsi_2btoul(cdb->length);
5315                 break;
5316         }
5317         }
5318
5319
5320         /*
5321          * XXX KDM right now, we only support LUN reservation.  We don't
5322          * support 3rd party reservations, or extent reservations, which
5323          * might actually need the parameter list.  If we've gotten this
5324          * far, we've got a LUN reservation.  Anything else got kicked out
5325          * above.  So, according to SPC, ignore the length.
5326          */
5327         length = 0;
5328
5329         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5330          && (length > 0)) {
5331                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5332                 ctsio->kern_data_len = length;
5333                 ctsio->kern_total_len = length;
5334                 ctsio->kern_data_resid = 0;
5335                 ctsio->kern_rel_offset = 0;
5336                 ctsio->kern_sg_entries = 0;
5337                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5338                 ctsio->be_move_done = ctl_config_move_done;
5339                 ctl_datamove((union ctl_io *)ctsio);
5340
5341                 return (CTL_RETVAL_COMPLETE);
5342         }
5343
5344         if (length > 0)
5345                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5346
5347         mtx_lock(&lun->lun_lock);
5348
5349         /*
5350          * According to SPC, it is not an error for an intiator to attempt
5351          * to release a reservation on a LUN that isn't reserved, or that
5352          * is reserved by another initiator.  The reservation can only be
5353          * released, though, by the initiator who made it or by one of
5354          * several reset type events.
5355          */
5356         if (lun->flags & CTL_LUN_RESERVED) {
5357                 if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5358                  && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5359                  && (ctsio->io_hdr.nexus.targ_target.id ==
5360                      lun->rsv_nexus.targ_target.id)) {
5361                         lun->flags &= ~CTL_LUN_RESERVED;
5362                 }
5363         }
5364
5365         mtx_unlock(&lun->lun_lock);
5366
5367         ctsio->scsi_status = SCSI_STATUS_OK;
5368         ctsio->io_hdr.status = CTL_SUCCESS;
5369
5370         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5371                 free(ctsio->kern_data_ptr, M_CTL);
5372                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5373         }
5374
5375         ctl_done((union ctl_io *)ctsio);
5376         return (CTL_RETVAL_COMPLETE);
5377 }
5378
5379 int
5380 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5381 {
5382         int extent, thirdparty, longid;
5383         int resv_id, length;
5384         uint64_t thirdparty_id;
5385         struct ctl_softc *ctl_softc;
5386         struct ctl_lun *lun;
5387
5388         extent = 0;
5389         thirdparty = 0;
5390         longid = 0;
5391         resv_id = 0;
5392         length = 0;
5393         thirdparty_id = 0;
5394
5395         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5396
5397         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5398         ctl_softc = control_softc;
5399
5400         switch (ctsio->cdb[0]) {
5401         case RESERVE_10: {
5402                 struct scsi_reserve_10 *cdb;
5403
5404                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5405
5406                 if (cdb->byte2 & SR10_LONGID)
5407                         longid = 1;
5408                 else
5409                         thirdparty_id = cdb->thirdparty_id;
5410
5411                 resv_id = cdb->resv_id;
5412                 length = scsi_2btoul(cdb->length);
5413                 break;
5414         }
5415         }
5416
5417         /*
5418          * XXX KDM right now, we only support LUN reservation.  We don't
5419          * support 3rd party reservations, or extent reservations, which
5420          * might actually need the parameter list.  If we've gotten this
5421          * far, we've got a LUN reservation.  Anything else got kicked out
5422          * above.  So, according to SPC, ignore the length.
5423          */
5424         length = 0;
5425
5426         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5427          && (length > 0)) {
5428                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5429                 ctsio->kern_data_len = length;
5430                 ctsio->kern_total_len = length;
5431                 ctsio->kern_data_resid = 0;
5432                 ctsio->kern_rel_offset = 0;
5433                 ctsio->kern_sg_entries = 0;
5434                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5435                 ctsio->be_move_done = ctl_config_move_done;
5436                 ctl_datamove((union ctl_io *)ctsio);
5437
5438                 return (CTL_RETVAL_COMPLETE);
5439         }
5440
5441         if (length > 0)
5442                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5443
5444         mtx_lock(&lun->lun_lock);
5445         if (lun->flags & CTL_LUN_RESERVED) {
5446                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5447                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5448                  || (ctsio->io_hdr.nexus.targ_target.id !=
5449                      lun->rsv_nexus.targ_target.id)) {
5450                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5451                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
5452                         goto bailout;
5453                 }
5454         }
5455
5456         lun->flags |= CTL_LUN_RESERVED;
5457         lun->rsv_nexus = ctsio->io_hdr.nexus;
5458
5459         ctsio->scsi_status = SCSI_STATUS_OK;
5460         ctsio->io_hdr.status = CTL_SUCCESS;
5461
5462 bailout:
5463         mtx_unlock(&lun->lun_lock);
5464
5465         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5466                 free(ctsio->kern_data_ptr, M_CTL);
5467                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5468         }
5469
5470         ctl_done((union ctl_io *)ctsio);
5471         return (CTL_RETVAL_COMPLETE);
5472 }
5473
5474 int
5475 ctl_start_stop(struct ctl_scsiio *ctsio)
5476 {
5477         struct scsi_start_stop_unit *cdb;
5478         struct ctl_lun *lun;
5479         struct ctl_softc *ctl_softc;
5480         int retval;
5481
5482         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5483
5484         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5485         ctl_softc = control_softc;
5486         retval = 0;
5487
5488         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5489
5490         /*
5491          * XXX KDM
5492          * We don't support the immediate bit on a stop unit.  In order to
5493          * do that, we would need to code up a way to know that a stop is
5494          * pending, and hold off any new commands until it completes, one
5495          * way or another.  Then we could accept or reject those commands
5496          * depending on its status.  We would almost need to do the reverse
5497          * of what we do below for an immediate start -- return the copy of
5498          * the ctl_io to the FETD with status to send to the host (and to
5499          * free the copy!) and then free the original I/O once the stop
5500          * actually completes.  That way, the OOA queue mechanism can work
5501          * to block commands that shouldn't proceed.  Another alternative
5502          * would be to put the copy in the queue in place of the original,
5503          * and return the original back to the caller.  That could be
5504          * slightly safer..
5505          */
5506         if ((cdb->byte2 & SSS_IMMED)
5507          && ((cdb->how & SSS_START) == 0)) {
5508                 ctl_set_invalid_field(ctsio,
5509                                       /*sks_valid*/ 1,
5510                                       /*command*/ 1,
5511                                       /*field*/ 1,
5512                                       /*bit_valid*/ 1,
5513                                       /*bit*/ 0);
5514                 ctl_done((union ctl_io *)ctsio);
5515                 return (CTL_RETVAL_COMPLETE);
5516         }
5517
5518         if ((lun->flags & CTL_LUN_PR_RESERVED)
5519          && ((cdb->how & SSS_START)==0)) {
5520                 uint32_t residx;
5521
5522                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5523                 if (!lun->per_res[residx].registered
5524                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5525
5526                         ctl_set_reservation_conflict(ctsio);
5527                         ctl_done((union ctl_io *)ctsio);
5528                         return (CTL_RETVAL_COMPLETE);
5529                 }
5530         }
5531
5532         /*
5533          * If there is no backend on this device, we can't start or stop
5534          * it.  In theory we shouldn't get any start/stop commands in the
5535          * first place at this level if the LUN doesn't have a backend.
5536          * That should get stopped by the command decode code.
5537          */
5538         if (lun->backend == NULL) {
5539                 ctl_set_invalid_opcode(ctsio);
5540                 ctl_done((union ctl_io *)ctsio);
5541                 return (CTL_RETVAL_COMPLETE);
5542         }
5543
5544         /*
5545          * XXX KDM Copan-specific offline behavior.
5546          * Figure out a reasonable way to port this?
5547          */
5548 #ifdef NEEDTOPORT
5549         mtx_lock(&lun->lun_lock);
5550
5551         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5552          && (lun->flags & CTL_LUN_OFFLINE)) {
5553                 /*
5554                  * If the LUN is offline, and the on/offline bit isn't set,
5555                  * reject the start or stop.  Otherwise, let it through.
5556                  */
5557                 mtx_unlock(&lun->lun_lock);
5558                 ctl_set_lun_not_ready(ctsio);
5559                 ctl_done((union ctl_io *)ctsio);
5560         } else {
5561                 mtx_unlock(&lun->lun_lock);
5562 #endif /* NEEDTOPORT */
5563                 /*
5564                  * This could be a start or a stop when we're online,
5565                  * or a stop/offline or start/online.  A start or stop when
5566                  * we're offline is covered in the case above.
5567                  */
5568                 /*
5569                  * In the non-immediate case, we send the request to
5570                  * the backend and return status to the user when
5571                  * it is done.
5572                  *
5573                  * In the immediate case, we allocate a new ctl_io
5574                  * to hold a copy of the request, and send that to
5575                  * the backend.  We then set good status on the
5576                  * user's request and return it immediately.
5577                  */
5578                 if (cdb->byte2 & SSS_IMMED) {
5579                         union ctl_io *new_io;
5580
5581                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5582                         if (new_io == NULL) {
5583                                 ctl_set_busy(ctsio);
5584                                 ctl_done((union ctl_io *)ctsio);
5585                         } else {
5586                                 ctl_copy_io((union ctl_io *)ctsio,
5587                                             new_io);
5588                                 retval = lun->backend->config_write(new_io);
5589                                 ctl_set_success(ctsio);
5590                                 ctl_done((union ctl_io *)ctsio);
5591                         }
5592                 } else {
5593                         retval = lun->backend->config_write(
5594                                 (union ctl_io *)ctsio);
5595                 }
5596 #ifdef NEEDTOPORT
5597         }
5598 #endif
5599         return (retval);
5600 }
5601
5602 /*
5603  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5604  * we don't really do anything with the LBA and length fields if the user
5605  * passes them in.  Instead we'll just flush out the cache for the entire
5606  * LUN.
5607  */
5608 int
5609 ctl_sync_cache(struct ctl_scsiio *ctsio)
5610 {
5611         struct ctl_lun *lun;
5612         struct ctl_softc *ctl_softc;
5613         uint64_t starting_lba;
5614         uint32_t block_count;
5615         int retval;
5616
5617         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5618
5619         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5620         ctl_softc = control_softc;
5621         retval = 0;
5622
5623         switch (ctsio->cdb[0]) {
5624         case SYNCHRONIZE_CACHE: {
5625                 struct scsi_sync_cache *cdb;
5626                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5627
5628                 starting_lba = scsi_4btoul(cdb->begin_lba);
5629                 block_count = scsi_2btoul(cdb->lb_count);
5630                 break;
5631         }
5632         case SYNCHRONIZE_CACHE_16: {
5633                 struct scsi_sync_cache_16 *cdb;
5634                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5635
5636                 starting_lba = scsi_8btou64(cdb->begin_lba);
5637                 block_count = scsi_4btoul(cdb->lb_count);
5638                 break;
5639         }
5640         default:
5641                 ctl_set_invalid_opcode(ctsio);
5642                 ctl_done((union ctl_io *)ctsio);
5643                 goto bailout;
5644                 break; /* NOTREACHED */
5645         }
5646
5647         /*
5648          * We check the LBA and length, but don't do anything with them.
5649          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5650          * get flushed.  This check will just help satisfy anyone who wants
5651          * to see an error for an out of range LBA.
5652          */
5653         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5654                 ctl_set_lba_out_of_range(ctsio);
5655                 ctl_done((union ctl_io *)ctsio);
5656                 goto bailout;
5657         }
5658
5659         /*
5660          * If this LUN has no backend, we can't flush the cache anyway.
5661          */
5662         if (lun->backend == NULL) {
5663                 ctl_set_invalid_opcode(ctsio);
5664                 ctl_done((union ctl_io *)ctsio);
5665                 goto bailout;
5666         }
5667
5668         /*
5669          * Check to see whether we're configured to send the SYNCHRONIZE
5670          * CACHE command directly to the back end.
5671          */
5672         mtx_lock(&lun->lun_lock);
5673         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5674          && (++(lun->sync_count) >= lun->sync_interval)) {
5675                 lun->sync_count = 0;
5676                 mtx_unlock(&lun->lun_lock);
5677                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5678         } else {
5679                 mtx_unlock(&lun->lun_lock);
5680                 ctl_set_success(ctsio);
5681                 ctl_done((union ctl_io *)ctsio);
5682         }
5683
5684 bailout:
5685
5686         return (retval);
5687 }
5688
5689 int
5690 ctl_format(struct ctl_scsiio *ctsio)
5691 {
5692         struct scsi_format *cdb;
5693         struct ctl_lun *lun;
5694         struct ctl_softc *ctl_softc;
5695         int length, defect_list_len;
5696
5697         CTL_DEBUG_PRINT(("ctl_format\n"));
5698
5699         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5700         ctl_softc = control_softc;
5701
5702         cdb = (struct scsi_format *)ctsio->cdb;
5703
5704         length = 0;
5705         if (cdb->byte2 & SF_FMTDATA) {
5706                 if (cdb->byte2 & SF_LONGLIST)
5707                         length = sizeof(struct scsi_format_header_long);
5708                 else
5709                         length = sizeof(struct scsi_format_header_short);
5710         }
5711
5712         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5713          && (length > 0)) {
5714                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5715                 ctsio->kern_data_len = length;
5716                 ctsio->kern_total_len = length;
5717                 ctsio->kern_data_resid = 0;
5718                 ctsio->kern_rel_offset = 0;
5719                 ctsio->kern_sg_entries = 0;
5720                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5721                 ctsio->be_move_done = ctl_config_move_done;
5722                 ctl_datamove((union ctl_io *)ctsio);
5723
5724                 return (CTL_RETVAL_COMPLETE);
5725         }
5726
5727         defect_list_len = 0;
5728
5729         if (cdb->byte2 & SF_FMTDATA) {
5730                 if (cdb->byte2 & SF_LONGLIST) {
5731                         struct scsi_format_header_long *header;
5732
5733                         header = (struct scsi_format_header_long *)
5734                                 ctsio->kern_data_ptr;
5735
5736                         defect_list_len = scsi_4btoul(header->defect_list_len);
5737                         if (defect_list_len != 0) {
5738                                 ctl_set_invalid_field(ctsio,
5739                                                       /*sks_valid*/ 1,
5740                                                       /*command*/ 0,
5741                                                       /*field*/ 2,
5742                                                       /*bit_valid*/ 0,
5743                                                       /*bit*/ 0);
5744                                 goto bailout;
5745                         }
5746                 } else {
5747                         struct scsi_format_header_short *header;
5748
5749                         header = (struct scsi_format_header_short *)
5750                                 ctsio->kern_data_ptr;
5751
5752                         defect_list_len = scsi_2btoul(header->defect_list_len);
5753                         if (defect_list_len != 0) {
5754                                 ctl_set_invalid_field(ctsio,
5755                                                       /*sks_valid*/ 1,
5756                                                       /*command*/ 0,
5757                                                       /*field*/ 2,
5758                                                       /*bit_valid*/ 0,
5759                                                       /*bit*/ 0);
5760                                 goto bailout;
5761                         }
5762                 }
5763         }
5764
5765         /*
5766          * The format command will clear out the "Medium format corrupted"
5767          * status if set by the configuration code.  That status is really
5768          * just a way to notify the host that we have lost the media, and
5769          * get them to issue a command that will basically make them think
5770          * they're blowing away the media.
5771          */
5772         mtx_lock(&lun->lun_lock);
5773         lun->flags &= ~CTL_LUN_INOPERABLE;
5774         mtx_unlock(&lun->lun_lock);
5775
5776         ctsio->scsi_status = SCSI_STATUS_OK;
5777         ctsio->io_hdr.status = CTL_SUCCESS;
5778 bailout:
5779
5780         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5781                 free(ctsio->kern_data_ptr, M_CTL);
5782                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5783         }
5784
5785         ctl_done((union ctl_io *)ctsio);
5786         return (CTL_RETVAL_COMPLETE);
5787 }
5788
5789 int
5790 ctl_read_buffer(struct ctl_scsiio *ctsio)
5791 {
5792         struct scsi_read_buffer *cdb;
5793         struct ctl_lun *lun;
5794         int buffer_offset, len;
5795         static uint8_t descr[4];
5796         static uint8_t echo_descr[4] = { 0 };
5797
5798         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5799
5800         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5801         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5802
5803         if (lun->flags & CTL_LUN_PR_RESERVED) {
5804                 uint32_t residx;
5805
5806                 /*
5807                  * XXX KDM need a lock here.
5808                  */
5809                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5810                 if ((lun->res_type == SPR_TYPE_EX_AC
5811                   && residx != lun->pr_res_idx)
5812                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
5813                    || lun->res_type == SPR_TYPE_EX_AC_AR)
5814                   && !lun->per_res[residx].registered)) {
5815                         ctl_set_reservation_conflict(ctsio);
5816                         ctl_done((union ctl_io *)ctsio);
5817                         return (CTL_RETVAL_COMPLETE);
5818                 }
5819         }
5820
5821         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5822             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5823             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5824                 ctl_set_invalid_field(ctsio,
5825                                       /*sks_valid*/ 1,
5826                                       /*command*/ 1,
5827                                       /*field*/ 1,
5828                                       /*bit_valid*/ 1,
5829                                       /*bit*/ 4);
5830                 ctl_done((union ctl_io *)ctsio);
5831                 return (CTL_RETVAL_COMPLETE);
5832         }
5833
5834         len = scsi_3btoul(cdb->length);
5835         buffer_offset = scsi_3btoul(cdb->offset);
5836
5837         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5838                 ctl_set_invalid_field(ctsio,
5839                                       /*sks_valid*/ 1,
5840                                       /*command*/ 1,
5841                                       /*field*/ 6,
5842                                       /*bit_valid*/ 0,
5843                                       /*bit*/ 0);
5844                 ctl_done((union ctl_io *)ctsio);
5845                 return (CTL_RETVAL_COMPLETE);
5846         }
5847
5848         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5849                 descr[0] = 0;
5850                 scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5851                 ctsio->kern_data_ptr = descr;
5852                 len = min(len, sizeof(descr));
5853         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5854                 ctsio->kern_data_ptr = echo_descr;
5855                 len = min(len, sizeof(echo_descr));
5856         } else
5857                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5858         ctsio->kern_data_len = len;
5859         ctsio->kern_total_len = len;
5860         ctsio->kern_data_resid = 0;
5861         ctsio->kern_rel_offset = 0;
5862         ctsio->kern_sg_entries = 0;
5863         ctsio->be_move_done = ctl_config_move_done;
5864         ctl_datamove((union ctl_io *)ctsio);
5865
5866         return (CTL_RETVAL_COMPLETE);
5867 }
5868
5869 int
5870 ctl_write_buffer(struct ctl_scsiio *ctsio)
5871 {
5872         struct scsi_write_buffer *cdb;
5873         struct ctl_lun *lun;
5874         int buffer_offset, len;
5875
5876         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5877
5878         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5879         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5880
5881         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5882                 ctl_set_invalid_field(ctsio,
5883                                       /*sks_valid*/ 1,
5884                                       /*command*/ 1,
5885                                       /*field*/ 1,
5886                                       /*bit_valid*/ 1,
5887                                       /*bit*/ 4);
5888                 ctl_done((union ctl_io *)ctsio);
5889                 return (CTL_RETVAL_COMPLETE);
5890         }
5891
5892         len = scsi_3btoul(cdb->length);
5893         buffer_offset = scsi_3btoul(cdb->offset);
5894
5895         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5896                 ctl_set_invalid_field(ctsio,
5897                                       /*sks_valid*/ 1,
5898                                       /*command*/ 1,
5899                                       /*field*/ 6,
5900                                       /*bit_valid*/ 0,
5901                                       /*bit*/ 0);
5902                 ctl_done((union ctl_io *)ctsio);
5903                 return (CTL_RETVAL_COMPLETE);
5904         }
5905
5906         /*
5907          * If we've got a kernel request that hasn't been malloced yet,
5908          * malloc it and tell the caller the data buffer is here.
5909          */
5910         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5911                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5912                 ctsio->kern_data_len = len;
5913                 ctsio->kern_total_len = len;
5914                 ctsio->kern_data_resid = 0;
5915                 ctsio->kern_rel_offset = 0;
5916                 ctsio->kern_sg_entries = 0;
5917                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5918                 ctsio->be_move_done = ctl_config_move_done;
5919                 ctl_datamove((union ctl_io *)ctsio);
5920
5921                 return (CTL_RETVAL_COMPLETE);
5922         }
5923
5924         ctl_done((union ctl_io *)ctsio);
5925
5926         return (CTL_RETVAL_COMPLETE);
5927 }
5928
5929 int
5930 ctl_write_same(struct ctl_scsiio *ctsio)
5931 {
5932         struct ctl_lun *lun;
5933         struct ctl_lba_len_flags *lbalen;
5934         uint64_t lba;
5935         uint32_t num_blocks;
5936         int len, retval;
5937         uint8_t byte2;
5938
5939         retval = CTL_RETVAL_COMPLETE;
5940
5941         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5942
5943         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5944
5945         switch (ctsio->cdb[0]) {
5946         case WRITE_SAME_10: {
5947                 struct scsi_write_same_10 *cdb;
5948
5949                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5950
5951                 lba = scsi_4btoul(cdb->addr);
5952                 num_blocks = scsi_2btoul(cdb->length);
5953                 byte2 = cdb->byte2;
5954                 break;
5955         }
5956         case WRITE_SAME_16: {
5957                 struct scsi_write_same_16 *cdb;
5958
5959                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5960
5961                 lba = scsi_8btou64(cdb->addr);
5962                 num_blocks = scsi_4btoul(cdb->length);
5963                 byte2 = cdb->byte2;
5964                 break;
5965         }
5966         default:
5967                 /*
5968                  * We got a command we don't support.  This shouldn't
5969                  * happen, commands should be filtered out above us.
5970                  */
5971                 ctl_set_invalid_opcode(ctsio);
5972                 ctl_done((union ctl_io *)ctsio);
5973
5974                 return (CTL_RETVAL_COMPLETE);
5975                 break; /* NOTREACHED */
5976         }
5977
5978         /*
5979          * The first check is to make sure we're in bounds, the second
5980          * check is to catch wrap-around problems.  If the lba + num blocks
5981          * is less than the lba, then we've wrapped around and the block
5982          * range is invalid anyway.
5983          */
5984         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5985          || ((lba + num_blocks) < lba)) {
5986                 ctl_set_lba_out_of_range(ctsio);
5987                 ctl_done((union ctl_io *)ctsio);
5988                 return (CTL_RETVAL_COMPLETE);
5989         }
5990
5991         /* Zero number of blocks means "to the last logical block" */
5992         if (num_blocks == 0) {
5993                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5994                         ctl_set_invalid_field(ctsio,
5995                                               /*sks_valid*/ 0,
5996                                               /*command*/ 1,
5997                                               /*field*/ 0,
5998                                               /*bit_valid*/ 0,
5999                                               /*bit*/ 0);
6000                         ctl_done((union ctl_io *)ctsio);
6001                         return (CTL_RETVAL_COMPLETE);
6002                 }
6003                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
6004         }
6005
6006         len = lun->be_lun->blocksize;
6007
6008         /*
6009          * If we've got a kernel request that hasn't been malloced yet,
6010          * malloc it and tell the caller the data buffer is here.
6011          */
6012         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6013                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6014                 ctsio->kern_data_len = len;
6015                 ctsio->kern_total_len = len;
6016                 ctsio->kern_data_resid = 0;
6017                 ctsio->kern_rel_offset = 0;
6018                 ctsio->kern_sg_entries = 0;
6019                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6020                 ctsio->be_move_done = ctl_config_move_done;
6021                 ctl_datamove((union ctl_io *)ctsio);
6022
6023                 return (CTL_RETVAL_COMPLETE);
6024         }
6025
6026         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6027         lbalen->lba = lba;
6028         lbalen->len = num_blocks;
6029         lbalen->flags = byte2;
6030         retval = lun->backend->config_write((union ctl_io *)ctsio);
6031
6032         return (retval);
6033 }
6034
6035 int
6036 ctl_unmap(struct ctl_scsiio *ctsio)
6037 {
6038         struct ctl_lun *lun;
6039         struct scsi_unmap *cdb;
6040         struct ctl_ptr_len_flags *ptrlen;
6041         struct scsi_unmap_header *hdr;
6042         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6043         uint64_t lba;
6044         uint32_t num_blocks;
6045         int len, retval;
6046         uint8_t byte2;
6047
6048         retval = CTL_RETVAL_COMPLETE;
6049
6050         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6051
6052         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6053         cdb = (struct scsi_unmap *)ctsio->cdb;
6054
6055         len = scsi_2btoul(cdb->length);
6056         byte2 = cdb->byte2;
6057
6058         /*
6059          * If we've got a kernel request that hasn't been malloced yet,
6060          * malloc it and tell the caller the data buffer is here.
6061          */
6062         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6063                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6064                 ctsio->kern_data_len = len;
6065                 ctsio->kern_total_len = len;
6066                 ctsio->kern_data_resid = 0;
6067                 ctsio->kern_rel_offset = 0;
6068                 ctsio->kern_sg_entries = 0;
6069                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6070                 ctsio->be_move_done = ctl_config_move_done;
6071                 ctl_datamove((union ctl_io *)ctsio);
6072
6073                 return (CTL_RETVAL_COMPLETE);
6074         }
6075
6076         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6077         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6078         if (len < sizeof (*hdr) ||
6079             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6080             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6081             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6082                 ctl_set_invalid_field(ctsio,
6083                                       /*sks_valid*/ 0,
6084                                       /*command*/ 0,
6085                                       /*field*/ 0,
6086                                       /*bit_valid*/ 0,
6087                                       /*bit*/ 0);
6088                 ctl_done((union ctl_io *)ctsio);
6089                 return (CTL_RETVAL_COMPLETE);
6090         }
6091         len = scsi_2btoul(hdr->desc_length);
6092         buf = (struct scsi_unmap_desc *)(hdr + 1);
6093         end = buf + len / sizeof(*buf);
6094
6095         endnz = buf;
6096         for (range = buf; range < end; range++) {
6097                 lba = scsi_8btou64(range->lba);
6098                 num_blocks = scsi_4btoul(range->length);
6099                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6100                  || ((lba + num_blocks) < lba)) {
6101                         ctl_set_lba_out_of_range(ctsio);
6102                         ctl_done((union ctl_io *)ctsio);
6103                         return (CTL_RETVAL_COMPLETE);
6104                 }
6105                 if (num_blocks != 0)
6106                         endnz = range + 1;
6107         }
6108
6109         /*
6110          * Block backend can not handle zero last range.
6111          * Filter it out and return if there is nothing left.
6112          */
6113         len = (uint8_t *)endnz - (uint8_t *)buf;
6114         if (len == 0) {
6115                 ctl_set_success(ctsio);
6116                 ctl_done((union ctl_io *)ctsio);
6117                 return (CTL_RETVAL_COMPLETE);
6118         }
6119
6120         ptrlen = (struct ctl_ptr_len_flags *)
6121             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6122         ptrlen->ptr = (void *)buf;
6123         ptrlen->len = len;
6124         ptrlen->flags = byte2;
6125
6126         retval = lun->backend->config_write((union ctl_io *)ctsio);
6127         return (retval);
6128 }
6129
6130 /*
6131  * Note that this function currently doesn't actually do anything inside
6132  * CTL to enforce things if the DQue bit is turned on.
6133  *
6134  * Also note that this function can't be used in the default case, because
6135  * the DQue bit isn't set in the changeable mask for the control mode page
6136  * anyway.  This is just here as an example for how to implement a page
6137  * handler, and a placeholder in case we want to allow the user to turn
6138  * tagged queueing on and off.
6139  *
6140  * The D_SENSE bit handling is functional, however, and will turn
6141  * descriptor sense on and off for a given LUN.
6142  */
6143 int
6144 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6145                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6146 {
6147         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6148         struct ctl_lun *lun;
6149         struct ctl_softc *softc;
6150         int set_ua;
6151         uint32_t initidx;
6152
6153         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6154         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6155         set_ua = 0;
6156
6157         user_cp = (struct scsi_control_page *)page_ptr;
6158         current_cp = (struct scsi_control_page *)
6159                 (page_index->page_data + (page_index->page_len *
6160                 CTL_PAGE_CURRENT));
6161         saved_cp = (struct scsi_control_page *)
6162                 (page_index->page_data + (page_index->page_len *
6163                 CTL_PAGE_SAVED));
6164
6165         softc = control_softc;
6166
6167         mtx_lock(&lun->lun_lock);
6168         if (((current_cp->rlec & SCP_DSENSE) == 0)
6169          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6170                 /*
6171                  * Descriptor sense is currently turned off and the user
6172                  * wants to turn it on.
6173                  */
6174                 current_cp->rlec |= SCP_DSENSE;
6175                 saved_cp->rlec |= SCP_DSENSE;
6176                 lun->flags |= CTL_LUN_SENSE_DESC;
6177                 set_ua = 1;
6178         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6179                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6180                 /*
6181                  * Descriptor sense is currently turned on, and the user
6182                  * wants to turn it off.
6183                  */
6184                 current_cp->rlec &= ~SCP_DSENSE;
6185                 saved_cp->rlec &= ~SCP_DSENSE;
6186                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6187                 set_ua = 1;
6188         }
6189         if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6190                 if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6191 #ifdef NEEDTOPORT
6192                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6193                                     CTL_UNTAG_TO_UNTAG,
6194                                     csevent_LogType_Trace,
6195                                     csevent_Severity_Information,
6196                                     csevent_AlertLevel_Green,
6197                                     csevent_FRU_Firmware,
6198                                     csevent_FRU_Unknown,
6199                                     "Received untagged to untagged transition");
6200 #endif /* NEEDTOPORT */
6201                 } else {
6202 #ifdef NEEDTOPORT
6203                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6204                                     CTL_UNTAG_TO_TAG,
6205                                     csevent_LogType_ConfigChange,
6206                                     csevent_Severity_Information,
6207                                     csevent_AlertLevel_Green,
6208                                     csevent_FRU_Firmware,
6209                                     csevent_FRU_Unknown,
6210                                     "Received untagged to tagged "
6211                                     "queueing transition");
6212 #endif /* NEEDTOPORT */
6213
6214                         current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6215                         saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6216                         set_ua = 1;
6217                 }
6218         } else {
6219                 if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6220 #ifdef NEEDTOPORT
6221                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6222                                     CTL_TAG_TO_UNTAG,
6223                                     csevent_LogType_ConfigChange,
6224                                     csevent_Severity_Warning,
6225                                     csevent_AlertLevel_Yellow,
6226                                     csevent_FRU_Firmware,
6227                                     csevent_FRU_Unknown,
6228                                     "Received tagged queueing to untagged "
6229                                     "transition");
6230 #endif /* NEEDTOPORT */
6231
6232                         current_cp->queue_flags |= SCP_QUEUE_DQUE;
6233                         saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6234                         set_ua = 1;
6235                 } else {
6236 #ifdef NEEDTOPORT
6237                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6238                                     CTL_TAG_TO_TAG,
6239                                     csevent_LogType_Trace,
6240                                     csevent_Severity_Information,
6241                                     csevent_AlertLevel_Green,
6242                                     csevent_FRU_Firmware,
6243                                     csevent_FRU_Unknown,
6244                                     "Received tagged queueing to tagged "
6245                                     "queueing transition");
6246 #endif /* NEEDTOPORT */
6247                 }
6248         }
6249         if (set_ua != 0) {
6250                 int i;
6251                 /*
6252                  * Let other initiators know that the mode
6253                  * parameters for this LUN have changed.
6254                  */
6255                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6256                         if (i == initidx)
6257                                 continue;
6258
6259                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6260                 }
6261         }
6262         mtx_unlock(&lun->lun_lock);
6263
6264         return (0);
6265 }
6266
6267 int
6268 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6269                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6270 {
6271         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6272         struct ctl_lun *lun;
6273         int set_ua;
6274         uint32_t initidx;
6275
6276         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6277         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6278         set_ua = 0;
6279
6280         user_cp = (struct scsi_caching_page *)page_ptr;
6281         current_cp = (struct scsi_caching_page *)
6282                 (page_index->page_data + (page_index->page_len *
6283                 CTL_PAGE_CURRENT));
6284         saved_cp = (struct scsi_caching_page *)
6285                 (page_index->page_data + (page_index->page_len *
6286                 CTL_PAGE_SAVED));
6287
6288         mtx_lock(&lun->lun_lock);
6289         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6290             (user_cp->flags1 & (SCP_WCE | SCP_RCD)))
6291                 set_ua = 1;
6292         current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6293         current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6294         saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6295         saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6296         if (set_ua != 0) {
6297                 int i;
6298                 /*
6299                  * Let other initiators know that the mode
6300                  * parameters for this LUN have changed.
6301                  */
6302                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6303                         if (i == initidx)
6304                                 continue;
6305
6306                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6307                 }
6308         }
6309         mtx_unlock(&lun->lun_lock);
6310
6311         return (0);
6312 }
6313
6314 int
6315 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6316                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6317 {
6318         return (0);
6319 }
6320
6321 int
6322 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6323                            struct ctl_page_index *page_index, int pc)
6324 {
6325         struct copan_power_subpage *page;
6326
6327         page = (struct copan_power_subpage *)page_index->page_data +
6328                 (page_index->page_len * pc);
6329
6330         switch (pc) {
6331         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6332                 /*
6333                  * We don't update the changable bits for this page.
6334                  */
6335                 break;
6336         case SMS_PAGE_CTRL_CURRENT >> 6:
6337         case SMS_PAGE_CTRL_DEFAULT >> 6:
6338         case SMS_PAGE_CTRL_SAVED >> 6:
6339 #ifdef NEEDTOPORT
6340                 ctl_update_power_subpage(page);
6341 #endif
6342                 break;
6343         default:
6344 #ifdef NEEDTOPORT
6345                 EPRINT(0, "Invalid PC %d!!", pc);
6346 #endif
6347                 break;
6348         }
6349         return (0);
6350 }
6351
6352
6353 int
6354 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6355                    struct ctl_page_index *page_index, uint8_t *page_ptr)
6356 {
6357         struct copan_aps_subpage *user_sp;
6358         struct copan_aps_subpage *current_sp;
6359         union ctl_modepage_info *modepage_info;
6360         struct ctl_softc *softc;
6361         struct ctl_lun *lun;
6362         int retval;
6363
6364         retval = CTL_RETVAL_COMPLETE;
6365         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6366                      (page_index->page_len * CTL_PAGE_CURRENT));
6367         softc = control_softc;
6368         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6369
6370         user_sp = (struct copan_aps_subpage *)page_ptr;
6371
6372         modepage_info = (union ctl_modepage_info *)
6373                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6374
6375         modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6376         modepage_info->header.subpage = page_index->subpage;
6377         modepage_info->aps.lock_active = user_sp->lock_active;
6378
6379         mtx_lock(&softc->ctl_lock);
6380
6381         /*
6382          * If there is a request to lock the LUN and another LUN is locked
6383          * this is an error. If the requested LUN is already locked ignore
6384          * the request. If no LUN is locked attempt to lock it.
6385          * if there is a request to unlock the LUN and the LUN is currently
6386          * locked attempt to unlock it. Otherwise ignore the request. i.e.
6387          * if another LUN is locked or no LUN is locked.
6388          */
6389         if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6390                 if (softc->aps_locked_lun == lun->lun) {
6391                         /*
6392                          * This LUN is already locked, so we're done.
6393                          */
6394                         retval = CTL_RETVAL_COMPLETE;
6395                 } else if (softc->aps_locked_lun == 0) {
6396                         /*
6397                          * No one has the lock, pass the request to the
6398                          * backend.
6399                          */
6400                         retval = lun->backend->config_write(
6401                                 (union ctl_io *)ctsio);
6402                 } else {
6403                         /*
6404                          * Someone else has the lock, throw out the request.
6405                          */
6406                         ctl_set_already_locked(ctsio);
6407                         free(ctsio->kern_data_ptr, M_CTL);
6408                         ctl_done((union ctl_io *)ctsio);
6409
6410                         /*
6411                          * Set the return value so that ctl_do_mode_select()
6412                          * won't try to complete the command.  We already
6413                          * completed it here.
6414                          */
6415                         retval = CTL_RETVAL_ERROR;
6416                 }
6417         } else if (softc->aps_locked_lun == lun->lun) {
6418                 /*
6419                  * This LUN is locked, so pass the unlock request to the
6420                  * backend.
6421                  */
6422                 retval = lun->backend->config_write((union ctl_io *)ctsio);
6423         }
6424         mtx_unlock(&softc->ctl_lock);
6425
6426         return (retval);
6427 }
6428
6429 int
6430 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6431                                 struct ctl_page_index *page_index,
6432                                 uint8_t *page_ptr)
6433 {
6434         uint8_t *c;
6435         int i;
6436
6437         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6438         ctl_time_io_secs =
6439                 (c[0] << 8) |
6440                 (c[1] << 0) |
6441                 0;
6442         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6443         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6444         printf("page data:");
6445         for (i=0; i<8; i++)
6446                 printf(" %.2x",page_ptr[i]);
6447         printf("\n");
6448         return (0);
6449 }
6450
6451 int
6452 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6453                                struct ctl_page_index *page_index,
6454                                int pc)
6455 {
6456         struct copan_debugconf_subpage *page;
6457
6458         page = (struct copan_debugconf_subpage *)page_index->page_data +
6459                 (page_index->page_len * pc);
6460
6461         switch (pc) {
6462         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6463         case SMS_PAGE_CTRL_DEFAULT >> 6:
6464         case SMS_PAGE_CTRL_SAVED >> 6:
6465                 /*
6466                  * We don't update the changable or default bits for this page.
6467                  */
6468                 break;
6469         case SMS_PAGE_CTRL_CURRENT >> 6:
6470                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6471                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6472                 break;
6473         default:
6474 #ifdef NEEDTOPORT
6475                 EPRINT(0, "Invalid PC %d!!", pc);
6476 #endif /* NEEDTOPORT */
6477                 break;
6478         }
6479         return (0);
6480 }
6481
6482
6483 static int
6484 ctl_do_mode_select(union ctl_io *io)
6485 {
6486         struct scsi_mode_page_header *page_header;
6487         struct ctl_page_index *page_index;
6488         struct ctl_scsiio *ctsio;
6489         int control_dev, page_len;
6490         int page_len_offset, page_len_size;
6491         union ctl_modepage_info *modepage_info;
6492         struct ctl_lun *lun;
6493         int *len_left, *len_used;
6494         int retval, i;
6495
6496         ctsio = &io->scsiio;
6497         page_index = NULL;
6498         page_len = 0;
6499         retval = CTL_RETVAL_COMPLETE;
6500
6501         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6502
6503         if (lun->be_lun->lun_type != T_DIRECT)
6504                 control_dev = 1;
6505         else
6506                 control_dev = 0;
6507
6508         modepage_info = (union ctl_modepage_info *)
6509                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6510         len_left = &modepage_info->header.len_left;
6511         len_used = &modepage_info->header.len_used;
6512
6513 do_next_page:
6514
6515         page_header = (struct scsi_mode_page_header *)
6516                 (ctsio->kern_data_ptr + *len_used);
6517
6518         if (*len_left == 0) {
6519                 free(ctsio->kern_data_ptr, M_CTL);
6520                 ctl_set_success(ctsio);
6521                 ctl_done((union ctl_io *)ctsio);
6522                 return (CTL_RETVAL_COMPLETE);
6523         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6524
6525                 free(ctsio->kern_data_ptr, M_CTL);
6526                 ctl_set_param_len_error(ctsio);
6527                 ctl_done((union ctl_io *)ctsio);
6528                 return (CTL_RETVAL_COMPLETE);
6529
6530         } else if ((page_header->page_code & SMPH_SPF)
6531                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6532
6533                 free(ctsio->kern_data_ptr, M_CTL);
6534                 ctl_set_param_len_error(ctsio);
6535                 ctl_done((union ctl_io *)ctsio);
6536                 return (CTL_RETVAL_COMPLETE);
6537         }
6538
6539
6540         /*
6541          * XXX KDM should we do something with the block descriptor?
6542          */
6543         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6544
6545                 if ((control_dev != 0)
6546                  && (lun->mode_pages.index[i].page_flags &
6547                      CTL_PAGE_FLAG_DISK_ONLY))
6548                         continue;
6549
6550                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6551                     (page_header->page_code & SMPH_PC_MASK))
6552                         continue;
6553
6554                 /*
6555                  * If neither page has a subpage code, then we've got a
6556                  * match.
6557                  */
6558                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6559                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6560                         page_index = &lun->mode_pages.index[i];
6561                         page_len = page_header->page_length;
6562                         break;
6563                 }
6564
6565                 /*
6566                  * If both pages have subpages, then the subpage numbers
6567                  * have to match.
6568                  */
6569                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6570                   && (page_header->page_code & SMPH_SPF)) {
6571                         struct scsi_mode_page_header_sp *sph;
6572
6573                         sph = (struct scsi_mode_page_header_sp *)page_header;
6574
6575                         if (lun->mode_pages.index[i].subpage ==
6576                             sph->subpage) {
6577                                 page_index = &lun->mode_pages.index[i];
6578                                 page_len = scsi_2btoul(sph->page_length);
6579                                 break;
6580                         }
6581                 }
6582         }
6583
6584         /*
6585          * If we couldn't find the page, or if we don't have a mode select
6586          * handler for it, send back an error to the user.
6587          */
6588         if ((page_index == NULL)
6589          || (page_index->select_handler == NULL)) {
6590                 ctl_set_invalid_field(ctsio,
6591                                       /*sks_valid*/ 1,
6592                                       /*command*/ 0,
6593                                       /*field*/ *len_used,
6594                                       /*bit_valid*/ 0,
6595                                       /*bit*/ 0);
6596                 free(ctsio->kern_data_ptr, M_CTL);
6597                 ctl_done((union ctl_io *)ctsio);
6598                 return (CTL_RETVAL_COMPLETE);
6599         }
6600
6601         if (page_index->page_code & SMPH_SPF) {
6602                 page_len_offset = 2;
6603                 page_len_size = 2;
6604         } else {
6605                 page_len_size = 1;
6606                 page_len_offset = 1;
6607         }
6608
6609         /*
6610          * If the length the initiator gives us isn't the one we specify in
6611          * the mode page header, or if they didn't specify enough data in
6612          * the CDB to avoid truncating this page, kick out the request.
6613          */
6614         if ((page_len != (page_index->page_len - page_len_offset -
6615                           page_len_size))
6616          || (*len_left < page_index->page_len)) {
6617
6618
6619                 ctl_set_invalid_field(ctsio,
6620                                       /*sks_valid*/ 1,
6621                                       /*command*/ 0,
6622                                       /*field*/ *len_used + page_len_offset,
6623                                       /*bit_valid*/ 0,
6624                                       /*bit*/ 0);
6625                 free(ctsio->kern_data_ptr, M_CTL);
6626                 ctl_done((union ctl_io *)ctsio);
6627                 return (CTL_RETVAL_COMPLETE);
6628         }
6629
6630         /*
6631          * Run through the mode page, checking to make sure that the bits
6632          * the user changed are actually legal for him to change.
6633          */
6634         for (i = 0; i < page_index->page_len; i++) {
6635                 uint8_t *user_byte, *change_mask, *current_byte;
6636                 int bad_bit;
6637                 int j;
6638
6639                 user_byte = (uint8_t *)page_header + i;
6640                 change_mask = page_index->page_data +
6641                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6642                 current_byte = page_index->page_data +
6643                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6644
6645                 /*
6646                  * Check to see whether the user set any bits in this byte
6647                  * that he is not allowed to set.
6648                  */
6649                 if ((*user_byte & ~(*change_mask)) ==
6650                     (*current_byte & ~(*change_mask)))
6651                         continue;
6652
6653                 /*
6654                  * Go through bit by bit to determine which one is illegal.
6655                  */
6656                 bad_bit = 0;
6657                 for (j = 7; j >= 0; j--) {
6658                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6659                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6660                                 bad_bit = i;
6661                                 break;
6662                         }
6663                 }
6664                 ctl_set_invalid_field(ctsio,
6665                                       /*sks_valid*/ 1,
6666                                       /*command*/ 0,
6667                                       /*field*/ *len_used + i,
6668                                       /*bit_valid*/ 1,
6669                                       /*bit*/ bad_bit);
6670                 free(ctsio->kern_data_ptr, M_CTL);
6671                 ctl_done((union ctl_io *)ctsio);
6672                 return (CTL_RETVAL_COMPLETE);
6673         }
6674
6675         /*
6676          * Decrement these before we call the page handler, since we may
6677          * end up getting called back one way or another before the handler
6678          * returns to this context.
6679          */
6680         *len_left -= page_index->page_len;
6681         *len_used += page_index->page_len;
6682
6683         retval = page_index->select_handler(ctsio, page_index,
6684                                             (uint8_t *)page_header);
6685
6686         /*
6687          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6688          * wait until this queued command completes to finish processing
6689          * the mode page.  If it returns anything other than
6690          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6691          * already set the sense information, freed the data pointer, and
6692          * completed the io for us.
6693          */
6694         if (retval != CTL_RETVAL_COMPLETE)
6695                 goto bailout_no_done;
6696
6697         /*
6698          * If the initiator sent us more than one page, parse the next one.
6699          */
6700         if (*len_left > 0)
6701                 goto do_next_page;
6702
6703         ctl_set_success(ctsio);
6704         free(ctsio->kern_data_ptr, M_CTL);
6705         ctl_done((union ctl_io *)ctsio);
6706
6707 bailout_no_done:
6708
6709         return (CTL_RETVAL_COMPLETE);
6710
6711 }
6712
6713 int
6714 ctl_mode_select(struct ctl_scsiio *ctsio)
6715 {
6716         int param_len, pf, sp;
6717         int header_size, bd_len;
6718         int len_left, len_used;
6719         struct ctl_page_index *page_index;
6720         struct ctl_lun *lun;
6721         int control_dev, page_len;
6722         union ctl_modepage_info *modepage_info;
6723         int retval;
6724
6725         pf = 0;
6726         sp = 0;
6727         page_len = 0;
6728         len_used = 0;
6729         len_left = 0;
6730         retval = 0;
6731         bd_len = 0;
6732         page_index = NULL;
6733
6734         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6735
6736         if (lun->be_lun->lun_type != T_DIRECT)
6737                 control_dev = 1;
6738         else
6739                 control_dev = 0;
6740
6741         switch (ctsio->cdb[0]) {
6742         case MODE_SELECT_6: {
6743                 struct scsi_mode_select_6 *cdb;
6744
6745                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6746
6747                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6748                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6749
6750                 param_len = cdb->length;
6751                 header_size = sizeof(struct scsi_mode_header_6);
6752                 break;
6753         }
6754         case MODE_SELECT_10: {
6755                 struct scsi_mode_select_10 *cdb;
6756
6757                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6758
6759                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6760                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6761
6762                 param_len = scsi_2btoul(cdb->length);
6763                 header_size = sizeof(struct scsi_mode_header_10);
6764                 break;
6765         }
6766         default:
6767                 ctl_set_invalid_opcode(ctsio);
6768                 ctl_done((union ctl_io *)ctsio);
6769                 return (CTL_RETVAL_COMPLETE);
6770                 break; /* NOTREACHED */
6771         }
6772
6773         /*
6774          * From SPC-3:
6775          * "A parameter list length of zero indicates that the Data-Out Buffer
6776          * shall be empty. This condition shall not be considered as an error."
6777          */
6778         if (param_len == 0) {
6779                 ctl_set_success(ctsio);
6780                 ctl_done((union ctl_io *)ctsio);
6781                 return (CTL_RETVAL_COMPLETE);
6782         }
6783
6784         /*
6785          * Since we'll hit this the first time through, prior to
6786          * allocation, we don't need to free a data buffer here.
6787          */
6788         if (param_len < header_size) {
6789                 ctl_set_param_len_error(ctsio);
6790                 ctl_done((union ctl_io *)ctsio);
6791                 return (CTL_RETVAL_COMPLETE);
6792         }
6793
6794         /*
6795          * Allocate the data buffer and grab the user's data.  In theory,
6796          * we shouldn't have to sanity check the parameter list length here
6797          * because the maximum size is 64K.  We should be able to malloc
6798          * that much without too many problems.
6799          */
6800         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6801                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6802                 ctsio->kern_data_len = param_len;
6803                 ctsio->kern_total_len = param_len;
6804                 ctsio->kern_data_resid = 0;
6805                 ctsio->kern_rel_offset = 0;
6806                 ctsio->kern_sg_entries = 0;
6807                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6808                 ctsio->be_move_done = ctl_config_move_done;
6809                 ctl_datamove((union ctl_io *)ctsio);
6810
6811                 return (CTL_RETVAL_COMPLETE);
6812         }
6813
6814         switch (ctsio->cdb[0]) {
6815         case MODE_SELECT_6: {
6816                 struct scsi_mode_header_6 *mh6;
6817
6818                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6819                 bd_len = mh6->blk_desc_len;
6820                 break;
6821         }
6822         case MODE_SELECT_10: {
6823                 struct scsi_mode_header_10 *mh10;
6824
6825                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6826                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6827                 break;
6828         }
6829         default:
6830                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6831                 break;
6832         }
6833
6834         if (param_len < (header_size + bd_len)) {
6835                 free(ctsio->kern_data_ptr, M_CTL);
6836                 ctl_set_param_len_error(ctsio);
6837                 ctl_done((union ctl_io *)ctsio);
6838                 return (CTL_RETVAL_COMPLETE);
6839         }
6840
6841         /*
6842          * Set the IO_CONT flag, so that if this I/O gets passed to
6843          * ctl_config_write_done(), it'll get passed back to
6844          * ctl_do_mode_select() for further processing, or completion if
6845          * we're all done.
6846          */
6847         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6848         ctsio->io_cont = ctl_do_mode_select;
6849
6850         modepage_info = (union ctl_modepage_info *)
6851                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6852
6853         memset(modepage_info, 0, sizeof(*modepage_info));
6854
6855         len_left = param_len - header_size - bd_len;
6856         len_used = header_size + bd_len;
6857
6858         modepage_info->header.len_left = len_left;
6859         modepage_info->header.len_used = len_used;
6860
6861         return (ctl_do_mode_select((union ctl_io *)ctsio));
6862 }
6863
6864 int
6865 ctl_mode_sense(struct ctl_scsiio *ctsio)
6866 {
6867         struct ctl_lun *lun;
6868         int pc, page_code, dbd, llba, subpage;
6869         int alloc_len, page_len, header_len, total_len;
6870         struct scsi_mode_block_descr *block_desc;
6871         struct ctl_page_index *page_index;
6872         int control_dev;
6873
6874         dbd = 0;
6875         llba = 0;
6876         block_desc = NULL;
6877         page_index = NULL;
6878
6879         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6880
6881         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6882
6883         if (lun->be_lun->lun_type != T_DIRECT)
6884                 control_dev = 1;
6885         else
6886                 control_dev = 0;
6887
6888         if (lun->flags & CTL_LUN_PR_RESERVED) {
6889                 uint32_t residx;
6890
6891                 /*
6892                  * XXX KDM need a lock here.
6893                  */
6894                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6895                 if ((lun->res_type == SPR_TYPE_EX_AC
6896                   && residx != lun->pr_res_idx)
6897                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6898                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6899                   && !lun->per_res[residx].registered)) {
6900                         ctl_set_reservation_conflict(ctsio);
6901                         ctl_done((union ctl_io *)ctsio);
6902                         return (CTL_RETVAL_COMPLETE);
6903                 }
6904         }
6905
6906         switch (ctsio->cdb[0]) {
6907         case MODE_SENSE_6: {
6908                 struct scsi_mode_sense_6 *cdb;
6909
6910                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6911
6912                 header_len = sizeof(struct scsi_mode_hdr_6);
6913                 if (cdb->byte2 & SMS_DBD)
6914                         dbd = 1;
6915                 else
6916                         header_len += sizeof(struct scsi_mode_block_descr);
6917
6918                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6919                 page_code = cdb->page & SMS_PAGE_CODE;
6920                 subpage = cdb->subpage;
6921                 alloc_len = cdb->length;
6922                 break;
6923         }
6924         case MODE_SENSE_10: {
6925                 struct scsi_mode_sense_10 *cdb;
6926
6927                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6928
6929                 header_len = sizeof(struct scsi_mode_hdr_10);
6930
6931                 if (cdb->byte2 & SMS_DBD)
6932                         dbd = 1;
6933                 else
6934                         header_len += sizeof(struct scsi_mode_block_descr);
6935                 if (cdb->byte2 & SMS10_LLBAA)
6936                         llba = 1;
6937                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6938                 page_code = cdb->page & SMS_PAGE_CODE;
6939                 subpage = cdb->subpage;
6940                 alloc_len = scsi_2btoul(cdb->length);
6941                 break;
6942         }
6943         default:
6944                 ctl_set_invalid_opcode(ctsio);
6945                 ctl_done((union ctl_io *)ctsio);
6946                 return (CTL_RETVAL_COMPLETE);
6947                 break; /* NOTREACHED */
6948         }
6949
6950         /*
6951          * We have to make a first pass through to calculate the size of
6952          * the pages that match the user's query.  Then we allocate enough
6953          * memory to hold it, and actually copy the data into the buffer.
6954          */
6955         switch (page_code) {
6956         case SMS_ALL_PAGES_PAGE: {
6957                 int i;
6958
6959                 page_len = 0;
6960
6961                 /*
6962                  * At the moment, values other than 0 and 0xff here are
6963                  * reserved according to SPC-3.
6964                  */
6965                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6966                  && (subpage != SMS_SUBPAGE_ALL)) {
6967                         ctl_set_invalid_field(ctsio,
6968                                               /*sks_valid*/ 1,
6969                                               /*command*/ 1,
6970                                               /*field*/ 3,
6971                                               /*bit_valid*/ 0,
6972                                               /*bit*/ 0);
6973                         ctl_done((union ctl_io *)ctsio);
6974                         return (CTL_RETVAL_COMPLETE);
6975                 }
6976
6977                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6978                         if ((control_dev != 0)
6979                          && (lun->mode_pages.index[i].page_flags &
6980                              CTL_PAGE_FLAG_DISK_ONLY))
6981                                 continue;
6982
6983                         /*
6984                          * We don't use this subpage if the user didn't
6985                          * request all subpages.
6986                          */
6987                         if ((lun->mode_pages.index[i].subpage != 0)
6988                          && (subpage == SMS_SUBPAGE_PAGE_0))
6989                                 continue;
6990
6991 #if 0
6992                         printf("found page %#x len %d\n",
6993                                lun->mode_pages.index[i].page_code &
6994                                SMPH_PC_MASK,
6995                                lun->mode_pages.index[i].page_len);
6996 #endif
6997                         page_len += lun->mode_pages.index[i].page_len;
6998                 }
6999                 break;
7000         }
7001         default: {
7002                 int i;
7003
7004                 page_len = 0;
7005
7006                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7007                         /* Look for the right page code */
7008                         if ((lun->mode_pages.index[i].page_code &
7009                              SMPH_PC_MASK) != page_code)
7010                                 continue;
7011
7012                         /* Look for the right subpage or the subpage wildcard*/
7013                         if ((lun->mode_pages.index[i].subpage != subpage)
7014                          && (subpage != SMS_SUBPAGE_ALL))
7015                                 continue;
7016
7017                         /* Make sure the page is supported for this dev type */
7018                         if ((control_dev != 0)
7019                          && (lun->mode_pages.index[i].page_flags &
7020                              CTL_PAGE_FLAG_DISK_ONLY))
7021                                 continue;
7022
7023 #if 0
7024                         printf("found page %#x len %d\n",
7025                                lun->mode_pages.index[i].page_code &
7026                                SMPH_PC_MASK,
7027                                lun->mode_pages.index[i].page_len);
7028 #endif
7029
7030                         page_len += lun->mode_pages.index[i].page_len;
7031                 }
7032
7033                 if (page_len == 0) {
7034                         ctl_set_invalid_field(ctsio,
7035                                               /*sks_valid*/ 1,
7036                                               /*command*/ 1,
7037                                               /*field*/ 2,
7038                                               /*bit_valid*/ 1,
7039                                               /*bit*/ 5);
7040                         ctl_done((union ctl_io *)ctsio);
7041                         return (CTL_RETVAL_COMPLETE);
7042                 }
7043                 break;
7044         }
7045         }
7046
7047         total_len = header_len + page_len;
7048 #if 0
7049         printf("header_len = %d, page_len = %d, total_len = %d\n",
7050                header_len, page_len, total_len);
7051 #endif
7052
7053         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7054         ctsio->kern_sg_entries = 0;
7055         ctsio->kern_data_resid = 0;
7056         ctsio->kern_rel_offset = 0;
7057         if (total_len < alloc_len) {
7058                 ctsio->residual = alloc_len - total_len;
7059                 ctsio->kern_data_len = total_len;
7060                 ctsio->kern_total_len = total_len;
7061         } else {
7062                 ctsio->residual = 0;
7063                 ctsio->kern_data_len = alloc_len;
7064                 ctsio->kern_total_len = alloc_len;
7065         }
7066
7067         switch (ctsio->cdb[0]) {
7068         case MODE_SENSE_6: {
7069                 struct scsi_mode_hdr_6 *header;
7070
7071                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7072
7073                 header->datalen = ctl_min(total_len - 1, 254);
7074
7075                 if (dbd)
7076                         header->block_descr_len = 0;
7077                 else
7078                         header->block_descr_len =
7079                                 sizeof(struct scsi_mode_block_descr);
7080                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7081                 break;
7082         }
7083         case MODE_SENSE_10: {
7084                 struct scsi_mode_hdr_10 *header;
7085                 int datalen;
7086
7087                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7088
7089                 datalen = ctl_min(total_len - 2, 65533);
7090                 scsi_ulto2b(datalen, header->datalen);
7091                 if (dbd)
7092                         scsi_ulto2b(0, header->block_descr_len);
7093                 else
7094                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7095                                     header->block_descr_len);
7096                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7097                 break;
7098         }
7099         default:
7100                 panic("invalid CDB type %#x", ctsio->cdb[0]);
7101                 break; /* NOTREACHED */
7102         }
7103
7104         /*
7105          * If we've got a disk, use its blocksize in the block
7106          * descriptor.  Otherwise, just set it to 0.
7107          */
7108         if (dbd == 0) {
7109                 if (control_dev != 0)
7110                         scsi_ulto3b(lun->be_lun->blocksize,
7111                                     block_desc->block_len);
7112                 else
7113                         scsi_ulto3b(0, block_desc->block_len);
7114         }
7115
7116         switch (page_code) {
7117         case SMS_ALL_PAGES_PAGE: {
7118                 int i, data_used;
7119
7120                 data_used = header_len;
7121                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7122                         struct ctl_page_index *page_index;
7123
7124                         page_index = &lun->mode_pages.index[i];
7125
7126                         if ((control_dev != 0)
7127                          && (page_index->page_flags &
7128                             CTL_PAGE_FLAG_DISK_ONLY))
7129                                 continue;
7130
7131                         /*
7132                          * We don't use this subpage if the user didn't
7133                          * request all subpages.  We already checked (above)
7134                          * to make sure the user only specified a subpage
7135                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7136                          */
7137                         if ((page_index->subpage != 0)
7138                          && (subpage == SMS_SUBPAGE_PAGE_0))
7139                                 continue;
7140
7141                         /*
7142                          * Call the handler, if it exists, to update the
7143                          * page to the latest values.
7144                          */
7145                         if (page_index->sense_handler != NULL)
7146                                 page_index->sense_handler(ctsio, page_index,pc);
7147
7148                         memcpy(ctsio->kern_data_ptr + data_used,
7149                                page_index->page_data +
7150                                (page_index->page_len * pc),
7151                                page_index->page_len);
7152                         data_used += page_index->page_len;
7153                 }
7154                 break;
7155         }
7156         default: {
7157                 int i, data_used;
7158
7159                 data_used = header_len;
7160
7161                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7162                         struct ctl_page_index *page_index;
7163
7164                         page_index = &lun->mode_pages.index[i];
7165
7166                         /* Look for the right page code */
7167                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7168                                 continue;
7169
7170                         /* Look for the right subpage or the subpage wildcard*/
7171                         if ((page_index->subpage != subpage)
7172                          && (subpage != SMS_SUBPAGE_ALL))
7173                                 continue;
7174
7175                         /* Make sure the page is supported for this dev type */
7176                         if ((control_dev != 0)
7177                          && (page_index->page_flags &
7178                              CTL_PAGE_FLAG_DISK_ONLY))
7179                                 continue;
7180
7181                         /*
7182                          * Call the handler, if it exists, to update the
7183                          * page to the latest values.
7184                          */
7185                         if (page_index->sense_handler != NULL)
7186                                 page_index->sense_handler(ctsio, page_index,pc);
7187
7188                         memcpy(ctsio->kern_data_ptr + data_used,
7189                                page_index->page_data +
7190                                (page_index->page_len * pc),
7191                                page_index->page_len);
7192                         data_used += page_index->page_len;
7193                 }
7194                 break;
7195         }
7196         }
7197
7198         ctsio->scsi_status = SCSI_STATUS_OK;
7199
7200         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7201         ctsio->be_move_done = ctl_config_move_done;
7202         ctl_datamove((union ctl_io *)ctsio);
7203
7204         return (CTL_RETVAL_COMPLETE);
7205 }
7206
7207 int
7208 ctl_read_capacity(struct ctl_scsiio *ctsio)
7209 {
7210         struct scsi_read_capacity *cdb;
7211         struct scsi_read_capacity_data *data;
7212         struct ctl_lun *lun;
7213         uint32_t lba;
7214
7215         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7216
7217         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7218
7219         lba = scsi_4btoul(cdb->addr);
7220         if (((cdb->pmi & SRC_PMI) == 0)
7221          && (lba != 0)) {
7222                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7223                                       /*sks_valid*/ 1,
7224                                       /*command*/ 1,
7225                                       /*field*/ 2,
7226                                       /*bit_valid*/ 0,
7227                                       /*bit*/ 0);
7228                 ctl_done((union ctl_io *)ctsio);
7229                 return (CTL_RETVAL_COMPLETE);
7230         }
7231
7232         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7233
7234         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7235         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7236         ctsio->residual = 0;
7237         ctsio->kern_data_len = sizeof(*data);
7238         ctsio->kern_total_len = sizeof(*data);
7239         ctsio->kern_data_resid = 0;
7240         ctsio->kern_rel_offset = 0;
7241         ctsio->kern_sg_entries = 0;
7242
7243         /*
7244          * If the maximum LBA is greater than 0xfffffffe, the user must
7245          * issue a SERVICE ACTION IN (16) command, with the read capacity
7246          * serivce action set.
7247          */
7248         if (lun->be_lun->maxlba > 0xfffffffe)
7249                 scsi_ulto4b(0xffffffff, data->addr);
7250         else
7251                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7252
7253         /*
7254          * XXX KDM this may not be 512 bytes...
7255          */
7256         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7257
7258         ctsio->scsi_status = SCSI_STATUS_OK;
7259
7260         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7261         ctsio->be_move_done = ctl_config_move_done;
7262         ctl_datamove((union ctl_io *)ctsio);
7263
7264         return (CTL_RETVAL_COMPLETE);
7265 }
7266
7267 int
7268 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7269 {
7270         struct scsi_read_capacity_16 *cdb;
7271         struct scsi_read_capacity_data_long *data;
7272         struct ctl_lun *lun;
7273         uint64_t lba;
7274         uint32_t alloc_len;
7275
7276         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7277
7278         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7279
7280         alloc_len = scsi_4btoul(cdb->alloc_len);
7281         lba = scsi_8btou64(cdb->addr);
7282
7283         if ((cdb->reladr & SRC16_PMI)
7284          && (lba != 0)) {
7285                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7286                                       /*sks_valid*/ 1,
7287                                       /*command*/ 1,
7288                                       /*field*/ 2,
7289                                       /*bit_valid*/ 0,
7290                                       /*bit*/ 0);
7291                 ctl_done((union ctl_io *)ctsio);
7292                 return (CTL_RETVAL_COMPLETE);
7293         }
7294
7295         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7296
7297         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7298         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7299
7300         if (sizeof(*data) < alloc_len) {
7301                 ctsio->residual = alloc_len - sizeof(*data);
7302                 ctsio->kern_data_len = sizeof(*data);
7303                 ctsio->kern_total_len = sizeof(*data);
7304         } else {
7305                 ctsio->residual = 0;
7306                 ctsio->kern_data_len = alloc_len;
7307                 ctsio->kern_total_len = alloc_len;
7308         }
7309         ctsio->kern_data_resid = 0;
7310         ctsio->kern_rel_offset = 0;
7311         ctsio->kern_sg_entries = 0;
7312
7313         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7314         /* XXX KDM this may not be 512 bytes... */
7315         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7316         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7317         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7318         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7319                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7320
7321         ctsio->scsi_status = SCSI_STATUS_OK;
7322
7323         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7324         ctsio->be_move_done = ctl_config_move_done;
7325         ctl_datamove((union ctl_io *)ctsio);
7326
7327         return (CTL_RETVAL_COMPLETE);
7328 }
7329
7330 int
7331 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7332 {
7333         struct scsi_maintenance_in *cdb;
7334         int retval;
7335         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7336         int num_target_port_groups, num_target_ports, single;
7337         struct ctl_lun *lun;
7338         struct ctl_softc *softc;
7339         struct ctl_port *port;
7340         struct scsi_target_group_data *rtg_ptr;
7341         struct scsi_target_group_data_extended *rtg_ext_ptr;
7342         struct scsi_target_port_group_descriptor *tpg_desc;
7343
7344         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7345
7346         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7347         softc = control_softc;
7348         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7349
7350         retval = CTL_RETVAL_COMPLETE;
7351
7352         switch (cdb->byte2 & STG_PDF_MASK) {
7353         case STG_PDF_LENGTH:
7354                 ext = 0;
7355                 break;
7356         case STG_PDF_EXTENDED:
7357                 ext = 1;
7358                 break;
7359         default:
7360                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7361                                       /*sks_valid*/ 1,
7362                                       /*command*/ 1,
7363                                       /*field*/ 2,
7364                                       /*bit_valid*/ 1,
7365                                       /*bit*/ 5);
7366                 ctl_done((union ctl_io *)ctsio);
7367                 return(retval);
7368         }
7369
7370         single = ctl_is_single;
7371         if (single)
7372                 num_target_port_groups = 1;
7373         else
7374                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7375         num_target_ports = 0;
7376         mtx_lock(&softc->ctl_lock);
7377         STAILQ_FOREACH(port, &softc->port_list, links) {
7378                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7379                         continue;
7380                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7381                         continue;
7382                 num_target_ports++;
7383         }
7384         mtx_unlock(&softc->ctl_lock);
7385
7386         if (ext)
7387                 total_len = sizeof(struct scsi_target_group_data_extended);
7388         else
7389                 total_len = sizeof(struct scsi_target_group_data);
7390         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7391                 num_target_port_groups +
7392             sizeof(struct scsi_target_port_descriptor) *
7393                 num_target_ports * num_target_port_groups;
7394
7395         alloc_len = scsi_4btoul(cdb->length);
7396
7397         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7398
7399         ctsio->kern_sg_entries = 0;
7400
7401         if (total_len < alloc_len) {
7402                 ctsio->residual = alloc_len - total_len;
7403                 ctsio->kern_data_len = total_len;
7404                 ctsio->kern_total_len = total_len;
7405         } else {
7406                 ctsio->residual = 0;
7407                 ctsio->kern_data_len = alloc_len;
7408                 ctsio->kern_total_len = alloc_len;
7409         }
7410         ctsio->kern_data_resid = 0;
7411         ctsio->kern_rel_offset = 0;
7412
7413         if (ext) {
7414                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7415                     ctsio->kern_data_ptr;
7416                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7417                 rtg_ext_ptr->format_type = 0x10;
7418                 rtg_ext_ptr->implicit_transition_time = 0;
7419                 tpg_desc = &rtg_ext_ptr->groups[0];
7420         } else {
7421                 rtg_ptr = (struct scsi_target_group_data *)
7422                     ctsio->kern_data_ptr;
7423                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7424                 tpg_desc = &rtg_ptr->groups[0];
7425         }
7426
7427         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7428         mtx_lock(&softc->ctl_lock);
7429         for (g = 0; g < num_target_port_groups; g++) {
7430                 if (g == pg)
7431                         tpg_desc->pref_state = TPG_PRIMARY |
7432                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7433                 else
7434                         tpg_desc->pref_state =
7435                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7436                 tpg_desc->support = TPG_AO_SUP;
7437                 if (!single)
7438                         tpg_desc->support |= TPG_AN_SUP;
7439                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7440                 tpg_desc->status = TPG_IMPLICIT;
7441                 pc = 0;
7442                 STAILQ_FOREACH(port, &softc->port_list, links) {
7443                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7444                                 continue;
7445                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7446                             CTL_MAX_LUNS)
7447                                 continue;
7448                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7449                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7450                             relative_target_port_identifier);
7451                         pc++;
7452                 }
7453                 tpg_desc->target_port_count = pc;
7454                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7455                     &tpg_desc->descriptors[pc];
7456         }
7457         mtx_unlock(&softc->ctl_lock);
7458
7459         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7460         ctsio->be_move_done = ctl_config_move_done;
7461
7462         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7463                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7464                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7465                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7466                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7467
7468         ctl_datamove((union ctl_io *)ctsio);
7469         return(retval);
7470 }
7471
7472 int
7473 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7474 {
7475         struct ctl_lun *lun;
7476         struct scsi_report_supported_opcodes *cdb;
7477         const struct ctl_cmd_entry *entry, *sentry;
7478         struct scsi_report_supported_opcodes_all *all;
7479         struct scsi_report_supported_opcodes_descr *descr;
7480         struct scsi_report_supported_opcodes_one *one;
7481         int retval;
7482         int alloc_len, total_len;
7483         int opcode, service_action, i, j, num;
7484
7485         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7486
7487         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7488         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7489
7490         retval = CTL_RETVAL_COMPLETE;
7491
7492         opcode = cdb->requested_opcode;
7493         service_action = scsi_2btoul(cdb->requested_service_action);
7494         switch (cdb->options & RSO_OPTIONS_MASK) {
7495         case RSO_OPTIONS_ALL:
7496                 num = 0;
7497                 for (i = 0; i < 256; i++) {
7498                         entry = &ctl_cmd_table[i];
7499                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7500                                 for (j = 0; j < 32; j++) {
7501                                         sentry = &((const struct ctl_cmd_entry *)
7502                                             entry->execute)[j];
7503                                         if (ctl_cmd_applicable(
7504                                             lun->be_lun->lun_type, sentry))
7505                                                 num++;
7506                                 }
7507                         } else {
7508                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7509                                     entry))
7510                                         num++;
7511                         }
7512                 }
7513                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7514                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7515                 break;
7516         case RSO_OPTIONS_OC:
7517                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7518                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7519                                               /*sks_valid*/ 1,
7520                                               /*command*/ 1,
7521                                               /*field*/ 2,
7522                                               /*bit_valid*/ 1,
7523                                               /*bit*/ 2);
7524                         ctl_done((union ctl_io *)ctsio);
7525                         return (CTL_RETVAL_COMPLETE);
7526                 }
7527                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7528                 break;
7529         case RSO_OPTIONS_OC_SA:
7530                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7531                     service_action >= 32) {
7532                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7533                                               /*sks_valid*/ 1,
7534                                               /*command*/ 1,
7535                                               /*field*/ 2,
7536                                               /*bit_valid*/ 1,
7537                                               /*bit*/ 2);
7538                         ctl_done((union ctl_io *)ctsio);
7539                         return (CTL_RETVAL_COMPLETE);
7540                 }
7541                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7542                 break;
7543         default:
7544                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7545                                       /*sks_valid*/ 1,
7546                                       /*command*/ 1,
7547                                       /*field*/ 2,
7548                                       /*bit_valid*/ 1,
7549                                       /*bit*/ 2);
7550                 ctl_done((union ctl_io *)ctsio);
7551                 return (CTL_RETVAL_COMPLETE);
7552         }
7553
7554         alloc_len = scsi_4btoul(cdb->length);
7555
7556         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7557
7558         ctsio->kern_sg_entries = 0;
7559
7560         if (total_len < alloc_len) {
7561                 ctsio->residual = alloc_len - total_len;
7562                 ctsio->kern_data_len = total_len;
7563                 ctsio->kern_total_len = total_len;
7564         } else {
7565                 ctsio->residual = 0;
7566                 ctsio->kern_data_len = alloc_len;
7567                 ctsio->kern_total_len = alloc_len;
7568         }
7569         ctsio->kern_data_resid = 0;
7570         ctsio->kern_rel_offset = 0;
7571
7572         switch (cdb->options & RSO_OPTIONS_MASK) {
7573         case RSO_OPTIONS_ALL:
7574                 all = (struct scsi_report_supported_opcodes_all *)
7575                     ctsio->kern_data_ptr;
7576                 num = 0;
7577                 for (i = 0; i < 256; i++) {
7578                         entry = &ctl_cmd_table[i];
7579                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7580                                 for (j = 0; j < 32; j++) {
7581                                         sentry = &((const struct ctl_cmd_entry *)
7582                                             entry->execute)[j];
7583                                         if (!ctl_cmd_applicable(
7584                                             lun->be_lun->lun_type, sentry))
7585                                                 continue;
7586                                         descr = &all->descr[num++];
7587                                         descr->opcode = i;
7588                                         scsi_ulto2b(j, descr->service_action);
7589                                         descr->flags = RSO_SERVACTV;
7590                                         scsi_ulto2b(sentry->length,
7591                                             descr->cdb_length);
7592                                 }
7593                         } else {
7594                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7595                                     entry))
7596                                         continue;
7597                                 descr = &all->descr[num++];
7598                                 descr->opcode = i;
7599                                 scsi_ulto2b(0, descr->service_action);
7600                                 descr->flags = 0;
7601                                 scsi_ulto2b(entry->length, descr->cdb_length);
7602                         }
7603                 }
7604                 scsi_ulto4b(
7605                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7606                     all->length);
7607                 break;
7608         case RSO_OPTIONS_OC:
7609                 one = (struct scsi_report_supported_opcodes_one *)
7610                     ctsio->kern_data_ptr;
7611                 entry = &ctl_cmd_table[opcode];
7612                 goto fill_one;
7613         case RSO_OPTIONS_OC_SA:
7614                 one = (struct scsi_report_supported_opcodes_one *)
7615                     ctsio->kern_data_ptr;
7616                 entry = &ctl_cmd_table[opcode];
7617                 entry = &((const struct ctl_cmd_entry *)
7618                     entry->execute)[service_action];
7619 fill_one:
7620                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7621                         one->support = 3;
7622                         scsi_ulto2b(entry->length, one->cdb_length);
7623                         one->cdb_usage[0] = opcode;
7624                         memcpy(&one->cdb_usage[1], entry->usage,
7625                             entry->length - 1);
7626                 } else
7627                         one->support = 1;
7628                 break;
7629         }
7630
7631         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7632         ctsio->be_move_done = ctl_config_move_done;
7633
7634         ctl_datamove((union ctl_io *)ctsio);
7635         return(retval);
7636 }
7637
7638 int
7639 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7640 {
7641         struct ctl_lun *lun;
7642         struct scsi_report_supported_tmf *cdb;
7643         struct scsi_report_supported_tmf_data *data;
7644         int retval;
7645         int alloc_len, total_len;
7646
7647         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7648
7649         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7650         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7651
7652         retval = CTL_RETVAL_COMPLETE;
7653
7654         total_len = sizeof(struct scsi_report_supported_tmf_data);
7655         alloc_len = scsi_4btoul(cdb->length);
7656
7657         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7658
7659         ctsio->kern_sg_entries = 0;
7660
7661         if (total_len < alloc_len) {
7662                 ctsio->residual = alloc_len - total_len;
7663                 ctsio->kern_data_len = total_len;
7664                 ctsio->kern_total_len = total_len;
7665         } else {
7666                 ctsio->residual = 0;
7667                 ctsio->kern_data_len = alloc_len;
7668                 ctsio->kern_total_len = alloc_len;
7669         }
7670         ctsio->kern_data_resid = 0;
7671         ctsio->kern_rel_offset = 0;
7672
7673         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7674         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7675         data->byte2 |= RST_ITNRS;
7676
7677         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7678         ctsio->be_move_done = ctl_config_move_done;
7679
7680         ctl_datamove((union ctl_io *)ctsio);
7681         return (retval);
7682 }
7683
7684 int
7685 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7686 {
7687         struct ctl_lun *lun;
7688         struct scsi_report_timestamp *cdb;
7689         struct scsi_report_timestamp_data *data;
7690         struct timeval tv;
7691         int64_t timestamp;
7692         int retval;
7693         int alloc_len, total_len;
7694
7695         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7696
7697         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7698         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7699
7700         retval = CTL_RETVAL_COMPLETE;
7701
7702         total_len = sizeof(struct scsi_report_timestamp_data);
7703         alloc_len = scsi_4btoul(cdb->length);
7704
7705         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7706
7707         ctsio->kern_sg_entries = 0;
7708
7709         if (total_len < alloc_len) {
7710                 ctsio->residual = alloc_len - total_len;
7711                 ctsio->kern_data_len = total_len;
7712                 ctsio->kern_total_len = total_len;
7713         } else {
7714                 ctsio->residual = 0;
7715                 ctsio->kern_data_len = alloc_len;
7716                 ctsio->kern_total_len = alloc_len;
7717         }
7718         ctsio->kern_data_resid = 0;
7719         ctsio->kern_rel_offset = 0;
7720
7721         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7722         scsi_ulto2b(sizeof(*data) - 2, data->length);
7723         data->origin = RTS_ORIG_OUTSIDE;
7724         getmicrotime(&tv);
7725         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7726         scsi_ulto4b(timestamp >> 16, data->timestamp);
7727         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7728
7729         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7730         ctsio->be_move_done = ctl_config_move_done;
7731
7732         ctl_datamove((union ctl_io *)ctsio);
7733         return (retval);
7734 }
7735
7736 int
7737 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7738 {
7739         struct scsi_per_res_in *cdb;
7740         int alloc_len, total_len = 0;
7741         /* struct scsi_per_res_in_rsrv in_data; */
7742         struct ctl_lun *lun;
7743         struct ctl_softc *softc;
7744
7745         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7746
7747         softc = control_softc;
7748
7749         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7750
7751         alloc_len = scsi_2btoul(cdb->length);
7752
7753         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7754
7755 retry:
7756         mtx_lock(&lun->lun_lock);
7757         switch (cdb->action) {
7758         case SPRI_RK: /* read keys */
7759                 total_len = sizeof(struct scsi_per_res_in_keys) +
7760                         lun->pr_key_count *
7761                         sizeof(struct scsi_per_res_key);
7762                 break;
7763         case SPRI_RR: /* read reservation */
7764                 if (lun->flags & CTL_LUN_PR_RESERVED)
7765                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7766                 else
7767                         total_len = sizeof(struct scsi_per_res_in_header);
7768                 break;
7769         case SPRI_RC: /* report capabilities */
7770                 total_len = sizeof(struct scsi_per_res_cap);
7771                 break;
7772         case SPRI_RS: /* read full status */
7773                 total_len = sizeof(struct scsi_per_res_in_header) +
7774                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7775                     lun->pr_key_count;
7776                 break;
7777         default:
7778                 panic("Invalid PR type %x", cdb->action);
7779         }
7780         mtx_unlock(&lun->lun_lock);
7781
7782         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7783
7784         if (total_len < alloc_len) {
7785                 ctsio->residual = alloc_len - total_len;
7786                 ctsio->kern_data_len = total_len;
7787                 ctsio->kern_total_len = total_len;
7788         } else {
7789                 ctsio->residual = 0;
7790                 ctsio->kern_data_len = alloc_len;
7791                 ctsio->kern_total_len = alloc_len;
7792         }
7793
7794         ctsio->kern_data_resid = 0;
7795         ctsio->kern_rel_offset = 0;
7796         ctsio->kern_sg_entries = 0;
7797
7798         mtx_lock(&lun->lun_lock);
7799         switch (cdb->action) {
7800         case SPRI_RK: { // read keys
7801         struct scsi_per_res_in_keys *res_keys;
7802                 int i, key_count;
7803
7804                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7805
7806                 /*
7807                  * We had to drop the lock to allocate our buffer, which
7808                  * leaves time for someone to come in with another
7809                  * persistent reservation.  (That is unlikely, though,
7810                  * since this should be the only persistent reservation
7811                  * command active right now.)
7812                  */
7813                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7814                     (lun->pr_key_count *
7815                      sizeof(struct scsi_per_res_key)))){
7816                         mtx_unlock(&lun->lun_lock);
7817                         free(ctsio->kern_data_ptr, M_CTL);
7818                         printf("%s: reservation length changed, retrying\n",
7819                                __func__);
7820                         goto retry;
7821                 }
7822
7823                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7824
7825                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7826                              lun->pr_key_count, res_keys->header.length);
7827
7828                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7829                         if (!lun->per_res[i].registered)
7830                                 continue;
7831
7832                         /*
7833                          * We used lun->pr_key_count to calculate the
7834                          * size to allocate.  If it turns out the number of
7835                          * initiators with the registered flag set is
7836                          * larger than that (i.e. they haven't been kept in
7837                          * sync), we've got a problem.
7838                          */
7839                         if (key_count >= lun->pr_key_count) {
7840 #ifdef NEEDTOPORT
7841                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7842                                             CTL_PR_ERROR,
7843                                             csevent_LogType_Fault,
7844                                             csevent_AlertLevel_Yellow,
7845                                             csevent_FRU_ShelfController,
7846                                             csevent_FRU_Firmware,
7847                                         csevent_FRU_Unknown,
7848                                             "registered keys %d >= key "
7849                                             "count %d", key_count,
7850                                             lun->pr_key_count);
7851 #endif
7852                                 key_count++;
7853                                 continue;
7854                         }
7855                         memcpy(res_keys->keys[key_count].key,
7856                                lun->per_res[i].res_key.key,
7857                                ctl_min(sizeof(res_keys->keys[key_count].key),
7858                                sizeof(lun->per_res[i].res_key)));
7859                         key_count++;
7860                 }
7861                 break;
7862         }
7863         case SPRI_RR: { // read reservation
7864                 struct scsi_per_res_in_rsrv *res;
7865                 int tmp_len, header_only;
7866
7867                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7868
7869                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7870
7871                 if (lun->flags & CTL_LUN_PR_RESERVED)
7872                 {
7873                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7874                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7875                                     res->header.length);
7876                         header_only = 0;
7877                 } else {
7878                         tmp_len = sizeof(struct scsi_per_res_in_header);
7879                         scsi_ulto4b(0, res->header.length);
7880                         header_only = 1;
7881                 }
7882
7883                 /*
7884                  * We had to drop the lock to allocate our buffer, which
7885                  * leaves time for someone to come in with another
7886                  * persistent reservation.  (That is unlikely, though,
7887                  * since this should be the only persistent reservation
7888                  * command active right now.)
7889                  */
7890                 if (tmp_len != total_len) {
7891                         mtx_unlock(&lun->lun_lock);
7892                         free(ctsio->kern_data_ptr, M_CTL);
7893                         printf("%s: reservation status changed, retrying\n",
7894                                __func__);
7895                         goto retry;
7896                 }
7897
7898                 /*
7899                  * No reservation held, so we're done.
7900                  */
7901                 if (header_only != 0)
7902                         break;
7903
7904                 /*
7905                  * If the registration is an All Registrants type, the key
7906                  * is 0, since it doesn't really matter.
7907                  */
7908                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7909                         memcpy(res->data.reservation,
7910                                &lun->per_res[lun->pr_res_idx].res_key,
7911                                sizeof(struct scsi_per_res_key));
7912                 }
7913                 res->data.scopetype = lun->res_type;
7914                 break;
7915         }
7916         case SPRI_RC:     //report capabilities
7917         {
7918                 struct scsi_per_res_cap *res_cap;
7919                 uint16_t type_mask;
7920
7921                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7922                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7923                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7924                 type_mask = SPRI_TM_WR_EX_AR |
7925                             SPRI_TM_EX_AC_RO |
7926                             SPRI_TM_WR_EX_RO |
7927                             SPRI_TM_EX_AC |
7928                             SPRI_TM_WR_EX |
7929                             SPRI_TM_EX_AC_AR;
7930                 scsi_ulto2b(type_mask, res_cap->type_mask);
7931                 break;
7932         }
7933         case SPRI_RS: { // read full status
7934                 struct scsi_per_res_in_full *res_status;
7935                 struct scsi_per_res_in_full_desc *res_desc;
7936                 struct ctl_port *port;
7937                 int i, len;
7938
7939                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7940
7941                 /*
7942                  * We had to drop the lock to allocate our buffer, which
7943                  * leaves time for someone to come in with another
7944                  * persistent reservation.  (That is unlikely, though,
7945                  * since this should be the only persistent reservation
7946                  * command active right now.)
7947                  */
7948                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7949                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7950                      lun->pr_key_count)){
7951                         mtx_unlock(&lun->lun_lock);
7952                         free(ctsio->kern_data_ptr, M_CTL);
7953                         printf("%s: reservation length changed, retrying\n",
7954                                __func__);
7955                         goto retry;
7956                 }
7957
7958                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7959
7960                 res_desc = &res_status->desc[0];
7961                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7962                         if (!lun->per_res[i].registered)
7963                                 continue;
7964
7965                         memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7966                             sizeof(res_desc->res_key));
7967                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7968                             (lun->pr_res_idx == i ||
7969                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7970                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7971                                 res_desc->scopetype = lun->res_type;
7972                         }
7973                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7974                             res_desc->rel_trgt_port_id);
7975                         len = 0;
7976                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7977                         if (port != NULL)
7978                                 len = ctl_create_iid(port,
7979                                     i % CTL_MAX_INIT_PER_PORT,
7980                                     res_desc->transport_id);
7981                         scsi_ulto4b(len, res_desc->additional_length);
7982                         res_desc = (struct scsi_per_res_in_full_desc *)
7983                             &res_desc->transport_id[len];
7984                 }
7985                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7986                     res_status->header.length);
7987                 break;
7988         }
7989         default:
7990                 /*
7991                  * This is a bug, because we just checked for this above,
7992                  * and should have returned an error.
7993                  */
7994                 panic("Invalid PR type %x", cdb->action);
7995                 break; /* NOTREACHED */
7996         }
7997         mtx_unlock(&lun->lun_lock);
7998
7999         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8000         ctsio->be_move_done = ctl_config_move_done;
8001
8002         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8003                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8004                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8005                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8006                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8007
8008         ctl_datamove((union ctl_io *)ctsio);
8009
8010         return (CTL_RETVAL_COMPLETE);
8011 }
8012
8013 /*
8014  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8015  * it should return.
8016  */
8017 static int
8018 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8019                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8020                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8021                 struct scsi_per_res_out_parms* param)
8022 {
8023         union ctl_ha_msg persis_io;
8024         int retval, i;
8025         int isc_retval;
8026
8027         retval = 0;
8028
8029         mtx_lock(&lun->lun_lock);
8030         if (sa_res_key == 0) {
8031                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8032                         /* validate scope and type */
8033                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8034                              SPR_LU_SCOPE) {
8035                                 mtx_unlock(&lun->lun_lock);
8036                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8037                                                       /*sks_valid*/ 1,
8038                                                       /*command*/ 1,
8039                                                       /*field*/ 2,
8040                                                       /*bit_valid*/ 1,
8041                                                       /*bit*/ 4);
8042                                 ctl_done((union ctl_io *)ctsio);
8043                                 return (1);
8044                         }
8045
8046                         if (type>8 || type==2 || type==4 || type==0) {
8047                                 mtx_unlock(&lun->lun_lock);
8048                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8049                                                       /*sks_valid*/ 1,
8050                                                       /*command*/ 1,
8051                                                       /*field*/ 2,
8052                                                       /*bit_valid*/ 1,
8053                                                       /*bit*/ 0);
8054                                 ctl_done((union ctl_io *)ctsio);
8055                                 return (1);
8056                         }
8057
8058                         /* temporarily unregister this nexus */
8059                         lun->per_res[residx].registered = 0;
8060
8061                         /*
8062                          * Unregister everybody else and build UA for
8063                          * them
8064                          */
8065                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8066                                 if (lun->per_res[i].registered == 0)
8067                                         continue;
8068
8069                                 if (!persis_offset
8070                                  && i <CTL_MAX_INITIATORS)
8071                                         lun->pending_ua[i] |=
8072                                                 CTL_UA_REG_PREEMPT;
8073                                 else if (persis_offset
8074                                       && i >= persis_offset)
8075                                         lun->pending_ua[i-persis_offset] |=
8076                                                 CTL_UA_REG_PREEMPT;
8077                                 lun->per_res[i].registered = 0;
8078                                 memset(&lun->per_res[i].res_key, 0,
8079                                        sizeof(struct scsi_per_res_key));
8080                         }
8081                         lun->per_res[residx].registered = 1;
8082                         lun->pr_key_count = 1;
8083                         lun->res_type = type;
8084                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8085                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8086                                 lun->pr_res_idx = residx;
8087
8088                         /* send msg to other side */
8089                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8090                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8091                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8092                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8093                         persis_io.pr.pr_info.res_type = type;
8094                         memcpy(persis_io.pr.pr_info.sa_res_key,
8095                                param->serv_act_res_key,
8096                                sizeof(param->serv_act_res_key));
8097                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8098                              &persis_io, sizeof(persis_io), 0)) >
8099                              CTL_HA_STATUS_SUCCESS) {
8100                                 printf("CTL:Persis Out error returned "
8101                                        "from ctl_ha_msg_send %d\n",
8102                                        isc_retval);
8103                         }
8104                 } else {
8105                         /* not all registrants */
8106                         mtx_unlock(&lun->lun_lock);
8107                         free(ctsio->kern_data_ptr, M_CTL);
8108                         ctl_set_invalid_field(ctsio,
8109                                               /*sks_valid*/ 1,
8110                                               /*command*/ 0,
8111                                               /*field*/ 8,
8112                                               /*bit_valid*/ 0,
8113                                               /*bit*/ 0);
8114                         ctl_done((union ctl_io *)ctsio);
8115                         return (1);
8116                 }
8117         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8118                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8119                 int found = 0;
8120
8121                 if (res_key == sa_res_key) {
8122                         /* special case */
8123                         /*
8124                          * The spec implies this is not good but doesn't
8125                          * say what to do. There are two choices either
8126                          * generate a res conflict or check condition
8127                          * with illegal field in parameter data. Since
8128                          * that is what is done when the sa_res_key is
8129                          * zero I'll take that approach since this has
8130                          * to do with the sa_res_key.
8131                          */
8132                         mtx_unlock(&lun->lun_lock);
8133                         free(ctsio->kern_data_ptr, M_CTL);
8134                         ctl_set_invalid_field(ctsio,
8135                                               /*sks_valid*/ 1,
8136                                               /*command*/ 0,
8137                                               /*field*/ 8,
8138                                               /*bit_valid*/ 0,
8139                                               /*bit*/ 0);
8140                         ctl_done((union ctl_io *)ctsio);
8141                         return (1);
8142                 }
8143
8144                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8145                         if (lun->per_res[i].registered
8146                          && memcmp(param->serv_act_res_key,
8147                             lun->per_res[i].res_key.key,
8148                             sizeof(struct scsi_per_res_key)) != 0)
8149                                 continue;
8150
8151                         found = 1;
8152                         lun->per_res[i].registered = 0;
8153                         memset(&lun->per_res[i].res_key, 0,
8154                                sizeof(struct scsi_per_res_key));
8155                         lun->pr_key_count--;
8156
8157                         if (!persis_offset && i < CTL_MAX_INITIATORS)
8158                                 lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8159                         else if (persis_offset && i >= persis_offset)
8160                                 lun->pending_ua[i-persis_offset] |=
8161                                         CTL_UA_REG_PREEMPT;
8162                 }
8163                 if (!found) {
8164                         mtx_unlock(&lun->lun_lock);
8165                         free(ctsio->kern_data_ptr, M_CTL);
8166                         ctl_set_reservation_conflict(ctsio);
8167                         ctl_done((union ctl_io *)ctsio);
8168                         return (CTL_RETVAL_COMPLETE);
8169                 }
8170                 /* send msg to other side */
8171                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8172                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8173                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8174                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8175                 persis_io.pr.pr_info.res_type = type;
8176                 memcpy(persis_io.pr.pr_info.sa_res_key,
8177                        param->serv_act_res_key,
8178                        sizeof(param->serv_act_res_key));
8179                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8180                      &persis_io, sizeof(persis_io), 0)) >
8181                      CTL_HA_STATUS_SUCCESS) {
8182                         printf("CTL:Persis Out error returned from "
8183                                "ctl_ha_msg_send %d\n", isc_retval);
8184                 }
8185         } else {
8186                 /* Reserved but not all registrants */
8187                 /* sa_res_key is res holder */
8188                 if (memcmp(param->serv_act_res_key,
8189                    lun->per_res[lun->pr_res_idx].res_key.key,
8190                    sizeof(struct scsi_per_res_key)) == 0) {
8191                         /* validate scope and type */
8192                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8193                              SPR_LU_SCOPE) {
8194                                 mtx_unlock(&lun->lun_lock);
8195                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8196                                                       /*sks_valid*/ 1,
8197                                                       /*command*/ 1,
8198                                                       /*field*/ 2,
8199                                                       /*bit_valid*/ 1,
8200                                                       /*bit*/ 4);
8201                                 ctl_done((union ctl_io *)ctsio);
8202                                 return (1);
8203                         }
8204
8205                         if (type>8 || type==2 || type==4 || type==0) {
8206                                 mtx_unlock(&lun->lun_lock);
8207                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8208                                                       /*sks_valid*/ 1,
8209                                                       /*command*/ 1,
8210                                                       /*field*/ 2,
8211                                                       /*bit_valid*/ 1,
8212                                                       /*bit*/ 0);
8213                                 ctl_done((union ctl_io *)ctsio);
8214                                 return (1);
8215                         }
8216
8217                         /*
8218                          * Do the following:
8219                          * if sa_res_key != res_key remove all
8220                          * registrants w/sa_res_key and generate UA
8221                          * for these registrants(Registrations
8222                          * Preempted) if it wasn't an exclusive
8223                          * reservation generate UA(Reservations
8224                          * Preempted) for all other registered nexuses
8225                          * if the type has changed. Establish the new
8226                          * reservation and holder. If res_key and
8227                          * sa_res_key are the same do the above
8228                          * except don't unregister the res holder.
8229                          */
8230
8231                         /*
8232                          * Temporarily unregister so it won't get
8233                          * removed or UA generated
8234                          */
8235                         lun->per_res[residx].registered = 0;
8236                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8237                                 if (lun->per_res[i].registered == 0)
8238                                         continue;
8239
8240                                 if (memcmp(param->serv_act_res_key,
8241                                     lun->per_res[i].res_key.key,
8242                                     sizeof(struct scsi_per_res_key)) == 0) {
8243                                         lun->per_res[i].registered = 0;
8244                                         memset(&lun->per_res[i].res_key,
8245                                                0,
8246                                                sizeof(struct scsi_per_res_key));
8247                                         lun->pr_key_count--;
8248
8249                                         if (!persis_offset
8250                                          && i < CTL_MAX_INITIATORS)
8251                                                 lun->pending_ua[i] |=
8252                                                         CTL_UA_REG_PREEMPT;
8253                                         else if (persis_offset
8254                                               && i >= persis_offset)
8255                                                 lun->pending_ua[i-persis_offset] |=
8256                                                   CTL_UA_REG_PREEMPT;
8257                                 } else if (type != lun->res_type
8258                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8259                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8260                                                 if (!persis_offset
8261                                                  && i < CTL_MAX_INITIATORS)
8262                                                         lun->pending_ua[i] |=
8263                                                         CTL_UA_RES_RELEASE;
8264                                                 else if (persis_offset
8265                                                       && i >= persis_offset)
8266                                                         lun->pending_ua[
8267                                                         i-persis_offset] |=
8268                                                         CTL_UA_RES_RELEASE;
8269                                 }
8270                         }
8271                         lun->per_res[residx].registered = 1;
8272                         lun->res_type = type;
8273                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8274                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8275                                 lun->pr_res_idx = residx;
8276                         else
8277                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8278
8279                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8280                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8281                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8282                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8283                         persis_io.pr.pr_info.res_type = type;
8284                         memcpy(persis_io.pr.pr_info.sa_res_key,
8285                                param->serv_act_res_key,
8286                                sizeof(param->serv_act_res_key));
8287                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8288                              &persis_io, sizeof(persis_io), 0)) >
8289                              CTL_HA_STATUS_SUCCESS) {
8290                                 printf("CTL:Persis Out error returned "
8291                                        "from ctl_ha_msg_send %d\n",
8292                                        isc_retval);
8293                         }
8294                 } else {
8295                         /*
8296                          * sa_res_key is not the res holder just
8297                          * remove registrants
8298                          */
8299                         int found=0;
8300
8301                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8302                                 if (memcmp(param->serv_act_res_key,
8303                                     lun->per_res[i].res_key.key,
8304                                     sizeof(struct scsi_per_res_key)) != 0)
8305                                         continue;
8306
8307                                 found = 1;
8308                                 lun->per_res[i].registered = 0;
8309                                 memset(&lun->per_res[i].res_key, 0,
8310                                        sizeof(struct scsi_per_res_key));
8311                                 lun->pr_key_count--;
8312
8313                                 if (!persis_offset
8314                                  && i < CTL_MAX_INITIATORS)
8315                                         lun->pending_ua[i] |=
8316                                                 CTL_UA_REG_PREEMPT;
8317                                 else if (persis_offset
8318                                       && i >= persis_offset)
8319                                         lun->pending_ua[i-persis_offset] |=
8320                                                 CTL_UA_REG_PREEMPT;
8321                         }
8322
8323                         if (!found) {
8324                                 mtx_unlock(&lun->lun_lock);
8325                                 free(ctsio->kern_data_ptr, M_CTL);
8326                                 ctl_set_reservation_conflict(ctsio);
8327                                 ctl_done((union ctl_io *)ctsio);
8328                                 return (1);
8329                         }
8330                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8331                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8332                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8333                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8334                         persis_io.pr.pr_info.res_type = type;
8335                         memcpy(persis_io.pr.pr_info.sa_res_key,
8336                                param->serv_act_res_key,
8337                                sizeof(param->serv_act_res_key));
8338                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8339                              &persis_io, sizeof(persis_io), 0)) >
8340                              CTL_HA_STATUS_SUCCESS) {
8341                                 printf("CTL:Persis Out error returned "
8342                                        "from ctl_ha_msg_send %d\n",
8343                                 isc_retval);
8344                         }
8345                 }
8346         }
8347
8348         lun->PRGeneration++;
8349         mtx_unlock(&lun->lun_lock);
8350
8351         return (retval);
8352 }
8353
8354 static void
8355 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8356 {
8357         int i;
8358
8359         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8360          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8361          || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8362                    msg->pr.pr_info.sa_res_key,
8363                    sizeof(struct scsi_per_res_key)) != 0) {
8364                 uint64_t sa_res_key;
8365                 sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8366
8367                 if (sa_res_key == 0) {
8368                         /* temporarily unregister this nexus */
8369                         lun->per_res[msg->pr.pr_info.residx].registered = 0;
8370
8371                         /*
8372                          * Unregister everybody else and build UA for
8373                          * them
8374                          */
8375                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8376                                 if (lun->per_res[i].registered == 0)
8377                                         continue;
8378
8379                                 if (!persis_offset
8380                                  && i < CTL_MAX_INITIATORS)
8381                                         lun->pending_ua[i] |=
8382                                                 CTL_UA_REG_PREEMPT;
8383                                 else if (persis_offset && i >= persis_offset)
8384                                         lun->pending_ua[i - persis_offset] |=
8385                                                 CTL_UA_REG_PREEMPT;
8386                                 lun->per_res[i].registered = 0;
8387                                 memset(&lun->per_res[i].res_key, 0,
8388                                        sizeof(struct scsi_per_res_key));
8389                         }
8390
8391                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8392                         lun->pr_key_count = 1;
8393                         lun->res_type = msg->pr.pr_info.res_type;
8394                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8395                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8396                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8397                 } else {
8398                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8399                                 if (memcmp(msg->pr.pr_info.sa_res_key,
8400                                    lun->per_res[i].res_key.key,
8401                                    sizeof(struct scsi_per_res_key)) != 0)
8402                                         continue;
8403
8404                                 lun->per_res[i].registered = 0;
8405                                 memset(&lun->per_res[i].res_key, 0,
8406                                        sizeof(struct scsi_per_res_key));
8407                                 lun->pr_key_count--;
8408
8409                                 if (!persis_offset
8410                                  && i < persis_offset)
8411                                         lun->pending_ua[i] |=
8412                                                 CTL_UA_REG_PREEMPT;
8413                                 else if (persis_offset
8414                                       && i >= persis_offset)
8415                                         lun->pending_ua[i - persis_offset] |=
8416                                                 CTL_UA_REG_PREEMPT;
8417                         }
8418                 }
8419         } else {
8420                 /*
8421                  * Temporarily unregister so it won't get removed
8422                  * or UA generated
8423                  */
8424                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8425                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8426                         if (lun->per_res[i].registered == 0)
8427                                 continue;
8428
8429                         if (memcmp(msg->pr.pr_info.sa_res_key,
8430                            lun->per_res[i].res_key.key,
8431                            sizeof(struct scsi_per_res_key)) == 0) {
8432                                 lun->per_res[i].registered = 0;
8433                                 memset(&lun->per_res[i].res_key, 0,
8434                                        sizeof(struct scsi_per_res_key));
8435                                 lun->pr_key_count--;
8436                                 if (!persis_offset
8437                                  && i < CTL_MAX_INITIATORS)
8438                                         lun->pending_ua[i] |=
8439                                                 CTL_UA_REG_PREEMPT;
8440                                 else if (persis_offset
8441                                       && i >= persis_offset)
8442                                         lun->pending_ua[i - persis_offset] |=
8443                                                 CTL_UA_REG_PREEMPT;
8444                         } else if (msg->pr.pr_info.res_type != lun->res_type
8445                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8446                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8447                                         if (!persis_offset
8448                                          && i < persis_offset)
8449                                                 lun->pending_ua[i] |=
8450                                                         CTL_UA_RES_RELEASE;
8451                                         else if (persis_offset
8452                                               && i >= persis_offset)
8453                                         lun->pending_ua[i - persis_offset] |=
8454                                                 CTL_UA_RES_RELEASE;
8455                         }
8456                 }
8457                 lun->per_res[msg->pr.pr_info.residx].registered = 1;
8458                 lun->res_type = msg->pr.pr_info.res_type;
8459                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8460                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8461                         lun->pr_res_idx = msg->pr.pr_info.residx;
8462                 else
8463                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8464         }
8465         lun->PRGeneration++;
8466
8467 }
8468
8469
8470 int
8471 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8472 {
8473         int retval;
8474         int isc_retval;
8475         u_int32_t param_len;
8476         struct scsi_per_res_out *cdb;
8477         struct ctl_lun *lun;
8478         struct scsi_per_res_out_parms* param;
8479         struct ctl_softc *softc;
8480         uint32_t residx;
8481         uint64_t res_key, sa_res_key;
8482         uint8_t type;
8483         union ctl_ha_msg persis_io;
8484         int    i;
8485
8486         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8487
8488         retval = CTL_RETVAL_COMPLETE;
8489
8490         softc = control_softc;
8491
8492         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8493         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8494
8495         /*
8496          * We only support whole-LUN scope.  The scope & type are ignored for
8497          * register, register and ignore existing key and clear.
8498          * We sometimes ignore scope and type on preempts too!!
8499          * Verify reservation type here as well.
8500          */
8501         type = cdb->scope_type & SPR_TYPE_MASK;
8502         if ((cdb->action == SPRO_RESERVE)
8503          || (cdb->action == SPRO_RELEASE)) {
8504                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8505                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8506                                               /*sks_valid*/ 1,
8507                                               /*command*/ 1,
8508                                               /*field*/ 2,
8509                                               /*bit_valid*/ 1,
8510                                               /*bit*/ 4);
8511                         ctl_done((union ctl_io *)ctsio);
8512                         return (CTL_RETVAL_COMPLETE);
8513                 }
8514
8515                 if (type>8 || type==2 || type==4 || type==0) {
8516                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8517                                               /*sks_valid*/ 1,
8518                                               /*command*/ 1,
8519                                               /*field*/ 2,
8520                                               /*bit_valid*/ 1,
8521                                               /*bit*/ 0);
8522                         ctl_done((union ctl_io *)ctsio);
8523                         return (CTL_RETVAL_COMPLETE);
8524                 }
8525         }
8526
8527         param_len = scsi_4btoul(cdb->length);
8528
8529         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8530                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8531                 ctsio->kern_data_len = param_len;
8532                 ctsio->kern_total_len = param_len;
8533                 ctsio->kern_data_resid = 0;
8534                 ctsio->kern_rel_offset = 0;
8535                 ctsio->kern_sg_entries = 0;
8536                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8537                 ctsio->be_move_done = ctl_config_move_done;
8538                 ctl_datamove((union ctl_io *)ctsio);
8539
8540                 return (CTL_RETVAL_COMPLETE);
8541         }
8542
8543         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8544
8545         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8546         res_key = scsi_8btou64(param->res_key.key);
8547         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8548
8549         /*
8550          * Validate the reservation key here except for SPRO_REG_IGNO
8551          * This must be done for all other service actions
8552          */
8553         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8554                 mtx_lock(&lun->lun_lock);
8555                 if (lun->per_res[residx].registered) {
8556                     if (memcmp(param->res_key.key,
8557                                lun->per_res[residx].res_key.key,
8558                                ctl_min(sizeof(param->res_key),
8559                                sizeof(lun->per_res[residx].res_key))) != 0) {
8560                                 /*
8561                                  * The current key passed in doesn't match
8562                                  * the one the initiator previously
8563                                  * registered.
8564                                  */
8565                                 mtx_unlock(&lun->lun_lock);
8566                                 free(ctsio->kern_data_ptr, M_CTL);
8567                                 ctl_set_reservation_conflict(ctsio);
8568                                 ctl_done((union ctl_io *)ctsio);
8569                                 return (CTL_RETVAL_COMPLETE);
8570                         }
8571                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8572                         /*
8573                          * We are not registered
8574                          */
8575                         mtx_unlock(&lun->lun_lock);
8576                         free(ctsio->kern_data_ptr, M_CTL);
8577                         ctl_set_reservation_conflict(ctsio);
8578                         ctl_done((union ctl_io *)ctsio);
8579                         return (CTL_RETVAL_COMPLETE);
8580                 } else if (res_key != 0) {
8581                         /*
8582                          * We are not registered and trying to register but
8583                          * the register key isn't zero.
8584                          */
8585                         mtx_unlock(&lun->lun_lock);
8586                         free(ctsio->kern_data_ptr, M_CTL);
8587                         ctl_set_reservation_conflict(ctsio);
8588                         ctl_done((union ctl_io *)ctsio);
8589                         return (CTL_RETVAL_COMPLETE);
8590                 }
8591                 mtx_unlock(&lun->lun_lock);
8592         }
8593
8594         switch (cdb->action & SPRO_ACTION_MASK) {
8595         case SPRO_REGISTER:
8596         case SPRO_REG_IGNO: {
8597
8598 #if 0
8599                 printf("Registration received\n");
8600 #endif
8601
8602                 /*
8603                  * We don't support any of these options, as we report in
8604                  * the read capabilities request (see
8605                  * ctl_persistent_reserve_in(), above).
8606                  */
8607                 if ((param->flags & SPR_SPEC_I_PT)
8608                  || (param->flags & SPR_ALL_TG_PT)
8609                  || (param->flags & SPR_APTPL)) {
8610                         int bit_ptr;
8611
8612                         if (param->flags & SPR_APTPL)
8613                                 bit_ptr = 0;
8614                         else if (param->flags & SPR_ALL_TG_PT)
8615                                 bit_ptr = 2;
8616                         else /* SPR_SPEC_I_PT */
8617                                 bit_ptr = 3;
8618
8619                         free(ctsio->kern_data_ptr, M_CTL);
8620                         ctl_set_invalid_field(ctsio,
8621                                               /*sks_valid*/ 1,
8622                                               /*command*/ 0,
8623                                               /*field*/ 20,
8624                                               /*bit_valid*/ 1,
8625                                               /*bit*/ bit_ptr);
8626                         ctl_done((union ctl_io *)ctsio);
8627                         return (CTL_RETVAL_COMPLETE);
8628                 }
8629
8630                 mtx_lock(&lun->lun_lock);
8631
8632                 /*
8633                  * The initiator wants to clear the
8634                  * key/unregister.
8635                  */
8636                 if (sa_res_key == 0) {
8637                         if ((res_key == 0
8638                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8639                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8640                           && !lun->per_res[residx].registered)) {
8641                                 mtx_unlock(&lun->lun_lock);
8642                                 goto done;
8643                         }
8644
8645                         lun->per_res[residx].registered = 0;
8646                         memset(&lun->per_res[residx].res_key,
8647                                0, sizeof(lun->per_res[residx].res_key));
8648                         lun->pr_key_count--;
8649
8650                         if (residx == lun->pr_res_idx) {
8651                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8652                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8653
8654                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8655                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8656                                  && lun->pr_key_count) {
8657                                         /*
8658                                          * If the reservation is a registrants
8659                                          * only type we need to generate a UA
8660                                          * for other registered inits.  The
8661                                          * sense code should be RESERVATIONS
8662                                          * RELEASED
8663                                          */
8664
8665                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8666                                                 if (lun->per_res[
8667                                                     i+persis_offset].registered
8668                                                     == 0)
8669                                                         continue;
8670                                                 lun->pending_ua[i] |=
8671                                                         CTL_UA_RES_RELEASE;
8672                                         }
8673                                 }
8674                                 lun->res_type = 0;
8675                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8676                                 if (lun->pr_key_count==0) {
8677                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8678                                         lun->res_type = 0;
8679                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8680                                 }
8681                         }
8682                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8683                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8684                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8685                         persis_io.pr.pr_info.residx = residx;
8686                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8687                              &persis_io, sizeof(persis_io), 0 )) >
8688                              CTL_HA_STATUS_SUCCESS) {
8689                                 printf("CTL:Persis Out error returned from "
8690                                        "ctl_ha_msg_send %d\n", isc_retval);
8691                         }
8692                 } else /* sa_res_key != 0 */ {
8693
8694                         /*
8695                          * If we aren't registered currently then increment
8696                          * the key count and set the registered flag.
8697                          */
8698                         if (!lun->per_res[residx].registered) {
8699                                 lun->pr_key_count++;
8700                                 lun->per_res[residx].registered = 1;
8701                         }
8702
8703                         memcpy(&lun->per_res[residx].res_key,
8704                                param->serv_act_res_key,
8705                                ctl_min(sizeof(param->serv_act_res_key),
8706                                sizeof(lun->per_res[residx].res_key)));
8707
8708                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8709                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8710                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8711                         persis_io.pr.pr_info.residx = residx;
8712                         memcpy(persis_io.pr.pr_info.sa_res_key,
8713                                param->serv_act_res_key,
8714                                sizeof(param->serv_act_res_key));
8715                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8716                              &persis_io, sizeof(persis_io), 0)) >
8717                              CTL_HA_STATUS_SUCCESS) {
8718                                 printf("CTL:Persis Out error returned from "
8719                                        "ctl_ha_msg_send %d\n", isc_retval);
8720                         }
8721                 }
8722                 lun->PRGeneration++;
8723                 mtx_unlock(&lun->lun_lock);
8724
8725                 break;
8726         }
8727         case SPRO_RESERVE:
8728 #if 0
8729                 printf("Reserve executed type %d\n", type);
8730 #endif
8731                 mtx_lock(&lun->lun_lock);
8732                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8733                         /*
8734                          * if this isn't the reservation holder and it's
8735                          * not a "all registrants" type or if the type is
8736                          * different then we have a conflict
8737                          */
8738                         if ((lun->pr_res_idx != residx
8739                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8740                          || lun->res_type != type) {
8741                                 mtx_unlock(&lun->lun_lock);
8742                                 free(ctsio->kern_data_ptr, M_CTL);
8743                                 ctl_set_reservation_conflict(ctsio);
8744                                 ctl_done((union ctl_io *)ctsio);
8745                                 return (CTL_RETVAL_COMPLETE);
8746                         }
8747                         mtx_unlock(&lun->lun_lock);
8748                 } else /* create a reservation */ {
8749                         /*
8750                          * If it's not an "all registrants" type record
8751                          * reservation holder
8752                          */
8753                         if (type != SPR_TYPE_WR_EX_AR
8754                          && type != SPR_TYPE_EX_AC_AR)
8755                                 lun->pr_res_idx = residx; /* Res holder */
8756                         else
8757                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8758
8759                         lun->flags |= CTL_LUN_PR_RESERVED;
8760                         lun->res_type = type;
8761
8762                         mtx_unlock(&lun->lun_lock);
8763
8764                         /* send msg to other side */
8765                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8766                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8767                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8768                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8769                         persis_io.pr.pr_info.res_type = type;
8770                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8771                              &persis_io, sizeof(persis_io), 0)) >
8772                              CTL_HA_STATUS_SUCCESS) {
8773                                 printf("CTL:Persis Out error returned from "
8774                                        "ctl_ha_msg_send %d\n", isc_retval);
8775                         }
8776                 }
8777                 break;
8778
8779         case SPRO_RELEASE:
8780                 mtx_lock(&lun->lun_lock);
8781                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8782                         /* No reservation exists return good status */
8783                         mtx_unlock(&lun->lun_lock);
8784                         goto done;
8785                 }
8786                 /*
8787                  * Is this nexus a reservation holder?
8788                  */
8789                 if (lun->pr_res_idx != residx
8790                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8791                         /*
8792                          * not a res holder return good status but
8793                          * do nothing
8794                          */
8795                         mtx_unlock(&lun->lun_lock);
8796                         goto done;
8797                 }
8798
8799                 if (lun->res_type != type) {
8800                         mtx_unlock(&lun->lun_lock);
8801                         free(ctsio->kern_data_ptr, M_CTL);
8802                         ctl_set_illegal_pr_release(ctsio);
8803                         ctl_done((union ctl_io *)ctsio);
8804                         return (CTL_RETVAL_COMPLETE);
8805                 }
8806
8807                 /* okay to release */
8808                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8809                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8810                 lun->res_type = 0;
8811
8812                 /*
8813                  * if this isn't an exclusive access
8814                  * res generate UA for all other
8815                  * registrants.
8816                  */
8817                 if (type != SPR_TYPE_EX_AC
8818                  && type != SPR_TYPE_WR_EX) {
8819                         /*
8820                          * temporarily unregister so we don't generate UA
8821                          */
8822                         lun->per_res[residx].registered = 0;
8823
8824                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8825                                 if (lun->per_res[i+persis_offset].registered
8826                                     == 0)
8827                                         continue;
8828                                 lun->pending_ua[i] |=
8829                                         CTL_UA_RES_RELEASE;
8830                         }
8831
8832                         lun->per_res[residx].registered = 1;
8833                 }
8834                 mtx_unlock(&lun->lun_lock);
8835                 /* Send msg to other side */
8836                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8837                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8838                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8839                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8840                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8841                         printf("CTL:Persis Out error returned from "
8842                                "ctl_ha_msg_send %d\n", isc_retval);
8843                 }
8844                 break;
8845
8846         case SPRO_CLEAR:
8847                 /* send msg to other side */
8848
8849                 mtx_lock(&lun->lun_lock);
8850                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8851                 lun->res_type = 0;
8852                 lun->pr_key_count = 0;
8853                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8854
8855
8856                 memset(&lun->per_res[residx].res_key,
8857                        0, sizeof(lun->per_res[residx].res_key));
8858                 lun->per_res[residx].registered = 0;
8859
8860                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8861                         if (lun->per_res[i].registered) {
8862                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8863                                         lun->pending_ua[i] |=
8864                                                 CTL_UA_RES_PREEMPT;
8865                                 else if (persis_offset && i >= persis_offset)
8866                                         lun->pending_ua[i-persis_offset] |=
8867                                             CTL_UA_RES_PREEMPT;
8868
8869                                 memset(&lun->per_res[i].res_key,
8870                                        0, sizeof(struct scsi_per_res_key));
8871                                 lun->per_res[i].registered = 0;
8872                         }
8873                 lun->PRGeneration++;
8874                 mtx_unlock(&lun->lun_lock);
8875                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8876                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8877                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8878                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8879                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8880                         printf("CTL:Persis Out error returned from "
8881                                "ctl_ha_msg_send %d\n", isc_retval);
8882                 }
8883                 break;
8884
8885         case SPRO_PREEMPT: {
8886                 int nretval;
8887
8888                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8889                                           residx, ctsio, cdb, param);
8890                 if (nretval != 0)
8891                         return (CTL_RETVAL_COMPLETE);
8892                 break;
8893         }
8894         default:
8895                 panic("Invalid PR type %x", cdb->action);
8896         }
8897
8898 done:
8899         free(ctsio->kern_data_ptr, M_CTL);
8900         ctl_set_success(ctsio);
8901         ctl_done((union ctl_io *)ctsio);
8902
8903         return (retval);
8904 }
8905
8906 /*
8907  * This routine is for handling a message from the other SC pertaining to
8908  * persistent reserve out. All the error checking will have been done
8909  * so only perorming the action need be done here to keep the two
8910  * in sync.
8911  */
8912 static void
8913 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8914 {
8915         struct ctl_lun *lun;
8916         struct ctl_softc *softc;
8917         int i;
8918         uint32_t targ_lun;
8919
8920         softc = control_softc;
8921
8922         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8923         lun = softc->ctl_luns[targ_lun];
8924         mtx_lock(&lun->lun_lock);
8925         switch(msg->pr.pr_info.action) {
8926         case CTL_PR_REG_KEY:
8927                 if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8928                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8929                         lun->pr_key_count++;
8930                 }
8931                 lun->PRGeneration++;
8932                 memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8933                        msg->pr.pr_info.sa_res_key,
8934                        sizeof(struct scsi_per_res_key));
8935                 break;
8936
8937         case CTL_PR_UNREG_KEY:
8938                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8939                 memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8940                        0, sizeof(struct scsi_per_res_key));
8941                 lun->pr_key_count--;
8942
8943                 /* XXX Need to see if the reservation has been released */
8944                 /* if so do we need to generate UA? */
8945                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8946                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8947                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8948
8949                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8950                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8951                          && lun->pr_key_count) {
8952                                 /*
8953                                  * If the reservation is a registrants
8954                                  * only type we need to generate a UA
8955                                  * for other registered inits.  The
8956                                  * sense code should be RESERVATIONS
8957                                  * RELEASED
8958                                  */
8959
8960                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8961                                         if (lun->per_res[i+
8962                                             persis_offset].registered == 0)
8963                                                 continue;
8964
8965                                         lun->pending_ua[i] |=
8966                                                 CTL_UA_RES_RELEASE;
8967                                 }
8968                         }
8969                         lun->res_type = 0;
8970                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8971                         if (lun->pr_key_count==0) {
8972                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8973                                 lun->res_type = 0;
8974                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8975                         }
8976                 }
8977                 lun->PRGeneration++;
8978                 break;
8979
8980         case CTL_PR_RESERVE:
8981                 lun->flags |= CTL_LUN_PR_RESERVED;
8982                 lun->res_type = msg->pr.pr_info.res_type;
8983                 lun->pr_res_idx = msg->pr.pr_info.residx;
8984
8985                 break;
8986
8987         case CTL_PR_RELEASE:
8988                 /*
8989                  * if this isn't an exclusive access res generate UA for all
8990                  * other registrants.
8991                  */
8992                 if (lun->res_type != SPR_TYPE_EX_AC
8993                  && lun->res_type != SPR_TYPE_WR_EX) {
8994                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8995                                 if (lun->per_res[i+persis_offset].registered)
8996                                         lun->pending_ua[i] |=
8997                                                 CTL_UA_RES_RELEASE;
8998                 }
8999
9000                 lun->flags &= ~CTL_LUN_PR_RESERVED;
9001                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9002                 lun->res_type = 0;
9003                 break;
9004
9005         case CTL_PR_PREEMPT:
9006                 ctl_pro_preempt_other(lun, msg);
9007                 break;
9008         case CTL_PR_CLEAR:
9009                 lun->flags &= ~CTL_LUN_PR_RESERVED;
9010                 lun->res_type = 0;
9011                 lun->pr_key_count = 0;
9012                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9013
9014                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9015                         if (lun->per_res[i].registered == 0)
9016                                 continue;
9017                         if (!persis_offset
9018                          && i < CTL_MAX_INITIATORS)
9019                                 lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9020                         else if (persis_offset
9021                               && i >= persis_offset)
9022                                 lun->pending_ua[i-persis_offset] |=
9023                                         CTL_UA_RES_PREEMPT;
9024                         memset(&lun->per_res[i].res_key, 0,
9025                                sizeof(struct scsi_per_res_key));
9026                         lun->per_res[i].registered = 0;
9027                 }
9028                 lun->PRGeneration++;
9029                 break;
9030         }
9031
9032         mtx_unlock(&lun->lun_lock);
9033 }
9034
9035 int
9036 ctl_read_write(struct ctl_scsiio *ctsio)
9037 {
9038         struct ctl_lun *lun;
9039         struct ctl_lba_len_flags *lbalen;
9040         uint64_t lba;
9041         uint32_t num_blocks;
9042         int flags, retval;
9043         int isread;
9044
9045         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9046
9047         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9048
9049         flags = 0;
9050         retval = CTL_RETVAL_COMPLETE;
9051
9052         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9053               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9054         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9055                 uint32_t residx;
9056
9057                 /*
9058                  * XXX KDM need a lock here.
9059                  */
9060                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9061                 if ((lun->res_type == SPR_TYPE_EX_AC
9062                   && residx != lun->pr_res_idx)
9063                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
9064                    || lun->res_type == SPR_TYPE_EX_AC_AR)
9065                   && !lun->per_res[residx].registered)) {
9066                         ctl_set_reservation_conflict(ctsio);
9067                         ctl_done((union ctl_io *)ctsio);
9068                         return (CTL_RETVAL_COMPLETE);
9069                 }
9070         }
9071
9072         switch (ctsio->cdb[0]) {
9073         case READ_6:
9074         case WRITE_6: {
9075                 struct scsi_rw_6 *cdb;
9076
9077                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
9078
9079                 lba = scsi_3btoul(cdb->addr);
9080                 /* only 5 bits are valid in the most significant address byte */
9081                 lba &= 0x1fffff;
9082                 num_blocks = cdb->length;
9083                 /*
9084                  * This is correct according to SBC-2.
9085                  */
9086                 if (num_blocks == 0)
9087                         num_blocks = 256;
9088                 break;
9089         }
9090         case READ_10:
9091         case WRITE_10: {
9092                 struct scsi_rw_10 *cdb;
9093
9094                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9095                 if (cdb->byte2 & SRW10_FUA)
9096                         flags |= CTL_LLF_FUA;
9097                 if (cdb->byte2 & SRW10_DPO)
9098                         flags |= CTL_LLF_DPO;
9099                 lba = scsi_4btoul(cdb->addr);
9100                 num_blocks = scsi_2btoul(cdb->length);
9101                 break;
9102         }
9103         case WRITE_VERIFY_10: {
9104                 struct scsi_write_verify_10 *cdb;
9105
9106                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9107                 flags |= CTL_LLF_FUA;
9108                 if (cdb->byte2 & SWV_DPO)
9109                         flags |= CTL_LLF_DPO;
9110                 lba = scsi_4btoul(cdb->addr);
9111                 num_blocks = scsi_2btoul(cdb->length);
9112                 break;
9113         }
9114         case READ_12:
9115         case WRITE_12: {
9116                 struct scsi_rw_12 *cdb;
9117
9118                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9119                 if (cdb->byte2 & SRW12_FUA)
9120                         flags |= CTL_LLF_FUA;
9121                 if (cdb->byte2 & SRW12_DPO)
9122                         flags |= CTL_LLF_DPO;
9123                 lba = scsi_4btoul(cdb->addr);
9124                 num_blocks = scsi_4btoul(cdb->length);
9125                 break;
9126         }
9127         case WRITE_VERIFY_12: {
9128                 struct scsi_write_verify_12 *cdb;
9129
9130                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9131                 flags |= CTL_LLF_FUA;
9132                 if (cdb->byte2 & SWV_DPO)
9133                         flags |= CTL_LLF_DPO;
9134                 lba = scsi_4btoul(cdb->addr);
9135                 num_blocks = scsi_4btoul(cdb->length);
9136                 break;
9137         }
9138         case READ_16:
9139         case WRITE_16: {
9140                 struct scsi_rw_16 *cdb;
9141
9142                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9143                 if (cdb->byte2 & SRW12_FUA)
9144                         flags |= CTL_LLF_FUA;
9145                 if (cdb->byte2 & SRW12_DPO)
9146                         flags |= CTL_LLF_DPO;
9147                 lba = scsi_8btou64(cdb->addr);
9148                 num_blocks = scsi_4btoul(cdb->length);
9149                 break;
9150         }
9151         case WRITE_VERIFY_16: {
9152                 struct scsi_write_verify_16 *cdb;
9153
9154                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9155                 flags |= CTL_LLF_FUA;
9156                 if (cdb->byte2 & SWV_DPO)
9157                         flags |= CTL_LLF_DPO;
9158                 lba = scsi_8btou64(cdb->addr);
9159                 num_blocks = scsi_4btoul(cdb->length);
9160                 break;
9161         }
9162         default:
9163                 /*
9164                  * We got a command we don't support.  This shouldn't
9165                  * happen, commands should be filtered out above us.
9166                  */
9167                 ctl_set_invalid_opcode(ctsio);
9168                 ctl_done((union ctl_io *)ctsio);
9169
9170                 return (CTL_RETVAL_COMPLETE);
9171                 break; /* NOTREACHED */
9172         }
9173
9174         /*
9175          * The first check is to make sure we're in bounds, the second
9176          * check is to catch wrap-around problems.  If the lba + num blocks
9177          * is less than the lba, then we've wrapped around and the block
9178          * range is invalid anyway.
9179          */
9180         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9181          || ((lba + num_blocks) < lba)) {
9182                 ctl_set_lba_out_of_range(ctsio);
9183                 ctl_done((union ctl_io *)ctsio);
9184                 return (CTL_RETVAL_COMPLETE);
9185         }
9186
9187         /*
9188          * According to SBC-3, a transfer length of 0 is not an error.
9189          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9190          * translates to 256 blocks for those commands.
9191          */
9192         if (num_blocks == 0) {
9193                 ctl_set_success(ctsio);
9194                 ctl_done((union ctl_io *)ctsio);
9195                 return (CTL_RETVAL_COMPLETE);
9196         }
9197
9198         /* Set FUA and/or DPO if caches are disabled. */
9199         if (isread) {
9200                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9201                     SCP_RCD) != 0)
9202                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9203         } else {
9204                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9205                     SCP_WCE) == 0)
9206                         flags |= CTL_LLF_FUA;
9207         }
9208
9209         lbalen = (struct ctl_lba_len_flags *)
9210             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9211         lbalen->lba = lba;
9212         lbalen->len = num_blocks;
9213         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9214
9215         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9216         ctsio->kern_rel_offset = 0;
9217
9218         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9219
9220         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9221
9222         return (retval);
9223 }
9224
9225 static int
9226 ctl_cnw_cont(union ctl_io *io)
9227 {
9228         struct ctl_scsiio *ctsio;
9229         struct ctl_lun *lun;
9230         struct ctl_lba_len_flags *lbalen;
9231         int retval;
9232
9233         ctsio = &io->scsiio;
9234         ctsio->io_hdr.status = CTL_STATUS_NONE;
9235         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9236         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9237         lbalen = (struct ctl_lba_len_flags *)
9238             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9239         lbalen->flags &= ~CTL_LLF_COMPARE;
9240         lbalen->flags |= CTL_LLF_WRITE;
9241
9242         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9243         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9244         return (retval);
9245 }
9246
9247 int
9248 ctl_cnw(struct ctl_scsiio *ctsio)
9249 {
9250         struct ctl_lun *lun;
9251         struct ctl_lba_len_flags *lbalen;
9252         uint64_t lba;
9253         uint32_t num_blocks;
9254         int flags, retval;
9255
9256         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9257
9258         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9259
9260         flags = 0;
9261         retval = CTL_RETVAL_COMPLETE;
9262
9263         switch (ctsio->cdb[0]) {
9264         case COMPARE_AND_WRITE: {
9265                 struct scsi_compare_and_write *cdb;
9266
9267                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9268                 if (cdb->byte2 & SRW10_FUA)
9269                         flags |= CTL_LLF_FUA;
9270                 if (cdb->byte2 & SRW10_DPO)
9271                         flags |= CTL_LLF_DPO;
9272                 lba = scsi_8btou64(cdb->addr);
9273                 num_blocks = cdb->length;
9274                 break;
9275         }
9276         default:
9277                 /*
9278                  * We got a command we don't support.  This shouldn't
9279                  * happen, commands should be filtered out above us.
9280                  */
9281                 ctl_set_invalid_opcode(ctsio);
9282                 ctl_done((union ctl_io *)ctsio);
9283
9284                 return (CTL_RETVAL_COMPLETE);
9285                 break; /* NOTREACHED */
9286         }
9287
9288         /*
9289          * The first check is to make sure we're in bounds, the second
9290          * check is to catch wrap-around problems.  If the lba + num blocks
9291          * is less than the lba, then we've wrapped around and the block
9292          * range is invalid anyway.
9293          */
9294         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9295          || ((lba + num_blocks) < lba)) {
9296                 ctl_set_lba_out_of_range(ctsio);
9297                 ctl_done((union ctl_io *)ctsio);
9298                 return (CTL_RETVAL_COMPLETE);
9299         }
9300
9301         /*
9302          * According to SBC-3, a transfer length of 0 is not an error.
9303          */
9304         if (num_blocks == 0) {
9305                 ctl_set_success(ctsio);
9306                 ctl_done((union ctl_io *)ctsio);
9307                 return (CTL_RETVAL_COMPLETE);
9308         }
9309
9310         /* Set FUA if write cache is disabled. */
9311         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9312             SCP_WCE) == 0)
9313                 flags |= CTL_LLF_FUA;
9314
9315         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9316         ctsio->kern_rel_offset = 0;
9317
9318         /*
9319          * Set the IO_CONT flag, so that if this I/O gets passed to
9320          * ctl_data_submit_done(), it'll get passed back to
9321          * ctl_ctl_cnw_cont() for further processing.
9322          */
9323         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9324         ctsio->io_cont = ctl_cnw_cont;
9325
9326         lbalen = (struct ctl_lba_len_flags *)
9327             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9328         lbalen->lba = lba;
9329         lbalen->len = num_blocks;
9330         lbalen->flags = CTL_LLF_COMPARE | flags;
9331
9332         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9333         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9334         return (retval);
9335 }
9336
9337 int
9338 ctl_verify(struct ctl_scsiio *ctsio)
9339 {
9340         struct ctl_lun *lun;
9341         struct ctl_lba_len_flags *lbalen;
9342         uint64_t lba;
9343         uint32_t num_blocks;
9344         int bytchk, flags;
9345         int retval;
9346
9347         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9348
9349         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9350
9351         bytchk = 0;
9352         flags = CTL_LLF_FUA;
9353         retval = CTL_RETVAL_COMPLETE;
9354
9355         switch (ctsio->cdb[0]) {
9356         case VERIFY_10: {
9357                 struct scsi_verify_10 *cdb;
9358
9359                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9360                 if (cdb->byte2 & SVFY_BYTCHK)
9361                         bytchk = 1;
9362                 if (cdb->byte2 & SVFY_DPO)
9363                         flags |= CTL_LLF_DPO;
9364                 lba = scsi_4btoul(cdb->addr);
9365                 num_blocks = scsi_2btoul(cdb->length);
9366                 break;
9367         }
9368         case VERIFY_12: {
9369                 struct scsi_verify_12 *cdb;
9370
9371                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9372                 if (cdb->byte2 & SVFY_BYTCHK)
9373                         bytchk = 1;
9374                 if (cdb->byte2 & SVFY_DPO)
9375                         flags |= CTL_LLF_DPO;
9376                 lba = scsi_4btoul(cdb->addr);
9377                 num_blocks = scsi_4btoul(cdb->length);
9378                 break;
9379         }
9380         case VERIFY_16: {
9381                 struct scsi_rw_16 *cdb;
9382
9383                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9384                 if (cdb->byte2 & SVFY_BYTCHK)
9385                         bytchk = 1;
9386                 if (cdb->byte2 & SVFY_DPO)
9387                         flags |= CTL_LLF_DPO;
9388                 lba = scsi_8btou64(cdb->addr);
9389                 num_blocks = scsi_4btoul(cdb->length);
9390                 break;
9391         }
9392         default:
9393                 /*
9394                  * We got a command we don't support.  This shouldn't
9395                  * happen, commands should be filtered out above us.
9396                  */
9397                 ctl_set_invalid_opcode(ctsio);
9398                 ctl_done((union ctl_io *)ctsio);
9399                 return (CTL_RETVAL_COMPLETE);
9400         }
9401
9402         /*
9403          * The first check is to make sure we're in bounds, the second
9404          * check is to catch wrap-around problems.  If the lba + num blocks
9405          * is less than the lba, then we've wrapped around and the block
9406          * range is invalid anyway.
9407          */
9408         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9409          || ((lba + num_blocks) < lba)) {
9410                 ctl_set_lba_out_of_range(ctsio);
9411                 ctl_done((union ctl_io *)ctsio);
9412                 return (CTL_RETVAL_COMPLETE);
9413         }
9414
9415         /*
9416          * According to SBC-3, a transfer length of 0 is not an error.
9417          */
9418         if (num_blocks == 0) {
9419                 ctl_set_success(ctsio);
9420                 ctl_done((union ctl_io *)ctsio);
9421                 return (CTL_RETVAL_COMPLETE);
9422         }
9423
9424         lbalen = (struct ctl_lba_len_flags *)
9425             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9426         lbalen->lba = lba;
9427         lbalen->len = num_blocks;
9428         if (bytchk) {
9429                 lbalen->flags = CTL_LLF_COMPARE | flags;
9430                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9431         } else {
9432                 lbalen->flags = CTL_LLF_VERIFY | flags;
9433                 ctsio->kern_total_len = 0;
9434         }
9435         ctsio->kern_rel_offset = 0;
9436
9437         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9438         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9439         return (retval);
9440 }
9441
9442 int
9443 ctl_report_luns(struct ctl_scsiio *ctsio)
9444 {
9445         struct scsi_report_luns *cdb;
9446         struct scsi_report_luns_data *lun_data;
9447         struct ctl_lun *lun, *request_lun;
9448         int num_luns, retval;
9449         uint32_t alloc_len, lun_datalen;
9450         int num_filled, well_known;
9451         uint32_t initidx, targ_lun_id, lun_id;
9452
9453         retval = CTL_RETVAL_COMPLETE;
9454         well_known = 0;
9455
9456         cdb = (struct scsi_report_luns *)ctsio->cdb;
9457
9458         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9459
9460         mtx_lock(&control_softc->ctl_lock);
9461         num_luns = control_softc->num_luns;
9462         mtx_unlock(&control_softc->ctl_lock);
9463
9464         switch (cdb->select_report) {
9465         case RPL_REPORT_DEFAULT:
9466         case RPL_REPORT_ALL:
9467                 break;
9468         case RPL_REPORT_WELLKNOWN:
9469                 well_known = 1;
9470                 num_luns = 0;
9471                 break;
9472         default:
9473                 ctl_set_invalid_field(ctsio,
9474                                       /*sks_valid*/ 1,
9475                                       /*command*/ 1,
9476                                       /*field*/ 2,
9477                                       /*bit_valid*/ 0,
9478                                       /*bit*/ 0);
9479                 ctl_done((union ctl_io *)ctsio);
9480                 return (retval);
9481                 break; /* NOTREACHED */
9482         }
9483
9484         alloc_len = scsi_4btoul(cdb->length);
9485         /*
9486          * The initiator has to allocate at least 16 bytes for this request,
9487          * so he can at least get the header and the first LUN.  Otherwise
9488          * we reject the request (per SPC-3 rev 14, section 6.21).
9489          */
9490         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9491             sizeof(struct scsi_report_luns_lundata))) {
9492                 ctl_set_invalid_field(ctsio,
9493                                       /*sks_valid*/ 1,
9494                                       /*command*/ 1,
9495                                       /*field*/ 6,
9496                                       /*bit_valid*/ 0,
9497                                       /*bit*/ 0);
9498                 ctl_done((union ctl_io *)ctsio);
9499                 return (retval);
9500         }
9501
9502         request_lun = (struct ctl_lun *)
9503                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9504
9505         lun_datalen = sizeof(*lun_data) +
9506                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9507
9508         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9509         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9510         ctsio->kern_sg_entries = 0;
9511
9512         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9513
9514         mtx_lock(&control_softc->ctl_lock);
9515         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9516                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9517                 if (lun_id >= CTL_MAX_LUNS)
9518                         continue;
9519                 lun = control_softc->ctl_luns[lun_id];
9520                 if (lun == NULL)
9521                         continue;
9522
9523                 if (targ_lun_id <= 0xff) {
9524                         /*
9525                          * Peripheral addressing method, bus number 0.
9526                          */
9527                         lun_data->luns[num_filled].lundata[0] =
9528                                 RPL_LUNDATA_ATYP_PERIPH;
9529                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9530                         num_filled++;
9531                 } else if (targ_lun_id <= 0x3fff) {
9532                         /*
9533                          * Flat addressing method.
9534                          */
9535                         lun_data->luns[num_filled].lundata[0] =
9536                                 RPL_LUNDATA_ATYP_FLAT |
9537                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9538 #ifdef OLDCTLHEADERS
9539                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9540                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9541 #endif
9542                         lun_data->luns[num_filled].lundata[1] =
9543 #ifdef OLDCTLHEADERS
9544                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9545 #endif
9546                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9547                         num_filled++;
9548                 } else {
9549                         printf("ctl_report_luns: bogus LUN number %jd, "
9550                                "skipping\n", (intmax_t)targ_lun_id);
9551                 }
9552                 /*
9553                  * According to SPC-3, rev 14 section 6.21:
9554                  *
9555                  * "The execution of a REPORT LUNS command to any valid and
9556                  * installed logical unit shall clear the REPORTED LUNS DATA
9557                  * HAS CHANGED unit attention condition for all logical
9558                  * units of that target with respect to the requesting
9559                  * initiator. A valid and installed logical unit is one
9560                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9561                  * INQUIRY data (see 6.4.2)."
9562                  *
9563                  * If request_lun is NULL, the LUN this report luns command
9564                  * was issued to is either disabled or doesn't exist. In that
9565                  * case, we shouldn't clear any pending lun change unit
9566                  * attention.
9567                  */
9568                 if (request_lun != NULL) {
9569                         mtx_lock(&lun->lun_lock);
9570                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9571                         mtx_unlock(&lun->lun_lock);
9572                 }
9573         }
9574         mtx_unlock(&control_softc->ctl_lock);
9575
9576         /*
9577          * It's quite possible that we've returned fewer LUNs than we allocated
9578          * space for.  Trim it.
9579          */
9580         lun_datalen = sizeof(*lun_data) +
9581                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9582
9583         if (lun_datalen < alloc_len) {
9584                 ctsio->residual = alloc_len - lun_datalen;
9585                 ctsio->kern_data_len = lun_datalen;
9586                 ctsio->kern_total_len = lun_datalen;
9587         } else {
9588                 ctsio->residual = 0;
9589                 ctsio->kern_data_len = alloc_len;
9590                 ctsio->kern_total_len = alloc_len;
9591         }
9592         ctsio->kern_data_resid = 0;
9593         ctsio->kern_rel_offset = 0;
9594         ctsio->kern_sg_entries = 0;
9595
9596         /*
9597          * We set this to the actual data length, regardless of how much
9598          * space we actually have to return results.  If the user looks at
9599          * this value, he'll know whether or not he allocated enough space
9600          * and reissue the command if necessary.  We don't support well
9601          * known logical units, so if the user asks for that, return none.
9602          */
9603         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9604
9605         /*
9606          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9607          * this request.
9608          */
9609         ctsio->scsi_status = SCSI_STATUS_OK;
9610
9611         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9612         ctsio->be_move_done = ctl_config_move_done;
9613         ctl_datamove((union ctl_io *)ctsio);
9614
9615         return (retval);
9616 }
9617
9618 int
9619 ctl_request_sense(struct ctl_scsiio *ctsio)
9620 {
9621         struct scsi_request_sense *cdb;
9622         struct scsi_sense_data *sense_ptr;
9623         struct ctl_lun *lun;
9624         uint32_t initidx;
9625         int have_error;
9626         scsi_sense_data_type sense_format;
9627
9628         cdb = (struct scsi_request_sense *)ctsio->cdb;
9629
9630         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9631
9632         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9633
9634         /*
9635          * Determine which sense format the user wants.
9636          */
9637         if (cdb->byte2 & SRS_DESC)
9638                 sense_format = SSD_TYPE_DESC;
9639         else
9640                 sense_format = SSD_TYPE_FIXED;
9641
9642         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9643         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9644         ctsio->kern_sg_entries = 0;
9645
9646         /*
9647          * struct scsi_sense_data, which is currently set to 256 bytes, is
9648          * larger than the largest allowed value for the length field in the
9649          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9650          */
9651         ctsio->residual = 0;
9652         ctsio->kern_data_len = cdb->length;
9653         ctsio->kern_total_len = cdb->length;
9654
9655         ctsio->kern_data_resid = 0;
9656         ctsio->kern_rel_offset = 0;
9657         ctsio->kern_sg_entries = 0;
9658
9659         /*
9660          * If we don't have a LUN, we don't have any pending sense.
9661          */
9662         if (lun == NULL)
9663                 goto no_sense;
9664
9665         have_error = 0;
9666         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9667         /*
9668          * Check for pending sense, and then for pending unit attentions.
9669          * Pending sense gets returned first, then pending unit attentions.
9670          */
9671         mtx_lock(&lun->lun_lock);
9672 #ifdef CTL_WITH_CA
9673         if (ctl_is_set(lun->have_ca, initidx)) {
9674                 scsi_sense_data_type stored_format;
9675
9676                 /*
9677                  * Check to see which sense format was used for the stored
9678                  * sense data.
9679                  */
9680                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9681
9682                 /*
9683                  * If the user requested a different sense format than the
9684                  * one we stored, then we need to convert it to the other
9685                  * format.  If we're going from descriptor to fixed format
9686                  * sense data, we may lose things in translation, depending
9687                  * on what options were used.
9688                  *
9689                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9690                  * for some reason we'll just copy it out as-is.
9691                  */
9692                 if ((stored_format == SSD_TYPE_FIXED)
9693                  && (sense_format == SSD_TYPE_DESC))
9694                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9695                             &lun->pending_sense[initidx],
9696                             (struct scsi_sense_data_desc *)sense_ptr);
9697                 else if ((stored_format == SSD_TYPE_DESC)
9698                       && (sense_format == SSD_TYPE_FIXED))
9699                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9700                             &lun->pending_sense[initidx],
9701                             (struct scsi_sense_data_fixed *)sense_ptr);
9702                 else
9703                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9704                                ctl_min(sizeof(*sense_ptr),
9705                                sizeof(lun->pending_sense[initidx])));
9706
9707                 ctl_clear_mask(lun->have_ca, initidx);
9708                 have_error = 1;
9709         } else
9710 #endif
9711         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9712                 ctl_ua_type ua_type;
9713
9714                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9715                                        sense_ptr, sense_format);
9716                 if (ua_type != CTL_UA_NONE)
9717                         have_error = 1;
9718         }
9719         mtx_unlock(&lun->lun_lock);
9720
9721         /*
9722          * We already have a pending error, return it.
9723          */
9724         if (have_error != 0) {
9725                 /*
9726                  * We report the SCSI status as OK, since the status of the
9727                  * request sense command itself is OK.
9728                  */
9729                 ctsio->scsi_status = SCSI_STATUS_OK;
9730
9731                 /*
9732                  * We report 0 for the sense length, because we aren't doing
9733                  * autosense in this case.  We're reporting sense as
9734                  * parameter data.
9735                  */
9736                 ctsio->sense_len = 0;
9737                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9738                 ctsio->be_move_done = ctl_config_move_done;
9739                 ctl_datamove((union ctl_io *)ctsio);
9740
9741                 return (CTL_RETVAL_COMPLETE);
9742         }
9743
9744 no_sense:
9745
9746         /*
9747          * No sense information to report, so we report that everything is
9748          * okay.
9749          */
9750         ctl_set_sense_data(sense_ptr,
9751                            lun,
9752                            sense_format,
9753                            /*current_error*/ 1,
9754                            /*sense_key*/ SSD_KEY_NO_SENSE,
9755                            /*asc*/ 0x00,
9756                            /*ascq*/ 0x00,
9757                            SSD_ELEM_NONE);
9758
9759         ctsio->scsi_status = SCSI_STATUS_OK;
9760
9761         /*
9762          * We report 0 for the sense length, because we aren't doing
9763          * autosense in this case.  We're reporting sense as parameter data.
9764          */
9765         ctsio->sense_len = 0;
9766         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9767         ctsio->be_move_done = ctl_config_move_done;
9768         ctl_datamove((union ctl_io *)ctsio);
9769
9770         return (CTL_RETVAL_COMPLETE);
9771 }
9772
9773 int
9774 ctl_tur(struct ctl_scsiio *ctsio)
9775 {
9776         struct ctl_lun *lun;
9777
9778         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9779
9780         CTL_DEBUG_PRINT(("ctl_tur\n"));
9781
9782         if (lun == NULL)
9783                 return (EINVAL);
9784
9785         ctsio->scsi_status = SCSI_STATUS_OK;
9786         ctsio->io_hdr.status = CTL_SUCCESS;
9787
9788         ctl_done((union ctl_io *)ctsio);
9789
9790         return (CTL_RETVAL_COMPLETE);
9791 }
9792
9793 #ifdef notyet
9794 static int
9795 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9796 {
9797
9798 }
9799 #endif
9800
9801 static int
9802 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9803 {
9804         struct scsi_vpd_supported_pages *pages;
9805         int sup_page_size;
9806         struct ctl_lun *lun;
9807
9808         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9809
9810         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9811             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9812         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9813         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9814         ctsio->kern_sg_entries = 0;
9815
9816         if (sup_page_size < alloc_len) {
9817                 ctsio->residual = alloc_len - sup_page_size;
9818                 ctsio->kern_data_len = sup_page_size;
9819                 ctsio->kern_total_len = sup_page_size;
9820         } else {
9821                 ctsio->residual = 0;
9822                 ctsio->kern_data_len = alloc_len;
9823                 ctsio->kern_total_len = alloc_len;
9824         }
9825         ctsio->kern_data_resid = 0;
9826         ctsio->kern_rel_offset = 0;
9827         ctsio->kern_sg_entries = 0;
9828
9829         /*
9830          * The control device is always connected.  The disk device, on the
9831          * other hand, may not be online all the time.  Need to change this
9832          * to figure out whether the disk device is actually online or not.
9833          */
9834         if (lun != NULL)
9835                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9836                                 lun->be_lun->lun_type;
9837         else
9838                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9839
9840         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9841         /* Supported VPD pages */
9842         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9843         /* Serial Number */
9844         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9845         /* Device Identification */
9846         pages->page_list[2] = SVPD_DEVICE_ID;
9847         /* SCSI Ports */
9848         pages->page_list[3] = SVPD_SCSI_PORTS;
9849         /* Third-party Copy */
9850         pages->page_list[4] = SVPD_SCSI_TPC;
9851         /* Block limits */
9852         pages->page_list[5] = SVPD_BLOCK_LIMITS;
9853         /* Block Device Characteristics */
9854         pages->page_list[6] = SVPD_BDC;
9855         /* Logical Block Provisioning */
9856         pages->page_list[7] = SVPD_LBP;
9857
9858         ctsio->scsi_status = SCSI_STATUS_OK;
9859
9860         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9861         ctsio->be_move_done = ctl_config_move_done;
9862         ctl_datamove((union ctl_io *)ctsio);
9863
9864         return (CTL_RETVAL_COMPLETE);
9865 }
9866
9867 static int
9868 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9869 {
9870         struct scsi_vpd_unit_serial_number *sn_ptr;
9871         struct ctl_lun *lun;
9872
9873         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9874
9875         ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9876         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9877         ctsio->kern_sg_entries = 0;
9878
9879         if (sizeof(*sn_ptr) < alloc_len) {
9880                 ctsio->residual = alloc_len - sizeof(*sn_ptr);
9881                 ctsio->kern_data_len = sizeof(*sn_ptr);
9882                 ctsio->kern_total_len = sizeof(*sn_ptr);
9883         } else {
9884                 ctsio->residual = 0;
9885                 ctsio->kern_data_len = alloc_len;
9886                 ctsio->kern_total_len = alloc_len;
9887         }
9888         ctsio->kern_data_resid = 0;
9889         ctsio->kern_rel_offset = 0;
9890         ctsio->kern_sg_entries = 0;
9891
9892         /*
9893          * The control device is always connected.  The disk device, on the
9894          * other hand, may not be online all the time.  Need to change this
9895          * to figure out whether the disk device is actually online or not.
9896          */
9897         if (lun != NULL)
9898                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9899                                   lun->be_lun->lun_type;
9900         else
9901                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9902
9903         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9904         sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9905         /*
9906          * If we don't have a LUN, we just leave the serial number as
9907          * all spaces.
9908          */
9909         memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9910         if (lun != NULL) {
9911                 strncpy((char *)sn_ptr->serial_num,
9912                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9913         }
9914         ctsio->scsi_status = SCSI_STATUS_OK;
9915
9916         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9917         ctsio->be_move_done = ctl_config_move_done;
9918         ctl_datamove((union ctl_io *)ctsio);
9919
9920         return (CTL_RETVAL_COMPLETE);
9921 }
9922
9923
9924 static int
9925 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9926 {
9927         struct scsi_vpd_device_id *devid_ptr;
9928         struct scsi_vpd_id_descriptor *desc;
9929         struct ctl_softc *ctl_softc;
9930         struct ctl_lun *lun;
9931         struct ctl_port *port;
9932         int data_len;
9933         uint8_t proto;
9934
9935         ctl_softc = control_softc;
9936
9937         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9938         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9939
9940         data_len = sizeof(struct scsi_vpd_device_id) +
9941             sizeof(struct scsi_vpd_id_descriptor) +
9942                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9943             sizeof(struct scsi_vpd_id_descriptor) +
9944                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9945         if (lun && lun->lun_devid)
9946                 data_len += lun->lun_devid->len;
9947         if (port->port_devid)
9948                 data_len += port->port_devid->len;
9949         if (port->target_devid)
9950                 data_len += port->target_devid->len;
9951
9952         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9953         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9954         ctsio->kern_sg_entries = 0;
9955
9956         if (data_len < alloc_len) {
9957                 ctsio->residual = alloc_len - data_len;
9958                 ctsio->kern_data_len = data_len;
9959                 ctsio->kern_total_len = data_len;
9960         } else {
9961                 ctsio->residual = 0;
9962                 ctsio->kern_data_len = alloc_len;
9963                 ctsio->kern_total_len = alloc_len;
9964         }
9965         ctsio->kern_data_resid = 0;
9966         ctsio->kern_rel_offset = 0;
9967         ctsio->kern_sg_entries = 0;
9968
9969         /*
9970          * The control device is always connected.  The disk device, on the
9971          * other hand, may not be online all the time.
9972          */
9973         if (lun != NULL)
9974                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9975                                      lun->be_lun->lun_type;
9976         else
9977                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9978         devid_ptr->page_code = SVPD_DEVICE_ID;
9979         scsi_ulto2b(data_len - 4, devid_ptr->length);
9980
9981         if (port->port_type == CTL_PORT_FC)
9982                 proto = SCSI_PROTO_FC << 4;
9983         else if (port->port_type == CTL_PORT_ISCSI)
9984                 proto = SCSI_PROTO_ISCSI << 4;
9985         else
9986                 proto = SCSI_PROTO_SPI << 4;
9987         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9988
9989         /*
9990          * We're using a LUN association here.  i.e., this device ID is a
9991          * per-LUN identifier.
9992          */
9993         if (lun && lun->lun_devid) {
9994                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9995                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9996                     lun->lun_devid->len);
9997         }
9998
9999         /*
10000          * This is for the WWPN which is a port association.
10001          */
10002         if (port->port_devid) {
10003                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10004                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10005                     port->port_devid->len);
10006         }
10007
10008         /*
10009          * This is for the Relative Target Port(type 4h) identifier
10010          */
10011         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10012         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10013             SVPD_ID_TYPE_RELTARG;
10014         desc->length = 4;
10015         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10016         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10017             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10018
10019         /*
10020          * This is for the Target Port Group(type 5h) identifier
10021          */
10022         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10023         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10024             SVPD_ID_TYPE_TPORTGRP;
10025         desc->length = 4;
10026         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10027             &desc->identifier[2]);
10028         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10029             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10030
10031         /*
10032          * This is for the Target identifier
10033          */
10034         if (port->target_devid) {
10035                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10036         }
10037
10038         ctsio->scsi_status = SCSI_STATUS_OK;
10039         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10040         ctsio->be_move_done = ctl_config_move_done;
10041         ctl_datamove((union ctl_io *)ctsio);
10042
10043         return (CTL_RETVAL_COMPLETE);
10044 }
10045
10046 static int
10047 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10048 {
10049         struct ctl_softc *softc = control_softc;
10050         struct scsi_vpd_scsi_ports *sp;
10051         struct scsi_vpd_port_designation *pd;
10052         struct scsi_vpd_port_designation_cont *pdc;
10053         struct ctl_lun *lun;
10054         struct ctl_port *port;
10055         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10056         int num_target_port_groups, single;
10057
10058         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10059
10060         single = ctl_is_single;
10061         if (single)
10062                 num_target_port_groups = 1;
10063         else
10064                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10065         num_target_ports = 0;
10066         iid_len = 0;
10067         id_len = 0;
10068         mtx_lock(&softc->ctl_lock);
10069         STAILQ_FOREACH(port, &softc->port_list, links) {
10070                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10071                         continue;
10072                 if (lun != NULL &&
10073                     ctl_map_lun_back(port->targ_port, lun->lun) >=
10074                     CTL_MAX_LUNS)
10075                         continue;
10076                 num_target_ports++;
10077                 if (port->init_devid)
10078                         iid_len += port->init_devid->len;
10079                 if (port->port_devid)
10080                         id_len += port->port_devid->len;
10081         }
10082         mtx_unlock(&softc->ctl_lock);
10083
10084         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10085             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10086              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10087         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10088         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10089         ctsio->kern_sg_entries = 0;
10090
10091         if (data_len < alloc_len) {
10092                 ctsio->residual = alloc_len - data_len;
10093                 ctsio->kern_data_len = data_len;
10094                 ctsio->kern_total_len = data_len;
10095         } else {
10096                 ctsio->residual = 0;
10097                 ctsio->kern_data_len = alloc_len;
10098                 ctsio->kern_total_len = alloc_len;
10099         }
10100         ctsio->kern_data_resid = 0;
10101         ctsio->kern_rel_offset = 0;
10102         ctsio->kern_sg_entries = 0;
10103
10104         /*
10105          * The control device is always connected.  The disk device, on the
10106          * other hand, may not be online all the time.  Need to change this
10107          * to figure out whether the disk device is actually online or not.
10108          */
10109         if (lun != NULL)
10110                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10111                                   lun->be_lun->lun_type;
10112         else
10113                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10114
10115         sp->page_code = SVPD_SCSI_PORTS;
10116         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10117             sp->page_length);
10118         pd = &sp->design[0];
10119
10120         mtx_lock(&softc->ctl_lock);
10121         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10122                 pg = 0;
10123         else
10124                 pg = 1;
10125         for (g = 0; g < num_target_port_groups; g++) {
10126                 STAILQ_FOREACH(port, &softc->port_list, links) {
10127                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10128                                 continue;
10129                         if (lun != NULL &&
10130                             ctl_map_lun_back(port->targ_port, lun->lun) >=
10131                             CTL_MAX_LUNS)
10132                                 continue;
10133                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10134                         scsi_ulto2b(p, pd->relative_port_id);
10135                         if (port->init_devid && g == pg) {
10136                                 iid_len = port->init_devid->len;
10137                                 memcpy(pd->initiator_transportid,
10138                                     port->init_devid->data, port->init_devid->len);
10139                         } else
10140                                 iid_len = 0;
10141                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10142                         pdc = (struct scsi_vpd_port_designation_cont *)
10143                             (&pd->initiator_transportid[iid_len]);
10144                         if (port->port_devid && g == pg) {
10145                                 id_len = port->port_devid->len;
10146                                 memcpy(pdc->target_port_descriptors,
10147                                     port->port_devid->data, port->port_devid->len);
10148                         } else
10149                                 id_len = 0;
10150                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10151                         pd = (struct scsi_vpd_port_designation *)
10152                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10153                 }
10154         }
10155         mtx_unlock(&softc->ctl_lock);
10156
10157         ctsio->scsi_status = SCSI_STATUS_OK;
10158         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10159         ctsio->be_move_done = ctl_config_move_done;
10160         ctl_datamove((union ctl_io *)ctsio);
10161
10162         return (CTL_RETVAL_COMPLETE);
10163 }
10164
10165 static int
10166 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10167 {
10168         struct scsi_vpd_block_limits *bl_ptr;
10169         struct ctl_lun *lun;
10170         int bs;
10171
10172         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10173
10174         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10175         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10176         ctsio->kern_sg_entries = 0;
10177
10178         if (sizeof(*bl_ptr) < alloc_len) {
10179                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10180                 ctsio->kern_data_len = sizeof(*bl_ptr);
10181                 ctsio->kern_total_len = sizeof(*bl_ptr);
10182         } else {
10183                 ctsio->residual = 0;
10184                 ctsio->kern_data_len = alloc_len;
10185                 ctsio->kern_total_len = alloc_len;
10186         }
10187         ctsio->kern_data_resid = 0;
10188         ctsio->kern_rel_offset = 0;
10189         ctsio->kern_sg_entries = 0;
10190
10191         /*
10192          * The control device is always connected.  The disk device, on the
10193          * other hand, may not be online all the time.  Need to change this
10194          * to figure out whether the disk device is actually online or not.
10195          */
10196         if (lun != NULL)
10197                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10198                                   lun->be_lun->lun_type;
10199         else
10200                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10201
10202         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10203         scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10204         bl_ptr->max_cmp_write_len = 0xff;
10205         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10206         if (lun != NULL) {
10207                 bs = lun->be_lun->blocksize;
10208                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10209                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10210                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10211                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10212                         if (lun->be_lun->pblockexp != 0) {
10213                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10214                                     bl_ptr->opt_unmap_grain);
10215                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10216                                     bl_ptr->unmap_grain_align);
10217                         }
10218                 }
10219         }
10220         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10221
10222         ctsio->scsi_status = SCSI_STATUS_OK;
10223         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10224         ctsio->be_move_done = ctl_config_move_done;
10225         ctl_datamove((union ctl_io *)ctsio);
10226
10227         return (CTL_RETVAL_COMPLETE);
10228 }
10229
10230 static int
10231 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10232 {
10233         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10234         struct ctl_lun *lun;
10235
10236         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10237
10238         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10239         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10240         ctsio->kern_sg_entries = 0;
10241
10242         if (sizeof(*bdc_ptr) < alloc_len) {
10243                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10244                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10245                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10246         } else {
10247                 ctsio->residual = 0;
10248                 ctsio->kern_data_len = alloc_len;
10249                 ctsio->kern_total_len = alloc_len;
10250         }
10251         ctsio->kern_data_resid = 0;
10252         ctsio->kern_rel_offset = 0;
10253         ctsio->kern_sg_entries = 0;
10254
10255         /*
10256          * The control device is always connected.  The disk device, on the
10257          * other hand, may not be online all the time.  Need to change this
10258          * to figure out whether the disk device is actually online or not.
10259          */
10260         if (lun != NULL)
10261                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10262                                   lun->be_lun->lun_type;
10263         else
10264                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10265         bdc_ptr->page_code = SVPD_BDC;
10266         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10267         scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10268         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10269
10270         ctsio->scsi_status = SCSI_STATUS_OK;
10271         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10272         ctsio->be_move_done = ctl_config_move_done;
10273         ctl_datamove((union ctl_io *)ctsio);
10274
10275         return (CTL_RETVAL_COMPLETE);
10276 }
10277
10278 static int
10279 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10280 {
10281         struct scsi_vpd_logical_block_prov *lbp_ptr;
10282         struct ctl_lun *lun;
10283
10284         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10285
10286         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10287         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10288         ctsio->kern_sg_entries = 0;
10289
10290         if (sizeof(*lbp_ptr) < alloc_len) {
10291                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10292                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10293                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10294         } else {
10295                 ctsio->residual = 0;
10296                 ctsio->kern_data_len = alloc_len;
10297                 ctsio->kern_total_len = alloc_len;
10298         }
10299         ctsio->kern_data_resid = 0;
10300         ctsio->kern_rel_offset = 0;
10301         ctsio->kern_sg_entries = 0;
10302
10303         /*
10304          * The control device is always connected.  The disk device, on the
10305          * other hand, may not be online all the time.  Need to change this
10306          * to figure out whether the disk device is actually online or not.
10307          */
10308         if (lun != NULL)
10309                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10310                                   lun->be_lun->lun_type;
10311         else
10312                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10313
10314         lbp_ptr->page_code = SVPD_LBP;
10315         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10316         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10317                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10318                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10319                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10320         }
10321
10322         ctsio->scsi_status = SCSI_STATUS_OK;
10323         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10324         ctsio->be_move_done = ctl_config_move_done;
10325         ctl_datamove((union ctl_io *)ctsio);
10326
10327         return (CTL_RETVAL_COMPLETE);
10328 }
10329
10330 static int
10331 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10332 {
10333         struct scsi_inquiry *cdb;
10334         struct ctl_lun *lun;
10335         int alloc_len, retval;
10336
10337         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10338         cdb = (struct scsi_inquiry *)ctsio->cdb;
10339
10340         retval = CTL_RETVAL_COMPLETE;
10341
10342         alloc_len = scsi_2btoul(cdb->length);
10343
10344         switch (cdb->page_code) {
10345         case SVPD_SUPPORTED_PAGES:
10346                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10347                 break;
10348         case SVPD_UNIT_SERIAL_NUMBER:
10349                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10350                 break;
10351         case SVPD_DEVICE_ID:
10352                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10353                 break;
10354         case SVPD_SCSI_PORTS:
10355                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10356                 break;
10357         case SVPD_SCSI_TPC:
10358                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10359                 break;
10360         case SVPD_BLOCK_LIMITS:
10361                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10362                 break;
10363         case SVPD_BDC:
10364                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10365                 break;
10366         case SVPD_LBP:
10367                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10368                 break;
10369         default:
10370                 ctl_set_invalid_field(ctsio,
10371                                       /*sks_valid*/ 1,
10372                                       /*command*/ 1,
10373                                       /*field*/ 2,
10374                                       /*bit_valid*/ 0,
10375                                       /*bit*/ 0);
10376                 ctl_done((union ctl_io *)ctsio);
10377                 retval = CTL_RETVAL_COMPLETE;
10378                 break;
10379         }
10380
10381         return (retval);
10382 }
10383
10384 static int
10385 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10386 {
10387         struct scsi_inquiry_data *inq_ptr;
10388         struct scsi_inquiry *cdb;
10389         struct ctl_softc *ctl_softc;
10390         struct ctl_lun *lun;
10391         char *val;
10392         uint32_t alloc_len;
10393         ctl_port_type port_type;
10394
10395         ctl_softc = control_softc;
10396
10397         /*
10398          * Figure out whether we're talking to a Fibre Channel port or not.
10399          * We treat the ioctl front end, and any SCSI adapters, as packetized
10400          * SCSI front ends.
10401          */
10402         port_type = ctl_softc->ctl_ports[
10403             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10404         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10405                 port_type = CTL_PORT_SCSI;
10406
10407         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10408         cdb = (struct scsi_inquiry *)ctsio->cdb;
10409         alloc_len = scsi_2btoul(cdb->length);
10410
10411         /*
10412          * We malloc the full inquiry data size here and fill it
10413          * in.  If the user only asks for less, we'll give him
10414          * that much.
10415          */
10416         ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10417         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10418         ctsio->kern_sg_entries = 0;
10419         ctsio->kern_data_resid = 0;
10420         ctsio->kern_rel_offset = 0;
10421
10422         if (sizeof(*inq_ptr) < alloc_len) {
10423                 ctsio->residual = alloc_len - sizeof(*inq_ptr);
10424                 ctsio->kern_data_len = sizeof(*inq_ptr);
10425                 ctsio->kern_total_len = sizeof(*inq_ptr);
10426         } else {
10427                 ctsio->residual = 0;
10428                 ctsio->kern_data_len = alloc_len;
10429                 ctsio->kern_total_len = alloc_len;
10430         }
10431
10432         /*
10433          * If we have a LUN configured, report it as connected.  Otherwise,
10434          * report that it is offline or no device is supported, depending 
10435          * on the value of inquiry_pq_no_lun.
10436          *
10437          * According to the spec (SPC-4 r34), the peripheral qualifier
10438          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10439          *
10440          * "A peripheral device having the specified peripheral device type 
10441          * is not connected to this logical unit. However, the device
10442          * server is capable of supporting the specified peripheral device
10443          * type on this logical unit."
10444          *
10445          * According to the same spec, the peripheral qualifier
10446          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10447          *
10448          * "The device server is not capable of supporting a peripheral
10449          * device on this logical unit. For this peripheral qualifier the
10450          * peripheral device type shall be set to 1Fh. All other peripheral
10451          * device type values are reserved for this peripheral qualifier."
10452          *
10453          * Given the text, it would seem that we probably want to report that
10454          * the LUN is offline here.  There is no LUN connected, but we can
10455          * support a LUN at the given LUN number.
10456          *
10457          * In the real world, though, it sounds like things are a little
10458          * different:
10459          *
10460          * - Linux, when presented with a LUN with the offline peripheral
10461          *   qualifier, will create an sg driver instance for it.  So when
10462          *   you attach it to CTL, you wind up with a ton of sg driver
10463          *   instances.  (One for every LUN that Linux bothered to probe.)
10464          *   Linux does this despite the fact that it issues a REPORT LUNs
10465          *   to LUN 0 to get the inventory of supported LUNs.
10466          *
10467          * - There is other anecdotal evidence (from Emulex folks) about
10468          *   arrays that use the offline peripheral qualifier for LUNs that
10469          *   are on the "passive" path in an active/passive array.
10470          *
10471          * So the solution is provide a hopefully reasonable default
10472          * (return bad/no LUN) and allow the user to change the behavior
10473          * with a tunable/sysctl variable.
10474          */
10475         if (lun != NULL)
10476                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10477                                   lun->be_lun->lun_type;
10478         else if (ctl_softc->inquiry_pq_no_lun == 0)
10479                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10480         else
10481                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10482
10483         /* RMB in byte 2 is 0 */
10484         inq_ptr->version = SCSI_REV_SPC4;
10485
10486         /*
10487          * According to SAM-3, even if a device only supports a single
10488          * level of LUN addressing, it should still set the HISUP bit:
10489          *
10490          * 4.9.1 Logical unit numbers overview
10491          *
10492          * All logical unit number formats described in this standard are
10493          * hierarchical in structure even when only a single level in that
10494          * hierarchy is used. The HISUP bit shall be set to one in the
10495          * standard INQUIRY data (see SPC-2) when any logical unit number
10496          * format described in this standard is used.  Non-hierarchical
10497          * formats are outside the scope of this standard.
10498          *
10499          * Therefore we set the HiSup bit here.
10500          *
10501          * The reponse format is 2, per SPC-3.
10502          */
10503         inq_ptr->response_format = SID_HiSup | 2;
10504
10505         inq_ptr->additional_length =
10506             offsetof(struct scsi_inquiry_data, vendor_specific1) -
10507             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10508         CTL_DEBUG_PRINT(("additional_length = %d\n",
10509                          inq_ptr->additional_length));
10510
10511         inq_ptr->spc3_flags = SPC3_SID_3PC;
10512         if (!ctl_is_single)
10513                 inq_ptr->spc3_flags |= SPC3_SID_TPGS_IMPLICIT;
10514         /* 16 bit addressing */
10515         if (port_type == CTL_PORT_SCSI)
10516                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10517         /* XXX set the SID_MultiP bit here if we're actually going to
10518            respond on multiple ports */
10519         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10520
10521         /* 16 bit data bus, synchronous transfers */
10522         if (port_type == CTL_PORT_SCSI)
10523                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10524         /*
10525          * XXX KDM do we want to support tagged queueing on the control
10526          * device at all?
10527          */
10528         if ((lun == NULL)
10529          || (lun->be_lun->lun_type != T_PROCESSOR))
10530                 inq_ptr->flags |= SID_CmdQue;
10531         /*
10532          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10533          * We have 8 bytes for the vendor name, and 16 bytes for the device
10534          * name and 4 bytes for the revision.
10535          */
10536         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10537             "vendor")) == NULL) {
10538                 strcpy(inq_ptr->vendor, CTL_VENDOR);
10539         } else {
10540                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10541                 strncpy(inq_ptr->vendor, val,
10542                     min(sizeof(inq_ptr->vendor), strlen(val)));
10543         }
10544         if (lun == NULL) {
10545                 strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10546         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10547                 switch (lun->be_lun->lun_type) {
10548                 case T_DIRECT:
10549                         strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10550                         break;
10551                 case T_PROCESSOR:
10552                         strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10553                         break;
10554                 default:
10555                         strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10556                         break;
10557                 }
10558         } else {
10559                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10560                 strncpy(inq_ptr->product, val,
10561                     min(sizeof(inq_ptr->product), strlen(val)));
10562         }
10563
10564         /*
10565          * XXX make this a macro somewhere so it automatically gets
10566          * incremented when we make changes.
10567          */
10568         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10569             "revision")) == NULL) {
10570                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10571         } else {
10572                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10573                 strncpy(inq_ptr->revision, val,
10574                     min(sizeof(inq_ptr->revision), strlen(val)));
10575         }
10576
10577         /*
10578          * For parallel SCSI, we support double transition and single
10579          * transition clocking.  We also support QAS (Quick Arbitration
10580          * and Selection) and Information Unit transfers on both the
10581          * control and array devices.
10582          */
10583         if (port_type == CTL_PORT_SCSI)
10584                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10585                                     SID_SPI_IUS;
10586
10587         /* SAM-5 (no version claimed) */
10588         scsi_ulto2b(0x00A0, inq_ptr->version1);
10589         /* SPC-4 (no version claimed) */
10590         scsi_ulto2b(0x0460, inq_ptr->version2);
10591         if (port_type == CTL_PORT_FC) {
10592                 /* FCP-2 ANSI INCITS.350:2003 */
10593                 scsi_ulto2b(0x0917, inq_ptr->version3);
10594         } else if (port_type == CTL_PORT_SCSI) {
10595                 /* SPI-4 ANSI INCITS.362:200x */
10596                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10597         } else if (port_type == CTL_PORT_ISCSI) {
10598                 /* iSCSI (no version claimed) */
10599                 scsi_ulto2b(0x0960, inq_ptr->version3);
10600         } else if (port_type == CTL_PORT_SAS) {
10601                 /* SAS (no version claimed) */
10602                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10603         }
10604
10605         if (lun == NULL) {
10606                 /* SBC-3 (no version claimed) */
10607                 scsi_ulto2b(0x04C0, inq_ptr->version4);
10608         } else {
10609                 switch (lun->be_lun->lun_type) {
10610                 case T_DIRECT:
10611                         /* SBC-3 (no version claimed) */
10612                         scsi_ulto2b(0x04C0, inq_ptr->version4);
10613                         break;
10614                 case T_PROCESSOR:
10615                 default:
10616                         break;
10617                 }
10618         }
10619
10620         ctsio->scsi_status = SCSI_STATUS_OK;
10621         if (ctsio->kern_data_len > 0) {
10622                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10623                 ctsio->be_move_done = ctl_config_move_done;
10624                 ctl_datamove((union ctl_io *)ctsio);
10625         } else {
10626                 ctsio->io_hdr.status = CTL_SUCCESS;
10627                 ctl_done((union ctl_io *)ctsio);
10628         }
10629
10630         return (CTL_RETVAL_COMPLETE);
10631 }
10632
10633 int
10634 ctl_inquiry(struct ctl_scsiio *ctsio)
10635 {
10636         struct scsi_inquiry *cdb;
10637         int retval;
10638
10639         cdb = (struct scsi_inquiry *)ctsio->cdb;
10640
10641         retval = 0;
10642
10643         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10644
10645         /*
10646          * Right now, we don't support the CmdDt inquiry information.
10647          * This would be nice to support in the future.  When we do
10648          * support it, we should change this test so that it checks to make
10649          * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10650          */
10651 #ifdef notyet
10652         if (((cdb->byte2 & SI_EVPD)
10653          && (cdb->byte2 & SI_CMDDT)))
10654 #endif
10655         if (cdb->byte2 & SI_CMDDT) {
10656                 /*
10657                  * Point to the SI_CMDDT bit.  We might change this
10658                  * when we support SI_CMDDT, but since both bits would be
10659                  * "wrong", this should probably just stay as-is then.
10660                  */
10661                 ctl_set_invalid_field(ctsio,
10662                                       /*sks_valid*/ 1,
10663                                       /*command*/ 1,
10664                                       /*field*/ 1,
10665                                       /*bit_valid*/ 1,
10666                                       /*bit*/ 1);
10667                 ctl_done((union ctl_io *)ctsio);
10668                 return (CTL_RETVAL_COMPLETE);
10669         }
10670         if (cdb->byte2 & SI_EVPD)
10671                 retval = ctl_inquiry_evpd(ctsio);
10672 #ifdef notyet
10673         else if (cdb->byte2 & SI_CMDDT)
10674                 retval = ctl_inquiry_cmddt(ctsio);
10675 #endif
10676         else
10677                 retval = ctl_inquiry_std(ctsio);
10678
10679         return (retval);
10680 }
10681
10682 /*
10683  * For known CDB types, parse the LBA and length.
10684  */
10685 static int
10686 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10687 {
10688         if (io->io_hdr.io_type != CTL_IO_SCSI)
10689                 return (1);
10690
10691         switch (io->scsiio.cdb[0]) {
10692         case COMPARE_AND_WRITE: {
10693                 struct scsi_compare_and_write *cdb;
10694
10695                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10696
10697                 *lba = scsi_8btou64(cdb->addr);
10698                 *len = cdb->length;
10699                 break;
10700         }
10701         case READ_6:
10702         case WRITE_6: {
10703                 struct scsi_rw_6 *cdb;
10704
10705                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10706
10707                 *lba = scsi_3btoul(cdb->addr);
10708                 /* only 5 bits are valid in the most significant address byte */
10709                 *lba &= 0x1fffff;
10710                 *len = cdb->length;
10711                 break;
10712         }
10713         case READ_10:
10714         case WRITE_10: {
10715                 struct scsi_rw_10 *cdb;
10716
10717                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10718
10719                 *lba = scsi_4btoul(cdb->addr);
10720                 *len = scsi_2btoul(cdb->length);
10721                 break;
10722         }
10723         case WRITE_VERIFY_10: {
10724                 struct scsi_write_verify_10 *cdb;
10725
10726                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10727
10728                 *lba = scsi_4btoul(cdb->addr);
10729                 *len = scsi_2btoul(cdb->length);
10730                 break;
10731         }
10732         case READ_12:
10733         case WRITE_12: {
10734                 struct scsi_rw_12 *cdb;
10735
10736                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10737
10738                 *lba = scsi_4btoul(cdb->addr);
10739                 *len = scsi_4btoul(cdb->length);
10740                 break;
10741         }
10742         case WRITE_VERIFY_12: {
10743                 struct scsi_write_verify_12 *cdb;
10744
10745                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10746
10747                 *lba = scsi_4btoul(cdb->addr);
10748                 *len = scsi_4btoul(cdb->length);
10749                 break;
10750         }
10751         case READ_16:
10752         case WRITE_16: {
10753                 struct scsi_rw_16 *cdb;
10754
10755                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10756
10757                 *lba = scsi_8btou64(cdb->addr);
10758                 *len = scsi_4btoul(cdb->length);
10759                 break;
10760         }
10761         case WRITE_VERIFY_16: {
10762                 struct scsi_write_verify_16 *cdb;
10763
10764                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10765
10766                 
10767                 *lba = scsi_8btou64(cdb->addr);
10768                 *len = scsi_4btoul(cdb->length);
10769                 break;
10770         }
10771         case WRITE_SAME_10: {
10772                 struct scsi_write_same_10 *cdb;
10773
10774                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10775
10776                 *lba = scsi_4btoul(cdb->addr);
10777                 *len = scsi_2btoul(cdb->length);
10778                 break;
10779         }
10780         case WRITE_SAME_16: {
10781                 struct scsi_write_same_16 *cdb;
10782
10783                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10784
10785                 *lba = scsi_8btou64(cdb->addr);
10786                 *len = scsi_4btoul(cdb->length);
10787                 break;
10788         }
10789         case VERIFY_10: {
10790                 struct scsi_verify_10 *cdb;
10791
10792                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10793
10794                 *lba = scsi_4btoul(cdb->addr);
10795                 *len = scsi_2btoul(cdb->length);
10796                 break;
10797         }
10798         case VERIFY_12: {
10799                 struct scsi_verify_12 *cdb;
10800
10801                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10802
10803                 *lba = scsi_4btoul(cdb->addr);
10804                 *len = scsi_4btoul(cdb->length);
10805                 break;
10806         }
10807         case VERIFY_16: {
10808                 struct scsi_verify_16 *cdb;
10809
10810                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10811
10812                 *lba = scsi_8btou64(cdb->addr);
10813                 *len = scsi_4btoul(cdb->length);
10814                 break;
10815         }
10816         default:
10817                 return (1);
10818                 break; /* NOTREACHED */
10819         }
10820
10821         return (0);
10822 }
10823
10824 static ctl_action
10825 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10826 {
10827         uint64_t endlba1, endlba2;
10828
10829         endlba1 = lba1 + len1 - 1;
10830         endlba2 = lba2 + len2 - 1;
10831
10832         if ((endlba1 < lba2)
10833          || (endlba2 < lba1))
10834                 return (CTL_ACTION_PASS);
10835         else
10836                 return (CTL_ACTION_BLOCK);
10837 }
10838
10839 static ctl_action
10840 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10841 {
10842         uint64_t lba1, lba2;
10843         uint32_t len1, len2;
10844         int retval;
10845
10846         retval = ctl_get_lba_len(io1, &lba1, &len1);
10847         if (retval != 0)
10848                 return (CTL_ACTION_ERROR);
10849
10850         retval = ctl_get_lba_len(io2, &lba2, &len2);
10851         if (retval != 0)
10852                 return (CTL_ACTION_ERROR);
10853
10854         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10855 }
10856
10857 static ctl_action
10858 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10859 {
10860         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10861         ctl_serialize_action *serialize_row;
10862
10863         /*
10864          * The initiator attempted multiple untagged commands at the same
10865          * time.  Can't do that.
10866          */
10867         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10868          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10869          && ((pending_io->io_hdr.nexus.targ_port ==
10870               ooa_io->io_hdr.nexus.targ_port)
10871           && (pending_io->io_hdr.nexus.initid.id ==
10872               ooa_io->io_hdr.nexus.initid.id))
10873          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10874                 return (CTL_ACTION_OVERLAP);
10875
10876         /*
10877          * The initiator attempted to send multiple tagged commands with
10878          * the same ID.  (It's fine if different initiators have the same
10879          * tag ID.)
10880          *
10881          * Even if all of those conditions are true, we don't kill the I/O
10882          * if the command ahead of us has been aborted.  We won't end up
10883          * sending it to the FETD, and it's perfectly legal to resend a
10884          * command with the same tag number as long as the previous
10885          * instance of this tag number has been aborted somehow.
10886          */
10887         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10888          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10889          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10890          && ((pending_io->io_hdr.nexus.targ_port ==
10891               ooa_io->io_hdr.nexus.targ_port)
10892           && (pending_io->io_hdr.nexus.initid.id ==
10893               ooa_io->io_hdr.nexus.initid.id))
10894          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10895                 return (CTL_ACTION_OVERLAP_TAG);
10896
10897         /*
10898          * If we get a head of queue tag, SAM-3 says that we should
10899          * immediately execute it.
10900          *
10901          * What happens if this command would normally block for some other
10902          * reason?  e.g. a request sense with a head of queue tag
10903          * immediately after a write.  Normally that would block, but this
10904          * will result in its getting executed immediately...
10905          *
10906          * We currently return "pass" instead of "skip", so we'll end up
10907          * going through the rest of the queue to check for overlapped tags.
10908          *
10909          * XXX KDM check for other types of blockage first??
10910          */
10911         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10912                 return (CTL_ACTION_PASS);
10913
10914         /*
10915          * Ordered tags have to block until all items ahead of them
10916          * have completed.  If we get called with an ordered tag, we always
10917          * block, if something else is ahead of us in the queue.
10918          */
10919         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10920                 return (CTL_ACTION_BLOCK);
10921
10922         /*
10923          * Simple tags get blocked until all head of queue and ordered tags
10924          * ahead of them have completed.  I'm lumping untagged commands in
10925          * with simple tags here.  XXX KDM is that the right thing to do?
10926          */
10927         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10928           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10929          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10930           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10931                 return (CTL_ACTION_BLOCK);
10932
10933         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10934         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10935
10936         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10937
10938         switch (serialize_row[pending_entry->seridx]) {
10939         case CTL_SER_BLOCK:
10940                 return (CTL_ACTION_BLOCK);
10941                 break; /* NOTREACHED */
10942         case CTL_SER_EXTENT:
10943                 return (ctl_extent_check(pending_io, ooa_io));
10944                 break; /* NOTREACHED */
10945         case CTL_SER_PASS:
10946                 return (CTL_ACTION_PASS);
10947                 break; /* NOTREACHED */
10948         case CTL_SER_SKIP:
10949                 return (CTL_ACTION_SKIP);
10950                 break;
10951         default:
10952                 panic("invalid serialization value %d",
10953                       serialize_row[pending_entry->seridx]);
10954                 break; /* NOTREACHED */
10955         }
10956
10957         return (CTL_ACTION_ERROR);
10958 }
10959
10960 /*
10961  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10962  * Assumptions:
10963  * - pending_io is generally either incoming, or on the blocked queue
10964  * - starting I/O is the I/O we want to start the check with.
10965  */
10966 static ctl_action
10967 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10968               union ctl_io *starting_io)
10969 {
10970         union ctl_io *ooa_io;
10971         ctl_action action;
10972
10973         mtx_assert(&lun->lun_lock, MA_OWNED);
10974
10975         /*
10976          * Run back along the OOA queue, starting with the current
10977          * blocked I/O and going through every I/O before it on the
10978          * queue.  If starting_io is NULL, we'll just end up returning
10979          * CTL_ACTION_PASS.
10980          */
10981         for (ooa_io = starting_io; ooa_io != NULL;
10982              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10983              ooa_links)){
10984
10985                 /*
10986                  * This routine just checks to see whether
10987                  * cur_blocked is blocked by ooa_io, which is ahead
10988                  * of it in the queue.  It doesn't queue/dequeue
10989                  * cur_blocked.
10990                  */
10991                 action = ctl_check_for_blockage(pending_io, ooa_io);
10992                 switch (action) {
10993                 case CTL_ACTION_BLOCK:
10994                 case CTL_ACTION_OVERLAP:
10995                 case CTL_ACTION_OVERLAP_TAG:
10996                 case CTL_ACTION_SKIP:
10997                 case CTL_ACTION_ERROR:
10998                         return (action);
10999                         break; /* NOTREACHED */
11000                 case CTL_ACTION_PASS:
11001                         break;
11002                 default:
11003                         panic("invalid action %d", action);
11004                         break;  /* NOTREACHED */
11005                 }
11006         }
11007
11008         return (CTL_ACTION_PASS);
11009 }
11010
11011 /*
11012  * Assumptions:
11013  * - An I/O has just completed, and has been removed from the per-LUN OOA
11014  *   queue, so some items on the blocked queue may now be unblocked.
11015  */
11016 static int
11017 ctl_check_blocked(struct ctl_lun *lun)
11018 {
11019         union ctl_io *cur_blocked, *next_blocked;
11020
11021         mtx_assert(&lun->lun_lock, MA_OWNED);
11022
11023         /*
11024          * Run forward from the head of the blocked queue, checking each
11025          * entry against the I/Os prior to it on the OOA queue to see if
11026          * there is still any blockage.
11027          *
11028          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11029          * with our removing a variable on it while it is traversing the
11030          * list.
11031          */
11032         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11033              cur_blocked != NULL; cur_blocked = next_blocked) {
11034                 union ctl_io *prev_ooa;
11035                 ctl_action action;
11036
11037                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11038                                                           blocked_links);
11039
11040                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11041                                                       ctl_ooaq, ooa_links);
11042
11043                 /*
11044                  * If cur_blocked happens to be the first item in the OOA
11045                  * queue now, prev_ooa will be NULL, and the action
11046                  * returned will just be CTL_ACTION_PASS.
11047                  */
11048                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11049
11050                 switch (action) {
11051                 case CTL_ACTION_BLOCK:
11052                         /* Nothing to do here, still blocked */
11053                         break;
11054                 case CTL_ACTION_OVERLAP:
11055                 case CTL_ACTION_OVERLAP_TAG:
11056                         /*
11057                          * This shouldn't happen!  In theory we've already
11058                          * checked this command for overlap...
11059                          */
11060                         break;
11061                 case CTL_ACTION_PASS:
11062                 case CTL_ACTION_SKIP: {
11063                         struct ctl_softc *softc;
11064                         const struct ctl_cmd_entry *entry;
11065                         uint32_t initidx;
11066                         int isc_retval;
11067
11068                         /*
11069                          * The skip case shouldn't happen, this transaction
11070                          * should have never made it onto the blocked queue.
11071                          */
11072                         /*
11073                          * This I/O is no longer blocked, we can remove it
11074                          * from the blocked queue.  Since this is a TAILQ
11075                          * (doubly linked list), we can do O(1) removals
11076                          * from any place on the list.
11077                          */
11078                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11079                                      blocked_links);
11080                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11081
11082                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11083                                 /*
11084                                  * Need to send IO back to original side to
11085                                  * run
11086                                  */
11087                                 union ctl_ha_msg msg_info;
11088
11089                                 msg_info.hdr.original_sc =
11090                                         cur_blocked->io_hdr.original_sc;
11091                                 msg_info.hdr.serializing_sc = cur_blocked;
11092                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11093                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11094                                      &msg_info, sizeof(msg_info), 0)) >
11095                                      CTL_HA_STATUS_SUCCESS) {
11096                                         printf("CTL:Check Blocked error from "
11097                                                "ctl_ha_msg_send %d\n",
11098                                                isc_retval);
11099                                 }
11100                                 break;
11101                         }
11102                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
11103                         softc = control_softc;
11104
11105                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11106
11107                         /*
11108                          * Check this I/O for LUN state changes that may
11109                          * have happened while this command was blocked.
11110                          * The LUN state may have been changed by a command
11111                          * ahead of us in the queue, so we need to re-check
11112                          * for any states that can be caused by SCSI
11113                          * commands.
11114                          */
11115                         if (ctl_scsiio_lun_check(softc, lun, entry,
11116                                                  &cur_blocked->scsiio) == 0) {
11117                                 cur_blocked->io_hdr.flags |=
11118                                                       CTL_FLAG_IS_WAS_ON_RTR;
11119                                 ctl_enqueue_rtr(cur_blocked);
11120                         } else
11121                                 ctl_done(cur_blocked);
11122                         break;
11123                 }
11124                 default:
11125                         /*
11126                          * This probably shouldn't happen -- we shouldn't
11127                          * get CTL_ACTION_ERROR, or anything else.
11128                          */
11129                         break;
11130                 }
11131         }
11132
11133         return (CTL_RETVAL_COMPLETE);
11134 }
11135
11136 /*
11137  * This routine (with one exception) checks LUN flags that can be set by
11138  * commands ahead of us in the OOA queue.  These flags have to be checked
11139  * when a command initially comes in, and when we pull a command off the
11140  * blocked queue and are preparing to execute it.  The reason we have to
11141  * check these flags for commands on the blocked queue is that the LUN
11142  * state may have been changed by a command ahead of us while we're on the
11143  * blocked queue.
11144  *
11145  * Ordering is somewhat important with these checks, so please pay
11146  * careful attention to the placement of any new checks.
11147  */
11148 static int
11149 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11150     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11151 {
11152         int retval;
11153
11154         retval = 0;
11155
11156         mtx_assert(&lun->lun_lock, MA_OWNED);
11157
11158         /*
11159          * If this shelf is a secondary shelf controller, we have to reject
11160          * any media access commands.
11161          */
11162 #if 0
11163         /* No longer needed for HA */
11164         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11165          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11166                 ctl_set_lun_standby(ctsio);
11167                 retval = 1;
11168                 goto bailout;
11169         }
11170 #endif
11171
11172         /*
11173          * Check for a reservation conflict.  If this command isn't allowed
11174          * even on reserved LUNs, and if this initiator isn't the one who
11175          * reserved us, reject the command with a reservation conflict.
11176          */
11177         if ((lun->flags & CTL_LUN_RESERVED)
11178          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11179                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11180                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11181                  || (ctsio->io_hdr.nexus.targ_target.id !=
11182                      lun->rsv_nexus.targ_target.id)) {
11183                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11184                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11185                         retval = 1;
11186                         goto bailout;
11187                 }
11188         }
11189
11190         if ( (lun->flags & CTL_LUN_PR_RESERVED)
11191          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11192                 uint32_t residx;
11193
11194                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11195                 /*
11196                  * if we aren't registered or it's a res holder type
11197                  * reservation and this isn't the res holder then set a
11198                  * conflict.
11199                  * NOTE: Commands which might be allowed on write exclusive
11200                  * type reservations are checked in the particular command
11201                  * for a conflict. Read and SSU are the only ones.
11202                  */
11203                 if (!lun->per_res[residx].registered
11204                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11205                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11206                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11207                         retval = 1;
11208                         goto bailout;
11209                 }
11210
11211         }
11212
11213         if ((lun->flags & CTL_LUN_OFFLINE)
11214          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11215                 ctl_set_lun_not_ready(ctsio);
11216                 retval = 1;
11217                 goto bailout;
11218         }
11219
11220         /*
11221          * If the LUN is stopped, see if this particular command is allowed
11222          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11223          */
11224         if ((lun->flags & CTL_LUN_STOPPED)
11225          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11226                 /* "Logical unit not ready, initializing cmd. required" */
11227                 ctl_set_lun_stopped(ctsio);
11228                 retval = 1;
11229                 goto bailout;
11230         }
11231
11232         if ((lun->flags & CTL_LUN_INOPERABLE)
11233          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11234                 /* "Medium format corrupted" */
11235                 ctl_set_medium_format_corrupted(ctsio);
11236                 retval = 1;
11237                 goto bailout;
11238         }
11239
11240 bailout:
11241         return (retval);
11242
11243 }
11244
11245 static void
11246 ctl_failover_io(union ctl_io *io, int have_lock)
11247 {
11248         ctl_set_busy(&io->scsiio);
11249         ctl_done(io);
11250 }
11251
11252 static void
11253 ctl_failover(void)
11254 {
11255         struct ctl_lun *lun;
11256         struct ctl_softc *ctl_softc;
11257         union ctl_io *next_io, *pending_io;
11258         union ctl_io *io;
11259         int lun_idx;
11260         int i;
11261
11262         ctl_softc = control_softc;
11263
11264         mtx_lock(&ctl_softc->ctl_lock);
11265         /*
11266          * Remove any cmds from the other SC from the rtr queue.  These
11267          * will obviously only be for LUNs for which we're the primary.
11268          * We can't send status or get/send data for these commands.
11269          * Since they haven't been executed yet, we can just remove them.
11270          * We'll either abort them or delete them below, depending on
11271          * which HA mode we're in.
11272          */
11273 #ifdef notyet
11274         mtx_lock(&ctl_softc->queue_lock);
11275         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11276              io != NULL; io = next_io) {
11277                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11278                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11279                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11280                                       ctl_io_hdr, links);
11281         }
11282         mtx_unlock(&ctl_softc->queue_lock);
11283 #endif
11284
11285         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11286                 lun = ctl_softc->ctl_luns[lun_idx];
11287                 if (lun==NULL)
11288                         continue;
11289
11290                 /*
11291                  * Processor LUNs are primary on both sides.
11292                  * XXX will this always be true?
11293                  */
11294                 if (lun->be_lun->lun_type == T_PROCESSOR)
11295                         continue;
11296
11297                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11298                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11299                         printf("FAILOVER: primary lun %d\n", lun_idx);
11300                         /*
11301                          * Remove all commands from the other SC. First from the
11302                          * blocked queue then from the ooa queue. Once we have
11303                          * removed them. Call ctl_check_blocked to see if there
11304                          * is anything that can run.
11305                          */
11306                         for (io = (union ctl_io *)TAILQ_FIRST(
11307                              &lun->blocked_queue); io != NULL; io = next_io) {
11308
11309                                 next_io = (union ctl_io *)TAILQ_NEXT(
11310                                     &io->io_hdr, blocked_links);
11311
11312                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11313                                         TAILQ_REMOVE(&lun->blocked_queue,
11314                                                      &io->io_hdr,blocked_links);
11315                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11316                                         TAILQ_REMOVE(&lun->ooa_queue,
11317                                                      &io->io_hdr, ooa_links);
11318
11319                                         ctl_free_io(io);
11320                                 }
11321                         }
11322
11323                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11324                              io != NULL; io = next_io) {
11325
11326                                 next_io = (union ctl_io *)TAILQ_NEXT(
11327                                     &io->io_hdr, ooa_links);
11328
11329                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11330
11331                                         TAILQ_REMOVE(&lun->ooa_queue,
11332                                                 &io->io_hdr,
11333                                                 ooa_links);
11334
11335                                         ctl_free_io(io);
11336                                 }
11337                         }
11338                         ctl_check_blocked(lun);
11339                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11340                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11341
11342                         printf("FAILOVER: primary lun %d\n", lun_idx);
11343                         /*
11344                          * Abort all commands from the other SC.  We can't
11345                          * send status back for them now.  These should get
11346                          * cleaned up when they are completed or come out
11347                          * for a datamove operation.
11348                          */
11349                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11350                              io != NULL; io = next_io) {
11351                                 next_io = (union ctl_io *)TAILQ_NEXT(
11352                                         &io->io_hdr, ooa_links);
11353
11354                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11355                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11356                         }
11357                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11358                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11359
11360                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11361
11362                         lun->flags |= CTL_LUN_PRIMARY_SC;
11363
11364                         /*
11365                          * We send all I/O that was sent to this controller
11366                          * and redirected to the other side back with
11367                          * busy status, and have the initiator retry it.
11368                          * Figuring out how much data has been transferred,
11369                          * etc. and picking up where we left off would be 
11370                          * very tricky.
11371                          *
11372                          * XXX KDM need to remove I/O from the blocked
11373                          * queue as well!
11374                          */
11375                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11376                              &lun->ooa_queue); pending_io != NULL;
11377                              pending_io = next_io) {
11378
11379                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11380                                         &pending_io->io_hdr, ooa_links);
11381
11382                                 pending_io->io_hdr.flags &=
11383                                         ~CTL_FLAG_SENT_2OTHER_SC;
11384
11385                                 if (pending_io->io_hdr.flags &
11386                                     CTL_FLAG_IO_ACTIVE) {
11387                                         pending_io->io_hdr.flags |=
11388                                                 CTL_FLAG_FAILOVER;
11389                                 } else {
11390                                         ctl_set_busy(&pending_io->scsiio);
11391                                         ctl_done(pending_io);
11392                                 }
11393                         }
11394
11395                         /*
11396                          * Build Unit Attention
11397                          */
11398                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11399                                 lun->pending_ua[i] |=
11400                                                      CTL_UA_ASYM_ACC_CHANGE;
11401                         }
11402                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11403                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11404                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11405                         /*
11406                          * if the first io on the OOA is not on the RtR queue
11407                          * add it.
11408                          */
11409                         lun->flags |= CTL_LUN_PRIMARY_SC;
11410
11411                         pending_io = (union ctl_io *)TAILQ_FIRST(
11412                             &lun->ooa_queue);
11413                         if (pending_io==NULL) {
11414                                 printf("Nothing on OOA queue\n");
11415                                 continue;
11416                         }
11417
11418                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11419                         if ((pending_io->io_hdr.flags &
11420                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11421                                 pending_io->io_hdr.flags |=
11422                                     CTL_FLAG_IS_WAS_ON_RTR;
11423                                 ctl_enqueue_rtr(pending_io);
11424                         }
11425 #if 0
11426                         else
11427                         {
11428                                 printf("Tag 0x%04x is running\n",
11429                                       pending_io->scsiio.tag_num);
11430                         }
11431 #endif
11432
11433                         next_io = (union ctl_io *)TAILQ_NEXT(
11434                             &pending_io->io_hdr, ooa_links);
11435                         for (pending_io=next_io; pending_io != NULL;
11436                              pending_io = next_io) {
11437                                 pending_io->io_hdr.flags &=
11438                                     ~CTL_FLAG_SENT_2OTHER_SC;
11439                                 next_io = (union ctl_io *)TAILQ_NEXT(
11440                                         &pending_io->io_hdr, ooa_links);
11441                                 if (pending_io->io_hdr.flags &
11442                                     CTL_FLAG_IS_WAS_ON_RTR) {
11443 #if 0
11444                                         printf("Tag 0x%04x is running\n",
11445                                                 pending_io->scsiio.tag_num);
11446 #endif
11447                                         continue;
11448                                 }
11449
11450                                 switch (ctl_check_ooa(lun, pending_io,
11451                                     (union ctl_io *)TAILQ_PREV(
11452                                     &pending_io->io_hdr, ctl_ooaq,
11453                                     ooa_links))) {
11454
11455                                 case CTL_ACTION_BLOCK:
11456                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11457                                                           &pending_io->io_hdr,
11458                                                           blocked_links);
11459                                         pending_io->io_hdr.flags |=
11460                                             CTL_FLAG_BLOCKED;
11461                                         break;
11462                                 case CTL_ACTION_PASS:
11463                                 case CTL_ACTION_SKIP:
11464                                         pending_io->io_hdr.flags |=
11465                                             CTL_FLAG_IS_WAS_ON_RTR;
11466                                         ctl_enqueue_rtr(pending_io);
11467                                         break;
11468                                 case CTL_ACTION_OVERLAP:
11469                                         ctl_set_overlapped_cmd(
11470                                             (struct ctl_scsiio *)pending_io);
11471                                         ctl_done(pending_io);
11472                                         break;
11473                                 case CTL_ACTION_OVERLAP_TAG:
11474                                         ctl_set_overlapped_tag(
11475                                             (struct ctl_scsiio *)pending_io,
11476                                             pending_io->scsiio.tag_num & 0xff);
11477                                         ctl_done(pending_io);
11478                                         break;
11479                                 case CTL_ACTION_ERROR:
11480                                 default:
11481                                         ctl_set_internal_failure(
11482                                                 (struct ctl_scsiio *)pending_io,
11483                                                 0,  // sks_valid
11484                                                 0); //retry count
11485                                         ctl_done(pending_io);
11486                                         break;
11487                                 }
11488                         }
11489
11490                         /*
11491                          * Build Unit Attention
11492                          */
11493                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11494                                 lun->pending_ua[i] |=
11495                                                      CTL_UA_ASYM_ACC_CHANGE;
11496                         }
11497                 } else {
11498                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11499                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11500                 }
11501         }
11502         ctl_pause_rtr = 0;
11503         mtx_unlock(&ctl_softc->ctl_lock);
11504 }
11505
11506 static int
11507 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11508 {
11509         struct ctl_lun *lun;
11510         const struct ctl_cmd_entry *entry;
11511         uint32_t initidx, targ_lun;
11512         int retval;
11513
11514         retval = 0;
11515
11516         lun = NULL;
11517
11518         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11519         if ((targ_lun < CTL_MAX_LUNS)
11520          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11521                 lun = ctl_softc->ctl_luns[targ_lun];
11522                 /*
11523                  * If the LUN is invalid, pretend that it doesn't exist.
11524                  * It will go away as soon as all pending I/O has been
11525                  * completed.
11526                  */
11527                 if (lun->flags & CTL_LUN_DISABLED) {
11528                         lun = NULL;
11529                 } else {
11530                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11531                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11532                                 lun->be_lun;
11533                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11534                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11535                         }
11536
11537                         /*
11538                          * Every I/O goes into the OOA queue for a
11539                          * particular LUN, and stays there until completion.
11540                          */
11541                         mtx_lock(&lun->lun_lock);
11542                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11543                             ooa_links);
11544                 }
11545         } else {
11546                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11547                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11548         }
11549
11550         /* Get command entry and return error if it is unsuppotyed. */
11551         entry = ctl_validate_command(ctsio);
11552         if (entry == NULL) {
11553                 if (lun)
11554                         mtx_unlock(&lun->lun_lock);
11555                 return (retval);
11556         }
11557
11558         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11559         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11560
11561         /*
11562          * Check to see whether we can send this command to LUNs that don't
11563          * exist.  This should pretty much only be the case for inquiry
11564          * and request sense.  Further checks, below, really require having
11565          * a LUN, so we can't really check the command anymore.  Just put
11566          * it on the rtr queue.
11567          */
11568         if (lun == NULL) {
11569                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11570                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11571                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11572                         return (retval);
11573                 }
11574
11575                 ctl_set_unsupported_lun(ctsio);
11576                 ctl_done((union ctl_io *)ctsio);
11577                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11578                 return (retval);
11579         } else {
11580                 /*
11581                  * Make sure we support this particular command on this LUN.
11582                  * e.g., we don't support writes to the control LUN.
11583                  */
11584                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11585                         mtx_unlock(&lun->lun_lock);
11586                         ctl_set_invalid_opcode(ctsio);
11587                         ctl_done((union ctl_io *)ctsio);
11588                         return (retval);
11589                 }
11590         }
11591
11592         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11593
11594 #ifdef CTL_WITH_CA
11595         /*
11596          * If we've got a request sense, it'll clear the contingent
11597          * allegiance condition.  Otherwise, if we have a CA condition for
11598          * this initiator, clear it, because it sent down a command other
11599          * than request sense.
11600          */
11601         if ((ctsio->cdb[0] != REQUEST_SENSE)
11602          && (ctl_is_set(lun->have_ca, initidx)))
11603                 ctl_clear_mask(lun->have_ca, initidx);
11604 #endif
11605
11606         /*
11607          * If the command has this flag set, it handles its own unit
11608          * attention reporting, we shouldn't do anything.  Otherwise we
11609          * check for any pending unit attentions, and send them back to the
11610          * initiator.  We only do this when a command initially comes in,
11611          * not when we pull it off the blocked queue.
11612          *
11613          * According to SAM-3, section 5.3.2, the order that things get
11614          * presented back to the host is basically unit attentions caused
11615          * by some sort of reset event, busy status, reservation conflicts
11616          * or task set full, and finally any other status.
11617          *
11618          * One issue here is that some of the unit attentions we report
11619          * don't fall into the "reset" category (e.g. "reported luns data
11620          * has changed").  So reporting it here, before the reservation
11621          * check, may be technically wrong.  I guess the only thing to do
11622          * would be to check for and report the reset events here, and then
11623          * check for the other unit attention types after we check for a
11624          * reservation conflict.
11625          *
11626          * XXX KDM need to fix this
11627          */
11628         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11629                 ctl_ua_type ua_type;
11630
11631                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11632                         scsi_sense_data_type sense_format;
11633
11634                         if (lun != NULL)
11635                                 sense_format = (lun->flags &
11636                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11637                                     SSD_TYPE_FIXED;
11638                         else
11639                                 sense_format = SSD_TYPE_FIXED;
11640
11641                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11642                             &ctsio->sense_data, sense_format);
11643                         if (ua_type != CTL_UA_NONE) {
11644                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11645                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11646                                                        CTL_AUTOSENSE;
11647                                 ctsio->sense_len = SSD_FULL_SIZE;
11648                                 mtx_unlock(&lun->lun_lock);
11649                                 ctl_done((union ctl_io *)ctsio);
11650                                 return (retval);
11651                         }
11652                 }
11653         }
11654
11655
11656         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11657                 mtx_unlock(&lun->lun_lock);
11658                 ctl_done((union ctl_io *)ctsio);
11659                 return (retval);
11660         }
11661
11662         /*
11663          * XXX CHD this is where we want to send IO to other side if
11664          * this LUN is secondary on this SC. We will need to make a copy
11665          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11666          * the copy we send as FROM_OTHER.
11667          * We also need to stuff the address of the original IO so we can
11668          * find it easily. Something similar will need be done on the other
11669          * side so when we are done we can find the copy.
11670          */
11671         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11672                 union ctl_ha_msg msg_info;
11673                 int isc_retval;
11674
11675                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11676
11677                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11678                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11679 #if 0
11680                 printf("1. ctsio %p\n", ctsio);
11681 #endif
11682                 msg_info.hdr.serializing_sc = NULL;
11683                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11684                 msg_info.scsi.tag_num = ctsio->tag_num;
11685                 msg_info.scsi.tag_type = ctsio->tag_type;
11686                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11687
11688                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11689
11690                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11691                     (void *)&msg_info, sizeof(msg_info), 0)) >
11692                     CTL_HA_STATUS_SUCCESS) {
11693                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11694                                isc_retval);
11695                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11696                 } else {
11697 #if 0
11698                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11699 #endif
11700                 }
11701
11702                 /*
11703                  * XXX KDM this I/O is off the incoming queue, but hasn't
11704                  * been inserted on any other queue.  We may need to come
11705                  * up with a holding queue while we wait for serialization
11706                  * so that we have an idea of what we're waiting for from
11707                  * the other side.
11708                  */
11709                 mtx_unlock(&lun->lun_lock);
11710                 return (retval);
11711         }
11712
11713         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11714                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11715                               ctl_ooaq, ooa_links))) {
11716         case CTL_ACTION_BLOCK:
11717                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11718                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11719                                   blocked_links);
11720                 mtx_unlock(&lun->lun_lock);
11721                 return (retval);
11722         case CTL_ACTION_PASS:
11723         case CTL_ACTION_SKIP:
11724                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11725                 mtx_unlock(&lun->lun_lock);
11726                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11727                 break;
11728         case CTL_ACTION_OVERLAP:
11729                 mtx_unlock(&lun->lun_lock);
11730                 ctl_set_overlapped_cmd(ctsio);
11731                 ctl_done((union ctl_io *)ctsio);
11732                 break;
11733         case CTL_ACTION_OVERLAP_TAG:
11734                 mtx_unlock(&lun->lun_lock);
11735                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11736                 ctl_done((union ctl_io *)ctsio);
11737                 break;
11738         case CTL_ACTION_ERROR:
11739         default:
11740                 mtx_unlock(&lun->lun_lock);
11741                 ctl_set_internal_failure(ctsio,
11742                                          /*sks_valid*/ 0,
11743                                          /*retry_count*/ 0);
11744                 ctl_done((union ctl_io *)ctsio);
11745                 break;
11746         }
11747         return (retval);
11748 }
11749
11750 const struct ctl_cmd_entry *
11751 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11752 {
11753         const struct ctl_cmd_entry *entry;
11754         int service_action;
11755
11756         entry = &ctl_cmd_table[ctsio->cdb[0]];
11757         if (entry->flags & CTL_CMD_FLAG_SA5) {
11758                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11759                 entry = &((const struct ctl_cmd_entry *)
11760                     entry->execute)[service_action];
11761         }
11762         return (entry);
11763 }
11764
11765 const struct ctl_cmd_entry *
11766 ctl_validate_command(struct ctl_scsiio *ctsio)
11767 {
11768         const struct ctl_cmd_entry *entry;
11769         int i;
11770         uint8_t diff;
11771
11772         entry = ctl_get_cmd_entry(ctsio);
11773         if (entry->execute == NULL) {
11774                 ctl_set_invalid_opcode(ctsio);
11775                 ctl_done((union ctl_io *)ctsio);
11776                 return (NULL);
11777         }
11778         KASSERT(entry->length > 0,
11779             ("Not defined length for command 0x%02x/0x%02x",
11780              ctsio->cdb[0], ctsio->cdb[1]));
11781         for (i = 1; i < entry->length; i++) {
11782                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11783                 if (diff == 0)
11784                         continue;
11785                 ctl_set_invalid_field(ctsio,
11786                                       /*sks_valid*/ 1,
11787                                       /*command*/ 1,
11788                                       /*field*/ i,
11789                                       /*bit_valid*/ 1,
11790                                       /*bit*/ fls(diff) - 1);
11791                 ctl_done((union ctl_io *)ctsio);
11792                 return (NULL);
11793         }
11794         return (entry);
11795 }
11796
11797 static int
11798 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11799 {
11800
11801         switch (lun_type) {
11802         case T_PROCESSOR:
11803                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11804                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11805                         return (0);
11806                 break;
11807         case T_DIRECT:
11808                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11809                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11810                         return (0);
11811                 break;
11812         default:
11813                 return (0);
11814         }
11815         return (1);
11816 }
11817
11818 static int
11819 ctl_scsiio(struct ctl_scsiio *ctsio)
11820 {
11821         int retval;
11822         const struct ctl_cmd_entry *entry;
11823
11824         retval = CTL_RETVAL_COMPLETE;
11825
11826         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11827
11828         entry = ctl_get_cmd_entry(ctsio);
11829
11830         /*
11831          * If this I/O has been aborted, just send it straight to
11832          * ctl_done() without executing it.
11833          */
11834         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11835                 ctl_done((union ctl_io *)ctsio);
11836                 goto bailout;
11837         }
11838
11839         /*
11840          * All the checks should have been handled by ctl_scsiio_precheck().
11841          * We should be clear now to just execute the I/O.
11842          */
11843         retval = entry->execute(ctsio);
11844
11845 bailout:
11846         return (retval);
11847 }
11848
11849 /*
11850  * Since we only implement one target right now, a bus reset simply resets
11851  * our single target.
11852  */
11853 static int
11854 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11855 {
11856         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11857 }
11858
11859 static int
11860 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11861                  ctl_ua_type ua_type)
11862 {
11863         struct ctl_lun *lun;
11864         int retval;
11865
11866         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11867                 union ctl_ha_msg msg_info;
11868
11869                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11870                 msg_info.hdr.nexus = io->io_hdr.nexus;
11871                 if (ua_type==CTL_UA_TARG_RESET)
11872                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11873                 else
11874                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11875                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11876                 msg_info.hdr.original_sc = NULL;
11877                 msg_info.hdr.serializing_sc = NULL;
11878                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11879                     (void *)&msg_info, sizeof(msg_info), 0)) {
11880                 }
11881         }
11882         retval = 0;
11883
11884         mtx_lock(&ctl_softc->ctl_lock);
11885         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11886                 retval += ctl_lun_reset(lun, io, ua_type);
11887         mtx_unlock(&ctl_softc->ctl_lock);
11888
11889         return (retval);
11890 }
11891
11892 /*
11893  * The LUN should always be set.  The I/O is optional, and is used to
11894  * distinguish between I/Os sent by this initiator, and by other
11895  * initiators.  We set unit attention for initiators other than this one.
11896  * SAM-3 is vague on this point.  It does say that a unit attention should
11897  * be established for other initiators when a LUN is reset (see section
11898  * 5.7.3), but it doesn't specifically say that the unit attention should
11899  * be established for this particular initiator when a LUN is reset.  Here
11900  * is the relevant text, from SAM-3 rev 8:
11901  *
11902  * 5.7.2 When a SCSI initiator port aborts its own tasks
11903  *
11904  * When a SCSI initiator port causes its own task(s) to be aborted, no
11905  * notification that the task(s) have been aborted shall be returned to
11906  * the SCSI initiator port other than the completion response for the
11907  * command or task management function action that caused the task(s) to
11908  * be aborted and notification(s) associated with related effects of the
11909  * action (e.g., a reset unit attention condition).
11910  *
11911  * XXX KDM for now, we're setting unit attention for all initiators.
11912  */
11913 static int
11914 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11915 {
11916         union ctl_io *xio;
11917 #if 0
11918         uint32_t initindex;
11919 #endif
11920         int i;
11921
11922         mtx_lock(&lun->lun_lock);
11923         /*
11924          * Run through the OOA queue and abort each I/O.
11925          */
11926 #if 0
11927         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11928 #endif
11929         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11930              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11931                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11932         }
11933
11934         /*
11935          * This version sets unit attention for every
11936          */
11937 #if 0
11938         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11939         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11940                 if (initindex == i)
11941                         continue;
11942                 lun->pending_ua[i] |= ua_type;
11943         }
11944 #endif
11945
11946         /*
11947          * A reset (any kind, really) clears reservations established with
11948          * RESERVE/RELEASE.  It does not clear reservations established
11949          * with PERSISTENT RESERVE OUT, but we don't support that at the
11950          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11951          * reservations made with the RESERVE/RELEASE commands, because
11952          * those commands are obsolete in SPC-3.
11953          */
11954         lun->flags &= ~CTL_LUN_RESERVED;
11955
11956         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11957 #ifdef CTL_WITH_CA
11958                 ctl_clear_mask(lun->have_ca, i);
11959 #endif
11960                 lun->pending_ua[i] |= ua_type;
11961         }
11962         mtx_unlock(&lun->lun_lock);
11963
11964         return (0);
11965 }
11966
11967 static int
11968 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11969     int other_sc)
11970 {
11971         union ctl_io *xio;
11972         int found;
11973
11974         mtx_assert(&lun->lun_lock, MA_OWNED);
11975
11976         /*
11977          * Run through the OOA queue and attempt to find the given I/O.
11978          * The target port, initiator ID, tag type and tag number have to
11979          * match the values that we got from the initiator.  If we have an
11980          * untagged command to abort, simply abort the first untagged command
11981          * we come to.  We only allow one untagged command at a time of course.
11982          */
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
11986                 if ((targ_port == UINT32_MAX ||
11987                      targ_port == xio->io_hdr.nexus.targ_port) &&
11988                     (init_id == UINT32_MAX ||
11989                      init_id == xio->io_hdr.nexus.initid.id)) {
11990                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11991                             init_id != xio->io_hdr.nexus.initid.id)
11992                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11993                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11994                         found = 1;
11995                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11996                                 union ctl_ha_msg msg_info;
11997
11998                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11999                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12000                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12001                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12002                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12003                                 msg_info.hdr.original_sc = NULL;
12004                                 msg_info.hdr.serializing_sc = NULL;
12005                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12006                                     (void *)&msg_info, sizeof(msg_info), 0);
12007                         }
12008                 }
12009         }
12010         return (found);
12011 }
12012
12013 static int
12014 ctl_abort_task_set(union ctl_io *io)
12015 {
12016         struct ctl_softc *softc = control_softc;
12017         struct ctl_lun *lun;
12018         uint32_t targ_lun;
12019
12020         /*
12021          * Look up the LUN.
12022          */
12023         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12024         mtx_lock(&softc->ctl_lock);
12025         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12026                 lun = softc->ctl_luns[targ_lun];
12027         else {
12028                 mtx_unlock(&softc->ctl_lock);
12029                 return (1);
12030         }
12031
12032         mtx_lock(&lun->lun_lock);
12033         mtx_unlock(&softc->ctl_lock);
12034         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12035                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12036                     io->io_hdr.nexus.initid.id,
12037                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12038         } else { /* CTL_TASK_CLEAR_TASK_SET */
12039                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12040                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12041         }
12042         mtx_unlock(&lun->lun_lock);
12043         return (0);
12044 }
12045
12046 static int
12047 ctl_i_t_nexus_reset(union ctl_io *io)
12048 {
12049         struct ctl_softc *softc = control_softc;
12050         struct ctl_lun *lun;
12051         uint32_t initindex;
12052
12053         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12054         mtx_lock(&softc->ctl_lock);
12055         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12056                 mtx_lock(&lun->lun_lock);
12057                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12058                     io->io_hdr.nexus.initid.id,
12059                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12060 #ifdef CTL_WITH_CA
12061                 ctl_clear_mask(lun->have_ca, initindex);
12062 #endif
12063                 lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12064                 mtx_unlock(&lun->lun_lock);
12065         }
12066         mtx_unlock(&softc->ctl_lock);
12067         return (0);
12068 }
12069
12070 static int
12071 ctl_abort_task(union ctl_io *io)
12072 {
12073         union ctl_io *xio;
12074         struct ctl_lun *lun;
12075         struct ctl_softc *ctl_softc;
12076 #if 0
12077         struct sbuf sb;
12078         char printbuf[128];
12079 #endif
12080         int found;
12081         uint32_t targ_lun;
12082
12083         ctl_softc = control_softc;
12084         found = 0;
12085
12086         /*
12087          * Look up the LUN.
12088          */
12089         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12090         mtx_lock(&ctl_softc->ctl_lock);
12091         if ((targ_lun < CTL_MAX_LUNS)
12092          && (ctl_softc->ctl_luns[targ_lun] != NULL))
12093                 lun = ctl_softc->ctl_luns[targ_lun];
12094         else {
12095                 mtx_unlock(&ctl_softc->ctl_lock);
12096                 return (1);
12097         }
12098
12099 #if 0
12100         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12101                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12102 #endif
12103
12104         mtx_lock(&lun->lun_lock);
12105         mtx_unlock(&ctl_softc->ctl_lock);
12106         /*
12107          * Run through the OOA queue and attempt to find the given I/O.
12108          * The target port, initiator ID, tag type and tag number have to
12109          * match the values that we got from the initiator.  If we have an
12110          * untagged command to abort, simply abort the first untagged command
12111          * we come to.  We only allow one untagged command at a time of course.
12112          */
12113 #if 0
12114         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12115 #endif
12116         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12117              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12118 #if 0
12119                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12120
12121                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12122                             lun->lun, xio->scsiio.tag_num,
12123                             xio->scsiio.tag_type,
12124                             (xio->io_hdr.blocked_links.tqe_prev
12125                             == NULL) ? "" : " BLOCKED",
12126                             (xio->io_hdr.flags &
12127                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12128                             (xio->io_hdr.flags &
12129                             CTL_FLAG_ABORT) ? " ABORT" : "",
12130                             (xio->io_hdr.flags &
12131                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12132                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12133                 sbuf_finish(&sb);
12134                 printf("%s\n", sbuf_data(&sb));
12135 #endif
12136
12137                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12138                  && (xio->io_hdr.nexus.initid.id ==
12139                      io->io_hdr.nexus.initid.id)) {
12140                         /*
12141                          * If the abort says that the task is untagged, the
12142                          * task in the queue must be untagged.  Otherwise,
12143                          * we just check to see whether the tag numbers
12144                          * match.  This is because the QLogic firmware
12145                          * doesn't pass back the tag type in an abort
12146                          * request.
12147                          */
12148 #if 0
12149                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12150                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12151                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12152 #endif
12153                         /*
12154                          * XXX KDM we've got problems with FC, because it
12155                          * doesn't send down a tag type with aborts.  So we
12156                          * can only really go by the tag number...
12157                          * This may cause problems with parallel SCSI.
12158                          * Need to figure that out!!
12159                          */
12160                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12161                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12162                                 found = 1;
12163                                 if ((io->io_hdr.flags &
12164                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12165                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12166                                         union ctl_ha_msg msg_info;
12167
12168                                         io->io_hdr.flags |=
12169                                                         CTL_FLAG_SENT_2OTHER_SC;
12170                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12171                                         msg_info.task.task_action =
12172                                                 CTL_TASK_ABORT_TASK;
12173                                         msg_info.task.tag_num =
12174                                                 io->taskio.tag_num;
12175                                         msg_info.task.tag_type =
12176                                                 io->taskio.tag_type;
12177                                         msg_info.hdr.msg_type =
12178                                                 CTL_MSG_MANAGE_TASKS;
12179                                         msg_info.hdr.original_sc = NULL;
12180                                         msg_info.hdr.serializing_sc = NULL;
12181 #if 0
12182                                         printf("Sent Abort to other side\n");
12183 #endif
12184                                         if (CTL_HA_STATUS_SUCCESS !=
12185                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12186                                                 (void *)&msg_info,
12187                                                 sizeof(msg_info), 0)) {
12188                                         }
12189                                 }
12190 #if 0
12191                                 printf("ctl_abort_task: found I/O to abort\n");
12192 #endif
12193                                 break;
12194                         }
12195                 }
12196         }
12197         mtx_unlock(&lun->lun_lock);
12198
12199         if (found == 0) {
12200                 /*
12201                  * This isn't really an error.  It's entirely possible for
12202                  * the abort and command completion to cross on the wire.
12203                  * This is more of an informative/diagnostic error.
12204                  */
12205 #if 0
12206                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12207                        "%d:%d:%d:%d tag %d type %d\n",
12208                        io->io_hdr.nexus.initid.id,
12209                        io->io_hdr.nexus.targ_port,
12210                        io->io_hdr.nexus.targ_target.id,
12211                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12212                        io->taskio.tag_type);
12213 #endif
12214         }
12215         return (0);
12216 }
12217
12218 static void
12219 ctl_run_task(union ctl_io *io)
12220 {
12221         struct ctl_softc *ctl_softc = control_softc;
12222         int retval = 1;
12223         const char *task_desc;
12224
12225         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12226
12227         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12228             ("ctl_run_task: Unextected io_type %d\n",
12229              io->io_hdr.io_type));
12230
12231         task_desc = ctl_scsi_task_string(&io->taskio);
12232         if (task_desc != NULL) {
12233 #ifdef NEEDTOPORT
12234                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12235                             CTL_TASK_REPORT,
12236                             csevent_LogType_Trace,
12237                             csevent_Severity_Information,
12238                             csevent_AlertLevel_Green,
12239                             csevent_FRU_Firmware,
12240                             csevent_FRU_Unknown,
12241                             "CTL: received task: %s",task_desc);
12242 #endif
12243         } else {
12244 #ifdef NEEDTOPORT
12245                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12246                             CTL_TASK_REPORT,
12247                             csevent_LogType_Trace,
12248                             csevent_Severity_Information,
12249                             csevent_AlertLevel_Green,
12250                             csevent_FRU_Firmware,
12251                             csevent_FRU_Unknown,
12252                             "CTL: received unknown task "
12253                             "type: %d (%#x)",
12254                             io->taskio.task_action,
12255                             io->taskio.task_action);
12256 #endif
12257         }
12258         switch (io->taskio.task_action) {
12259         case CTL_TASK_ABORT_TASK:
12260                 retval = ctl_abort_task(io);
12261                 break;
12262         case CTL_TASK_ABORT_TASK_SET:
12263         case CTL_TASK_CLEAR_TASK_SET:
12264                 retval = ctl_abort_task_set(io);
12265                 break;
12266         case CTL_TASK_CLEAR_ACA:
12267                 break;
12268         case CTL_TASK_I_T_NEXUS_RESET:
12269                 retval = ctl_i_t_nexus_reset(io);
12270                 break;
12271         case CTL_TASK_LUN_RESET: {
12272                 struct ctl_lun *lun;
12273                 uint32_t targ_lun;
12274
12275                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12276                 mtx_lock(&ctl_softc->ctl_lock);
12277                 if ((targ_lun < CTL_MAX_LUNS)
12278                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12279                         lun = ctl_softc->ctl_luns[targ_lun];
12280                 else {
12281                         mtx_unlock(&ctl_softc->ctl_lock);
12282                         retval = 1;
12283                         break;
12284                 }
12285
12286                 if (!(io->io_hdr.flags &
12287                     CTL_FLAG_FROM_OTHER_SC)) {
12288                         union ctl_ha_msg msg_info;
12289
12290                         io->io_hdr.flags |=
12291                                 CTL_FLAG_SENT_2OTHER_SC;
12292                         msg_info.hdr.msg_type =
12293                                 CTL_MSG_MANAGE_TASKS;
12294                         msg_info.hdr.nexus = io->io_hdr.nexus;
12295                         msg_info.task.task_action =
12296                                 CTL_TASK_LUN_RESET;
12297                         msg_info.hdr.original_sc = NULL;
12298                         msg_info.hdr.serializing_sc = NULL;
12299                         if (CTL_HA_STATUS_SUCCESS !=
12300                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12301                             (void *)&msg_info,
12302                             sizeof(msg_info), 0)) {
12303                         }
12304                 }
12305
12306                 retval = ctl_lun_reset(lun, io,
12307                                        CTL_UA_LUN_RESET);
12308                 mtx_unlock(&ctl_softc->ctl_lock);
12309                 break;
12310         }
12311         case CTL_TASK_TARGET_RESET:
12312                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12313                 break;
12314         case CTL_TASK_BUS_RESET:
12315                 retval = ctl_bus_reset(ctl_softc, io);
12316                 break;
12317         case CTL_TASK_PORT_LOGIN:
12318                 break;
12319         case CTL_TASK_PORT_LOGOUT:
12320                 break;
12321         default:
12322                 printf("ctl_run_task: got unknown task management event %d\n",
12323                        io->taskio.task_action);
12324                 break;
12325         }
12326         if (retval == 0)
12327                 io->io_hdr.status = CTL_SUCCESS;
12328         else
12329                 io->io_hdr.status = CTL_ERROR;
12330         ctl_done(io);
12331 }
12332
12333 /*
12334  * For HA operation.  Handle commands that come in from the other
12335  * controller.
12336  */
12337 static void
12338 ctl_handle_isc(union ctl_io *io)
12339 {
12340         int free_io;
12341         struct ctl_lun *lun;
12342         struct ctl_softc *ctl_softc;
12343         uint32_t targ_lun;
12344
12345         ctl_softc = control_softc;
12346
12347         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12348         lun = ctl_softc->ctl_luns[targ_lun];
12349
12350         switch (io->io_hdr.msg_type) {
12351         case CTL_MSG_SERIALIZE:
12352                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12353                 break;
12354         case CTL_MSG_R2R: {
12355                 const struct ctl_cmd_entry *entry;
12356
12357                 /*
12358                  * This is only used in SER_ONLY mode.
12359                  */
12360                 free_io = 0;
12361                 entry = ctl_get_cmd_entry(&io->scsiio);
12362                 mtx_lock(&lun->lun_lock);
12363                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12364                     entry, (struct ctl_scsiio *)io) != 0) {
12365                         mtx_unlock(&lun->lun_lock);
12366                         ctl_done(io);
12367                         break;
12368                 }
12369                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12370                 mtx_unlock(&lun->lun_lock);
12371                 ctl_enqueue_rtr(io);
12372                 break;
12373         }
12374         case CTL_MSG_FINISH_IO:
12375                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12376                         free_io = 0;
12377                         ctl_done(io);
12378                 } else {
12379                         free_io = 1;
12380                         mtx_lock(&lun->lun_lock);
12381                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12382                                      ooa_links);
12383                         ctl_check_blocked(lun);
12384                         mtx_unlock(&lun->lun_lock);
12385                 }
12386                 break;
12387         case CTL_MSG_PERS_ACTION:
12388                 ctl_hndl_per_res_out_on_other_sc(
12389                         (union ctl_ha_msg *)&io->presio.pr_msg);
12390                 free_io = 1;
12391                 break;
12392         case CTL_MSG_BAD_JUJU:
12393                 free_io = 0;
12394                 ctl_done(io);
12395                 break;
12396         case CTL_MSG_DATAMOVE:
12397                 /* Only used in XFER mode */
12398                 free_io = 0;
12399                 ctl_datamove_remote(io);
12400                 break;
12401         case CTL_MSG_DATAMOVE_DONE:
12402                 /* Only used in XFER mode */
12403                 free_io = 0;
12404                 io->scsiio.be_move_done(io);
12405                 break;
12406         default:
12407                 free_io = 1;
12408                 printf("%s: Invalid message type %d\n",
12409                        __func__, io->io_hdr.msg_type);
12410                 break;
12411         }
12412         if (free_io)
12413                 ctl_free_io(io);
12414
12415 }
12416
12417
12418 /*
12419  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12420  * there is no match.
12421  */
12422 static ctl_lun_error_pattern
12423 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12424 {
12425         const struct ctl_cmd_entry *entry;
12426         ctl_lun_error_pattern filtered_pattern, pattern;
12427
12428         pattern = desc->error_pattern;
12429
12430         /*
12431          * XXX KDM we need more data passed into this function to match a
12432          * custom pattern, and we actually need to implement custom pattern
12433          * matching.
12434          */
12435         if (pattern & CTL_LUN_PAT_CMD)
12436                 return (CTL_LUN_PAT_CMD);
12437
12438         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12439                 return (CTL_LUN_PAT_ANY);
12440
12441         entry = ctl_get_cmd_entry(ctsio);
12442
12443         filtered_pattern = entry->pattern & pattern;
12444
12445         /*
12446          * If the user requested specific flags in the pattern (e.g.
12447          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12448          * flags.
12449          *
12450          * If the user did not specify any flags, it doesn't matter whether
12451          * or not the command supports the flags.
12452          */
12453         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12454              (pattern & ~CTL_LUN_PAT_MASK))
12455                 return (CTL_LUN_PAT_NONE);
12456
12457         /*
12458          * If the user asked for a range check, see if the requested LBA
12459          * range overlaps with this command's LBA range.
12460          */
12461         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12462                 uint64_t lba1;
12463                 uint32_t len1;
12464                 ctl_action action;
12465                 int retval;
12466
12467                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12468                 if (retval != 0)
12469                         return (CTL_LUN_PAT_NONE);
12470
12471                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12472                                               desc->lba_range.len);
12473                 /*
12474                  * A "pass" means that the LBA ranges don't overlap, so
12475                  * this doesn't match the user's range criteria.
12476                  */
12477                 if (action == CTL_ACTION_PASS)
12478                         return (CTL_LUN_PAT_NONE);
12479         }
12480
12481         return (filtered_pattern);
12482 }
12483
12484 static void
12485 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12486 {
12487         struct ctl_error_desc *desc, *desc2;
12488
12489         mtx_assert(&lun->lun_lock, MA_OWNED);
12490
12491         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12492                 ctl_lun_error_pattern pattern;
12493                 /*
12494                  * Check to see whether this particular command matches
12495                  * the pattern in the descriptor.
12496                  */
12497                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12498                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12499                         continue;
12500
12501                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12502                 case CTL_LUN_INJ_ABORTED:
12503                         ctl_set_aborted(&io->scsiio);
12504                         break;
12505                 case CTL_LUN_INJ_MEDIUM_ERR:
12506                         ctl_set_medium_error(&io->scsiio);
12507                         break;
12508                 case CTL_LUN_INJ_UA:
12509                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12510                          * OCCURRED */
12511                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12512                         break;
12513                 case CTL_LUN_INJ_CUSTOM:
12514                         /*
12515                          * We're assuming the user knows what he is doing.
12516                          * Just copy the sense information without doing
12517                          * checks.
12518                          */
12519                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12520                               ctl_min(sizeof(desc->custom_sense),
12521                                       sizeof(io->scsiio.sense_data)));
12522                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12523                         io->scsiio.sense_len = SSD_FULL_SIZE;
12524                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12525                         break;
12526                 case CTL_LUN_INJ_NONE:
12527                 default:
12528                         /*
12529                          * If this is an error injection type we don't know
12530                          * about, clear the continuous flag (if it is set)
12531                          * so it will get deleted below.
12532                          */
12533                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12534                         break;
12535                 }
12536                 /*
12537                  * By default, each error injection action is a one-shot
12538                  */
12539                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12540                         continue;
12541
12542                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12543
12544                 free(desc, M_CTL);
12545         }
12546 }
12547
12548 #ifdef CTL_IO_DELAY
12549 static void
12550 ctl_datamove_timer_wakeup(void *arg)
12551 {
12552         union ctl_io *io;
12553
12554         io = (union ctl_io *)arg;
12555
12556         ctl_datamove(io);
12557 }
12558 #endif /* CTL_IO_DELAY */
12559
12560 void
12561 ctl_datamove(union ctl_io *io)
12562 {
12563         void (*fe_datamove)(union ctl_io *io);
12564
12565         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12566
12567         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12568
12569 #ifdef CTL_TIME_IO
12570         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12571                 char str[256];
12572                 char path_str[64];
12573                 struct sbuf sb;
12574
12575                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12576                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12577
12578                 sbuf_cat(&sb, path_str);
12579                 switch (io->io_hdr.io_type) {
12580                 case CTL_IO_SCSI:
12581                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12582                         sbuf_printf(&sb, "\n");
12583                         sbuf_cat(&sb, path_str);
12584                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12585                                     io->scsiio.tag_num, io->scsiio.tag_type);
12586                         break;
12587                 case CTL_IO_TASK:
12588                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12589                                     "Tag Type: %d\n", io->taskio.task_action,
12590                                     io->taskio.tag_num, io->taskio.tag_type);
12591                         break;
12592                 default:
12593                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12594                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12595                         break;
12596                 }
12597                 sbuf_cat(&sb, path_str);
12598                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12599                             (intmax_t)time_uptime - io->io_hdr.start_time);
12600                 sbuf_finish(&sb);
12601                 printf("%s", sbuf_data(&sb));
12602         }
12603 #endif /* CTL_TIME_IO */
12604
12605 #ifdef CTL_IO_DELAY
12606         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12607                 struct ctl_lun *lun;
12608
12609                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12610
12611                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12612         } else {
12613                 struct ctl_lun *lun;
12614
12615                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12616                 if ((lun != NULL)
12617                  && (lun->delay_info.datamove_delay > 0)) {
12618                         struct callout *callout;
12619
12620                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12621                         callout_init(callout, /*mpsafe*/ 1);
12622                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12623                         callout_reset(callout,
12624                                       lun->delay_info.datamove_delay * hz,
12625                                       ctl_datamove_timer_wakeup, io);
12626                         if (lun->delay_info.datamove_type ==
12627                             CTL_DELAY_TYPE_ONESHOT)
12628                                 lun->delay_info.datamove_delay = 0;
12629                         return;
12630                 }
12631         }
12632 #endif
12633
12634         /*
12635          * This command has been aborted.  Set the port status, so we fail
12636          * the data move.
12637          */
12638         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12639                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12640                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12641                        io->io_hdr.nexus.targ_port,
12642                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12643                        io->io_hdr.nexus.targ_lun);
12644                 io->io_hdr.port_status = 31337;
12645                 /*
12646                  * Note that the backend, in this case, will get the
12647                  * callback in its context.  In other cases it may get
12648                  * called in the frontend's interrupt thread context.
12649                  */
12650                 io->scsiio.be_move_done(io);
12651                 return;
12652         }
12653
12654         /*
12655          * If we're in XFER mode and this I/O is from the other shelf
12656          * controller, we need to send the DMA to the other side to
12657          * actually transfer the data to/from the host.  In serialize only
12658          * mode the transfer happens below CTL and ctl_datamove() is only
12659          * called on the machine that originally received the I/O.
12660          */
12661         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12662          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12663                 union ctl_ha_msg msg;
12664                 uint32_t sg_entries_sent;
12665                 int do_sg_copy;
12666                 int i;
12667
12668                 memset(&msg, 0, sizeof(msg));
12669                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12670                 msg.hdr.original_sc = io->io_hdr.original_sc;
12671                 msg.hdr.serializing_sc = io;
12672                 msg.hdr.nexus = io->io_hdr.nexus;
12673                 msg.dt.flags = io->io_hdr.flags;
12674                 /*
12675                  * We convert everything into a S/G list here.  We can't
12676                  * pass by reference, only by value between controllers.
12677                  * So we can't pass a pointer to the S/G list, only as many
12678                  * S/G entries as we can fit in here.  If it's possible for
12679                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12680                  * then we need to break this up into multiple transfers.
12681                  */
12682                 if (io->scsiio.kern_sg_entries == 0) {
12683                         msg.dt.kern_sg_entries = 1;
12684                         /*
12685                          * If this is in cached memory, flush the cache
12686                          * before we send the DMA request to the other
12687                          * controller.  We want to do this in either the
12688                          * read or the write case.  The read case is
12689                          * straightforward.  In the write case, we want to
12690                          * make sure nothing is in the local cache that
12691                          * could overwrite the DMAed data.
12692                          */
12693                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12694                                 /*
12695                                  * XXX KDM use bus_dmamap_sync() here.
12696                                  */
12697                         }
12698
12699                         /*
12700                          * Convert to a physical address if this is a
12701                          * virtual address.
12702                          */
12703                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12704                                 msg.dt.sg_list[0].addr =
12705                                         io->scsiio.kern_data_ptr;
12706                         } else {
12707                                 /*
12708                                  * XXX KDM use busdma here!
12709                                  */
12710 #if 0
12711                                 msg.dt.sg_list[0].addr = (void *)
12712                                         vtophys(io->scsiio.kern_data_ptr);
12713 #endif
12714                         }
12715
12716                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12717                         do_sg_copy = 0;
12718                 } else {
12719                         struct ctl_sg_entry *sgl;
12720
12721                         do_sg_copy = 1;
12722                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12723                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12724                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12725                                 /*
12726                                  * XXX KDM use bus_dmamap_sync() here.
12727                                  */
12728                         }
12729                 }
12730
12731                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12732                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12733                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12734                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12735                 msg.dt.sg_sequence = 0;
12736
12737                 /*
12738                  * Loop until we've sent all of the S/G entries.  On the
12739                  * other end, we'll recompose these S/G entries into one
12740                  * contiguous list before passing it to the
12741                  */
12742                 for (sg_entries_sent = 0; sg_entries_sent <
12743                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12744                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12745                                 sizeof(msg.dt.sg_list[0])),
12746                                 msg.dt.kern_sg_entries - sg_entries_sent);
12747
12748                         if (do_sg_copy != 0) {
12749                                 struct ctl_sg_entry *sgl;
12750                                 int j;
12751
12752                                 sgl = (struct ctl_sg_entry *)
12753                                         io->scsiio.kern_data_ptr;
12754                                 /*
12755                                  * If this is in cached memory, flush the cache
12756                                  * before we send the DMA request to the other
12757                                  * controller.  We want to do this in either
12758                                  * the * read or the write case.  The read
12759                                  * case is straightforward.  In the write
12760                                  * case, we want to make sure nothing is
12761                                  * in the local cache that could overwrite
12762                                  * the DMAed data.
12763                                  */
12764
12765                                 for (i = sg_entries_sent, j = 0;
12766                                      i < msg.dt.cur_sg_entries; i++, j++) {
12767                                         if ((io->io_hdr.flags &
12768                                              CTL_FLAG_NO_DATASYNC) == 0) {
12769                                                 /*
12770                                                  * XXX KDM use bus_dmamap_sync()
12771                                                  */
12772                                         }
12773                                         if ((io->io_hdr.flags &
12774                                              CTL_FLAG_BUS_ADDR) == 0) {
12775                                                 /*
12776                                                  * XXX KDM use busdma.
12777                                                  */
12778 #if 0
12779                                                 msg.dt.sg_list[j].addr =(void *)
12780                                                        vtophys(sgl[i].addr);
12781 #endif
12782                                         } else {
12783                                                 msg.dt.sg_list[j].addr =
12784                                                         sgl[i].addr;
12785                                         }
12786                                         msg.dt.sg_list[j].len = sgl[i].len;
12787                                 }
12788                         }
12789
12790                         sg_entries_sent += msg.dt.cur_sg_entries;
12791                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12792                                 msg.dt.sg_last = 1;
12793                         else
12794                                 msg.dt.sg_last = 0;
12795
12796                         /*
12797                          * XXX KDM drop and reacquire the lock here?
12798                          */
12799                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12800                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12801                                 /*
12802                                  * XXX do something here.
12803                                  */
12804                         }
12805
12806                         msg.dt.sent_sg_entries = sg_entries_sent;
12807                 }
12808                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12809                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12810                         ctl_failover_io(io, /*have_lock*/ 0);
12811
12812         } else {
12813
12814                 /*
12815                  * Lookup the fe_datamove() function for this particular
12816                  * front end.
12817                  */
12818                 fe_datamove =
12819                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12820
12821                 fe_datamove(io);
12822         }
12823 }
12824
12825 static void
12826 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12827 {
12828         union ctl_ha_msg msg;
12829         int isc_status;
12830
12831         memset(&msg, 0, sizeof(msg));
12832
12833         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12834         msg.hdr.original_sc = io;
12835         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12836         msg.hdr.nexus = io->io_hdr.nexus;
12837         msg.hdr.status = io->io_hdr.status;
12838         msg.scsi.tag_num = io->scsiio.tag_num;
12839         msg.scsi.tag_type = io->scsiio.tag_type;
12840         msg.scsi.scsi_status = io->scsiio.scsi_status;
12841         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12842                sizeof(io->scsiio.sense_data));
12843         msg.scsi.sense_len = io->scsiio.sense_len;
12844         msg.scsi.sense_residual = io->scsiio.sense_residual;
12845         msg.scsi.fetd_status = io->io_hdr.port_status;
12846         msg.scsi.residual = io->scsiio.residual;
12847         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12848
12849         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12850                 ctl_failover_io(io, /*have_lock*/ have_lock);
12851                 return;
12852         }
12853
12854         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12855         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12856                 /* XXX do something if this fails */
12857         }
12858
12859 }
12860
12861 /*
12862  * The DMA to the remote side is done, now we need to tell the other side
12863  * we're done so it can continue with its data movement.
12864  */
12865 static void
12866 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12867 {
12868         union ctl_io *io;
12869
12870         io = rq->context;
12871
12872         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12873                 printf("%s: ISC DMA write failed with error %d", __func__,
12874                        rq->ret);
12875                 ctl_set_internal_failure(&io->scsiio,
12876                                          /*sks_valid*/ 1,
12877                                          /*retry_count*/ rq->ret);
12878         }
12879
12880         ctl_dt_req_free(rq);
12881
12882         /*
12883          * In this case, we had to malloc the memory locally.  Free it.
12884          */
12885         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12886                 int i;
12887                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12888                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12889         }
12890         /*
12891          * The data is in local and remote memory, so now we need to send
12892          * status (good or back) back to the other side.
12893          */
12894         ctl_send_datamove_done(io, /*have_lock*/ 0);
12895 }
12896
12897 /*
12898  * We've moved the data from the host/controller into local memory.  Now we
12899  * need to push it over to the remote controller's memory.
12900  */
12901 static int
12902 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12903 {
12904         int retval;
12905
12906         retval = 0;
12907
12908         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12909                                           ctl_datamove_remote_write_cb);
12910
12911         return (retval);
12912 }
12913
12914 static void
12915 ctl_datamove_remote_write(union ctl_io *io)
12916 {
12917         int retval;
12918         void (*fe_datamove)(union ctl_io *io);
12919
12920         /*
12921          * - Get the data from the host/HBA into local memory.
12922          * - DMA memory from the local controller to the remote controller.
12923          * - Send status back to the remote controller.
12924          */
12925
12926         retval = ctl_datamove_remote_sgl_setup(io);
12927         if (retval != 0)
12928                 return;
12929
12930         /* Switch the pointer over so the FETD knows what to do */
12931         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12932
12933         /*
12934          * Use a custom move done callback, since we need to send completion
12935          * back to the other controller, not to the backend on this side.
12936          */
12937         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12938
12939         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12940
12941         fe_datamove(io);
12942
12943         return;
12944
12945 }
12946
12947 static int
12948 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12949 {
12950 #if 0
12951         char str[256];
12952         char path_str[64];
12953         struct sbuf sb;
12954 #endif
12955
12956         /*
12957          * In this case, we had to malloc the memory locally.  Free it.
12958          */
12959         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12960                 int i;
12961                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12962                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12963         }
12964
12965 #if 0
12966         scsi_path_string(io, path_str, sizeof(path_str));
12967         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12968         sbuf_cat(&sb, path_str);
12969         scsi_command_string(&io->scsiio, NULL, &sb);
12970         sbuf_printf(&sb, "\n");
12971         sbuf_cat(&sb, path_str);
12972         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12973                     io->scsiio.tag_num, io->scsiio.tag_type);
12974         sbuf_cat(&sb, path_str);
12975         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12976                     io->io_hdr.flags, io->io_hdr.status);
12977         sbuf_finish(&sb);
12978         printk("%s", sbuf_data(&sb));
12979 #endif
12980
12981
12982         /*
12983          * The read is done, now we need to send status (good or bad) back
12984          * to the other side.
12985          */
12986         ctl_send_datamove_done(io, /*have_lock*/ 0);
12987
12988         return (0);
12989 }
12990
12991 static void
12992 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12993 {
12994         union ctl_io *io;
12995         void (*fe_datamove)(union ctl_io *io);
12996
12997         io = rq->context;
12998
12999         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13000                 printf("%s: ISC DMA read failed with error %d", __func__,
13001                        rq->ret);
13002                 ctl_set_internal_failure(&io->scsiio,
13003                                          /*sks_valid*/ 1,
13004                                          /*retry_count*/ rq->ret);
13005         }
13006
13007         ctl_dt_req_free(rq);
13008
13009         /* Switch the pointer over so the FETD knows what to do */
13010         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13011
13012         /*
13013          * Use a custom move done callback, since we need to send completion
13014          * back to the other controller, not to the backend on this side.
13015          */
13016         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13017
13018         /* XXX KDM add checks like the ones in ctl_datamove? */
13019
13020         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13021
13022         fe_datamove(io);
13023 }
13024
13025 static int
13026 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13027 {
13028         struct ctl_sg_entry *local_sglist, *remote_sglist;
13029         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13030         struct ctl_softc *softc;
13031         int retval;
13032         int i;
13033
13034         retval = 0;
13035         softc = control_softc;
13036
13037         local_sglist = io->io_hdr.local_sglist;
13038         local_dma_sglist = io->io_hdr.local_dma_sglist;
13039         remote_sglist = io->io_hdr.remote_sglist;
13040         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13041
13042         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13043                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13044                         local_sglist[i].len = remote_sglist[i].len;
13045
13046                         /*
13047                          * XXX Detect the situation where the RS-level I/O
13048                          * redirector on the other side has already read the
13049                          * data off of the AOR RS on this side, and
13050                          * transferred it to remote (mirror) memory on the
13051                          * other side.  Since we already have the data in
13052                          * memory here, we just need to use it.
13053                          *
13054                          * XXX KDM this can probably be removed once we
13055                          * get the cache device code in and take the
13056                          * current AOR implementation out.
13057                          */
13058 #ifdef NEEDTOPORT
13059                         if ((remote_sglist[i].addr >=
13060                              (void *)vtophys(softc->mirr->addr))
13061                          && (remote_sglist[i].addr <
13062                              ((void *)vtophys(softc->mirr->addr) +
13063                              CacheMirrorOffset))) {
13064                                 local_sglist[i].addr = remote_sglist[i].addr -
13065                                         CacheMirrorOffset;
13066                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13067                                      CTL_FLAG_DATA_IN)
13068                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13069                         } else {
13070                                 local_sglist[i].addr = remote_sglist[i].addr +
13071                                         CacheMirrorOffset;
13072                         }
13073 #endif
13074 #if 0
13075                         printf("%s: local %p, remote %p, len %d\n",
13076                                __func__, local_sglist[i].addr,
13077                                remote_sglist[i].addr, local_sglist[i].len);
13078 #endif
13079                 }
13080         } else {
13081                 uint32_t len_to_go;
13082
13083                 /*
13084                  * In this case, we don't have automatically allocated
13085                  * memory for this I/O on this controller.  This typically
13086                  * happens with internal CTL I/O -- e.g. inquiry, mode
13087                  * sense, etc.  Anything coming from RAIDCore will have
13088                  * a mirror area available.
13089                  */
13090                 len_to_go = io->scsiio.kern_data_len;
13091
13092                 /*
13093                  * Clear the no datasync flag, we have to use malloced
13094                  * buffers.
13095                  */
13096                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13097
13098                 /*
13099                  * The difficult thing here is that the size of the various
13100                  * S/G segments may be different than the size from the
13101                  * remote controller.  That'll make it harder when DMAing
13102                  * the data back to the other side.
13103                  */
13104                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13105                      sizeof(io->io_hdr.remote_sglist[0])) &&
13106                      (len_to_go > 0); i++) {
13107                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13108                         CTL_SIZE_8B(local_dma_sglist[i].len,
13109                                     local_sglist[i].len);
13110                         local_sglist[i].addr =
13111                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13112
13113                         local_dma_sglist[i].addr = local_sglist[i].addr;
13114
13115                         if (local_sglist[i].addr == NULL) {
13116                                 int j;
13117
13118                                 printf("malloc failed for %zd bytes!",
13119                                        local_dma_sglist[i].len);
13120                                 for (j = 0; j < i; j++) {
13121                                         free(local_sglist[j].addr, M_CTL);
13122                                 }
13123                                 ctl_set_internal_failure(&io->scsiio,
13124                                                          /*sks_valid*/ 1,
13125                                                          /*retry_count*/ 4857);
13126                                 retval = 1;
13127                                 goto bailout_error;
13128                                 
13129                         }
13130                         /* XXX KDM do we need a sync here? */
13131
13132                         len_to_go -= local_sglist[i].len;
13133                 }
13134                 /*
13135                  * Reset the number of S/G entries accordingly.  The
13136                  * original number of S/G entries is available in
13137                  * rem_sg_entries.
13138                  */
13139                 io->scsiio.kern_sg_entries = i;
13140
13141 #if 0
13142                 printf("%s: kern_sg_entries = %d\n", __func__,
13143                        io->scsiio.kern_sg_entries);
13144                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13145                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13146                                local_sglist[i].addr, local_sglist[i].len,
13147                                local_dma_sglist[i].len);
13148 #endif
13149         }
13150
13151
13152         return (retval);
13153
13154 bailout_error:
13155
13156         ctl_send_datamove_done(io, /*have_lock*/ 0);
13157
13158         return (retval);
13159 }
13160
13161 static int
13162 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13163                          ctl_ha_dt_cb callback)
13164 {
13165         struct ctl_ha_dt_req *rq;
13166         struct ctl_sg_entry *remote_sglist, *local_sglist;
13167         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13168         uint32_t local_used, remote_used, total_used;
13169         int retval;
13170         int i, j;
13171
13172         retval = 0;
13173
13174         rq = ctl_dt_req_alloc();
13175
13176         /*
13177          * If we failed to allocate the request, and if the DMA didn't fail
13178          * anyway, set busy status.  This is just a resource allocation
13179          * failure.
13180          */
13181         if ((rq == NULL)
13182          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13183                 ctl_set_busy(&io->scsiio);
13184
13185         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13186
13187                 if (rq != NULL)
13188                         ctl_dt_req_free(rq);
13189
13190                 /*
13191                  * The data move failed.  We need to return status back
13192                  * to the other controller.  No point in trying to DMA
13193                  * data to the remote controller.
13194                  */
13195
13196                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13197
13198                 retval = 1;
13199
13200                 goto bailout;
13201         }
13202
13203         local_sglist = io->io_hdr.local_sglist;
13204         local_dma_sglist = io->io_hdr.local_dma_sglist;
13205         remote_sglist = io->io_hdr.remote_sglist;
13206         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13207         local_used = 0;
13208         remote_used = 0;
13209         total_used = 0;
13210
13211         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13212                 rq->ret = CTL_HA_STATUS_SUCCESS;
13213                 rq->context = io;
13214                 callback(rq);
13215                 goto bailout;
13216         }
13217
13218         /*
13219          * Pull/push the data over the wire from/to the other controller.
13220          * This takes into account the possibility that the local and
13221          * remote sglists may not be identical in terms of the size of
13222          * the elements and the number of elements.
13223          *
13224          * One fundamental assumption here is that the length allocated for
13225          * both the local and remote sglists is identical.  Otherwise, we've
13226          * essentially got a coding error of some sort.
13227          */
13228         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13229                 int isc_ret;
13230                 uint32_t cur_len, dma_length;
13231                 uint8_t *tmp_ptr;
13232
13233                 rq->id = CTL_HA_DATA_CTL;
13234                 rq->command = command;
13235                 rq->context = io;
13236
13237                 /*
13238                  * Both pointers should be aligned.  But it is possible
13239                  * that the allocation length is not.  They should both
13240                  * also have enough slack left over at the end, though,
13241                  * to round up to the next 8 byte boundary.
13242                  */
13243                 cur_len = ctl_min(local_sglist[i].len - local_used,
13244                                   remote_sglist[j].len - remote_used);
13245
13246                 /*
13247                  * In this case, we have a size issue and need to decrease
13248                  * the size, except in the case where we actually have less
13249                  * than 8 bytes left.  In that case, we need to increase
13250                  * the DMA length to get the last bit.
13251                  */
13252                 if ((cur_len & 0x7) != 0) {
13253                         if (cur_len > 0x7) {
13254                                 cur_len = cur_len - (cur_len & 0x7);
13255                                 dma_length = cur_len;
13256                         } else {
13257                                 CTL_SIZE_8B(dma_length, cur_len);
13258                         }
13259
13260                 } else
13261                         dma_length = cur_len;
13262
13263                 /*
13264                  * If we had to allocate memory for this I/O, instead of using
13265                  * the non-cached mirror memory, we'll need to flush the cache
13266                  * before trying to DMA to the other controller.
13267                  *
13268                  * We could end up doing this multiple times for the same
13269                  * segment if we have a larger local segment than remote
13270                  * segment.  That shouldn't be an issue.
13271                  */
13272                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13273                         /*
13274                          * XXX KDM use bus_dmamap_sync() here.
13275                          */
13276                 }
13277
13278                 rq->size = dma_length;
13279
13280                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13281                 tmp_ptr += local_used;
13282
13283                 /* Use physical addresses when talking to ISC hardware */
13284                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13285                         /* XXX KDM use busdma */
13286 #if 0
13287                         rq->local = vtophys(tmp_ptr);
13288 #endif
13289                 } else
13290                         rq->local = tmp_ptr;
13291
13292                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13293                 tmp_ptr += remote_used;
13294                 rq->remote = tmp_ptr;
13295
13296                 rq->callback = NULL;
13297
13298                 local_used += cur_len;
13299                 if (local_used >= local_sglist[i].len) {
13300                         i++;
13301                         local_used = 0;
13302                 }
13303
13304                 remote_used += cur_len;
13305                 if (remote_used >= remote_sglist[j].len) {
13306                         j++;
13307                         remote_used = 0;
13308                 }
13309                 total_used += cur_len;
13310
13311                 if (total_used >= io->scsiio.kern_data_len)
13312                         rq->callback = callback;
13313
13314                 if ((rq->size & 0x7) != 0) {
13315                         printf("%s: warning: size %d is not on 8b boundary\n",
13316                                __func__, rq->size);
13317                 }
13318                 if (((uintptr_t)rq->local & 0x7) != 0) {
13319                         printf("%s: warning: local %p not on 8b boundary\n",
13320                                __func__, rq->local);
13321                 }
13322                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13323                         printf("%s: warning: remote %p not on 8b boundary\n",
13324                                __func__, rq->local);
13325                 }
13326 #if 0
13327                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13328                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13329                        rq->local, rq->remote, rq->size);
13330 #endif
13331
13332                 isc_ret = ctl_dt_single(rq);
13333                 if (isc_ret == CTL_HA_STATUS_WAIT)
13334                         continue;
13335
13336                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13337                         rq->ret = CTL_HA_STATUS_SUCCESS;
13338                 } else {
13339                         rq->ret = isc_ret;
13340                 }
13341                 callback(rq);
13342                 goto bailout;
13343         }
13344
13345 bailout:
13346         return (retval);
13347
13348 }
13349
13350 static void
13351 ctl_datamove_remote_read(union ctl_io *io)
13352 {
13353         int retval;
13354         int i;
13355
13356         /*
13357          * This will send an error to the other controller in the case of a
13358          * failure.
13359          */
13360         retval = ctl_datamove_remote_sgl_setup(io);
13361         if (retval != 0)
13362                 return;
13363
13364         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13365                                           ctl_datamove_remote_read_cb);
13366         if ((retval != 0)
13367          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13368                 /*
13369                  * Make sure we free memory if there was an error..  The
13370                  * ctl_datamove_remote_xfer() function will send the
13371                  * datamove done message, or call the callback with an
13372                  * error if there is a problem.
13373                  */
13374                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13375                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13376         }
13377
13378         return;
13379 }
13380
13381 /*
13382  * Process a datamove request from the other controller.  This is used for
13383  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13384  * first.  Once that is complete, the data gets DMAed into the remote
13385  * controller's memory.  For reads, we DMA from the remote controller's
13386  * memory into our memory first, and then move it out to the FETD.
13387  */
13388 static void
13389 ctl_datamove_remote(union ctl_io *io)
13390 {
13391         struct ctl_softc *softc;
13392
13393         softc = control_softc;
13394
13395         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13396
13397         /*
13398          * Note that we look for an aborted I/O here, but don't do some of
13399          * the other checks that ctl_datamove() normally does.
13400          * We don't need to run the datamove delay code, since that should
13401          * have been done if need be on the other controller.
13402          */
13403         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13404                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13405                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13406                        io->io_hdr.nexus.targ_port,
13407                        io->io_hdr.nexus.targ_target.id,
13408                        io->io_hdr.nexus.targ_lun);
13409                 io->io_hdr.port_status = 31338;
13410                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13411                 return;
13412         }
13413
13414         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13415                 ctl_datamove_remote_write(io);
13416         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13417                 ctl_datamove_remote_read(io);
13418         } else {
13419                 union ctl_ha_msg msg;
13420                 struct scsi_sense_data *sense;
13421                 uint8_t sks[3];
13422                 int retry_count;
13423
13424                 memset(&msg, 0, sizeof(msg));
13425
13426                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13427                 msg.hdr.status = CTL_SCSI_ERROR;
13428                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13429
13430                 retry_count = 4243;
13431
13432                 sense = &msg.scsi.sense_data;
13433                 sks[0] = SSD_SCS_VALID;
13434                 sks[1] = (retry_count >> 8) & 0xff;
13435                 sks[2] = retry_count & 0xff;
13436
13437                 /* "Internal target failure" */
13438                 scsi_set_sense_data(sense,
13439                                     /*sense_format*/ SSD_TYPE_NONE,
13440                                     /*current_error*/ 1,
13441                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13442                                     /*asc*/ 0x44,
13443                                     /*ascq*/ 0x00,
13444                                     /*type*/ SSD_ELEM_SKS,
13445                                     /*size*/ sizeof(sks),
13446                                     /*data*/ sks,
13447                                     SSD_ELEM_NONE);
13448
13449                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13450                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13451                         ctl_failover_io(io, /*have_lock*/ 1);
13452                         return;
13453                 }
13454
13455                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13456                     CTL_HA_STATUS_SUCCESS) {
13457                         /* XXX KDM what to do if this fails? */
13458                 }
13459                 return;
13460         }
13461         
13462 }
13463
13464 static int
13465 ctl_process_done(union ctl_io *io)
13466 {
13467         struct ctl_lun *lun;
13468         struct ctl_softc *ctl_softc;
13469         void (*fe_done)(union ctl_io *io);
13470         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13471
13472         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13473
13474         fe_done =
13475             control_softc->ctl_ports[targ_port]->fe_done;
13476
13477 #ifdef CTL_TIME_IO
13478         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13479                 char str[256];
13480                 char path_str[64];
13481                 struct sbuf sb;
13482
13483                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13484                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13485
13486                 sbuf_cat(&sb, path_str);
13487                 switch (io->io_hdr.io_type) {
13488                 case CTL_IO_SCSI:
13489                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13490                         sbuf_printf(&sb, "\n");
13491                         sbuf_cat(&sb, path_str);
13492                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13493                                     io->scsiio.tag_num, io->scsiio.tag_type);
13494                         break;
13495                 case CTL_IO_TASK:
13496                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13497                                     "Tag Type: %d\n", io->taskio.task_action,
13498                                     io->taskio.tag_num, io->taskio.tag_type);
13499                         break;
13500                 default:
13501                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13502                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13503                         break;
13504                 }
13505                 sbuf_cat(&sb, path_str);
13506                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13507                             (intmax_t)time_uptime - io->io_hdr.start_time);
13508                 sbuf_finish(&sb);
13509                 printf("%s", sbuf_data(&sb));
13510         }
13511 #endif /* CTL_TIME_IO */
13512
13513         switch (io->io_hdr.io_type) {
13514         case CTL_IO_SCSI:
13515                 break;
13516         case CTL_IO_TASK:
13517                 if (bootverbose || verbose > 0)
13518                         ctl_io_error_print(io, NULL);
13519                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13520                         ctl_free_io(io);
13521                 else
13522                         fe_done(io);
13523                 return (CTL_RETVAL_COMPLETE);
13524                 break;
13525         default:
13526                 printf("ctl_process_done: invalid io type %d\n",
13527                        io->io_hdr.io_type);
13528                 panic("ctl_process_done: invalid io type %d\n",
13529                       io->io_hdr.io_type);
13530                 break; /* NOTREACHED */
13531         }
13532
13533         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13534         if (lun == NULL) {
13535                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13536                                  io->io_hdr.nexus.targ_mapped_lun));
13537                 fe_done(io);
13538                 goto bailout;
13539         }
13540         ctl_softc = lun->ctl_softc;
13541
13542         mtx_lock(&lun->lun_lock);
13543
13544         /*
13545          * Check to see if we have any errors to inject here.  We only
13546          * inject errors for commands that don't already have errors set.
13547          */
13548         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13549          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13550                 ctl_inject_error(lun, io);
13551
13552         /*
13553          * XXX KDM how do we treat commands that aren't completed
13554          * successfully?
13555          *
13556          * XXX KDM should we also track I/O latency?
13557          */
13558         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13559             io->io_hdr.io_type == CTL_IO_SCSI) {
13560 #ifdef CTL_TIME_IO
13561                 struct bintime cur_bt;
13562 #endif
13563                 int type;
13564
13565                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13566                     CTL_FLAG_DATA_IN)
13567                         type = CTL_STATS_READ;
13568                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13569                     CTL_FLAG_DATA_OUT)
13570                         type = CTL_STATS_WRITE;
13571                 else
13572                         type = CTL_STATS_NO_IO;
13573
13574                 lun->stats.ports[targ_port].bytes[type] +=
13575                     io->scsiio.kern_total_len;
13576                 lun->stats.ports[targ_port].operations[type]++;
13577 #ifdef CTL_TIME_IO
13578                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13579                    &io->io_hdr.dma_bt);
13580                 lun->stats.ports[targ_port].num_dmas[type] +=
13581                     io->io_hdr.num_dmas;
13582                 getbintime(&cur_bt);
13583                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13584                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13585 #endif
13586         }
13587
13588         /*
13589          * Remove this from the OOA queue.
13590          */
13591         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13592
13593         /*
13594          * Run through the blocked queue on this LUN and see if anything
13595          * has become unblocked, now that this transaction is done.
13596          */
13597         ctl_check_blocked(lun);
13598
13599         /*
13600          * If the LUN has been invalidated, free it if there is nothing
13601          * left on its OOA queue.
13602          */
13603         if ((lun->flags & CTL_LUN_INVALID)
13604          && TAILQ_EMPTY(&lun->ooa_queue)) {
13605                 mtx_unlock(&lun->lun_lock);
13606                 mtx_lock(&ctl_softc->ctl_lock);
13607                 ctl_free_lun(lun);
13608                 mtx_unlock(&ctl_softc->ctl_lock);
13609         } else
13610                 mtx_unlock(&lun->lun_lock);
13611
13612         /*
13613          * If this command has been aborted, make sure we set the status
13614          * properly.  The FETD is responsible for freeing the I/O and doing
13615          * whatever it needs to do to clean up its state.
13616          */
13617         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13618                 ctl_set_task_aborted(&io->scsiio);
13619
13620         /*
13621          * We print out status for every task management command.  For SCSI
13622          * commands, we filter out any unit attention errors; they happen
13623          * on every boot, and would clutter up the log.  Note:  task
13624          * management commands aren't printed here, they are printed above,
13625          * since they should never even make it down here.
13626          */
13627         switch (io->io_hdr.io_type) {
13628         case CTL_IO_SCSI: {
13629                 int error_code, sense_key, asc, ascq;
13630
13631                 sense_key = 0;
13632
13633                 if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13634                  && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13635                         /*
13636                          * Since this is just for printing, no need to
13637                          * show errors here.
13638                          */
13639                         scsi_extract_sense_len(&io->scsiio.sense_data,
13640                                                io->scsiio.sense_len,
13641                                                &error_code,
13642                                                &sense_key,
13643                                                &asc,
13644                                                &ascq,
13645                                                /*show_errors*/ 0);
13646                 }
13647
13648                 if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13649                  && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13650                   || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13651                   || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13652
13653                         if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13654                                 ctl_softc->skipped_prints++;
13655                         } else {
13656                                 uint32_t skipped_prints;
13657
13658                                 skipped_prints = ctl_softc->skipped_prints;
13659
13660                                 ctl_softc->skipped_prints = 0;
13661                                 ctl_softc->last_print_jiffies = time_uptime;
13662
13663                                 if (skipped_prints > 0) {
13664 #ifdef NEEDTOPORT
13665                                         csevent_log(CSC_CTL | CSC_SHELF_SW |
13666                                             CTL_ERROR_REPORT,
13667                                             csevent_LogType_Trace,
13668                                             csevent_Severity_Information,
13669                                             csevent_AlertLevel_Green,
13670                                             csevent_FRU_Firmware,
13671                                             csevent_FRU_Unknown,
13672                                             "High CTL error volume, %d prints "
13673                                             "skipped", skipped_prints);
13674 #endif
13675                                 }
13676                                 if (bootverbose || verbose > 0)
13677                                         ctl_io_error_print(io, NULL);
13678                         }
13679                 }
13680                 break;
13681         }
13682         case CTL_IO_TASK:
13683                 if (bootverbose || verbose > 0)
13684                         ctl_io_error_print(io, NULL);
13685                 break;
13686         default:
13687                 break;
13688         }
13689
13690         /*
13691          * Tell the FETD or the other shelf controller we're done with this
13692          * command.  Note that only SCSI commands get to this point.  Task
13693          * management commands are completed above.
13694          *
13695          * We only send status to the other controller if we're in XFER
13696          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13697          * received the I/O (from CTL's perspective), and so the status is
13698          * generated there.
13699          * 
13700          * XXX KDM if we hold the lock here, we could cause a deadlock
13701          * if the frontend comes back in in this context to queue
13702          * something.
13703          */
13704         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13705          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13706                 union ctl_ha_msg msg;
13707
13708                 memset(&msg, 0, sizeof(msg));
13709                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13710                 msg.hdr.original_sc = io->io_hdr.original_sc;
13711                 msg.hdr.nexus = io->io_hdr.nexus;
13712                 msg.hdr.status = io->io_hdr.status;
13713                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13714                 msg.scsi.tag_num = io->scsiio.tag_num;
13715                 msg.scsi.tag_type = io->scsiio.tag_type;
13716                 msg.scsi.sense_len = io->scsiio.sense_len;
13717                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13718                 msg.scsi.residual = io->scsiio.residual;
13719                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13720                        sizeof(io->scsiio.sense_data));
13721                 /*
13722                  * We copy this whether or not this is an I/O-related
13723                  * command.  Otherwise, we'd have to go and check to see
13724                  * whether it's a read/write command, and it really isn't
13725                  * worth it.
13726                  */
13727                 memcpy(&msg.scsi.lbalen,
13728                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13729                        sizeof(msg.scsi.lbalen));
13730
13731                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13732                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13733                         /* XXX do something here */
13734                 }
13735
13736                 ctl_free_io(io);
13737         } else 
13738                 fe_done(io);
13739
13740 bailout:
13741
13742         return (CTL_RETVAL_COMPLETE);
13743 }
13744
13745 #ifdef CTL_WITH_CA
13746 /*
13747  * Front end should call this if it doesn't do autosense.  When the request
13748  * sense comes back in from the initiator, we'll dequeue this and send it.
13749  */
13750 int
13751 ctl_queue_sense(union ctl_io *io)
13752 {
13753         struct ctl_lun *lun;
13754         struct ctl_softc *ctl_softc;
13755         uint32_t initidx, targ_lun;
13756
13757         ctl_softc = control_softc;
13758
13759         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13760
13761         /*
13762          * LUN lookup will likely move to the ctl_work_thread() once we
13763          * have our new queueing infrastructure (that doesn't put things on
13764          * a per-LUN queue initially).  That is so that we can handle
13765          * things like an INQUIRY to a LUN that we don't have enabled.  We
13766          * can't deal with that right now.
13767          */
13768         mtx_lock(&ctl_softc->ctl_lock);
13769
13770         /*
13771          * If we don't have a LUN for this, just toss the sense
13772          * information.
13773          */
13774         targ_lun = io->io_hdr.nexus.targ_lun;
13775         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13776         if ((targ_lun < CTL_MAX_LUNS)
13777          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13778                 lun = ctl_softc->ctl_luns[targ_lun];
13779         else
13780                 goto bailout;
13781
13782         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13783
13784         mtx_lock(&lun->lun_lock);
13785         /*
13786          * Already have CA set for this LUN...toss the sense information.
13787          */
13788         if (ctl_is_set(lun->have_ca, initidx)) {
13789                 mtx_unlock(&lun->lun_lock);
13790                 goto bailout;
13791         }
13792
13793         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13794                ctl_min(sizeof(lun->pending_sense[initidx]),
13795                sizeof(io->scsiio.sense_data)));
13796         ctl_set_mask(lun->have_ca, initidx);
13797         mtx_unlock(&lun->lun_lock);
13798
13799 bailout:
13800         mtx_unlock(&ctl_softc->ctl_lock);
13801
13802         ctl_free_io(io);
13803
13804         return (CTL_RETVAL_COMPLETE);
13805 }
13806 #endif
13807
13808 /*
13809  * Primary command inlet from frontend ports.  All SCSI and task I/O
13810  * requests must go through this function.
13811  */
13812 int
13813 ctl_queue(union ctl_io *io)
13814 {
13815         struct ctl_softc *ctl_softc;
13816
13817         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13818
13819         ctl_softc = control_softc;
13820
13821 #ifdef CTL_TIME_IO
13822         io->io_hdr.start_time = time_uptime;
13823         getbintime(&io->io_hdr.start_bt);
13824 #endif /* CTL_TIME_IO */
13825
13826         /* Map FE-specific LUN ID into global one. */
13827         io->io_hdr.nexus.targ_mapped_lun =
13828             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13829
13830         switch (io->io_hdr.io_type) {
13831         case CTL_IO_SCSI:
13832         case CTL_IO_TASK:
13833                 ctl_enqueue_incoming(io);
13834                 break;
13835         default:
13836                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13837                 return (EINVAL);
13838         }
13839
13840         return (CTL_RETVAL_COMPLETE);
13841 }
13842
13843 #ifdef CTL_IO_DELAY
13844 static void
13845 ctl_done_timer_wakeup(void *arg)
13846 {
13847         union ctl_io *io;
13848
13849         io = (union ctl_io *)arg;
13850         ctl_done(io);
13851 }
13852 #endif /* CTL_IO_DELAY */
13853
13854 void
13855 ctl_done(union ctl_io *io)
13856 {
13857         struct ctl_softc *ctl_softc;
13858
13859         ctl_softc = control_softc;
13860
13861         /*
13862          * Enable this to catch duplicate completion issues.
13863          */
13864 #if 0
13865         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13866                 printf("%s: type %d msg %d cdb %x iptl: "
13867                        "%d:%d:%d:%d tag 0x%04x "
13868                        "flag %#x status %x\n",
13869                         __func__,
13870                         io->io_hdr.io_type,
13871                         io->io_hdr.msg_type,
13872                         io->scsiio.cdb[0],
13873                         io->io_hdr.nexus.initid.id,
13874                         io->io_hdr.nexus.targ_port,
13875                         io->io_hdr.nexus.targ_target.id,
13876                         io->io_hdr.nexus.targ_lun,
13877                         (io->io_hdr.io_type ==
13878                         CTL_IO_TASK) ?
13879                         io->taskio.tag_num :
13880                         io->scsiio.tag_num,
13881                         io->io_hdr.flags,
13882                         io->io_hdr.status);
13883         } else
13884                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13885 #endif
13886
13887         /*
13888          * This is an internal copy of an I/O, and should not go through
13889          * the normal done processing logic.
13890          */
13891         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13892                 return;
13893
13894         /*
13895          * We need to send a msg to the serializing shelf to finish the IO
13896          * as well.  We don't send a finish message to the other shelf if
13897          * this is a task management command.  Task management commands
13898          * aren't serialized in the OOA queue, but rather just executed on
13899          * both shelf controllers for commands that originated on that
13900          * controller.
13901          */
13902         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13903          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13904                 union ctl_ha_msg msg_io;
13905
13906                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13907                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13908                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13909                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13910                 }
13911                 /* continue on to finish IO */
13912         }
13913 #ifdef CTL_IO_DELAY
13914         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13915                 struct ctl_lun *lun;
13916
13917                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13918
13919                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13920         } else {
13921                 struct ctl_lun *lun;
13922
13923                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13924
13925                 if ((lun != NULL)
13926                  && (lun->delay_info.done_delay > 0)) {
13927                         struct callout *callout;
13928
13929                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13930                         callout_init(callout, /*mpsafe*/ 1);
13931                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13932                         callout_reset(callout,
13933                                       lun->delay_info.done_delay * hz,
13934                                       ctl_done_timer_wakeup, io);
13935                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13936                                 lun->delay_info.done_delay = 0;
13937                         return;
13938                 }
13939         }
13940 #endif /* CTL_IO_DELAY */
13941
13942         ctl_enqueue_done(io);
13943 }
13944
13945 int
13946 ctl_isc(struct ctl_scsiio *ctsio)
13947 {
13948         struct ctl_lun *lun;
13949         int retval;
13950
13951         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13952
13953         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13954
13955         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13956
13957         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13958
13959         return (retval);
13960 }
13961
13962
13963 static void
13964 ctl_work_thread(void *arg)
13965 {
13966         struct ctl_thread *thr = (struct ctl_thread *)arg;
13967         struct ctl_softc *softc = thr->ctl_softc;
13968         union ctl_io *io;
13969         int retval;
13970
13971         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13972
13973         for (;;) {
13974                 retval = 0;
13975
13976                 /*
13977                  * We handle the queues in this order:
13978                  * - ISC
13979                  * - done queue (to free up resources, unblock other commands)
13980                  * - RtR queue
13981                  * - incoming queue
13982                  *
13983                  * If those queues are empty, we break out of the loop and
13984                  * go to sleep.
13985                  */
13986                 mtx_lock(&thr->queue_lock);
13987                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13988                 if (io != NULL) {
13989                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13990                         mtx_unlock(&thr->queue_lock);
13991                         ctl_handle_isc(io);
13992                         continue;
13993                 }
13994                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13995                 if (io != NULL) {
13996                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13997                         /* clear any blocked commands, call fe_done */
13998                         mtx_unlock(&thr->queue_lock);
13999                         retval = ctl_process_done(io);
14000                         continue;
14001                 }
14002                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14003                 if (io != NULL) {
14004                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14005                         mtx_unlock(&thr->queue_lock);
14006                         if (io->io_hdr.io_type == CTL_IO_TASK)
14007                                 ctl_run_task(io);
14008                         else
14009                                 ctl_scsiio_precheck(softc, &io->scsiio);
14010                         continue;
14011                 }
14012                 if (!ctl_pause_rtr) {
14013                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14014                         if (io != NULL) {
14015                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14016                                 mtx_unlock(&thr->queue_lock);
14017                                 retval = ctl_scsiio(&io->scsiio);
14018                                 if (retval != CTL_RETVAL_COMPLETE)
14019                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14020                                 continue;
14021                         }
14022                 }
14023
14024                 /* Sleep until we have something to do. */
14025                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14026         }
14027 }
14028
14029 static void
14030 ctl_lun_thread(void *arg)
14031 {
14032         struct ctl_softc *softc = (struct ctl_softc *)arg;
14033         struct ctl_be_lun *be_lun;
14034         int retval;
14035
14036         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14037
14038         for (;;) {
14039                 retval = 0;
14040                 mtx_lock(&softc->ctl_lock);
14041                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14042                 if (be_lun != NULL) {
14043                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14044                         mtx_unlock(&softc->ctl_lock);
14045                         ctl_create_lun(be_lun);
14046                         continue;
14047                 }
14048
14049                 /* Sleep until we have something to do. */
14050                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14051                     PDROP | PRIBIO, "-", 0);
14052         }
14053 }
14054
14055 static void
14056 ctl_enqueue_incoming(union ctl_io *io)
14057 {
14058         struct ctl_softc *softc = control_softc;
14059         struct ctl_thread *thr;
14060         u_int idx;
14061
14062         idx = (io->io_hdr.nexus.targ_port * 127 +
14063                io->io_hdr.nexus.initid.id) % worker_threads;
14064         thr = &softc->threads[idx];
14065         mtx_lock(&thr->queue_lock);
14066         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14067         mtx_unlock(&thr->queue_lock);
14068         wakeup(thr);
14069 }
14070
14071 static void
14072 ctl_enqueue_rtr(union ctl_io *io)
14073 {
14074         struct ctl_softc *softc = control_softc;
14075         struct ctl_thread *thr;
14076
14077         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14078         mtx_lock(&thr->queue_lock);
14079         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14080         mtx_unlock(&thr->queue_lock);
14081         wakeup(thr);
14082 }
14083
14084 static void
14085 ctl_enqueue_done(union ctl_io *io)
14086 {
14087         struct ctl_softc *softc = control_softc;
14088         struct ctl_thread *thr;
14089
14090         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14091         mtx_lock(&thr->queue_lock);
14092         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14093         mtx_unlock(&thr->queue_lock);
14094         wakeup(thr);
14095 }
14096
14097 static void
14098 ctl_enqueue_isc(union ctl_io *io)
14099 {
14100         struct ctl_softc *softc = control_softc;
14101         struct ctl_thread *thr;
14102
14103         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14104         mtx_lock(&thr->queue_lock);
14105         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14106         mtx_unlock(&thr->queue_lock);
14107         wakeup(thr);
14108 }
14109
14110 /* Initialization and failover */
14111
14112 void
14113 ctl_init_isc_msg(void)
14114 {
14115         printf("CTL: Still calling this thing\n");
14116 }
14117
14118 /*
14119  * Init component
14120  *      Initializes component into configuration defined by bootMode
14121  *      (see hasc-sv.c)
14122  *      returns hasc_Status:
14123  *              OK
14124  *              ERROR - fatal error
14125  */
14126 static ctl_ha_comp_status
14127 ctl_isc_init(struct ctl_ha_component *c)
14128 {
14129         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14130
14131         c->status = ret;
14132         return ret;
14133 }
14134
14135 /* Start component
14136  *      Starts component in state requested. If component starts successfully,
14137  *      it must set its own state to the requestrd state
14138  *      When requested state is HASC_STATE_HA, the component may refine it
14139  *      by adding _SLAVE or _MASTER flags.
14140  *      Currently allowed state transitions are:
14141  *      UNKNOWN->HA             - initial startup
14142  *      UNKNOWN->SINGLE - initial startup when no parter detected
14143  *      HA->SINGLE              - failover
14144  * returns ctl_ha_comp_status:
14145  *              OK      - component successfully started in requested state
14146  *              FAILED  - could not start the requested state, failover may
14147  *                        be possible
14148  *              ERROR   - fatal error detected, no future startup possible
14149  */
14150 static ctl_ha_comp_status
14151 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14152 {
14153         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14154
14155         printf("%s: go\n", __func__);
14156
14157         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14158         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14159                 ctl_is_single = 0;
14160                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14161                     != CTL_HA_STATUS_SUCCESS) {
14162                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14163                         ret = CTL_HA_COMP_STATUS_ERROR;
14164                 }
14165         } else if (CTL_HA_STATE_IS_HA(c->state)
14166                 && CTL_HA_STATE_IS_SINGLE(state)){
14167                 // HA->SINGLE transition
14168                 ctl_failover();
14169                 ctl_is_single = 1;
14170         } else {
14171                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14172                        c->state, state);
14173                 ret = CTL_HA_COMP_STATUS_ERROR;
14174         }
14175         if (CTL_HA_STATE_IS_SINGLE(state))
14176                 ctl_is_single = 1;
14177
14178         c->state = state;
14179         c->status = ret;
14180         return ret;
14181 }
14182
14183 /*
14184  * Quiesce component
14185  * The component must clear any error conditions (set status to OK) and
14186  * prepare itself to another Start call
14187  * returns ctl_ha_comp_status:
14188  *      OK
14189  *      ERROR
14190  */
14191 static ctl_ha_comp_status
14192 ctl_isc_quiesce(struct ctl_ha_component *c)
14193 {
14194         int ret = CTL_HA_COMP_STATUS_OK;
14195
14196         ctl_pause_rtr = 1;
14197         c->status = ret;
14198         return ret;
14199 }
14200
14201 struct ctl_ha_component ctl_ha_component_ctlisc =
14202 {
14203         .name = "CTL ISC",
14204         .state = CTL_HA_STATE_UNKNOWN,
14205         .init = ctl_isc_init,
14206         .start = ctl_isc_start,
14207         .quiesce = ctl_isc_quiesce
14208 };
14209
14210 /*
14211  *  vim: ts=8
14212  */