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