]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r273708: Fix support for LUN flat space addressing.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67
68 #include <cam/cam.h>
69 #include <cam/scsi/scsi_all.h>
70 #include <cam/scsi/scsi_da.h>
71 #include <cam/ctl/ctl_io.h>
72 #include <cam/ctl/ctl.h>
73 #include <cam/ctl/ctl_frontend.h>
74 #include <cam/ctl/ctl_frontend_internal.h>
75 #include <cam/ctl/ctl_util.h>
76 #include <cam/ctl/ctl_backend.h>
77 #include <cam/ctl/ctl_ioctl.h>
78 #include <cam/ctl/ctl_ha.h>
79 #include <cam/ctl/ctl_private.h>
80 #include <cam/ctl/ctl_debug.h>
81 #include <cam/ctl/ctl_scsi_all.h>
82 #include <cam/ctl/ctl_error.h>
83
84 struct ctl_softc *control_softc = NULL;
85
86 /*
87  * Size and alignment macros needed for Copan-specific HA hardware.  These
88  * can go away when the HA code is re-written, and uses busdma for any
89  * hardware.
90  */
91 #define CTL_ALIGN_8B(target, source, type)                              \
92         if (((uint32_t)source & 0x7) != 0)                              \
93                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
94         else                                                            \
95                 target = (type)source;
96
97 #define CTL_SIZE_8B(target, size)                                       \
98         if ((size & 0x7) != 0)                                          \
99                 target = size + (0x8 - (size & 0x7));                   \
100         else                                                            \
101                 target = size;
102
103 #define CTL_ALIGN_8B_MARGIN     16
104
105 /*
106  * Template mode pages.
107  */
108
109 /*
110  * Note that these are default values only.  The actual values will be
111  * filled in when the user does a mode sense.
112  */
113 static struct copan_debugconf_subpage debugconf_page_default = {
114         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
115         DBGCNF_SUBPAGE_CODE,            /* subpage */
116         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
117          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
118         DBGCNF_VERSION,                 /* page_version */
119         {CTL_TIME_IO_DEFAULT_SECS>>8,
120          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
121 };
122
123 static struct copan_debugconf_subpage debugconf_page_changeable = {
124         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
125         DBGCNF_SUBPAGE_CODE,            /* subpage */
126         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
127          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
128         0,                              /* page_version */
129         {0xff,0xff},                    /* ctl_time_io_secs */
130 };
131
132 static struct scsi_da_rw_recovery_page rw_er_page_default = {
133         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
134         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
135         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
136         /*read_retry_count*/0,
137         /*correction_span*/0,
138         /*head_offset_count*/0,
139         /*data_strobe_offset_cnt*/0,
140         /*byte8*/0,
141         /*write_retry_count*/0,
142         /*reserved2*/0,
143         /*recovery_time_limit*/{0, 0},
144 };
145
146 static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
147         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
148         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
149         /*byte3*/0,
150         /*read_retry_count*/0,
151         /*correction_span*/0,
152         /*head_offset_count*/0,
153         /*data_strobe_offset_cnt*/0,
154         /*byte8*/0,
155         /*write_retry_count*/0,
156         /*reserved2*/0,
157         /*recovery_time_limit*/{0, 0},
158 };
159
160 static struct scsi_format_page format_page_default = {
161         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
162         /*page_length*/sizeof(struct scsi_format_page) - 2,
163         /*tracks_per_zone*/ {0, 0},
164         /*alt_sectors_per_zone*/ {0, 0},
165         /*alt_tracks_per_zone*/ {0, 0},
166         /*alt_tracks_per_lun*/ {0, 0},
167         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
168                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
169         /*bytes_per_sector*/ {0, 0},
170         /*interleave*/ {0, 0},
171         /*track_skew*/ {0, 0},
172         /*cylinder_skew*/ {0, 0},
173         /*flags*/ SFP_HSEC,
174         /*reserved*/ {0, 0, 0}
175 };
176
177 static struct scsi_format_page format_page_changeable = {
178         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
179         /*page_length*/sizeof(struct scsi_format_page) - 2,
180         /*tracks_per_zone*/ {0, 0},
181         /*alt_sectors_per_zone*/ {0, 0},
182         /*alt_tracks_per_zone*/ {0, 0},
183         /*alt_tracks_per_lun*/ {0, 0},
184         /*sectors_per_track*/ {0, 0},
185         /*bytes_per_sector*/ {0, 0},
186         /*interleave*/ {0, 0},
187         /*track_skew*/ {0, 0},
188         /*cylinder_skew*/ {0, 0},
189         /*flags*/ 0,
190         /*reserved*/ {0, 0, 0}
191 };
192
193 static struct scsi_rigid_disk_page rigid_disk_page_default = {
194         /*page_code*/SMS_RIGID_DISK_PAGE,
195         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196         /*cylinders*/ {0, 0, 0},
197         /*heads*/ CTL_DEFAULT_HEADS,
198         /*start_write_precomp*/ {0, 0, 0},
199         /*start_reduced_current*/ {0, 0, 0},
200         /*step_rate*/ {0, 0},
201         /*landing_zone_cylinder*/ {0, 0, 0},
202         /*rpl*/ SRDP_RPL_DISABLED,
203         /*rotational_offset*/ 0,
204         /*reserved1*/ 0,
205         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
206                            CTL_DEFAULT_ROTATION_RATE & 0xff},
207         /*reserved2*/ {0, 0}
208 };
209
210 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
211         /*page_code*/SMS_RIGID_DISK_PAGE,
212         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
213         /*cylinders*/ {0, 0, 0},
214         /*heads*/ 0,
215         /*start_write_precomp*/ {0, 0, 0},
216         /*start_reduced_current*/ {0, 0, 0},
217         /*step_rate*/ {0, 0},
218         /*landing_zone_cylinder*/ {0, 0, 0},
219         /*rpl*/ 0,
220         /*rotational_offset*/ 0,
221         /*reserved1*/ 0,
222         /*rotation_rate*/ {0, 0},
223         /*reserved2*/ {0, 0}
224 };
225
226 static struct scsi_caching_page caching_page_default = {
227         /*page_code*/SMS_CACHING_PAGE,
228         /*page_length*/sizeof(struct scsi_caching_page) - 2,
229         /*flags1*/ SCP_DISC | SCP_WCE,
230         /*ret_priority*/ 0,
231         /*disable_pf_transfer_len*/ {0xff, 0xff},
232         /*min_prefetch*/ {0, 0},
233         /*max_prefetch*/ {0xff, 0xff},
234         /*max_pf_ceiling*/ {0xff, 0xff},
235         /*flags2*/ 0,
236         /*cache_segments*/ 0,
237         /*cache_seg_size*/ {0, 0},
238         /*reserved*/ 0,
239         /*non_cache_seg_size*/ {0, 0, 0}
240 };
241
242 static struct scsi_caching_page caching_page_changeable = {
243         /*page_code*/SMS_CACHING_PAGE,
244         /*page_length*/sizeof(struct scsi_caching_page) - 2,
245         /*flags1*/ SCP_WCE | SCP_RCD,
246         /*ret_priority*/ 0,
247         /*disable_pf_transfer_len*/ {0, 0},
248         /*min_prefetch*/ {0, 0},
249         /*max_prefetch*/ {0, 0},
250         /*max_pf_ceiling*/ {0, 0},
251         /*flags2*/ 0,
252         /*cache_segments*/ 0,
253         /*cache_seg_size*/ {0, 0},
254         /*reserved*/ 0,
255         /*non_cache_seg_size*/ {0, 0, 0}
256 };
257
258 static struct scsi_control_page control_page_default = {
259         /*page_code*/SMS_CONTROL_MODE_PAGE,
260         /*page_length*/sizeof(struct scsi_control_page) - 2,
261         /*rlec*/0,
262         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
263         /*eca_and_aen*/0,
264         /*flags4*/SCP_TAS,
265         /*aen_holdoff_period*/{0, 0},
266         /*busy_timeout_period*/{0, 0},
267         /*extended_selftest_completion_time*/{0, 0}
268 };
269
270 static struct scsi_control_page control_page_changeable = {
271         /*page_code*/SMS_CONTROL_MODE_PAGE,
272         /*page_length*/sizeof(struct scsi_control_page) - 2,
273         /*rlec*/SCP_DSENSE,
274         /*queue_flags*/SCP_QUEUE_ALG_MASK,
275         /*eca_and_aen*/SCP_SWP,
276         /*flags4*/0,
277         /*aen_holdoff_period*/{0, 0},
278         /*busy_timeout_period*/{0, 0},
279         /*extended_selftest_completion_time*/{0, 0}
280 };
281
282 static struct scsi_info_exceptions_page ie_page_default = {
283         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
284         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
285         /*info_flags*/SIEP_FLAGS_DEXCPT,
286         /*mrie*/0,
287         /*interval_timer*/{0, 0, 0, 0},
288         /*report_count*/{0, 0, 0, 0}
289 };
290
291 static struct scsi_info_exceptions_page ie_page_changeable = {
292         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
293         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
294         /*info_flags*/0,
295         /*mrie*/0,
296         /*interval_timer*/{0, 0, 0, 0},
297         /*report_count*/{0, 0, 0, 0}
298 };
299
300 static struct scsi_logical_block_provisioning_page lbp_page_default = {
301         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
302         /*subpage_code*/0x02,
303         /*page_length*/{0, sizeof(struct scsi_logical_block_provisioning_page) - 4},
304         /*flags*/0,
305         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
306         /*descr*/{}
307 };
308
309 static struct scsi_logical_block_provisioning_page lbp_page_changeable = {
310         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
311         /*subpage_code*/0x02,
312         /*page_length*/{0, sizeof(struct scsi_logical_block_provisioning_page) - 4},
313         /*flags*/0,
314         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
315         /*descr*/{}
316 };
317
318 /*
319  * XXX KDM move these into the softc.
320  */
321 static int rcv_sync_msg;
322 static int persis_offset;
323 static uint8_t ctl_pause_rtr;
324 static int     ctl_is_single = 1;
325
326 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
327 static int worker_threads = -1;
328 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
329 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
330     &worker_threads, 1, "Number of worker threads");
331 static int ctl_debug = CTL_DEBUG_NONE;
332 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
333 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
334     &ctl_debug, 0, "Enabled debug flags");
335
336 /*
337  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
338  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
339  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
340  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
341  */
342 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
343
344 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
345                                   int param);
346 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
347 static int ctl_init(void);
348 void ctl_shutdown(void);
349 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
350 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
351 static void ctl_ioctl_online(void *arg);
352 static void ctl_ioctl_offline(void *arg);
353 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
354 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
355 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
356 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
357 static int ctl_ioctl_submit_wait(union ctl_io *io);
358 static void ctl_ioctl_datamove(union ctl_io *io);
359 static void ctl_ioctl_done(union ctl_io *io);
360 static void ctl_ioctl_hard_startstop_callback(void *arg,
361                                               struct cfi_metatask *metatask);
362 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
363 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
364                               struct ctl_ooa *ooa_hdr,
365                               struct ctl_ooa_entry *kern_entries);
366 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
367                      struct thread *td);
368 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
369 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
370 #ifdef unused
371 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
372                                    uint32_t targ_target, uint32_t targ_lun,
373                                    int can_wait);
374 static void ctl_kfree_io(union ctl_io *io);
375 #endif /* unused */
376 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
377                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
378 static int ctl_free_lun(struct ctl_lun *lun);
379 static void ctl_create_lun(struct ctl_be_lun *be_lun);
380 /**
381 static void ctl_failover_change_pages(struct ctl_softc *softc,
382                                       struct ctl_scsiio *ctsio, int master);
383 **/
384
385 static int ctl_do_mode_select(union ctl_io *io);
386 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
387                            uint64_t res_key, uint64_t sa_res_key,
388                            uint8_t type, uint32_t residx,
389                            struct ctl_scsiio *ctsio,
390                            struct scsi_per_res_out *cdb,
391                            struct scsi_per_res_out_parms* param);
392 static void ctl_pro_preempt_other(struct ctl_lun *lun,
393                                   union ctl_ha_msg *msg);
394 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
395 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
396 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
397 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
398 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
399 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
400 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
401                                          int alloc_len);
402 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
403                                          int alloc_len);
404 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
405 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
406 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
407 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
408 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
409 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
410 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
411     union ctl_io *pending_io, union ctl_io *ooa_io);
412 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
413                                 union ctl_io *starting_io);
414 static int ctl_check_blocked(struct ctl_lun *lun);
415 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
416                                 struct ctl_lun *lun,
417                                 const struct ctl_cmd_entry *entry,
418                                 struct ctl_scsiio *ctsio);
419 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
420 static void ctl_failover(void);
421 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
422                                struct ctl_scsiio *ctsio);
423 static int ctl_scsiio(struct ctl_scsiio *ctsio);
424
425 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
426 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
427                             ctl_ua_type ua_type);
428 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
429                          ctl_ua_type ua_type);
430 static int ctl_abort_task(union ctl_io *io);
431 static int ctl_abort_task_set(union ctl_io *io);
432 static int ctl_i_t_nexus_reset(union ctl_io *io);
433 static void ctl_run_task(union ctl_io *io);
434 #ifdef CTL_IO_DELAY
435 static void ctl_datamove_timer_wakeup(void *arg);
436 static void ctl_done_timer_wakeup(void *arg);
437 #endif /* CTL_IO_DELAY */
438
439 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
440 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
441 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
442 static void ctl_datamove_remote_write(union ctl_io *io);
443 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
444 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
445 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
446 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
447                                     ctl_ha_dt_cb callback);
448 static void ctl_datamove_remote_read(union ctl_io *io);
449 static void ctl_datamove_remote(union ctl_io *io);
450 static int ctl_process_done(union ctl_io *io);
451 static void ctl_lun_thread(void *arg);
452 static void ctl_work_thread(void *arg);
453 static void ctl_enqueue_incoming(union ctl_io *io);
454 static void ctl_enqueue_rtr(union ctl_io *io);
455 static void ctl_enqueue_done(union ctl_io *io);
456 static void ctl_enqueue_isc(union ctl_io *io);
457 static const struct ctl_cmd_entry *
458     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
459 static const struct ctl_cmd_entry *
460     ctl_validate_command(struct ctl_scsiio *ctsio);
461 static int ctl_cmd_applicable(uint8_t lun_type,
462     const struct ctl_cmd_entry *entry);
463
464 /*
465  * Load the serialization table.  This isn't very pretty, but is probably
466  * the easiest way to do it.
467  */
468 #include "ctl_ser_table.c"
469
470 /*
471  * We only need to define open, close and ioctl routines for this driver.
472  */
473 static struct cdevsw ctl_cdevsw = {
474         .d_version =    D_VERSION,
475         .d_flags =      0,
476         .d_open =       ctl_open,
477         .d_close =      ctl_close,
478         .d_ioctl =      ctl_ioctl,
479         .d_name =       "ctl",
480 };
481
482
483 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
484 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
485
486 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
487
488 static moduledata_t ctl_moduledata = {
489         "ctl",
490         ctl_module_event_handler,
491         NULL
492 };
493
494 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
495 MODULE_VERSION(ctl, 1);
496
497 static struct ctl_frontend ioctl_frontend =
498 {
499         .name = "ioctl",
500 };
501
502 static void
503 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
504                             union ctl_ha_msg *msg_info)
505 {
506         struct ctl_scsiio *ctsio;
507
508         if (msg_info->hdr.original_sc == NULL) {
509                 printf("%s: original_sc == NULL!\n", __func__);
510                 /* XXX KDM now what? */
511                 return;
512         }
513
514         ctsio = &msg_info->hdr.original_sc->scsiio;
515         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
516         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
517         ctsio->io_hdr.status = msg_info->hdr.status;
518         ctsio->scsi_status = msg_info->scsi.scsi_status;
519         ctsio->sense_len = msg_info->scsi.sense_len;
520         ctsio->sense_residual = msg_info->scsi.sense_residual;
521         ctsio->residual = msg_info->scsi.residual;
522         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
523                sizeof(ctsio->sense_data));
524         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
525                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
526         ctl_enqueue_isc((union ctl_io *)ctsio);
527 }
528
529 static void
530 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
531                                 union ctl_ha_msg *msg_info)
532 {
533         struct ctl_scsiio *ctsio;
534
535         if (msg_info->hdr.serializing_sc == NULL) {
536                 printf("%s: serializing_sc == NULL!\n", __func__);
537                 /* XXX KDM now what? */
538                 return;
539         }
540
541         ctsio = &msg_info->hdr.serializing_sc->scsiio;
542 #if 0
543         /*
544          * Attempt to catch the situation where an I/O has
545          * been freed, and we're using it again.
546          */
547         if (ctsio->io_hdr.io_type == 0xff) {
548                 union ctl_io *tmp_io;
549                 tmp_io = (union ctl_io *)ctsio;
550                 printf("%s: %p use after free!\n", __func__,
551                        ctsio);
552                 printf("%s: type %d msg %d cdb %x iptl: "
553                        "%d:%d:%d:%d tag 0x%04x "
554                        "flag %#x status %x\n",
555                         __func__,
556                         tmp_io->io_hdr.io_type,
557                         tmp_io->io_hdr.msg_type,
558                         tmp_io->scsiio.cdb[0],
559                         tmp_io->io_hdr.nexus.initid.id,
560                         tmp_io->io_hdr.nexus.targ_port,
561                         tmp_io->io_hdr.nexus.targ_target.id,
562                         tmp_io->io_hdr.nexus.targ_lun,
563                         (tmp_io->io_hdr.io_type ==
564                         CTL_IO_TASK) ?
565                         tmp_io->taskio.tag_num :
566                         tmp_io->scsiio.tag_num,
567                         tmp_io->io_hdr.flags,
568                         tmp_io->io_hdr.status);
569         }
570 #endif
571         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
572         ctl_enqueue_isc((union ctl_io *)ctsio);
573 }
574
575 /*
576  * ISC (Inter Shelf Communication) event handler.  Events from the HA
577  * subsystem come in here.
578  */
579 static void
580 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
581 {
582         struct ctl_softc *ctl_softc;
583         union ctl_io *io;
584         struct ctl_prio *presio;
585         ctl_ha_status isc_status;
586
587         ctl_softc = control_softc;
588         io = NULL;
589
590
591 #if 0
592         printf("CTL: Isc Msg event %d\n", event);
593 #endif
594         if (event == CTL_HA_EVT_MSG_RECV) {
595                 union ctl_ha_msg msg_info;
596
597                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
598                                              sizeof(msg_info), /*wait*/ 0);
599 #if 0
600                 printf("CTL: msg_type %d\n", msg_info.msg_type);
601 #endif
602                 if (isc_status != 0) {
603                         printf("Error receiving message, status = %d\n",
604                                isc_status);
605                         return;
606                 }
607
608                 switch (msg_info.hdr.msg_type) {
609                 case CTL_MSG_SERIALIZE:
610 #if 0
611                         printf("Serialize\n");
612 #endif
613                         io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
614                         if (io == NULL) {
615                                 printf("ctl_isc_event_handler: can't allocate "
616                                        "ctl_io!\n");
617                                 /* Bad Juju */
618                                 /* Need to set busy and send msg back */
619                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
620                                 msg_info.hdr.status = CTL_SCSI_ERROR;
621                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
622                                 msg_info.scsi.sense_len = 0;
623                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
624                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
625                                 }
626                                 goto bailout;
627                         }
628                         ctl_zero_io(io);
629                         // populate ctsio from msg_info
630                         io->io_hdr.io_type = CTL_IO_SCSI;
631                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
632                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
633 #if 0
634                         printf("pOrig %x\n", (int)msg_info.original_sc);
635 #endif
636                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
637                                             CTL_FLAG_IO_ACTIVE;
638                         /*
639                          * If we're in serialization-only mode, we don't
640                          * want to go through full done processing.  Thus
641                          * the COPY flag.
642                          *
643                          * XXX KDM add another flag that is more specific.
644                          */
645                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
646                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
647                         io->io_hdr.nexus = msg_info.hdr.nexus;
648 #if 0
649                         printf("targ %d, port %d, iid %d, lun %d\n",
650                                io->io_hdr.nexus.targ_target.id,
651                                io->io_hdr.nexus.targ_port,
652                                io->io_hdr.nexus.initid.id,
653                                io->io_hdr.nexus.targ_lun);
654 #endif
655                         io->scsiio.tag_num = msg_info.scsi.tag_num;
656                         io->scsiio.tag_type = msg_info.scsi.tag_type;
657                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
658                                CTL_MAX_CDBLEN);
659                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
660                                 const struct ctl_cmd_entry *entry;
661
662                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
663                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
664                                 io->io_hdr.flags |=
665                                         entry->flags & CTL_FLAG_DATA_MASK;
666                         }
667                         ctl_enqueue_isc(io);
668                         break;
669
670                 /* Performed on the Originating SC, XFER mode only */
671                 case CTL_MSG_DATAMOVE: {
672                         struct ctl_sg_entry *sgl;
673                         int i, j;
674
675                         io = msg_info.hdr.original_sc;
676                         if (io == NULL) {
677                                 printf("%s: original_sc == NULL!\n", __func__);
678                                 /* XXX KDM do something here */
679                                 break;
680                         }
681                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
682                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
683                         /*
684                          * Keep track of this, we need to send it back over
685                          * when the datamove is complete.
686                          */
687                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
688
689                         if (msg_info.dt.sg_sequence == 0) {
690                                 /*
691                                  * XXX KDM we use the preallocated S/G list
692                                  * here, but we'll need to change this to
693                                  * dynamic allocation if we need larger S/G
694                                  * lists.
695                                  */
696                                 if (msg_info.dt.kern_sg_entries >
697                                     sizeof(io->io_hdr.remote_sglist) /
698                                     sizeof(io->io_hdr.remote_sglist[0])) {
699                                         printf("%s: number of S/G entries "
700                                             "needed %u > allocated num %zd\n",
701                                             __func__,
702                                             msg_info.dt.kern_sg_entries,
703                                             sizeof(io->io_hdr.remote_sglist)/
704                                             sizeof(io->io_hdr.remote_sglist[0]));
705                                 
706                                         /*
707                                          * XXX KDM send a message back to
708                                          * the other side to shut down the
709                                          * DMA.  The error will come back
710                                          * through via the normal channel.
711                                          */
712                                         break;
713                                 }
714                                 sgl = io->io_hdr.remote_sglist;
715                                 memset(sgl, 0,
716                                        sizeof(io->io_hdr.remote_sglist));
717
718                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
719
720                                 io->scsiio.kern_sg_entries =
721                                         msg_info.dt.kern_sg_entries;
722                                 io->scsiio.rem_sg_entries =
723                                         msg_info.dt.kern_sg_entries;
724                                 io->scsiio.kern_data_len =
725                                         msg_info.dt.kern_data_len;
726                                 io->scsiio.kern_total_len =
727                                         msg_info.dt.kern_total_len;
728                                 io->scsiio.kern_data_resid =
729                                         msg_info.dt.kern_data_resid;
730                                 io->scsiio.kern_rel_offset =
731                                         msg_info.dt.kern_rel_offset;
732                                 /*
733                                  * Clear out per-DMA flags.
734                                  */
735                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
736                                 /*
737                                  * Add per-DMA flags that are set for this
738                                  * particular DMA request.
739                                  */
740                                 io->io_hdr.flags |= msg_info.dt.flags &
741                                                     CTL_FLAG_RDMA_MASK;
742                         } else
743                                 sgl = (struct ctl_sg_entry *)
744                                         io->scsiio.kern_data_ptr;
745
746                         for (i = msg_info.dt.sent_sg_entries, j = 0;
747                              i < (msg_info.dt.sent_sg_entries +
748                              msg_info.dt.cur_sg_entries); i++, j++) {
749                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
750                                 sgl[i].len = msg_info.dt.sg_list[j].len;
751
752 #if 0
753                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
754                                        __func__,
755                                        msg_info.dt.sg_list[j].addr,
756                                        msg_info.dt.sg_list[j].len,
757                                        sgl[i].addr, sgl[i].len, j, i);
758 #endif
759                         }
760 #if 0
761                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
762                                msg_info.dt.sg_list,
763                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
764 #endif
765
766                         /*
767                          * If this is the last piece of the I/O, we've got
768                          * the full S/G list.  Queue processing in the thread.
769                          * Otherwise wait for the next piece.
770                          */
771                         if (msg_info.dt.sg_last != 0)
772                                 ctl_enqueue_isc(io);
773                         break;
774                 }
775                 /* Performed on the Serializing (primary) SC, XFER mode only */
776                 case CTL_MSG_DATAMOVE_DONE: {
777                         if (msg_info.hdr.serializing_sc == NULL) {
778                                 printf("%s: serializing_sc == NULL!\n",
779                                        __func__);
780                                 /* XXX KDM now what? */
781                                 break;
782                         }
783                         /*
784                          * We grab the sense information here in case
785                          * there was a failure, so we can return status
786                          * back to the initiator.
787                          */
788                         io = msg_info.hdr.serializing_sc;
789                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
790                         io->io_hdr.status = msg_info.hdr.status;
791                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
792                         io->scsiio.sense_len = msg_info.scsi.sense_len;
793                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
794                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
795                         io->scsiio.residual = msg_info.scsi.residual;
796                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
797                                sizeof(io->scsiio.sense_data));
798                         ctl_enqueue_isc(io);
799                         break;
800                 }
801
802                 /* Preformed on Originating SC, SER_ONLY mode */
803                 case CTL_MSG_R2R:
804                         io = msg_info.hdr.original_sc;
805                         if (io == NULL) {
806                                 printf("%s: Major Bummer\n", __func__);
807                                 return;
808                         } else {
809 #if 0
810                                 printf("pOrig %x\n",(int) ctsio);
811 #endif
812                         }
813                         io->io_hdr.msg_type = CTL_MSG_R2R;
814                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
815                         ctl_enqueue_isc(io);
816                         break;
817
818                 /*
819                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
820                  * mode.
821                  * Performed on the Originating (i.e. secondary) SC in XFER
822                  * mode
823                  */
824                 case CTL_MSG_FINISH_IO:
825                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
826                                 ctl_isc_handler_finish_xfer(ctl_softc,
827                                                             &msg_info);
828                         else
829                                 ctl_isc_handler_finish_ser_only(ctl_softc,
830                                                                 &msg_info);
831                         break;
832
833                 /* Preformed on Originating SC */
834                 case CTL_MSG_BAD_JUJU:
835                         io = msg_info.hdr.original_sc;
836                         if (io == NULL) {
837                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
838                                        __func__);
839                                 break;
840                         }
841                         ctl_copy_sense_data(&msg_info, io);
842                         /*
843                          * IO should have already been cleaned up on other
844                          * SC so clear this flag so we won't send a message
845                          * back to finish the IO there.
846                          */
847                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
848                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
849
850                         /* io = msg_info.hdr.serializing_sc; */
851                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
852                         ctl_enqueue_isc(io);
853                         break;
854
855                 /* Handle resets sent from the other side */
856                 case CTL_MSG_MANAGE_TASKS: {
857                         struct ctl_taskio *taskio;
858                         taskio = (struct ctl_taskio *)ctl_alloc_io(
859                                 (void *)ctl_softc->othersc_pool);
860                         if (taskio == NULL) {
861                                 printf("ctl_isc_event_handler: can't allocate "
862                                        "ctl_io!\n");
863                                 /* Bad Juju */
864                                 /* should I just call the proper reset func
865                                    here??? */
866                                 goto bailout;
867                         }
868                         ctl_zero_io((union ctl_io *)taskio);
869                         taskio->io_hdr.io_type = CTL_IO_TASK;
870                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
871                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
872                         taskio->task_action = msg_info.task.task_action;
873                         taskio->tag_num = msg_info.task.tag_num;
874                         taskio->tag_type = msg_info.task.tag_type;
875 #ifdef CTL_TIME_IO
876                         taskio->io_hdr.start_time = time_uptime;
877                         getbintime(&taskio->io_hdr.start_bt);
878 #if 0
879                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
880 #endif
881 #endif /* CTL_TIME_IO */
882                         ctl_run_task((union ctl_io *)taskio);
883                         break;
884                 }
885                 /* Persistent Reserve action which needs attention */
886                 case CTL_MSG_PERS_ACTION:
887                         presio = (struct ctl_prio *)ctl_alloc_io(
888                                 (void *)ctl_softc->othersc_pool);
889                         if (presio == NULL) {
890                                 printf("ctl_isc_event_handler: can't allocate "
891                                        "ctl_io!\n");
892                                 /* Bad Juju */
893                                 /* Need to set busy and send msg back */
894                                 goto bailout;
895                         }
896                         ctl_zero_io((union ctl_io *)presio);
897                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
898                         presio->pr_msg = msg_info.pr;
899                         ctl_enqueue_isc((union ctl_io *)presio);
900                         break;
901                 case CTL_MSG_SYNC_FE:
902                         rcv_sync_msg = 1;
903                         break;
904                 default:
905                         printf("How did I get here?\n");
906                 }
907         } else if (event == CTL_HA_EVT_MSG_SENT) {
908                 if (param != CTL_HA_STATUS_SUCCESS) {
909                         printf("Bad status from ctl_ha_msg_send status %d\n",
910                                param);
911                 }
912                 return;
913         } else if (event == CTL_HA_EVT_DISCONNECT) {
914                 printf("CTL: Got a disconnect from Isc\n");
915                 return;
916         } else {
917                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
918                 return;
919         }
920
921 bailout:
922         return;
923 }
924
925 static void
926 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
927 {
928         struct scsi_sense_data *sense;
929
930         sense = &dest->scsiio.sense_data;
931         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
932         dest->scsiio.scsi_status = src->scsi.scsi_status;
933         dest->scsiio.sense_len = src->scsi.sense_len;
934         dest->io_hdr.status = src->hdr.status;
935 }
936
937 static int
938 ctl_init(void)
939 {
940         struct ctl_softc *softc;
941         struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
942         struct ctl_port *port;
943         uint8_t sc_id =0;
944         int i, error, retval;
945         //int isc_retval;
946
947         retval = 0;
948         ctl_pause_rtr = 0;
949         rcv_sync_msg = 0;
950
951         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
952                                M_WAITOK | M_ZERO);
953         softc = control_softc;
954
955         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
956                               "cam/ctl");
957
958         softc->dev->si_drv1 = softc;
959
960         /*
961          * By default, return a "bad LUN" peripheral qualifier for unknown
962          * LUNs.  The user can override this default using the tunable or
963          * sysctl.  See the comment in ctl_inquiry_std() for more details.
964          */
965         softc->inquiry_pq_no_lun = 1;
966         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
967                           &softc->inquiry_pq_no_lun);
968         sysctl_ctx_init(&softc->sysctl_ctx);
969         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
970                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
971                 CTLFLAG_RD, 0, "CAM Target Layer");
972
973         if (softc->sysctl_tree == NULL) {
974                 printf("%s: unable to allocate sysctl tree\n", __func__);
975                 destroy_dev(softc->dev);
976                 free(control_softc, M_DEVBUF);
977                 control_softc = NULL;
978                 return (ENOMEM);
979         }
980
981         SYSCTL_ADD_INT(&softc->sysctl_ctx,
982                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
983                        "inquiry_pq_no_lun", CTLFLAG_RW,
984                        &softc->inquiry_pq_no_lun, 0,
985                        "Report no lun possible for invalid LUNs");
986
987         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
988         mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
989         softc->open_count = 0;
990
991         /*
992          * Default to actually sending a SYNCHRONIZE CACHE command down to
993          * the drive.
994          */
995         softc->flags = CTL_FLAG_REAL_SYNC;
996
997         /*
998          * In Copan's HA scheme, the "master" and "slave" roles are
999          * figured out through the slot the controller is in.  Although it
1000          * is an active/active system, someone has to be in charge.
1001          */
1002 #ifdef NEEDTOPORT
1003         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1004 #endif
1005
1006         if (sc_id == 0) {
1007                 softc->flags |= CTL_FLAG_MASTER_SHELF;
1008                 persis_offset = 0;
1009         } else
1010                 persis_offset = CTL_MAX_INITIATORS;
1011
1012         /*
1013          * XXX KDM need to figure out where we want to get our target ID
1014          * and WWID.  Is it different on each port?
1015          */
1016         softc->target.id = 0;
1017         softc->target.wwid[0] = 0x12345678;
1018         softc->target.wwid[1] = 0x87654321;
1019         STAILQ_INIT(&softc->lun_list);
1020         STAILQ_INIT(&softc->pending_lun_queue);
1021         STAILQ_INIT(&softc->fe_list);
1022         STAILQ_INIT(&softc->port_list);
1023         STAILQ_INIT(&softc->be_list);
1024         STAILQ_INIT(&softc->io_pools);
1025         ctl_tpc_init(softc);
1026
1027         if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1028                             &internal_pool)!= 0){
1029                 printf("ctl: can't allocate %d entry internal pool, "
1030                        "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1031                 return (ENOMEM);
1032         }
1033
1034         if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1035                             CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1036                 printf("ctl: can't allocate %d entry emergency pool, "
1037                        "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1038                 ctl_pool_free(internal_pool);
1039                 return (ENOMEM);
1040         }
1041
1042         if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1043                             &other_pool) != 0)
1044         {
1045                 printf("ctl: can't allocate %d entry other SC pool, "
1046                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1047                 ctl_pool_free(internal_pool);
1048                 ctl_pool_free(emergency_pool);
1049                 return (ENOMEM);
1050         }
1051
1052         softc->internal_pool = internal_pool;
1053         softc->emergency_pool = emergency_pool;
1054         softc->othersc_pool = other_pool;
1055
1056         if (worker_threads <= 0)
1057                 worker_threads = max(1, mp_ncpus / 4);
1058         if (worker_threads > CTL_MAX_THREADS)
1059                 worker_threads = CTL_MAX_THREADS;
1060
1061         for (i = 0; i < worker_threads; i++) {
1062                 struct ctl_thread *thr = &softc->threads[i];
1063
1064                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1065                 thr->ctl_softc = softc;
1066                 STAILQ_INIT(&thr->incoming_queue);
1067                 STAILQ_INIT(&thr->rtr_queue);
1068                 STAILQ_INIT(&thr->done_queue);
1069                 STAILQ_INIT(&thr->isc_queue);
1070
1071                 error = kproc_kthread_add(ctl_work_thread, thr,
1072                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1073                 if (error != 0) {
1074                         printf("error creating CTL work thread!\n");
1075                         ctl_pool_free(internal_pool);
1076                         ctl_pool_free(emergency_pool);
1077                         ctl_pool_free(other_pool);
1078                         return (error);
1079                 }
1080         }
1081         error = kproc_kthread_add(ctl_lun_thread, softc,
1082             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1083         if (error != 0) {
1084                 printf("error creating CTL lun thread!\n");
1085                 ctl_pool_free(internal_pool);
1086                 ctl_pool_free(emergency_pool);
1087                 ctl_pool_free(other_pool);
1088                 return (error);
1089         }
1090         if (bootverbose)
1091                 printf("ctl: CAM Target Layer loaded\n");
1092
1093         /*
1094          * Initialize the ioctl front end.
1095          */
1096         ctl_frontend_register(&ioctl_frontend);
1097         port = &softc->ioctl_info.port;
1098         port->frontend = &ioctl_frontend;
1099         sprintf(softc->ioctl_info.port_name, "ioctl");
1100         port->port_type = CTL_PORT_IOCTL;
1101         port->num_requested_ctl_io = 100;
1102         port->port_name = softc->ioctl_info.port_name;
1103         port->port_online = ctl_ioctl_online;
1104         port->port_offline = ctl_ioctl_offline;
1105         port->onoff_arg = &softc->ioctl_info;
1106         port->lun_enable = ctl_ioctl_lun_enable;
1107         port->lun_disable = ctl_ioctl_lun_disable;
1108         port->targ_lun_arg = &softc->ioctl_info;
1109         port->fe_datamove = ctl_ioctl_datamove;
1110         port->fe_done = ctl_ioctl_done;
1111         port->max_targets = 15;
1112         port->max_target_id = 15;
1113
1114         if (ctl_port_register(&softc->ioctl_info.port,
1115                           (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1116                 printf("ctl: ioctl front end registration failed, will "
1117                        "continue anyway\n");
1118         }
1119
1120 #ifdef CTL_IO_DELAY
1121         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1122                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1123                        sizeof(struct callout), CTL_TIMER_BYTES);
1124                 return (EINVAL);
1125         }
1126 #endif /* CTL_IO_DELAY */
1127
1128         return (0);
1129 }
1130
1131 void
1132 ctl_shutdown(void)
1133 {
1134         struct ctl_softc *softc;
1135         struct ctl_lun *lun, *next_lun;
1136         struct ctl_io_pool *pool;
1137
1138         softc = (struct ctl_softc *)control_softc;
1139
1140         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1141                 printf("ctl: ioctl front end deregistration failed\n");
1142
1143         mtx_lock(&softc->ctl_lock);
1144
1145         /*
1146          * Free up each LUN.
1147          */
1148         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1149                 next_lun = STAILQ_NEXT(lun, links);
1150                 ctl_free_lun(lun);
1151         }
1152
1153         mtx_unlock(&softc->ctl_lock);
1154
1155         ctl_frontend_deregister(&ioctl_frontend);
1156
1157         /*
1158          * This will rip the rug out from under any FETDs or anyone else
1159          * that has a pool allocated.  Since we increment our module
1160          * refcount any time someone outside the main CTL module allocates
1161          * a pool, we shouldn't have any problems here.  The user won't be
1162          * able to unload the CTL module until client modules have
1163          * successfully unloaded.
1164          */
1165         while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1166                 ctl_pool_free(pool);
1167
1168 #if 0
1169         ctl_shutdown_thread(softc->work_thread);
1170         mtx_destroy(&softc->queue_lock);
1171 #endif
1172
1173         ctl_tpc_shutdown(softc);
1174         mtx_destroy(&softc->pool_lock);
1175         mtx_destroy(&softc->ctl_lock);
1176
1177         destroy_dev(softc->dev);
1178
1179         sysctl_ctx_free(&softc->sysctl_ctx);
1180
1181         free(control_softc, M_DEVBUF);
1182         control_softc = NULL;
1183
1184         if (bootverbose)
1185                 printf("ctl: CAM Target Layer unloaded\n");
1186 }
1187
1188 static int
1189 ctl_module_event_handler(module_t mod, int what, void *arg)
1190 {
1191
1192         switch (what) {
1193         case MOD_LOAD:
1194                 return (ctl_init());
1195         case MOD_UNLOAD:
1196                 return (EBUSY);
1197         default:
1198                 return (EOPNOTSUPP);
1199         }
1200 }
1201
1202 /*
1203  * XXX KDM should we do some access checks here?  Bump a reference count to
1204  * prevent a CTL module from being unloaded while someone has it open?
1205  */
1206 static int
1207 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1208 {
1209         return (0);
1210 }
1211
1212 static int
1213 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1214 {
1215         return (0);
1216 }
1217
1218 int
1219 ctl_port_enable(ctl_port_type port_type)
1220 {
1221         struct ctl_softc *softc;
1222         struct ctl_port *port;
1223
1224         if (ctl_is_single == 0) {
1225                 union ctl_ha_msg msg_info;
1226                 int isc_retval;
1227
1228 #if 0
1229                 printf("%s: HA mode, synchronizing frontend enable\n",
1230                         __func__);
1231 #endif
1232                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1233                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1234                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1235                         printf("Sync msg send error retval %d\n", isc_retval);
1236                 }
1237                 if (!rcv_sync_msg) {
1238                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1239                                 sizeof(msg_info), 1);
1240                 }
1241 #if 0
1242                 printf("CTL:Frontend Enable\n");
1243         } else {
1244                 printf("%s: single mode, skipping frontend synchronization\n",
1245                         __func__);
1246 #endif
1247         }
1248
1249         softc = control_softc;
1250
1251         STAILQ_FOREACH(port, &softc->port_list, links) {
1252                 if (port_type & port->port_type)
1253                 {
1254 #if 0
1255                         printf("port %d\n", port->targ_port);
1256 #endif
1257                         ctl_port_online(port);
1258                 }
1259         }
1260
1261         return (0);
1262 }
1263
1264 int
1265 ctl_port_disable(ctl_port_type port_type)
1266 {
1267         struct ctl_softc *softc;
1268         struct ctl_port *port;
1269
1270         softc = control_softc;
1271
1272         STAILQ_FOREACH(port, &softc->port_list, links) {
1273                 if (port_type & port->port_type)
1274                         ctl_port_offline(port);
1275         }
1276
1277         return (0);
1278 }
1279
1280 /*
1281  * Returns 0 for success, 1 for failure.
1282  * Currently the only failure mode is if there aren't enough entries
1283  * allocated.  So, in case of a failure, look at num_entries_dropped,
1284  * reallocate and try again.
1285  */
1286 int
1287 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1288               int *num_entries_filled, int *num_entries_dropped,
1289               ctl_port_type port_type, int no_virtual)
1290 {
1291         struct ctl_softc *softc;
1292         struct ctl_port *port;
1293         int entries_dropped, entries_filled;
1294         int retval;
1295         int i;
1296
1297         softc = control_softc;
1298
1299         retval = 0;
1300         entries_filled = 0;
1301         entries_dropped = 0;
1302
1303         i = 0;
1304         mtx_lock(&softc->ctl_lock);
1305         STAILQ_FOREACH(port, &softc->port_list, links) {
1306                 struct ctl_port_entry *entry;
1307
1308                 if ((port->port_type & port_type) == 0)
1309                         continue;
1310
1311                 if ((no_virtual != 0)
1312                  && (port->virtual_port != 0))
1313                         continue;
1314
1315                 if (entries_filled >= num_entries_alloced) {
1316                         entries_dropped++;
1317                         continue;
1318                 }
1319                 entry = &entries[i];
1320
1321                 entry->port_type = port->port_type;
1322                 strlcpy(entry->port_name, port->port_name,
1323                         sizeof(entry->port_name));
1324                 entry->physical_port = port->physical_port;
1325                 entry->virtual_port = port->virtual_port;
1326                 entry->wwnn = port->wwnn;
1327                 entry->wwpn = port->wwpn;
1328
1329                 i++;
1330                 entries_filled++;
1331         }
1332
1333         mtx_unlock(&softc->ctl_lock);
1334
1335         if (entries_dropped > 0)
1336                 retval = 1;
1337
1338         *num_entries_dropped = entries_dropped;
1339         *num_entries_filled = entries_filled;
1340
1341         return (retval);
1342 }
1343
1344 static void
1345 ctl_ioctl_online(void *arg)
1346 {
1347         struct ctl_ioctl_info *ioctl_info;
1348
1349         ioctl_info = (struct ctl_ioctl_info *)arg;
1350
1351         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1352 }
1353
1354 static void
1355 ctl_ioctl_offline(void *arg)
1356 {
1357         struct ctl_ioctl_info *ioctl_info;
1358
1359         ioctl_info = (struct ctl_ioctl_info *)arg;
1360
1361         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1362 }
1363
1364 /*
1365  * Remove an initiator by port number and initiator ID.
1366  * Returns 0 for success, -1 for failure.
1367  */
1368 int
1369 ctl_remove_initiator(struct ctl_port *port, int iid)
1370 {
1371         struct ctl_softc *softc = control_softc;
1372
1373         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1374
1375         if (iid > CTL_MAX_INIT_PER_PORT) {
1376                 printf("%s: initiator ID %u > maximun %u!\n",
1377                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1378                 return (-1);
1379         }
1380
1381         mtx_lock(&softc->ctl_lock);
1382         port->wwpn_iid[iid].in_use--;
1383         port->wwpn_iid[iid].last_use = time_uptime;
1384         mtx_unlock(&softc->ctl_lock);
1385
1386         return (0);
1387 }
1388
1389 /*
1390  * Add an initiator to the initiator map.
1391  * Returns iid for success, < 0 for failure.
1392  */
1393 int
1394 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1395 {
1396         struct ctl_softc *softc = control_softc;
1397         time_t best_time;
1398         int i, best;
1399
1400         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1401
1402         if (iid >= CTL_MAX_INIT_PER_PORT) {
1403                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1404                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1405                 free(name, M_CTL);
1406                 return (-1);
1407         }
1408
1409         mtx_lock(&softc->ctl_lock);
1410
1411         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1412                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1413                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1414                                 iid = i;
1415                                 break;
1416                         }
1417                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1418                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1419                                 iid = i;
1420                                 break;
1421                         }
1422                 }
1423         }
1424
1425         if (iid < 0) {
1426                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1427                         if (port->wwpn_iid[i].in_use == 0 &&
1428                             port->wwpn_iid[i].wwpn == 0 &&
1429                             port->wwpn_iid[i].name == NULL) {
1430                                 iid = i;
1431                                 break;
1432                         }
1433                 }
1434         }
1435
1436         if (iid < 0) {
1437                 best = -1;
1438                 best_time = INT32_MAX;
1439                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1440                         if (port->wwpn_iid[i].in_use == 0) {
1441                                 if (port->wwpn_iid[i].last_use < best_time) {
1442                                         best = i;
1443                                         best_time = port->wwpn_iid[i].last_use;
1444                                 }
1445                         }
1446                 }
1447                 iid = best;
1448         }
1449
1450         if (iid < 0) {
1451                 mtx_unlock(&softc->ctl_lock);
1452                 free(name, M_CTL);
1453                 return (-2);
1454         }
1455
1456         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1457                 /*
1458                  * This is not an error yet.
1459                  */
1460                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1461 #if 0
1462                         printf("%s: port %d iid %u WWPN %#jx arrived"
1463                             " again\n", __func__, port->targ_port,
1464                             iid, (uintmax_t)wwpn);
1465 #endif
1466                         goto take;
1467                 }
1468                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1469                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1470 #if 0
1471                         printf("%s: port %d iid %u name '%s' arrived"
1472                             " again\n", __func__, port->targ_port,
1473                             iid, name);
1474 #endif
1475                         goto take;
1476                 }
1477
1478                 /*
1479                  * This is an error, but what do we do about it?  The
1480                  * driver is telling us we have a new WWPN for this
1481                  * initiator ID, so we pretty much need to use it.
1482                  */
1483                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1484                     " but WWPN %#jx '%s' is still at that address\n",
1485                     __func__, port->targ_port, iid, wwpn, name,
1486                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1487                     port->wwpn_iid[iid].name);
1488
1489                 /*
1490                  * XXX KDM clear have_ca and ua_pending on each LUN for
1491                  * this initiator.
1492                  */
1493         }
1494 take:
1495         free(port->wwpn_iid[iid].name, M_CTL);
1496         port->wwpn_iid[iid].name = name;
1497         port->wwpn_iid[iid].wwpn = wwpn;
1498         port->wwpn_iid[iid].in_use++;
1499         mtx_unlock(&softc->ctl_lock);
1500
1501         return (iid);
1502 }
1503
1504 static int
1505 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1506 {
1507         int len;
1508
1509         switch (port->port_type) {
1510         case CTL_PORT_FC:
1511         {
1512                 struct scsi_transportid_fcp *id =
1513                     (struct scsi_transportid_fcp *)buf;
1514                 if (port->wwpn_iid[iid].wwpn == 0)
1515                         return (0);
1516                 memset(id, 0, sizeof(*id));
1517                 id->format_protocol = SCSI_PROTO_FC;
1518                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1519                 return (sizeof(*id));
1520         }
1521         case CTL_PORT_ISCSI:
1522         {
1523                 struct scsi_transportid_iscsi_port *id =
1524                     (struct scsi_transportid_iscsi_port *)buf;
1525                 if (port->wwpn_iid[iid].name == NULL)
1526                         return (0);
1527                 memset(id, 0, 256);
1528                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1529                     SCSI_PROTO_ISCSI;
1530                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1531                 len = roundup2(min(len, 252), 4);
1532                 scsi_ulto2b(len, id->additional_length);
1533                 return (sizeof(*id) + len);
1534         }
1535         case CTL_PORT_SAS:
1536         {
1537                 struct scsi_transportid_sas *id =
1538                     (struct scsi_transportid_sas *)buf;
1539                 if (port->wwpn_iid[iid].wwpn == 0)
1540                         return (0);
1541                 memset(id, 0, sizeof(*id));
1542                 id->format_protocol = SCSI_PROTO_SAS;
1543                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1544                 return (sizeof(*id));
1545         }
1546         default:
1547         {
1548                 struct scsi_transportid_spi *id =
1549                     (struct scsi_transportid_spi *)buf;
1550                 memset(id, 0, sizeof(*id));
1551                 id->format_protocol = SCSI_PROTO_SPI;
1552                 scsi_ulto2b(iid, id->scsi_addr);
1553                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1554                 return (sizeof(*id));
1555         }
1556         }
1557 }
1558
1559 static int
1560 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1561 {
1562         return (0);
1563 }
1564
1565 static int
1566 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1567 {
1568         return (0);
1569 }
1570
1571 /*
1572  * Data movement routine for the CTL ioctl frontend port.
1573  */
1574 static int
1575 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1576 {
1577         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1578         struct ctl_sg_entry ext_entry, kern_entry;
1579         int ext_sglen, ext_sg_entries, kern_sg_entries;
1580         int ext_sg_start, ext_offset;
1581         int len_to_copy, len_copied;
1582         int kern_watermark, ext_watermark;
1583         int ext_sglist_malloced;
1584         int i, j;
1585
1586         ext_sglist_malloced = 0;
1587         ext_sg_start = 0;
1588         ext_offset = 0;
1589
1590         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1591
1592         /*
1593          * If this flag is set, fake the data transfer.
1594          */
1595         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1596                 ctsio->ext_data_filled = ctsio->ext_data_len;
1597                 goto bailout;
1598         }
1599
1600         /*
1601          * To simplify things here, if we have a single buffer, stick it in
1602          * a S/G entry and just make it a single entry S/G list.
1603          */
1604         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1605                 int len_seen;
1606
1607                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1608
1609                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1610                                                            M_WAITOK);
1611                 ext_sglist_malloced = 1;
1612                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1613                                    ext_sglen) != 0) {
1614                         ctl_set_internal_failure(ctsio,
1615                                                  /*sks_valid*/ 0,
1616                                                  /*retry_count*/ 0);
1617                         goto bailout;
1618                 }
1619                 ext_sg_entries = ctsio->ext_sg_entries;
1620                 len_seen = 0;
1621                 for (i = 0; i < ext_sg_entries; i++) {
1622                         if ((len_seen + ext_sglist[i].len) >=
1623                              ctsio->ext_data_filled) {
1624                                 ext_sg_start = i;
1625                                 ext_offset = ctsio->ext_data_filled - len_seen;
1626                                 break;
1627                         }
1628                         len_seen += ext_sglist[i].len;
1629                 }
1630         } else {
1631                 ext_sglist = &ext_entry;
1632                 ext_sglist->addr = ctsio->ext_data_ptr;
1633                 ext_sglist->len = ctsio->ext_data_len;
1634                 ext_sg_entries = 1;
1635                 ext_sg_start = 0;
1636                 ext_offset = ctsio->ext_data_filled;
1637         }
1638
1639         if (ctsio->kern_sg_entries > 0) {
1640                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1641                 kern_sg_entries = ctsio->kern_sg_entries;
1642         } else {
1643                 kern_sglist = &kern_entry;
1644                 kern_sglist->addr = ctsio->kern_data_ptr;
1645                 kern_sglist->len = ctsio->kern_data_len;
1646                 kern_sg_entries = 1;
1647         }
1648
1649
1650         kern_watermark = 0;
1651         ext_watermark = ext_offset;
1652         len_copied = 0;
1653         for (i = ext_sg_start, j = 0;
1654              i < ext_sg_entries && j < kern_sg_entries;) {
1655                 uint8_t *ext_ptr, *kern_ptr;
1656
1657                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1658                                       kern_sglist[j].len - kern_watermark);
1659
1660                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1661                 ext_ptr = ext_ptr + ext_watermark;
1662                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1663                         /*
1664                          * XXX KDM fix this!
1665                          */
1666                         panic("need to implement bus address support");
1667 #if 0
1668                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1669 #endif
1670                 } else
1671                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1672                 kern_ptr = kern_ptr + kern_watermark;
1673
1674                 kern_watermark += len_to_copy;
1675                 ext_watermark += len_to_copy;
1676
1677                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1678                      CTL_FLAG_DATA_IN) {
1679                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1680                                          "bytes to user\n", len_to_copy));
1681                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1682                                          "to %p\n", kern_ptr, ext_ptr));
1683                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1684                                 ctl_set_internal_failure(ctsio,
1685                                                          /*sks_valid*/ 0,
1686                                                          /*retry_count*/ 0);
1687                                 goto bailout;
1688                         }
1689                 } else {
1690                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1691                                          "bytes from user\n", len_to_copy));
1692                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1693                                          "to %p\n", ext_ptr, kern_ptr));
1694                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1695                                 ctl_set_internal_failure(ctsio,
1696                                                          /*sks_valid*/ 0,
1697                                                          /*retry_count*/0);
1698                                 goto bailout;
1699                         }
1700                 }
1701
1702                 len_copied += len_to_copy;
1703
1704                 if (ext_sglist[i].len == ext_watermark) {
1705                         i++;
1706                         ext_watermark = 0;
1707                 }
1708
1709                 if (kern_sglist[j].len == kern_watermark) {
1710                         j++;
1711                         kern_watermark = 0;
1712                 }
1713         }
1714
1715         ctsio->ext_data_filled += len_copied;
1716
1717         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1718                          "kern_sg_entries: %d\n", ext_sg_entries,
1719                          kern_sg_entries));
1720         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1721                          "kern_data_len = %d\n", ctsio->ext_data_len,
1722                          ctsio->kern_data_len));
1723
1724
1725         /* XXX KDM set residual?? */
1726 bailout:
1727
1728         if (ext_sglist_malloced != 0)
1729                 free(ext_sglist, M_CTL);
1730
1731         return (CTL_RETVAL_COMPLETE);
1732 }
1733
1734 /*
1735  * Serialize a command that went down the "wrong" side, and so was sent to
1736  * this controller for execution.  The logic is a little different than the
1737  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1738  * sent back to the other side, but in the success case, we execute the
1739  * command on this side (XFER mode) or tell the other side to execute it
1740  * (SER_ONLY mode).
1741  */
1742 static int
1743 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1744 {
1745         struct ctl_softc *ctl_softc;
1746         union ctl_ha_msg msg_info;
1747         struct ctl_lun *lun;
1748         int retval = 0;
1749         uint32_t targ_lun;
1750
1751         ctl_softc = control_softc;
1752
1753         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1754         lun = ctl_softc->ctl_luns[targ_lun];
1755         if (lun==NULL)
1756         {
1757                 /*
1758                  * Why isn't LUN defined? The other side wouldn't
1759                  * send a cmd if the LUN is undefined.
1760                  */
1761                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1762
1763                 /* "Logical unit not supported" */
1764                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1765                                    lun,
1766                                    /*sense_format*/SSD_TYPE_NONE,
1767                                    /*current_error*/ 1,
1768                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1769                                    /*asc*/ 0x25,
1770                                    /*ascq*/ 0x00,
1771                                    SSD_ELEM_NONE);
1772
1773                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1774                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1775                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1776                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1777                 msg_info.hdr.serializing_sc = NULL;
1778                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1779                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1780                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1781                 }
1782                 return(1);
1783
1784         }
1785
1786         mtx_lock(&lun->lun_lock);
1787         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1788
1789         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1790                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1791                  ooa_links))) {
1792         case CTL_ACTION_BLOCK:
1793                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1794                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1795                                   blocked_links);
1796                 break;
1797         case CTL_ACTION_PASS:
1798         case CTL_ACTION_SKIP:
1799                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1800                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1801                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1802                 } else {
1803
1804                         /* send msg back to other side */
1805                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1806                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1807                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1808 #if 0
1809                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1810 #endif
1811                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1812                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1813                         }
1814                 }
1815                 break;
1816         case CTL_ACTION_OVERLAP:
1817                 /* OVERLAPPED COMMANDS ATTEMPTED */
1818                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1819                                    lun,
1820                                    /*sense_format*/SSD_TYPE_NONE,
1821                                    /*current_error*/ 1,
1822                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1823                                    /*asc*/ 0x4E,
1824                                    /*ascq*/ 0x00,
1825                                    SSD_ELEM_NONE);
1826
1827                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1828                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1829                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1830                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1831                 msg_info.hdr.serializing_sc = NULL;
1832                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1833 #if 0
1834                 printf("BAD JUJU:Major Bummer Overlap\n");
1835 #endif
1836                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1837                 retval = 1;
1838                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1839                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1840                 }
1841                 break;
1842         case CTL_ACTION_OVERLAP_TAG:
1843                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1844                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1845                                    lun,
1846                                    /*sense_format*/SSD_TYPE_NONE,
1847                                    /*current_error*/ 1,
1848                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1849                                    /*asc*/ 0x4D,
1850                                    /*ascq*/ ctsio->tag_num & 0xff,
1851                                    SSD_ELEM_NONE);
1852
1853                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1854                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1855                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1856                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1857                 msg_info.hdr.serializing_sc = NULL;
1858                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1859 #if 0
1860                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1861 #endif
1862                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1863                 retval = 1;
1864                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1865                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1866                 }
1867                 break;
1868         case CTL_ACTION_ERROR:
1869         default:
1870                 /* "Internal target failure" */
1871                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1872                                    lun,
1873                                    /*sense_format*/SSD_TYPE_NONE,
1874                                    /*current_error*/ 1,
1875                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1876                                    /*asc*/ 0x44,
1877                                    /*ascq*/ 0x00,
1878                                    SSD_ELEM_NONE);
1879
1880                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1881                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1882                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1883                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1884                 msg_info.hdr.serializing_sc = NULL;
1885                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1886 #if 0
1887                 printf("BAD JUJU:Major Bummer HW Error\n");
1888 #endif
1889                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1890                 retval = 1;
1891                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1892                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1893                 }
1894                 break;
1895         }
1896         mtx_unlock(&lun->lun_lock);
1897         return (retval);
1898 }
1899
1900 static int
1901 ctl_ioctl_submit_wait(union ctl_io *io)
1902 {
1903         struct ctl_fe_ioctl_params params;
1904         ctl_fe_ioctl_state last_state;
1905         int done, retval;
1906
1907         retval = 0;
1908
1909         bzero(&params, sizeof(params));
1910
1911         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1912         cv_init(&params.sem, "ctlioccv");
1913         params.state = CTL_IOCTL_INPROG;
1914         last_state = params.state;
1915
1916         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1917
1918         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1919
1920         /* This shouldn't happen */
1921         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1922                 return (retval);
1923
1924         done = 0;
1925
1926         do {
1927                 mtx_lock(&params.ioctl_mtx);
1928                 /*
1929                  * Check the state here, and don't sleep if the state has
1930                  * already changed (i.e. wakeup has already occured, but we
1931                  * weren't waiting yet).
1932                  */
1933                 if (params.state == last_state) {
1934                         /* XXX KDM cv_wait_sig instead? */
1935                         cv_wait(&params.sem, &params.ioctl_mtx);
1936                 }
1937                 last_state = params.state;
1938
1939                 switch (params.state) {
1940                 case CTL_IOCTL_INPROG:
1941                         /* Why did we wake up? */
1942                         /* XXX KDM error here? */
1943                         mtx_unlock(&params.ioctl_mtx);
1944                         break;
1945                 case CTL_IOCTL_DATAMOVE:
1946                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1947
1948                         /*
1949                          * change last_state back to INPROG to avoid
1950                          * deadlock on subsequent data moves.
1951                          */
1952                         params.state = last_state = CTL_IOCTL_INPROG;
1953
1954                         mtx_unlock(&params.ioctl_mtx);
1955                         ctl_ioctl_do_datamove(&io->scsiio);
1956                         /*
1957                          * Note that in some cases, most notably writes,
1958                          * this will queue the I/O and call us back later.
1959                          * In other cases, generally reads, this routine
1960                          * will immediately call back and wake us up,
1961                          * probably using our own context.
1962                          */
1963                         io->scsiio.be_move_done(io);
1964                         break;
1965                 case CTL_IOCTL_DONE:
1966                         mtx_unlock(&params.ioctl_mtx);
1967                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1968                         done = 1;
1969                         break;
1970                 default:
1971                         mtx_unlock(&params.ioctl_mtx);
1972                         /* XXX KDM error here? */
1973                         break;
1974                 }
1975         } while (done == 0);
1976
1977         mtx_destroy(&params.ioctl_mtx);
1978         cv_destroy(&params.sem);
1979
1980         return (CTL_RETVAL_COMPLETE);
1981 }
1982
1983 static void
1984 ctl_ioctl_datamove(union ctl_io *io)
1985 {
1986         struct ctl_fe_ioctl_params *params;
1987
1988         params = (struct ctl_fe_ioctl_params *)
1989                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1990
1991         mtx_lock(&params->ioctl_mtx);
1992         params->state = CTL_IOCTL_DATAMOVE;
1993         cv_broadcast(&params->sem);
1994         mtx_unlock(&params->ioctl_mtx);
1995 }
1996
1997 static void
1998 ctl_ioctl_done(union ctl_io *io)
1999 {
2000         struct ctl_fe_ioctl_params *params;
2001
2002         params = (struct ctl_fe_ioctl_params *)
2003                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2004
2005         mtx_lock(&params->ioctl_mtx);
2006         params->state = CTL_IOCTL_DONE;
2007         cv_broadcast(&params->sem);
2008         mtx_unlock(&params->ioctl_mtx);
2009 }
2010
2011 static void
2012 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2013 {
2014         struct ctl_fe_ioctl_startstop_info *sd_info;
2015
2016         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2017
2018         sd_info->hs_info.status = metatask->status;
2019         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2020         sd_info->hs_info.luns_complete =
2021                 metatask->taskinfo.startstop.luns_complete;
2022         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2023
2024         cv_broadcast(&sd_info->sem);
2025 }
2026
2027 static void
2028 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2029 {
2030         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2031
2032         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2033
2034         mtx_lock(fe_bbr_info->lock);
2035         fe_bbr_info->bbr_info->status = metatask->status;
2036         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2037         fe_bbr_info->wakeup_done = 1;
2038         mtx_unlock(fe_bbr_info->lock);
2039
2040         cv_broadcast(&fe_bbr_info->sem);
2041 }
2042
2043 /*
2044  * Returns 0 for success, errno for failure.
2045  */
2046 static int
2047 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2048                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2049 {
2050         union ctl_io *io;
2051         int retval;
2052
2053         retval = 0;
2054
2055         mtx_lock(&lun->lun_lock);
2056         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2057              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2058              ooa_links)) {
2059                 struct ctl_ooa_entry *entry;
2060
2061                 /*
2062                  * If we've got more than we can fit, just count the
2063                  * remaining entries.
2064                  */
2065                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2066                         continue;
2067
2068                 entry = &kern_entries[*cur_fill_num];
2069
2070                 entry->tag_num = io->scsiio.tag_num;
2071                 entry->lun_num = lun->lun;
2072 #ifdef CTL_TIME_IO
2073                 entry->start_bt = io->io_hdr.start_bt;
2074 #endif
2075                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2076                 entry->cdb_len = io->scsiio.cdb_len;
2077                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2078                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2079
2080                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2081                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2082
2083                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2084                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2085
2086                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2087                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2088
2089                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2090                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2091         }
2092         mtx_unlock(&lun->lun_lock);
2093
2094         return (retval);
2095 }
2096
2097 static void *
2098 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2099                  size_t error_str_len)
2100 {
2101         void *kptr;
2102
2103         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2104
2105         if (copyin(user_addr, kptr, len) != 0) {
2106                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2107                          "from user address %p to kernel address %p", len,
2108                          user_addr, kptr);
2109                 free(kptr, M_CTL);
2110                 return (NULL);
2111         }
2112
2113         return (kptr);
2114 }
2115
2116 static void
2117 ctl_free_args(int num_args, struct ctl_be_arg *args)
2118 {
2119         int i;
2120
2121         if (args == NULL)
2122                 return;
2123
2124         for (i = 0; i < num_args; i++) {
2125                 free(args[i].kname, M_CTL);
2126                 free(args[i].kvalue, M_CTL);
2127         }
2128
2129         free(args, M_CTL);
2130 }
2131
2132 static struct ctl_be_arg *
2133 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2134                 char *error_str, size_t error_str_len)
2135 {
2136         struct ctl_be_arg *args;
2137         int i;
2138
2139         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2140                                 error_str, error_str_len);
2141
2142         if (args == NULL)
2143                 goto bailout;
2144
2145         for (i = 0; i < num_args; i++) {
2146                 args[i].kname = NULL;
2147                 args[i].kvalue = NULL;
2148         }
2149
2150         for (i = 0; i < num_args; i++) {
2151                 uint8_t *tmpptr;
2152
2153                 args[i].kname = ctl_copyin_alloc(args[i].name,
2154                         args[i].namelen, error_str, error_str_len);
2155                 if (args[i].kname == NULL)
2156                         goto bailout;
2157
2158                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2159                         snprintf(error_str, error_str_len, "Argument %d "
2160                                  "name is not NUL-terminated", i);
2161                         goto bailout;
2162                 }
2163
2164                 if (args[i].flags & CTL_BEARG_RD) {
2165                         tmpptr = ctl_copyin_alloc(args[i].value,
2166                                 args[i].vallen, error_str, error_str_len);
2167                         if (tmpptr == NULL)
2168                                 goto bailout;
2169                         if ((args[i].flags & CTL_BEARG_ASCII)
2170                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2171                                 snprintf(error_str, error_str_len, "Argument "
2172                                     "%d value is not NUL-terminated", i);
2173                                 goto bailout;
2174                         }
2175                         args[i].kvalue = tmpptr;
2176                 } else {
2177                         args[i].kvalue = malloc(args[i].vallen,
2178                             M_CTL, M_WAITOK | M_ZERO);
2179                 }
2180         }
2181
2182         return (args);
2183 bailout:
2184
2185         ctl_free_args(num_args, args);
2186
2187         return (NULL);
2188 }
2189
2190 static void
2191 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2192 {
2193         int i;
2194
2195         for (i = 0; i < num_args; i++) {
2196                 if (args[i].flags & CTL_BEARG_WR)
2197                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2198         }
2199 }
2200
2201 /*
2202  * Escape characters that are illegal or not recommended in XML.
2203  */
2204 int
2205 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2206 {
2207         char *end = str + size;
2208         int retval;
2209
2210         retval = 0;
2211
2212         for (; *str && str < end; str++) {
2213                 switch (*str) {
2214                 case '&':
2215                         retval = sbuf_printf(sb, "&amp;");
2216                         break;
2217                 case '>':
2218                         retval = sbuf_printf(sb, "&gt;");
2219                         break;
2220                 case '<':
2221                         retval = sbuf_printf(sb, "&lt;");
2222                         break;
2223                 default:
2224                         retval = sbuf_putc(sb, *str);
2225                         break;
2226                 }
2227
2228                 if (retval != 0)
2229                         break;
2230
2231         }
2232
2233         return (retval);
2234 }
2235
2236 static void
2237 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2238 {
2239         struct scsi_vpd_id_descriptor *desc;
2240         int i;
2241
2242         if (id == NULL || id->len < 4)
2243                 return;
2244         desc = (struct scsi_vpd_id_descriptor *)id->data;
2245         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2246         case SVPD_ID_TYPE_T10:
2247                 sbuf_printf(sb, "t10.");
2248                 break;
2249         case SVPD_ID_TYPE_EUI64:
2250                 sbuf_printf(sb, "eui.");
2251                 break;
2252         case SVPD_ID_TYPE_NAA:
2253                 sbuf_printf(sb, "naa.");
2254                 break;
2255         case SVPD_ID_TYPE_SCSI_NAME:
2256                 break;
2257         }
2258         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2259         case SVPD_ID_CODESET_BINARY:
2260                 for (i = 0; i < desc->length; i++)
2261                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2262                 break;
2263         case SVPD_ID_CODESET_ASCII:
2264                 sbuf_printf(sb, "%.*s", (int)desc->length,
2265                     (char *)desc->identifier);
2266                 break;
2267         case SVPD_ID_CODESET_UTF8:
2268                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2269                 break;
2270         }
2271 }
2272
2273 static int
2274 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2275           struct thread *td)
2276 {
2277         struct ctl_softc *softc;
2278         int retval;
2279
2280         softc = control_softc;
2281
2282         retval = 0;
2283
2284         switch (cmd) {
2285         case CTL_IO: {
2286                 union ctl_io *io;
2287                 void *pool_tmp;
2288
2289                 /*
2290                  * If we haven't been "enabled", don't allow any SCSI I/O
2291                  * to this FETD.
2292                  */
2293                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2294                         retval = EPERM;
2295                         break;
2296                 }
2297
2298                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2299                 if (io == NULL) {
2300                         printf("ctl_ioctl: can't allocate ctl_io!\n");
2301                         retval = ENOSPC;
2302                         break;
2303                 }
2304
2305                 /*
2306                  * Need to save the pool reference so it doesn't get
2307                  * spammed by the user's ctl_io.
2308                  */
2309                 pool_tmp = io->io_hdr.pool;
2310
2311                 memcpy(io, (void *)addr, sizeof(*io));
2312
2313                 io->io_hdr.pool = pool_tmp;
2314                 /*
2315                  * No status yet, so make sure the status is set properly.
2316                  */
2317                 io->io_hdr.status = CTL_STATUS_NONE;
2318
2319                 /*
2320                  * The user sets the initiator ID, target and LUN IDs.
2321                  */
2322                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2323                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2324                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2325                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2326                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2327
2328                 retval = ctl_ioctl_submit_wait(io);
2329
2330                 if (retval != 0) {
2331                         ctl_free_io(io);
2332                         break;
2333                 }
2334
2335                 memcpy((void *)addr, io, sizeof(*io));
2336
2337                 /* return this to our pool */
2338                 ctl_free_io(io);
2339
2340                 break;
2341         }
2342         case CTL_ENABLE_PORT:
2343         case CTL_DISABLE_PORT:
2344         case CTL_SET_PORT_WWNS: {
2345                 struct ctl_port *port;
2346                 struct ctl_port_entry *entry;
2347
2348                 entry = (struct ctl_port_entry *)addr;
2349                 
2350                 mtx_lock(&softc->ctl_lock);
2351                 STAILQ_FOREACH(port, &softc->port_list, links) {
2352                         int action, done;
2353
2354                         action = 0;
2355                         done = 0;
2356
2357                         if ((entry->port_type == CTL_PORT_NONE)
2358                          && (entry->targ_port == port->targ_port)) {
2359                                 /*
2360                                  * If the user only wants to enable or
2361                                  * disable or set WWNs on a specific port,
2362                                  * do the operation and we're done.
2363                                  */
2364                                 action = 1;
2365                                 done = 1;
2366                         } else if (entry->port_type & port->port_type) {
2367                                 /*
2368                                  * Compare the user's type mask with the
2369                                  * particular frontend type to see if we
2370                                  * have a match.
2371                                  */
2372                                 action = 1;
2373                                 done = 0;
2374
2375                                 /*
2376                                  * Make sure the user isn't trying to set
2377                                  * WWNs on multiple ports at the same time.
2378                                  */
2379                                 if (cmd == CTL_SET_PORT_WWNS) {
2380                                         printf("%s: Can't set WWNs on "
2381                                                "multiple ports\n", __func__);
2382                                         retval = EINVAL;
2383                                         break;
2384                                 }
2385                         }
2386                         if (action != 0) {
2387                                 /*
2388                                  * XXX KDM we have to drop the lock here,
2389                                  * because the online/offline operations
2390                                  * can potentially block.  We need to
2391                                  * reference count the frontends so they
2392                                  * can't go away,
2393                                  */
2394                                 mtx_unlock(&softc->ctl_lock);
2395
2396                                 if (cmd == CTL_ENABLE_PORT) {
2397                                         struct ctl_lun *lun;
2398
2399                                         STAILQ_FOREACH(lun, &softc->lun_list,
2400                                                        links) {
2401                                                 port->lun_enable(port->targ_lun_arg,
2402                                                     lun->target,
2403                                                     lun->lun);
2404                                         }
2405
2406                                         ctl_port_online(port);
2407                                 } else if (cmd == CTL_DISABLE_PORT) {
2408                                         struct ctl_lun *lun;
2409
2410                                         ctl_port_offline(port);
2411
2412                                         STAILQ_FOREACH(lun, &softc->lun_list,
2413                                                        links) {
2414                                                 port->lun_disable(
2415                                                     port->targ_lun_arg,
2416                                                     lun->target,
2417                                                     lun->lun);
2418                                         }
2419                                 }
2420
2421                                 mtx_lock(&softc->ctl_lock);
2422
2423                                 if (cmd == CTL_SET_PORT_WWNS)
2424                                         ctl_port_set_wwns(port,
2425                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2426                                             1 : 0, entry->wwnn,
2427                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2428                                             1 : 0, entry->wwpn);
2429                         }
2430                         if (done != 0)
2431                                 break;
2432                 }
2433                 mtx_unlock(&softc->ctl_lock);
2434                 break;
2435         }
2436         case CTL_GET_PORT_LIST: {
2437                 struct ctl_port *port;
2438                 struct ctl_port_list *list;
2439                 int i;
2440
2441                 list = (struct ctl_port_list *)addr;
2442
2443                 if (list->alloc_len != (list->alloc_num *
2444                     sizeof(struct ctl_port_entry))) {
2445                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2446                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2447                                "%zu\n", __func__, list->alloc_len,
2448                                list->alloc_num, sizeof(struct ctl_port_entry));
2449                         retval = EINVAL;
2450                         break;
2451                 }
2452                 list->fill_len = 0;
2453                 list->fill_num = 0;
2454                 list->dropped_num = 0;
2455                 i = 0;
2456                 mtx_lock(&softc->ctl_lock);
2457                 STAILQ_FOREACH(port, &softc->port_list, links) {
2458                         struct ctl_port_entry entry, *list_entry;
2459
2460                         if (list->fill_num >= list->alloc_num) {
2461                                 list->dropped_num++;
2462                                 continue;
2463                         }
2464
2465                         entry.port_type = port->port_type;
2466                         strlcpy(entry.port_name, port->port_name,
2467                                 sizeof(entry.port_name));
2468                         entry.targ_port = port->targ_port;
2469                         entry.physical_port = port->physical_port;
2470                         entry.virtual_port = port->virtual_port;
2471                         entry.wwnn = port->wwnn;
2472                         entry.wwpn = port->wwpn;
2473                         if (port->status & CTL_PORT_STATUS_ONLINE)
2474                                 entry.online = 1;
2475                         else
2476                                 entry.online = 0;
2477
2478                         list_entry = &list->entries[i];
2479
2480                         retval = copyout(&entry, list_entry, sizeof(entry));
2481                         if (retval != 0) {
2482                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2483                                        "returned %d\n", __func__, retval);
2484                                 break;
2485                         }
2486                         i++;
2487                         list->fill_num++;
2488                         list->fill_len += sizeof(entry);
2489                 }
2490                 mtx_unlock(&softc->ctl_lock);
2491
2492                 /*
2493                  * If this is non-zero, we had a copyout fault, so there's
2494                  * probably no point in attempting to set the status inside
2495                  * the structure.
2496                  */
2497                 if (retval != 0)
2498                         break;
2499
2500                 if (list->dropped_num > 0)
2501                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2502                 else
2503                         list->status = CTL_PORT_LIST_OK;
2504                 break;
2505         }
2506         case CTL_DUMP_OOA: {
2507                 struct ctl_lun *lun;
2508                 union ctl_io *io;
2509                 char printbuf[128];
2510                 struct sbuf sb;
2511
2512                 mtx_lock(&softc->ctl_lock);
2513                 printf("Dumping OOA queues:\n");
2514                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2515                         mtx_lock(&lun->lun_lock);
2516                         for (io = (union ctl_io *)TAILQ_FIRST(
2517                              &lun->ooa_queue); io != NULL;
2518                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2519                              ooa_links)) {
2520                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2521                                          SBUF_FIXEDLEN);
2522                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2523                                             (intmax_t)lun->lun,
2524                                             io->scsiio.tag_num,
2525                                             (io->io_hdr.flags &
2526                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2527                                             (io->io_hdr.flags &
2528                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2529                                             (io->io_hdr.flags &
2530                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2531                                             (io->io_hdr.flags &
2532                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2533                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2534                                 sbuf_finish(&sb);
2535                                 printf("%s\n", sbuf_data(&sb));
2536                         }
2537                         mtx_unlock(&lun->lun_lock);
2538                 }
2539                 printf("OOA queues dump done\n");
2540                 mtx_unlock(&softc->ctl_lock);
2541                 break;
2542         }
2543         case CTL_GET_OOA: {
2544                 struct ctl_lun *lun;
2545                 struct ctl_ooa *ooa_hdr;
2546                 struct ctl_ooa_entry *entries;
2547                 uint32_t cur_fill_num;
2548
2549                 ooa_hdr = (struct ctl_ooa *)addr;
2550
2551                 if ((ooa_hdr->alloc_len == 0)
2552                  || (ooa_hdr->alloc_num == 0)) {
2553                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2554                                "must be non-zero\n", __func__,
2555                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2556                         retval = EINVAL;
2557                         break;
2558                 }
2559
2560                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2561                     sizeof(struct ctl_ooa_entry))) {
2562                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2563                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2564                                __func__, ooa_hdr->alloc_len,
2565                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2566                         retval = EINVAL;
2567                         break;
2568                 }
2569
2570                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2571                 if (entries == NULL) {
2572                         printf("%s: could not allocate %d bytes for OOA "
2573                                "dump\n", __func__, ooa_hdr->alloc_len);
2574                         retval = ENOMEM;
2575                         break;
2576                 }
2577
2578                 mtx_lock(&softc->ctl_lock);
2579                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2580                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2581                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2582                         mtx_unlock(&softc->ctl_lock);
2583                         free(entries, M_CTL);
2584                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2585                                __func__, (uintmax_t)ooa_hdr->lun_num);
2586                         retval = EINVAL;
2587                         break;
2588                 }
2589
2590                 cur_fill_num = 0;
2591
2592                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2593                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2594                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2595                                         ooa_hdr, entries);
2596                                 if (retval != 0)
2597                                         break;
2598                         }
2599                         if (retval != 0) {
2600                                 mtx_unlock(&softc->ctl_lock);
2601                                 free(entries, M_CTL);
2602                                 break;
2603                         }
2604                 } else {
2605                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2606
2607                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2608                                                     entries);
2609                 }
2610                 mtx_unlock(&softc->ctl_lock);
2611
2612                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2613                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2614                         sizeof(struct ctl_ooa_entry);
2615                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2616                 if (retval != 0) {
2617                         printf("%s: error copying out %d bytes for OOA dump\n", 
2618                                __func__, ooa_hdr->fill_len);
2619                 }
2620
2621                 getbintime(&ooa_hdr->cur_bt);
2622
2623                 if (cur_fill_num > ooa_hdr->alloc_num) {
2624                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2625                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2626                 } else {
2627                         ooa_hdr->dropped_num = 0;
2628                         ooa_hdr->status = CTL_OOA_OK;
2629                 }
2630
2631                 free(entries, M_CTL);
2632                 break;
2633         }
2634         case CTL_CHECK_OOA: {
2635                 union ctl_io *io;
2636                 struct ctl_lun *lun;
2637                 struct ctl_ooa_info *ooa_info;
2638
2639
2640                 ooa_info = (struct ctl_ooa_info *)addr;
2641
2642                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2643                         ooa_info->status = CTL_OOA_INVALID_LUN;
2644                         break;
2645                 }
2646                 mtx_lock(&softc->ctl_lock);
2647                 lun = softc->ctl_luns[ooa_info->lun_id];
2648                 if (lun == NULL) {
2649                         mtx_unlock(&softc->ctl_lock);
2650                         ooa_info->status = CTL_OOA_INVALID_LUN;
2651                         break;
2652                 }
2653                 mtx_lock(&lun->lun_lock);
2654                 mtx_unlock(&softc->ctl_lock);
2655                 ooa_info->num_entries = 0;
2656                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2657                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2658                      &io->io_hdr, ooa_links)) {
2659                         ooa_info->num_entries++;
2660                 }
2661                 mtx_unlock(&lun->lun_lock);
2662
2663                 ooa_info->status = CTL_OOA_SUCCESS;
2664
2665                 break;
2666         }
2667         case CTL_HARD_START:
2668         case CTL_HARD_STOP: {
2669                 struct ctl_fe_ioctl_startstop_info ss_info;
2670                 struct cfi_metatask *metatask;
2671                 struct mtx hs_mtx;
2672
2673                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2674
2675                 cv_init(&ss_info.sem, "hard start/stop cv" );
2676
2677                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2678                 if (metatask == NULL) {
2679                         retval = ENOMEM;
2680                         mtx_destroy(&hs_mtx);
2681                         break;
2682                 }
2683
2684                 if (cmd == CTL_HARD_START)
2685                         metatask->tasktype = CFI_TASK_STARTUP;
2686                 else
2687                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2688
2689                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2690                 metatask->callback_arg = &ss_info;
2691
2692                 cfi_action(metatask);
2693
2694                 /* Wait for the callback */
2695                 mtx_lock(&hs_mtx);
2696                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2697                 mtx_unlock(&hs_mtx);
2698
2699                 /*
2700                  * All information has been copied from the metatask by the
2701                  * time cv_broadcast() is called, so we free the metatask here.
2702                  */
2703                 cfi_free_metatask(metatask);
2704
2705                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2706
2707                 mtx_destroy(&hs_mtx);
2708                 break;
2709         }
2710         case CTL_BBRREAD: {
2711                 struct ctl_bbrread_info *bbr_info;
2712                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2713                 struct mtx bbr_mtx;
2714                 struct cfi_metatask *metatask;
2715
2716                 bbr_info = (struct ctl_bbrread_info *)addr;
2717
2718                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2719
2720                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2721                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2722
2723                 fe_bbr_info.bbr_info = bbr_info;
2724                 fe_bbr_info.lock = &bbr_mtx;
2725
2726                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2727                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2728
2729                 if (metatask == NULL) {
2730                         mtx_destroy(&bbr_mtx);
2731                         cv_destroy(&fe_bbr_info.sem);
2732                         retval = ENOMEM;
2733                         break;
2734                 }
2735                 metatask->tasktype = CFI_TASK_BBRREAD;
2736                 metatask->callback = ctl_ioctl_bbrread_callback;
2737                 metatask->callback_arg = &fe_bbr_info;
2738                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2739                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2740                 metatask->taskinfo.bbrread.len = bbr_info->len;
2741
2742                 cfi_action(metatask);
2743
2744                 mtx_lock(&bbr_mtx);
2745                 while (fe_bbr_info.wakeup_done == 0)
2746                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2747                 mtx_unlock(&bbr_mtx);
2748
2749                 bbr_info->status = metatask->status;
2750                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2751                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2752                 memcpy(&bbr_info->sense_data,
2753                        &metatask->taskinfo.bbrread.sense_data,
2754                        ctl_min(sizeof(bbr_info->sense_data),
2755                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2756
2757                 cfi_free_metatask(metatask);
2758
2759                 mtx_destroy(&bbr_mtx);
2760                 cv_destroy(&fe_bbr_info.sem);
2761
2762                 break;
2763         }
2764         case CTL_DELAY_IO: {
2765                 struct ctl_io_delay_info *delay_info;
2766 #ifdef CTL_IO_DELAY
2767                 struct ctl_lun *lun;
2768 #endif /* CTL_IO_DELAY */
2769
2770                 delay_info = (struct ctl_io_delay_info *)addr;
2771
2772 #ifdef CTL_IO_DELAY
2773                 mtx_lock(&softc->ctl_lock);
2774
2775                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2776                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2777                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2778                 } else {
2779                         lun = softc->ctl_luns[delay_info->lun_id];
2780                         mtx_lock(&lun->lun_lock);
2781
2782                         delay_info->status = CTL_DELAY_STATUS_OK;
2783
2784                         switch (delay_info->delay_type) {
2785                         case CTL_DELAY_TYPE_CONT:
2786                                 break;
2787                         case CTL_DELAY_TYPE_ONESHOT:
2788                                 break;
2789                         default:
2790                                 delay_info->status =
2791                                         CTL_DELAY_STATUS_INVALID_TYPE;
2792                                 break;
2793                         }
2794
2795                         switch (delay_info->delay_loc) {
2796                         case CTL_DELAY_LOC_DATAMOVE:
2797                                 lun->delay_info.datamove_type =
2798                                         delay_info->delay_type;
2799                                 lun->delay_info.datamove_delay =
2800                                         delay_info->delay_secs;
2801                                 break;
2802                         case CTL_DELAY_LOC_DONE:
2803                                 lun->delay_info.done_type =
2804                                         delay_info->delay_type;
2805                                 lun->delay_info.done_delay =
2806                                         delay_info->delay_secs;
2807                                 break;
2808                         default:
2809                                 delay_info->status =
2810                                         CTL_DELAY_STATUS_INVALID_LOC;
2811                                 break;
2812                         }
2813                         mtx_unlock(&lun->lun_lock);
2814                 }
2815
2816                 mtx_unlock(&softc->ctl_lock);
2817 #else
2818                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2819 #endif /* CTL_IO_DELAY */
2820                 break;
2821         }
2822         case CTL_REALSYNC_SET: {
2823                 int *syncstate;
2824
2825                 syncstate = (int *)addr;
2826
2827                 mtx_lock(&softc->ctl_lock);
2828                 switch (*syncstate) {
2829                 case 0:
2830                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2831                         break;
2832                 case 1:
2833                         softc->flags |= CTL_FLAG_REAL_SYNC;
2834                         break;
2835                 default:
2836                         retval = EINVAL;
2837                         break;
2838                 }
2839                 mtx_unlock(&softc->ctl_lock);
2840                 break;
2841         }
2842         case CTL_REALSYNC_GET: {
2843                 int *syncstate;
2844
2845                 syncstate = (int*)addr;
2846
2847                 mtx_lock(&softc->ctl_lock);
2848                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2849                         *syncstate = 1;
2850                 else
2851                         *syncstate = 0;
2852                 mtx_unlock(&softc->ctl_lock);
2853
2854                 break;
2855         }
2856         case CTL_SETSYNC:
2857         case CTL_GETSYNC: {
2858                 struct ctl_sync_info *sync_info;
2859                 struct ctl_lun *lun;
2860
2861                 sync_info = (struct ctl_sync_info *)addr;
2862
2863                 mtx_lock(&softc->ctl_lock);
2864                 lun = softc->ctl_luns[sync_info->lun_id];
2865                 if (lun == NULL) {
2866                         mtx_unlock(&softc->ctl_lock);
2867                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2868                 }
2869                 /*
2870                  * Get or set the sync interval.  We're not bounds checking
2871                  * in the set case, hopefully the user won't do something
2872                  * silly.
2873                  */
2874                 mtx_lock(&lun->lun_lock);
2875                 mtx_unlock(&softc->ctl_lock);
2876                 if (cmd == CTL_GETSYNC)
2877                         sync_info->sync_interval = lun->sync_interval;
2878                 else
2879                         lun->sync_interval = sync_info->sync_interval;
2880                 mtx_unlock(&lun->lun_lock);
2881
2882                 sync_info->status = CTL_GS_SYNC_OK;
2883
2884                 break;
2885         }
2886         case CTL_GETSTATS: {
2887                 struct ctl_stats *stats;
2888                 struct ctl_lun *lun;
2889                 int i;
2890
2891                 stats = (struct ctl_stats *)addr;
2892
2893                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2894                      stats->alloc_len) {
2895                         stats->status = CTL_SS_NEED_MORE_SPACE;
2896                         stats->num_luns = softc->num_luns;
2897                         break;
2898                 }
2899                 /*
2900                  * XXX KDM no locking here.  If the LUN list changes,
2901                  * things can blow up.
2902                  */
2903                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2904                      i++, lun = STAILQ_NEXT(lun, links)) {
2905                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2906                                          sizeof(lun->stats));
2907                         if (retval != 0)
2908                                 break;
2909                 }
2910                 stats->num_luns = softc->num_luns;
2911                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2912                                  softc->num_luns;
2913                 stats->status = CTL_SS_OK;
2914 #ifdef CTL_TIME_IO
2915                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2916 #else
2917                 stats->flags = CTL_STATS_FLAG_NONE;
2918 #endif
2919                 getnanouptime(&stats->timestamp);
2920                 break;
2921         }
2922         case CTL_ERROR_INJECT: {
2923                 struct ctl_error_desc *err_desc, *new_err_desc;
2924                 struct ctl_lun *lun;
2925
2926                 err_desc = (struct ctl_error_desc *)addr;
2927
2928                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2929                                       M_WAITOK | M_ZERO);
2930                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2931
2932                 mtx_lock(&softc->ctl_lock);
2933                 lun = softc->ctl_luns[err_desc->lun_id];
2934                 if (lun == NULL) {
2935                         mtx_unlock(&softc->ctl_lock);
2936                         free(new_err_desc, M_CTL);
2937                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2938                                __func__, (uintmax_t)err_desc->lun_id);
2939                         retval = EINVAL;
2940                         break;
2941                 }
2942                 mtx_lock(&lun->lun_lock);
2943                 mtx_unlock(&softc->ctl_lock);
2944
2945                 /*
2946                  * We could do some checking here to verify the validity
2947                  * of the request, but given the complexity of error
2948                  * injection requests, the checking logic would be fairly
2949                  * complex.
2950                  *
2951                  * For now, if the request is invalid, it just won't get
2952                  * executed and might get deleted.
2953                  */
2954                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2955
2956                 /*
2957                  * XXX KDM check to make sure the serial number is unique,
2958                  * in case we somehow manage to wrap.  That shouldn't
2959                  * happen for a very long time, but it's the right thing to
2960                  * do.
2961                  */
2962                 new_err_desc->serial = lun->error_serial;
2963                 err_desc->serial = lun->error_serial;
2964                 lun->error_serial++;
2965
2966                 mtx_unlock(&lun->lun_lock);
2967                 break;
2968         }
2969         case CTL_ERROR_INJECT_DELETE: {
2970                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2971                 struct ctl_lun *lun;
2972                 int delete_done;
2973
2974                 delete_desc = (struct ctl_error_desc *)addr;
2975                 delete_done = 0;
2976
2977                 mtx_lock(&softc->ctl_lock);
2978                 lun = softc->ctl_luns[delete_desc->lun_id];
2979                 if (lun == NULL) {
2980                         mtx_unlock(&softc->ctl_lock);
2981                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2982                                __func__, (uintmax_t)delete_desc->lun_id);
2983                         retval = EINVAL;
2984                         break;
2985                 }
2986                 mtx_lock(&lun->lun_lock);
2987                 mtx_unlock(&softc->ctl_lock);
2988                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2989                         if (desc->serial != delete_desc->serial)
2990                                 continue;
2991
2992                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2993                                       links);
2994                         free(desc, M_CTL);
2995                         delete_done = 1;
2996                 }
2997                 mtx_unlock(&lun->lun_lock);
2998                 if (delete_done == 0) {
2999                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3000                                "error serial %ju on LUN %u\n", __func__, 
3001                                delete_desc->serial, delete_desc->lun_id);
3002                         retval = EINVAL;
3003                         break;
3004                 }
3005                 break;
3006         }
3007         case CTL_DUMP_STRUCTS: {
3008                 int i, j, k, idx;
3009                 struct ctl_port *port;
3010                 struct ctl_frontend *fe;
3011
3012                 mtx_lock(&softc->ctl_lock);
3013                 printf("CTL Persistent Reservation information start:\n");
3014                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3015                         struct ctl_lun *lun;
3016
3017                         lun = softc->ctl_luns[i];
3018
3019                         if ((lun == NULL)
3020                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3021                                 continue;
3022
3023                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3024                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3025                                         idx = j * CTL_MAX_INIT_PER_PORT + k;
3026                                         if (lun->pr_keys[idx] == 0)
3027                                                 continue;
3028                                         printf("  LUN %d port %d iid %d key "
3029                                                "%#jx\n", i, j, k,
3030                                                (uintmax_t)lun->pr_keys[idx]);
3031                                 }
3032                         }
3033                 }
3034                 printf("CTL Persistent Reservation information end\n");
3035                 printf("CTL Ports:\n");
3036                 STAILQ_FOREACH(port, &softc->port_list, links) {
3037                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3038                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3039                                port->frontend->name, port->port_type,
3040                                port->physical_port, port->virtual_port,
3041                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3042                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3043                                 if (port->wwpn_iid[j].in_use == 0 &&
3044                                     port->wwpn_iid[j].wwpn == 0 &&
3045                                     port->wwpn_iid[j].name == NULL)
3046                                         continue;
3047
3048                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3049                                     j, port->wwpn_iid[j].in_use,
3050                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3051                                     port->wwpn_iid[j].name);
3052                         }
3053                 }
3054                 printf("CTL Port information end\n");
3055                 mtx_unlock(&softc->ctl_lock);
3056                 /*
3057                  * XXX KDM calling this without a lock.  We'd likely want
3058                  * to drop the lock before calling the frontend's dump
3059                  * routine anyway.
3060                  */
3061                 printf("CTL Frontends:\n");
3062                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3063                         printf("  Frontend '%s'\n", fe->name);
3064                         if (fe->fe_dump != NULL)
3065                                 fe->fe_dump();
3066                 }
3067                 printf("CTL Frontend information end\n");
3068                 break;
3069         }
3070         case CTL_LUN_REQ: {
3071                 struct ctl_lun_req *lun_req;
3072                 struct ctl_backend_driver *backend;
3073
3074                 lun_req = (struct ctl_lun_req *)addr;
3075
3076                 backend = ctl_backend_find(lun_req->backend);
3077                 if (backend == NULL) {
3078                         lun_req->status = CTL_LUN_ERROR;
3079                         snprintf(lun_req->error_str,
3080                                  sizeof(lun_req->error_str),
3081                                  "Backend \"%s\" not found.",
3082                                  lun_req->backend);
3083                         break;
3084                 }
3085                 if (lun_req->num_be_args > 0) {
3086                         lun_req->kern_be_args = ctl_copyin_args(
3087                                 lun_req->num_be_args,
3088                                 lun_req->be_args,
3089                                 lun_req->error_str,
3090                                 sizeof(lun_req->error_str));
3091                         if (lun_req->kern_be_args == NULL) {
3092                                 lun_req->status = CTL_LUN_ERROR;
3093                                 break;
3094                         }
3095                 }
3096
3097                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3098
3099                 if (lun_req->num_be_args > 0) {
3100                         ctl_copyout_args(lun_req->num_be_args,
3101                                       lun_req->kern_be_args);
3102                         ctl_free_args(lun_req->num_be_args,
3103                                       lun_req->kern_be_args);
3104                 }
3105                 break;
3106         }
3107         case CTL_LUN_LIST: {
3108                 struct sbuf *sb;
3109                 struct ctl_lun *lun;
3110                 struct ctl_lun_list *list;
3111                 struct ctl_option *opt;
3112
3113                 list = (struct ctl_lun_list *)addr;
3114
3115                 /*
3116                  * Allocate a fixed length sbuf here, based on the length
3117                  * of the user's buffer.  We could allocate an auto-extending
3118                  * buffer, and then tell the user how much larger our
3119                  * amount of data is than his buffer, but that presents
3120                  * some problems:
3121                  *
3122                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3123                  *     we can't hold a lock while calling them with an
3124                  *     auto-extending buffer.
3125                  *
3126                  * 2.  There is not currently a LUN reference counting
3127                  *     mechanism, outside of outstanding transactions on
3128                  *     the LUN's OOA queue.  So a LUN could go away on us
3129                  *     while we're getting the LUN number, backend-specific
3130                  *     information, etc.  Thus, given the way things
3131                  *     currently work, we need to hold the CTL lock while
3132                  *     grabbing LUN information.
3133                  *
3134                  * So, from the user's standpoint, the best thing to do is
3135                  * allocate what he thinks is a reasonable buffer length,
3136                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3137                  * double the buffer length and try again.  (And repeat
3138                  * that until he succeeds.)
3139                  */
3140                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3141                 if (sb == NULL) {
3142                         list->status = CTL_LUN_LIST_ERROR;
3143                         snprintf(list->error_str, sizeof(list->error_str),
3144                                  "Unable to allocate %d bytes for LUN list",
3145                                  list->alloc_len);
3146                         break;
3147                 }
3148
3149                 sbuf_printf(sb, "<ctllunlist>\n");
3150
3151                 mtx_lock(&softc->ctl_lock);
3152                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3153                         mtx_lock(&lun->lun_lock);
3154                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3155                                              (uintmax_t)lun->lun);
3156
3157                         /*
3158                          * Bail out as soon as we see that we've overfilled
3159                          * the buffer.
3160                          */
3161                         if (retval != 0)
3162                                 break;
3163
3164                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3165                                              "</backend_type>\n",
3166                                              (lun->backend == NULL) ?  "none" :
3167                                              lun->backend->name);
3168
3169                         if (retval != 0)
3170                                 break;
3171
3172                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3173                                              lun->be_lun->lun_type);
3174
3175                         if (retval != 0)
3176                                 break;
3177
3178                         if (lun->backend == NULL) {
3179                                 retval = sbuf_printf(sb, "</lun>\n");
3180                                 if (retval != 0)
3181                                         break;
3182                                 continue;
3183                         }
3184
3185                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3186                                              (lun->be_lun->maxlba > 0) ?
3187                                              lun->be_lun->maxlba + 1 : 0);
3188
3189                         if (retval != 0)
3190                                 break;
3191
3192                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3193                                              lun->be_lun->blocksize);
3194
3195                         if (retval != 0)
3196                                 break;
3197
3198                         retval = sbuf_printf(sb, "\t<serial_number>");
3199
3200                         if (retval != 0)
3201                                 break;
3202
3203                         retval = ctl_sbuf_printf_esc(sb,
3204                             lun->be_lun->serial_num,
3205                             sizeof(lun->be_lun->serial_num));
3206
3207                         if (retval != 0)
3208                                 break;
3209
3210                         retval = sbuf_printf(sb, "</serial_number>\n");
3211                 
3212                         if (retval != 0)
3213                                 break;
3214
3215                         retval = sbuf_printf(sb, "\t<device_id>");
3216
3217                         if (retval != 0)
3218                                 break;
3219
3220                         retval = ctl_sbuf_printf_esc(sb,
3221                             lun->be_lun->device_id,
3222                             sizeof(lun->be_lun->device_id));
3223
3224                         if (retval != 0)
3225                                 break;
3226
3227                         retval = sbuf_printf(sb, "</device_id>\n");
3228
3229                         if (retval != 0)
3230                                 break;
3231
3232                         if (lun->backend->lun_info != NULL) {
3233                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3234                                 if (retval != 0)
3235                                         break;
3236                         }
3237                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3238                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3239                                     opt->name, opt->value, opt->name);
3240                                 if (retval != 0)
3241                                         break;
3242                         }
3243
3244                         retval = sbuf_printf(sb, "</lun>\n");
3245
3246                         if (retval != 0)
3247                                 break;
3248                         mtx_unlock(&lun->lun_lock);
3249                 }
3250                 if (lun != NULL)
3251                         mtx_unlock(&lun->lun_lock);
3252                 mtx_unlock(&softc->ctl_lock);
3253
3254                 if ((retval != 0)
3255                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3256                         retval = 0;
3257                         sbuf_delete(sb);
3258                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3259                         snprintf(list->error_str, sizeof(list->error_str),
3260                                  "Out of space, %d bytes is too small",
3261                                  list->alloc_len);
3262                         break;
3263                 }
3264
3265                 sbuf_finish(sb);
3266
3267                 retval = copyout(sbuf_data(sb), list->lun_xml,
3268                                  sbuf_len(sb) + 1);
3269
3270                 list->fill_len = sbuf_len(sb) + 1;
3271                 list->status = CTL_LUN_LIST_OK;
3272                 sbuf_delete(sb);
3273                 break;
3274         }
3275         case CTL_ISCSI: {
3276                 struct ctl_iscsi *ci;
3277                 struct ctl_frontend *fe;
3278
3279                 ci = (struct ctl_iscsi *)addr;
3280
3281                 fe = ctl_frontend_find("iscsi");
3282                 if (fe == NULL) {
3283                         ci->status = CTL_ISCSI_ERROR;
3284                         snprintf(ci->error_str, sizeof(ci->error_str),
3285                             "Frontend \"iscsi\" not found.");
3286                         break;
3287                 }
3288
3289                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3290                 break;
3291         }
3292         case CTL_PORT_REQ: {
3293                 struct ctl_req *req;
3294                 struct ctl_frontend *fe;
3295
3296                 req = (struct ctl_req *)addr;
3297
3298                 fe = ctl_frontend_find(req->driver);
3299                 if (fe == NULL) {
3300                         req->status = CTL_LUN_ERROR;
3301                         snprintf(req->error_str, sizeof(req->error_str),
3302                             "Frontend \"%s\" not found.", req->driver);
3303                         break;
3304                 }
3305                 if (req->num_args > 0) {
3306                         req->kern_args = ctl_copyin_args(req->num_args,
3307                             req->args, req->error_str, sizeof(req->error_str));
3308                         if (req->kern_args == NULL) {
3309                                 req->status = CTL_LUN_ERROR;
3310                                 break;
3311                         }
3312                 }
3313
3314                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3315
3316                 if (req->num_args > 0) {
3317                         ctl_copyout_args(req->num_args, req->kern_args);
3318                         ctl_free_args(req->num_args, req->kern_args);
3319                 }
3320                 break;
3321         }
3322         case CTL_PORT_LIST: {
3323                 struct sbuf *sb;
3324                 struct ctl_port *port;
3325                 struct ctl_lun_list *list;
3326                 struct ctl_option *opt;
3327                 int j;
3328
3329                 list = (struct ctl_lun_list *)addr;
3330
3331                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3332                 if (sb == NULL) {
3333                         list->status = CTL_LUN_LIST_ERROR;
3334                         snprintf(list->error_str, sizeof(list->error_str),
3335                                  "Unable to allocate %d bytes for LUN list",
3336                                  list->alloc_len);
3337                         break;
3338                 }
3339
3340                 sbuf_printf(sb, "<ctlportlist>\n");
3341
3342                 mtx_lock(&softc->ctl_lock);
3343                 STAILQ_FOREACH(port, &softc->port_list, links) {
3344                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3345                                              (uintmax_t)port->targ_port);
3346
3347                         /*
3348                          * Bail out as soon as we see that we've overfilled
3349                          * the buffer.
3350                          */
3351                         if (retval != 0)
3352                                 break;
3353
3354                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3355                             "</frontend_type>\n", port->frontend->name);
3356                         if (retval != 0)
3357                                 break;
3358
3359                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3360                                              port->port_type);
3361                         if (retval != 0)
3362                                 break;
3363
3364                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3365                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3366                         if (retval != 0)
3367                                 break;
3368
3369                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3370                             port->port_name);
3371                         if (retval != 0)
3372                                 break;
3373
3374                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3375                             port->physical_port);
3376                         if (retval != 0)
3377                                 break;
3378
3379                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3380                             port->virtual_port);
3381                         if (retval != 0)
3382                                 break;
3383
3384                         if (port->target_devid != NULL) {
3385                                 sbuf_printf(sb, "\t<target>");
3386                                 ctl_id_sbuf(port->target_devid, sb);
3387                                 sbuf_printf(sb, "</target>\n");
3388                         }
3389
3390                         if (port->port_devid != NULL) {
3391                                 sbuf_printf(sb, "\t<port>");
3392                                 ctl_id_sbuf(port->port_devid, sb);
3393                                 sbuf_printf(sb, "</port>\n");
3394                         }
3395
3396                         if (port->port_info != NULL) {
3397                                 retval = port->port_info(port->onoff_arg, sb);
3398                                 if (retval != 0)
3399                                         break;
3400                         }
3401                         STAILQ_FOREACH(opt, &port->options, links) {
3402                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3403                                     opt->name, opt->value, opt->name);
3404                                 if (retval != 0)
3405                                         break;
3406                         }
3407
3408                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3409                                 if (port->wwpn_iid[j].in_use == 0 ||
3410                                     (port->wwpn_iid[j].wwpn == 0 &&
3411                                      port->wwpn_iid[j].name == NULL))
3412                                         continue;
3413
3414                                 if (port->wwpn_iid[j].name != NULL)
3415                                         retval = sbuf_printf(sb,
3416                                             "\t<initiator>%u %s</initiator>\n",
3417                                             j, port->wwpn_iid[j].name);
3418                                 else
3419                                         retval = sbuf_printf(sb,
3420                                             "\t<initiator>%u naa.%08jx</initiator>\n",
3421                                             j, port->wwpn_iid[j].wwpn);
3422                                 if (retval != 0)
3423                                         break;
3424                         }
3425                         if (retval != 0)
3426                                 break;
3427
3428                         retval = sbuf_printf(sb, "</targ_port>\n");
3429                         if (retval != 0)
3430                                 break;
3431                 }
3432                 mtx_unlock(&softc->ctl_lock);
3433
3434                 if ((retval != 0)
3435                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3436                         retval = 0;
3437                         sbuf_delete(sb);
3438                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3439                         snprintf(list->error_str, sizeof(list->error_str),
3440                                  "Out of space, %d bytes is too small",
3441                                  list->alloc_len);
3442                         break;
3443                 }
3444
3445                 sbuf_finish(sb);
3446
3447                 retval = copyout(sbuf_data(sb), list->lun_xml,
3448                                  sbuf_len(sb) + 1);
3449
3450                 list->fill_len = sbuf_len(sb) + 1;
3451                 list->status = CTL_LUN_LIST_OK;
3452                 sbuf_delete(sb);
3453                 break;
3454         }
3455         default: {
3456                 /* XXX KDM should we fix this? */
3457 #if 0
3458                 struct ctl_backend_driver *backend;
3459                 unsigned int type;
3460                 int found;
3461
3462                 found = 0;
3463
3464                 /*
3465                  * We encode the backend type as the ioctl type for backend
3466                  * ioctls.  So parse it out here, and then search for a
3467                  * backend of this type.
3468                  */
3469                 type = _IOC_TYPE(cmd);
3470
3471                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3472                         if (backend->type == type) {
3473                                 found = 1;
3474                                 break;
3475                         }
3476                 }
3477                 if (found == 0) {
3478                         printf("ctl: unknown ioctl command %#lx or backend "
3479                                "%d\n", cmd, type);
3480                         retval = EINVAL;
3481                         break;
3482                 }
3483                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3484 #endif
3485                 retval = ENOTTY;
3486                 break;
3487         }
3488         }
3489         return (retval);
3490 }
3491
3492 uint32_t
3493 ctl_get_initindex(struct ctl_nexus *nexus)
3494 {
3495         if (nexus->targ_port < CTL_MAX_PORTS)
3496                 return (nexus->initid.id +
3497                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3498         else
3499                 return (nexus->initid.id +
3500                        ((nexus->targ_port - CTL_MAX_PORTS) *
3501                         CTL_MAX_INIT_PER_PORT));
3502 }
3503
3504 uint32_t
3505 ctl_get_resindex(struct ctl_nexus *nexus)
3506 {
3507         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3508 }
3509
3510 uint32_t
3511 ctl_port_idx(int port_num)
3512 {
3513         if (port_num < CTL_MAX_PORTS)
3514                 return(port_num);
3515         else
3516                 return(port_num - CTL_MAX_PORTS);
3517 }
3518
3519 static uint32_t
3520 ctl_map_lun(int port_num, uint32_t lun_id)
3521 {
3522         struct ctl_port *port;
3523
3524         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3525         if (port == NULL)
3526                 return (UINT32_MAX);
3527         if (port->lun_map == NULL)
3528                 return (lun_id);
3529         return (port->lun_map(port->targ_lun_arg, lun_id));
3530 }
3531
3532 static uint32_t
3533 ctl_map_lun_back(int port_num, uint32_t lun_id)
3534 {
3535         struct ctl_port *port;
3536         uint32_t i;
3537
3538         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3539         if (port->lun_map == NULL)
3540                 return (lun_id);
3541         for (i = 0; i < CTL_MAX_LUNS; i++) {
3542                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3543                         return (i);
3544         }
3545         return (UINT32_MAX);
3546 }
3547
3548 /*
3549  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3550  * that are a power of 2.
3551  */
3552 int
3553 ctl_ffz(uint32_t *mask, uint32_t size)
3554 {
3555         uint32_t num_chunks, num_pieces;
3556         int i, j;
3557
3558         num_chunks = (size >> 5);
3559         if (num_chunks == 0)
3560                 num_chunks++;
3561         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3562
3563         for (i = 0; i < num_chunks; i++) {
3564                 for (j = 0; j < num_pieces; j++) {
3565                         if ((mask[i] & (1 << j)) == 0)
3566                                 return ((i << 5) + j);
3567                 }
3568         }
3569
3570         return (-1);
3571 }
3572
3573 int
3574 ctl_set_mask(uint32_t *mask, uint32_t bit)
3575 {
3576         uint32_t chunk, piece;
3577
3578         chunk = bit >> 5;
3579         piece = bit % (sizeof(uint32_t) * 8);
3580
3581         if ((mask[chunk] & (1 << piece)) != 0)
3582                 return (-1);
3583         else
3584                 mask[chunk] |= (1 << piece);
3585
3586         return (0);
3587 }
3588
3589 int
3590 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3591 {
3592         uint32_t chunk, piece;
3593
3594         chunk = bit >> 5;
3595         piece = bit % (sizeof(uint32_t) * 8);
3596
3597         if ((mask[chunk] & (1 << piece)) == 0)
3598                 return (-1);
3599         else
3600                 mask[chunk] &= ~(1 << piece);
3601
3602         return (0);
3603 }
3604
3605 int
3606 ctl_is_set(uint32_t *mask, uint32_t bit)
3607 {
3608         uint32_t chunk, piece;
3609
3610         chunk = bit >> 5;
3611         piece = bit % (sizeof(uint32_t) * 8);
3612
3613         if ((mask[chunk] & (1 << piece)) == 0)
3614                 return (0);
3615         else
3616                 return (1);
3617 }
3618
3619 #ifdef unused
3620 /*
3621  * The bus, target and lun are optional, they can be filled in later.
3622  * can_wait is used to determine whether we can wait on the malloc or not.
3623  */
3624 union ctl_io*
3625 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3626               uint32_t targ_lun, int can_wait)
3627 {
3628         union ctl_io *io;
3629
3630         if (can_wait)
3631                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3632         else
3633                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3634
3635         if (io != NULL) {
3636                 io->io_hdr.io_type = io_type;
3637                 io->io_hdr.targ_port = targ_port;
3638                 /*
3639                  * XXX KDM this needs to change/go away.  We need to move
3640                  * to a preallocated pool of ctl_scsiio structures.
3641                  */
3642                 io->io_hdr.nexus.targ_target.id = targ_target;
3643                 io->io_hdr.nexus.targ_lun = targ_lun;
3644         }
3645
3646         return (io);
3647 }
3648
3649 void
3650 ctl_kfree_io(union ctl_io *io)
3651 {
3652         free(io, M_CTL);
3653 }
3654 #endif /* unused */
3655
3656 /*
3657  * ctl_softc, pool_type, total_ctl_io are passed in.
3658  * npool is passed out.
3659  */
3660 int
3661 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3662                 uint32_t total_ctl_io, struct ctl_io_pool **npool)
3663 {
3664         uint32_t i;
3665         union ctl_io *cur_io, *next_io;
3666         struct ctl_io_pool *pool;
3667         int retval;
3668
3669         retval = 0;
3670
3671         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3672                                             M_NOWAIT | M_ZERO);
3673         if (pool == NULL) {
3674                 retval = ENOMEM;
3675                 goto bailout;
3676         }
3677
3678         pool->type = pool_type;
3679         pool->ctl_softc = ctl_softc;
3680
3681         mtx_lock(&ctl_softc->pool_lock);
3682         pool->id = ctl_softc->cur_pool_id++;
3683         mtx_unlock(&ctl_softc->pool_lock);
3684
3685         pool->flags = CTL_POOL_FLAG_NONE;
3686         pool->refcount = 1;             /* Reference for validity. */
3687         STAILQ_INIT(&pool->free_queue);
3688
3689         /*
3690          * XXX KDM other options here:
3691          * - allocate a page at a time
3692          * - allocate one big chunk of memory.
3693          * Page allocation might work well, but would take a little more
3694          * tracking.
3695          */
3696         for (i = 0; i < total_ctl_io; i++) {
3697                 cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3698                                                 M_NOWAIT);
3699                 if (cur_io == NULL) {
3700                         retval = ENOMEM;
3701                         break;
3702                 }
3703                 cur_io->io_hdr.pool = pool;
3704                 STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3705                 pool->total_ctl_io++;
3706                 pool->free_ctl_io++;
3707         }
3708
3709         if (retval != 0) {
3710                 for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3711                      cur_io != NULL; cur_io = next_io) {
3712                         next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3713                                                               links);
3714                         STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3715                                       ctl_io_hdr, links);
3716                         free(cur_io, M_CTLIO);
3717                 }
3718
3719                 free(pool, M_CTL);
3720                 goto bailout;
3721         }
3722         mtx_lock(&ctl_softc->pool_lock);
3723         ctl_softc->num_pools++;
3724         STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3725         /*
3726          * Increment our usage count if this is an external consumer, so we
3727          * can't get unloaded until the external consumer (most likely a
3728          * FETD) unloads and frees his pool.
3729          *
3730          * XXX KDM will this increment the caller's module use count, or
3731          * mine?
3732          */
3733 #if 0
3734         if ((pool_type != CTL_POOL_EMERGENCY)
3735          && (pool_type != CTL_POOL_INTERNAL)
3736          && (pool_type != CTL_POOL_4OTHERSC))
3737                 MOD_INC_USE_COUNT;
3738 #endif
3739
3740         mtx_unlock(&ctl_softc->pool_lock);
3741
3742         *npool = pool;
3743
3744 bailout:
3745
3746         return (retval);
3747 }
3748
3749 static int
3750 ctl_pool_acquire(struct ctl_io_pool *pool)
3751 {
3752
3753         mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3754
3755         if (pool->flags & CTL_POOL_FLAG_INVALID)
3756                 return (EINVAL);
3757
3758         pool->refcount++;
3759
3760         return (0);
3761 }
3762
3763 static void
3764 ctl_pool_release(struct ctl_io_pool *pool)
3765 {
3766         struct ctl_softc *ctl_softc = pool->ctl_softc;
3767         union ctl_io *io;
3768
3769         mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3770
3771         if (--pool->refcount != 0)
3772                 return;
3773
3774         while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3775                 STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3776                               links);
3777                 free(io, M_CTLIO);
3778         }
3779
3780         STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3781         ctl_softc->num_pools--;
3782
3783         /*
3784          * XXX KDM will this decrement the caller's usage count or mine?
3785          */
3786 #if 0
3787         if ((pool->type != CTL_POOL_EMERGENCY)
3788          && (pool->type != CTL_POOL_INTERNAL)
3789          && (pool->type != CTL_POOL_4OTHERSC))
3790                 MOD_DEC_USE_COUNT;
3791 #endif
3792
3793         free(pool, M_CTL);
3794 }
3795
3796 void
3797 ctl_pool_free(struct ctl_io_pool *pool)
3798 {
3799         struct ctl_softc *ctl_softc;
3800
3801         if (pool == NULL)
3802                 return;
3803
3804         ctl_softc = pool->ctl_softc;
3805         mtx_lock(&ctl_softc->pool_lock);
3806         pool->flags |= CTL_POOL_FLAG_INVALID;
3807         ctl_pool_release(pool);
3808         mtx_unlock(&ctl_softc->pool_lock);
3809 }
3810
3811 /*
3812  * This routine does not block (except for spinlocks of course).
3813  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3814  * possible.
3815  */
3816 union ctl_io *
3817 ctl_alloc_io(void *pool_ref)
3818 {
3819         union ctl_io *io;
3820         struct ctl_softc *ctl_softc;
3821         struct ctl_io_pool *pool, *npool;
3822         struct ctl_io_pool *emergency_pool;
3823
3824         pool = (struct ctl_io_pool *)pool_ref;
3825
3826         if (pool == NULL) {
3827                 printf("%s: pool is NULL\n", __func__);
3828                 return (NULL);
3829         }
3830
3831         emergency_pool = NULL;
3832
3833         ctl_softc = pool->ctl_softc;
3834
3835         mtx_lock(&ctl_softc->pool_lock);
3836         /*
3837          * First, try to get the io structure from the user's pool.
3838          */
3839         if (ctl_pool_acquire(pool) == 0) {
3840                 io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3841                 if (io != NULL) {
3842                         STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3843                         pool->total_allocated++;
3844                         pool->free_ctl_io--;
3845                         mtx_unlock(&ctl_softc->pool_lock);
3846                         return (io);
3847                 } else
3848                         ctl_pool_release(pool);
3849         }
3850         /*
3851          * If he doesn't have any io structures left, search for an
3852          * emergency pool and grab one from there.
3853          */
3854         STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3855                 if (npool->type != CTL_POOL_EMERGENCY)
3856                         continue;
3857
3858                 if (ctl_pool_acquire(npool) != 0)
3859                         continue;
3860
3861                 emergency_pool = npool;
3862
3863                 io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3864                 if (io != NULL) {
3865                         STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3866                         npool->total_allocated++;
3867                         npool->free_ctl_io--;
3868                         mtx_unlock(&ctl_softc->pool_lock);
3869                         return (io);
3870                 } else
3871                         ctl_pool_release(npool);
3872         }
3873
3874         /* Drop the spinlock before we malloc */
3875         mtx_unlock(&ctl_softc->pool_lock);
3876
3877         /*
3878          * The emergency pool (if it exists) didn't have one, so try an
3879          * atomic (i.e. nonblocking) malloc and see if we get lucky.
3880          */
3881         io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3882         if (io != NULL) {
3883                 /*
3884                  * If the emergency pool exists but is empty, add this
3885                  * ctl_io to its list when it gets freed.
3886                  */
3887                 if (emergency_pool != NULL) {
3888                         mtx_lock(&ctl_softc->pool_lock);
3889                         if (ctl_pool_acquire(emergency_pool) == 0) {
3890                                 io->io_hdr.pool = emergency_pool;
3891                                 emergency_pool->total_ctl_io++;
3892                                 /*
3893                                  * Need to bump this, otherwise
3894                                  * total_allocated and total_freed won't
3895                                  * match when we no longer have anything
3896                                  * outstanding.
3897                                  */
3898                                 emergency_pool->total_allocated++;
3899                         }
3900                         mtx_unlock(&ctl_softc->pool_lock);
3901                 } else
3902                         io->io_hdr.pool = NULL;
3903         }
3904
3905         return (io);
3906 }
3907
3908 void
3909 ctl_free_io(union ctl_io *io)
3910 {
3911         if (io == NULL)
3912                 return;
3913
3914         /*
3915          * If this ctl_io has a pool, return it to that pool.
3916          */
3917         if (io->io_hdr.pool != NULL) {
3918                 struct ctl_io_pool *pool;
3919
3920                 pool = (struct ctl_io_pool *)io->io_hdr.pool;
3921                 mtx_lock(&pool->ctl_softc->pool_lock);
3922                 io->io_hdr.io_type = 0xff;
3923                 STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3924                 pool->total_freed++;
3925                 pool->free_ctl_io++;
3926                 ctl_pool_release(pool);
3927                 mtx_unlock(&pool->ctl_softc->pool_lock);
3928         } else {
3929                 /*
3930                  * Otherwise, just free it.  We probably malloced it and
3931                  * the emergency pool wasn't available.
3932                  */
3933                 free(io, M_CTLIO);
3934         }
3935
3936 }
3937
3938 void
3939 ctl_zero_io(union ctl_io *io)
3940 {
3941         void *pool_ref;
3942
3943         if (io == NULL)
3944                 return;
3945
3946         /*
3947          * May need to preserve linked list pointers at some point too.
3948          */
3949         pool_ref = io->io_hdr.pool;
3950
3951         memset(io, 0, sizeof(*io));
3952
3953         io->io_hdr.pool = pool_ref;
3954 }
3955
3956 /*
3957  * This routine is currently used for internal copies of ctl_ios that need
3958  * to persist for some reason after we've already returned status to the
3959  * FETD.  (Thus the flag set.)
3960  *
3961  * XXX XXX
3962  * Note that this makes a blind copy of all fields in the ctl_io, except
3963  * for the pool reference.  This includes any memory that has been
3964  * allocated!  That memory will no longer be valid after done has been
3965  * called, so this would be VERY DANGEROUS for command that actually does
3966  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3967  * start and stop commands, which don't transfer any data, so this is not a
3968  * problem.  If it is used for anything else, the caller would also need to
3969  * allocate data buffer space and this routine would need to be modified to
3970  * copy the data buffer(s) as well.
3971  */
3972 void
3973 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3974 {
3975         void *pool_ref;
3976
3977         if ((src == NULL)
3978          || (dest == NULL))
3979                 return;
3980
3981         /*
3982          * May need to preserve linked list pointers at some point too.
3983          */
3984         pool_ref = dest->io_hdr.pool;
3985
3986         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3987
3988         dest->io_hdr.pool = pool_ref;
3989         /*
3990          * We need to know that this is an internal copy, and doesn't need
3991          * to get passed back to the FETD that allocated it.
3992          */
3993         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3994 }
3995
3996 /*
3997  * This routine could be used in the future to load default and/or saved
3998  * mode page parameters for a particuar lun.
3999  */
4000 static int
4001 ctl_init_page_index(struct ctl_lun *lun)
4002 {
4003         int i;
4004         struct ctl_page_index *page_index;
4005         const char *value;
4006
4007         memcpy(&lun->mode_pages.index, page_index_template,
4008                sizeof(page_index_template));
4009
4010         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4011
4012                 page_index = &lun->mode_pages.index[i];
4013                 /*
4014                  * If this is a disk-only mode page, there's no point in
4015                  * setting it up.  For some pages, we have to have some
4016                  * basic information about the disk in order to calculate the
4017                  * mode page data.
4018                  */
4019                 if ((lun->be_lun->lun_type != T_DIRECT)
4020                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4021                         continue;
4022
4023                 switch (page_index->page_code & SMPH_PC_MASK) {
4024                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4025                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4026                                 panic("subpage is incorrect!");
4027                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4028                                &rw_er_page_default,
4029                                sizeof(rw_er_page_default));
4030                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4031                                &rw_er_page_changeable,
4032                                sizeof(rw_er_page_changeable));
4033                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4034                                &rw_er_page_default,
4035                                sizeof(rw_er_page_default));
4036                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4037                                &rw_er_page_default,
4038                                sizeof(rw_er_page_default));
4039                         page_index->page_data =
4040                                 (uint8_t *)lun->mode_pages.rw_er_page;
4041                         break;
4042                 }
4043                 case SMS_FORMAT_DEVICE_PAGE: {
4044                         struct scsi_format_page *format_page;
4045
4046                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4047                                 panic("subpage is incorrect!");
4048
4049                         /*
4050                          * Sectors per track are set above.  Bytes per
4051                          * sector need to be set here on a per-LUN basis.
4052                          */
4053                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4054                                &format_page_default,
4055                                sizeof(format_page_default));
4056                         memcpy(&lun->mode_pages.format_page[
4057                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4058                                sizeof(format_page_changeable));
4059                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4060                                &format_page_default,
4061                                sizeof(format_page_default));
4062                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4063                                &format_page_default,
4064                                sizeof(format_page_default));
4065
4066                         format_page = &lun->mode_pages.format_page[
4067                                 CTL_PAGE_CURRENT];
4068                         scsi_ulto2b(lun->be_lun->blocksize,
4069                                     format_page->bytes_per_sector);
4070
4071                         format_page = &lun->mode_pages.format_page[
4072                                 CTL_PAGE_DEFAULT];
4073                         scsi_ulto2b(lun->be_lun->blocksize,
4074                                     format_page->bytes_per_sector);
4075
4076                         format_page = &lun->mode_pages.format_page[
4077                                 CTL_PAGE_SAVED];
4078                         scsi_ulto2b(lun->be_lun->blocksize,
4079                                     format_page->bytes_per_sector);
4080
4081                         page_index->page_data =
4082                                 (uint8_t *)lun->mode_pages.format_page;
4083                         break;
4084                 }
4085                 case SMS_RIGID_DISK_PAGE: {
4086                         struct scsi_rigid_disk_page *rigid_disk_page;
4087                         uint32_t sectors_per_cylinder;
4088                         uint64_t cylinders;
4089 #ifndef __XSCALE__
4090                         int shift;
4091 #endif /* !__XSCALE__ */
4092
4093                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4094                                 panic("invalid subpage value %d",
4095                                       page_index->subpage);
4096
4097                         /*
4098                          * Rotation rate and sectors per track are set
4099                          * above.  We calculate the cylinders here based on
4100                          * capacity.  Due to the number of heads and
4101                          * sectors per track we're using, smaller arrays
4102                          * may turn out to have 0 cylinders.  Linux and
4103                          * FreeBSD don't pay attention to these mode pages
4104                          * to figure out capacity, but Solaris does.  It
4105                          * seems to deal with 0 cylinders just fine, and
4106                          * works out a fake geometry based on the capacity.
4107                          */
4108                         memcpy(&lun->mode_pages.rigid_disk_page[
4109                                CTL_PAGE_CURRENT], &rigid_disk_page_default,
4110                                sizeof(rigid_disk_page_default));
4111                         memcpy(&lun->mode_pages.rigid_disk_page[
4112                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4113                                sizeof(rigid_disk_page_changeable));
4114                         memcpy(&lun->mode_pages.rigid_disk_page[
4115                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4116                                sizeof(rigid_disk_page_default));
4117                         memcpy(&lun->mode_pages.rigid_disk_page[
4118                                CTL_PAGE_SAVED], &rigid_disk_page_default,
4119                                sizeof(rigid_disk_page_default));
4120
4121                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4122                                 CTL_DEFAULT_HEADS;
4123
4124                         /*
4125                          * The divide method here will be more accurate,
4126                          * probably, but results in floating point being
4127                          * used in the kernel on i386 (__udivdi3()).  On the
4128                          * XScale, though, __udivdi3() is implemented in
4129                          * software.
4130                          *
4131                          * The shift method for cylinder calculation is
4132                          * accurate if sectors_per_cylinder is a power of
4133                          * 2.  Otherwise it might be slightly off -- you
4134                          * might have a bit of a truncation problem.
4135                          */
4136 #ifdef  __XSCALE__
4137                         cylinders = (lun->be_lun->maxlba + 1) /
4138                                 sectors_per_cylinder;
4139 #else
4140                         for (shift = 31; shift > 0; shift--) {
4141                                 if (sectors_per_cylinder & (1 << shift))
4142                                         break;
4143                         }
4144                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4145 #endif
4146
4147                         /*
4148                          * We've basically got 3 bytes, or 24 bits for the
4149                          * cylinder size in the mode page.  If we're over,
4150                          * just round down to 2^24.
4151                          */
4152                         if (cylinders > 0xffffff)
4153                                 cylinders = 0xffffff;
4154
4155                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4156                                 CTL_PAGE_CURRENT];
4157                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4158
4159                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4160                                 CTL_PAGE_DEFAULT];
4161                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4162
4163                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4164                                 CTL_PAGE_SAVED];
4165                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4166
4167                         page_index->page_data =
4168                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4169                         break;
4170                 }
4171                 case SMS_CACHING_PAGE: {
4172                         struct scsi_caching_page *caching_page;
4173
4174                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4175                                 panic("invalid subpage value %d",
4176                                       page_index->subpage);
4177                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4178                                &caching_page_default,
4179                                sizeof(caching_page_default));
4180                         memcpy(&lun->mode_pages.caching_page[
4181                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4182                                sizeof(caching_page_changeable));
4183                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4184                                &caching_page_default,
4185                                sizeof(caching_page_default));
4186                         caching_page = &lun->mode_pages.caching_page[
4187                             CTL_PAGE_SAVED];
4188                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4189                         if (value != NULL && strcmp(value, "off") == 0)
4190                                 caching_page->flags1 &= ~SCP_WCE;
4191                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4192                         if (value != NULL && strcmp(value, "off") == 0)
4193                                 caching_page->flags1 |= SCP_RCD;
4194                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4195                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4196                                sizeof(caching_page_default));
4197                         page_index->page_data =
4198                                 (uint8_t *)lun->mode_pages.caching_page;
4199                         break;
4200                 }
4201                 case SMS_CONTROL_MODE_PAGE: {
4202                         struct scsi_control_page *control_page;
4203
4204                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4205                                 panic("invalid subpage value %d",
4206                                       page_index->subpage);
4207
4208                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4209                                &control_page_default,
4210                                sizeof(control_page_default));
4211                         memcpy(&lun->mode_pages.control_page[
4212                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4213                                sizeof(control_page_changeable));
4214                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4215                                &control_page_default,
4216                                sizeof(control_page_default));
4217                         control_page = &lun->mode_pages.control_page[
4218                             CTL_PAGE_SAVED];
4219                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4220                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4221                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4222                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4223                         }
4224                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4225                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4226                                sizeof(control_page_default));
4227                         page_index->page_data =
4228                                 (uint8_t *)lun->mode_pages.control_page;
4229                         break;
4230
4231                 }
4232                 case SMS_INFO_EXCEPTIONS_PAGE: {
4233                         switch (page_index->subpage) {
4234                         case SMS_SUBPAGE_PAGE_0:
4235                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4236                                        &ie_page_default,
4237                                        sizeof(ie_page_default));
4238                                 memcpy(&lun->mode_pages.ie_page[
4239                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4240                                        sizeof(ie_page_changeable));
4241                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4242                                        &ie_page_default,
4243                                        sizeof(ie_page_default));
4244                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4245                                        &ie_page_default,
4246                                        sizeof(ie_page_default));
4247                                 page_index->page_data =
4248                                         (uint8_t *)lun->mode_pages.ie_page;
4249                                 break;
4250                         case 0x02:
4251                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4252                                        &lbp_page_default,
4253                                        sizeof(lbp_page_default));
4254                                 memcpy(&lun->mode_pages.lbp_page[
4255                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4256                                        sizeof(lbp_page_changeable));
4257                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4258                                        &lbp_page_default,
4259                                        sizeof(lbp_page_default));
4260                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4261                                        &lbp_page_default,
4262                                        sizeof(lbp_page_default));
4263                                 page_index->page_data =
4264                                         (uint8_t *)lun->mode_pages.lbp_page;
4265                         }
4266                         break;
4267                 }
4268                 case SMS_VENDOR_SPECIFIC_PAGE:{
4269                         switch (page_index->subpage) {
4270                         case DBGCNF_SUBPAGE_CODE: {
4271                                 struct copan_debugconf_subpage *current_page,
4272                                                                *saved_page;
4273
4274                                 memcpy(&lun->mode_pages.debugconf_subpage[
4275                                        CTL_PAGE_CURRENT],
4276                                        &debugconf_page_default,
4277                                        sizeof(debugconf_page_default));
4278                                 memcpy(&lun->mode_pages.debugconf_subpage[
4279                                        CTL_PAGE_CHANGEABLE],
4280                                        &debugconf_page_changeable,
4281                                        sizeof(debugconf_page_changeable));
4282                                 memcpy(&lun->mode_pages.debugconf_subpage[
4283                                        CTL_PAGE_DEFAULT],
4284                                        &debugconf_page_default,
4285                                        sizeof(debugconf_page_default));
4286                                 memcpy(&lun->mode_pages.debugconf_subpage[
4287                                        CTL_PAGE_SAVED],
4288                                        &debugconf_page_default,
4289                                        sizeof(debugconf_page_default));
4290                                 page_index->page_data =
4291                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4292
4293                                 current_page = (struct copan_debugconf_subpage *)
4294                                         (page_index->page_data +
4295                                          (page_index->page_len *
4296                                           CTL_PAGE_CURRENT));
4297                                 saved_page = (struct copan_debugconf_subpage *)
4298                                         (page_index->page_data +
4299                                          (page_index->page_len *
4300                                           CTL_PAGE_SAVED));
4301                                 break;
4302                         }
4303                         default:
4304                                 panic("invalid subpage value %d",
4305                                       page_index->subpage);
4306                                 break;
4307                         }
4308                         break;
4309                 }
4310                 default:
4311                         panic("invalid page value %d",
4312                               page_index->page_code & SMPH_PC_MASK);
4313                         break;
4314         }
4315         }
4316
4317         return (CTL_RETVAL_COMPLETE);
4318 }
4319
4320 static int
4321 ctl_init_log_page_index(struct ctl_lun *lun)
4322 {
4323         struct ctl_page_index *page_index;
4324         int i, j, prev;
4325
4326         memcpy(&lun->log_pages.index, log_page_index_template,
4327                sizeof(log_page_index_template));
4328
4329         prev = -1;
4330         for (i = 0, j = 0; i < CTL_NUM_LOG_PAGES; i++) {
4331
4332                 page_index = &lun->log_pages.index[i];
4333                 /*
4334                  * If this is a disk-only mode page, there's no point in
4335                  * setting it up.  For some pages, we have to have some
4336                  * basic information about the disk in order to calculate the
4337                  * mode page data.
4338                  */
4339                 if ((lun->be_lun->lun_type != T_DIRECT)
4340                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4341                         continue;
4342
4343                 if (page_index->page_code != prev) {
4344                         lun->log_pages.pages_page[j] = page_index->page_code;
4345                         prev = page_index->page_code;
4346                         j++;
4347                 }
4348                 lun->log_pages.subpages_page[i*2] = page_index->page_code;
4349                 lun->log_pages.subpages_page[i*2+1] = page_index->subpage;
4350         }
4351         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4352         lun->log_pages.index[0].page_len = j;
4353         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4354         lun->log_pages.index[1].page_len = i * 2;
4355
4356         return (CTL_RETVAL_COMPLETE);
4357 }
4358
4359 static int
4360 hex2bin(const char *str, uint8_t *buf, int buf_size)
4361 {
4362         int i;
4363         u_char c;
4364
4365         memset(buf, 0, buf_size);
4366         while (isspace(str[0]))
4367                 str++;
4368         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4369                 str += 2;
4370         buf_size *= 2;
4371         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4372                 c = str[i];
4373                 if (isdigit(c))
4374                         c -= '0';
4375                 else if (isalpha(c))
4376                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4377                 else
4378                         break;
4379                 if (c >= 16)
4380                         break;
4381                 if ((i & 1) == 0)
4382                         buf[i / 2] |= (c << 4);
4383                 else
4384                         buf[i / 2] |= c;
4385         }
4386         return ((i + 1) / 2);
4387 }
4388
4389 /*
4390  * LUN allocation.
4391  *
4392  * Requirements:
4393  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4394  *   wants us to allocate the LUN and he can block.
4395  * - ctl_softc is always set
4396  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4397  *
4398  * Returns 0 for success, non-zero (errno) for failure.
4399  */
4400 static int
4401 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4402               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4403 {
4404         struct ctl_lun *nlun, *lun;
4405         struct ctl_port *port;
4406         struct scsi_vpd_id_descriptor *desc;
4407         struct scsi_vpd_id_t10 *t10id;
4408         const char *eui, *naa, *scsiname, *vendor, *value;
4409         int lun_number, i, lun_malloced;
4410         int devidlen, idlen1, idlen2 = 0, len;
4411
4412         if (be_lun == NULL)
4413                 return (EINVAL);
4414
4415         /*
4416          * We currently only support Direct Access or Processor LUN types.
4417          */
4418         switch (be_lun->lun_type) {
4419         case T_DIRECT:
4420                 break;
4421         case T_PROCESSOR:
4422                 break;
4423         case T_SEQUENTIAL:
4424         case T_CHANGER:
4425         default:
4426                 be_lun->lun_config_status(be_lun->be_lun,
4427                                           CTL_LUN_CONFIG_FAILURE);
4428                 break;
4429         }
4430         if (ctl_lun == NULL) {
4431                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4432                 lun_malloced = 1;
4433         } else {
4434                 lun_malloced = 0;
4435                 lun = ctl_lun;
4436         }
4437
4438         memset(lun, 0, sizeof(*lun));
4439         if (lun_malloced)
4440                 lun->flags = CTL_LUN_MALLOCED;
4441
4442         /* Generate LUN ID. */
4443         devidlen = max(CTL_DEVID_MIN_LEN,
4444             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4445         idlen1 = sizeof(*t10id) + devidlen;
4446         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4447         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4448         if (scsiname != NULL) {
4449                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4450                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4451         }
4452         eui = ctl_get_opt(&be_lun->options, "eui");
4453         if (eui != NULL) {
4454                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4455         }
4456         naa = ctl_get_opt(&be_lun->options, "naa");
4457         if (naa != NULL) {
4458                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4459         }
4460         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4461             M_CTL, M_WAITOK | M_ZERO);
4462         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4463         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4464         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4465         desc->length = idlen1;
4466         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4467         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4468         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4469                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4470         } else {
4471                 strncpy(t10id->vendor, vendor,
4472                     min(sizeof(t10id->vendor), strlen(vendor)));
4473         }
4474         strncpy((char *)t10id->vendor_spec_id,
4475             (char *)be_lun->device_id, devidlen);
4476         if (scsiname != NULL) {
4477                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4478                     desc->length);
4479                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4480                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4481                     SVPD_ID_TYPE_SCSI_NAME;
4482                 desc->length = idlen2;
4483                 strlcpy(desc->identifier, scsiname, idlen2);
4484         }
4485         if (eui != NULL) {
4486                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4487                     desc->length);
4488                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4489                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4490                     SVPD_ID_TYPE_EUI64;
4491                 desc->length = hex2bin(eui, desc->identifier, 16);
4492                 desc->length = desc->length > 12 ? 16 :
4493                     (desc->length > 8 ? 12 : 8);
4494                 len -= 16 - desc->length;
4495         }
4496         if (naa != NULL) {
4497                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4498                     desc->length);
4499                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4500                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4501                     SVPD_ID_TYPE_NAA;
4502                 desc->length = hex2bin(naa, desc->identifier, 16);
4503                 desc->length = desc->length > 8 ? 16 : 8;
4504                 len -= 16 - desc->length;
4505         }
4506         lun->lun_devid->len = len;
4507
4508         mtx_lock(&ctl_softc->ctl_lock);
4509         /*
4510          * See if the caller requested a particular LUN number.  If so, see
4511          * if it is available.  Otherwise, allocate the first available LUN.
4512          */
4513         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4514                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4515                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4516                         mtx_unlock(&ctl_softc->ctl_lock);
4517                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4518                                 printf("ctl: requested LUN ID %d is higher "
4519                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4520                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4521                         } else {
4522                                 /*
4523                                  * XXX KDM return an error, or just assign
4524                                  * another LUN ID in this case??
4525                                  */
4526                                 printf("ctl: requested LUN ID %d is already "
4527                                        "in use\n", be_lun->req_lun_id);
4528                         }
4529                         if (lun->flags & CTL_LUN_MALLOCED)
4530                                 free(lun, M_CTL);
4531                         be_lun->lun_config_status(be_lun->be_lun,
4532                                                   CTL_LUN_CONFIG_FAILURE);
4533                         return (ENOSPC);
4534                 }
4535                 lun_number = be_lun->req_lun_id;
4536         } else {
4537                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4538                 if (lun_number == -1) {
4539                         mtx_unlock(&ctl_softc->ctl_lock);
4540                         printf("ctl: can't allocate LUN on target %ju, out of "
4541                                "LUNs\n", (uintmax_t)target_id.id);
4542                         if (lun->flags & CTL_LUN_MALLOCED)
4543                                 free(lun, M_CTL);
4544                         be_lun->lun_config_status(be_lun->be_lun,
4545                                                   CTL_LUN_CONFIG_FAILURE);
4546                         return (ENOSPC);
4547                 }
4548         }
4549         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4550
4551         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4552         lun->target = target_id;
4553         lun->lun = lun_number;
4554         lun->be_lun = be_lun;
4555         /*
4556          * The processor LUN is always enabled.  Disk LUNs come on line
4557          * disabled, and must be enabled by the backend.
4558          */
4559         lun->flags |= CTL_LUN_DISABLED;
4560         lun->backend = be_lun->be;
4561         be_lun->ctl_lun = lun;
4562         be_lun->lun_id = lun_number;
4563         atomic_add_int(&be_lun->be->num_luns, 1);
4564         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4565                 lun->flags |= CTL_LUN_OFFLINE;
4566
4567         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4568                 lun->flags |= CTL_LUN_STOPPED;
4569
4570         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4571                 lun->flags |= CTL_LUN_INOPERABLE;
4572
4573         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4574                 lun->flags |= CTL_LUN_PRIMARY_SC;
4575
4576         value = ctl_get_opt(&be_lun->options, "readonly");
4577         if (value != NULL && strcmp(value, "on") == 0)
4578                 lun->flags |= CTL_LUN_READONLY;
4579
4580         lun->ctl_softc = ctl_softc;
4581         TAILQ_INIT(&lun->ooa_queue);
4582         TAILQ_INIT(&lun->blocked_queue);
4583         STAILQ_INIT(&lun->error_list);
4584         ctl_tpc_lun_init(lun);
4585
4586         /*
4587          * Initialize the mode and log page index.
4588          */
4589         ctl_init_page_index(lun);
4590         ctl_init_log_page_index(lun);
4591
4592         /*
4593          * Set the poweron UA for all initiators on this LUN only.
4594          */
4595         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4596                 lun->pending_ua[i] = CTL_UA_POWERON;
4597
4598         /*
4599          * Now, before we insert this lun on the lun list, set the lun
4600          * inventory changed UA for all other luns.
4601          */
4602         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4603                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4604                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4605                 }
4606         }
4607
4608         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4609
4610         ctl_softc->ctl_luns[lun_number] = lun;
4611
4612         ctl_softc->num_luns++;
4613
4614         /* Setup statistics gathering */
4615         lun->stats.device_type = be_lun->lun_type;
4616         lun->stats.lun_number = lun_number;
4617         if (lun->stats.device_type == T_DIRECT)
4618                 lun->stats.blocksize = be_lun->blocksize;
4619         else
4620                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4621         for (i = 0;i < CTL_MAX_PORTS;i++)
4622                 lun->stats.ports[i].targ_port = i;
4623
4624         mtx_unlock(&ctl_softc->ctl_lock);
4625
4626         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4627
4628         /*
4629          * Run through each registered FETD and bring it online if it isn't
4630          * already.  Enable the target ID if it hasn't been enabled, and
4631          * enable this particular LUN.
4632          */
4633         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4634                 int retval;
4635
4636                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4637                 if (retval != 0) {
4638                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4639                                "%d for lun_enable on target %ju lun %d\n",
4640                                port->port_name, port->targ_port, retval,
4641                                (uintmax_t)target_id.id, lun_number);
4642                 } else
4643                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4644         }
4645         return (0);
4646 }
4647
4648 /*
4649  * Delete a LUN.
4650  * Assumptions:
4651  * - LUN has already been marked invalid and any pending I/O has been taken
4652  *   care of.
4653  */
4654 static int
4655 ctl_free_lun(struct ctl_lun *lun)
4656 {
4657         struct ctl_softc *softc;
4658 #if 0
4659         struct ctl_port *port;
4660 #endif
4661         struct ctl_lun *nlun;
4662         int i;
4663
4664         softc = lun->ctl_softc;
4665
4666         mtx_assert(&softc->ctl_lock, MA_OWNED);
4667
4668         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4669
4670         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4671
4672         softc->ctl_luns[lun->lun] = NULL;
4673
4674         if (!TAILQ_EMPTY(&lun->ooa_queue))
4675                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4676
4677         softc->num_luns--;
4678
4679         /*
4680          * XXX KDM this scheme only works for a single target/multiple LUN
4681          * setup.  It needs to be revamped for a multiple target scheme.
4682          *
4683          * XXX KDM this results in port->lun_disable() getting called twice,
4684          * once when ctl_disable_lun() is called, and a second time here.
4685          * We really need to re-think the LUN disable semantics.  There
4686          * should probably be several steps/levels to LUN removal:
4687          *  - disable
4688          *  - invalidate
4689          *  - free
4690          *
4691          * Right now we only have a disable method when communicating to
4692          * the front end ports, at least for individual LUNs.
4693          */
4694 #if 0
4695         STAILQ_FOREACH(port, &softc->port_list, links) {
4696                 int retval;
4697
4698                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4699                                          lun->lun);
4700                 if (retval != 0) {
4701                         printf("ctl_free_lun: FETD %s port %d returned error "
4702                                "%d for lun_disable on target %ju lun %jd\n",
4703                                port->port_name, port->targ_port, retval,
4704                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4705                 }
4706
4707                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4708                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4709
4710                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4711                         if (retval != 0) {
4712                                 printf("ctl_free_lun: FETD %s port %d "
4713                                        "returned error %d for targ_disable on "
4714                                        "target %ju\n", port->port_name,
4715                                        port->targ_port, retval,
4716                                        (uintmax_t)lun->target.id);
4717                         } else
4718                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4719
4720                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4721                                 continue;
4722
4723 #if 0
4724                         port->port_offline(port->onoff_arg);
4725                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4726 #endif
4727                 }
4728         }
4729 #endif
4730
4731         /*
4732          * Tell the backend to free resources, if this LUN has a backend.
4733          */
4734         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4735         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4736
4737         ctl_tpc_lun_shutdown(lun);
4738         mtx_destroy(&lun->lun_lock);
4739         free(lun->lun_devid, M_CTL);
4740         if (lun->flags & CTL_LUN_MALLOCED)
4741                 free(lun, M_CTL);
4742
4743         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4744                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4745                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4746                 }
4747         }
4748
4749         return (0);
4750 }
4751
4752 static void
4753 ctl_create_lun(struct ctl_be_lun *be_lun)
4754 {
4755         struct ctl_softc *ctl_softc;
4756
4757         ctl_softc = control_softc;
4758
4759         /*
4760          * ctl_alloc_lun() should handle all potential failure cases.
4761          */
4762         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4763 }
4764
4765 int
4766 ctl_add_lun(struct ctl_be_lun *be_lun)
4767 {
4768         struct ctl_softc *ctl_softc = control_softc;
4769
4770         mtx_lock(&ctl_softc->ctl_lock);
4771         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4772         mtx_unlock(&ctl_softc->ctl_lock);
4773         wakeup(&ctl_softc->pending_lun_queue);
4774
4775         return (0);
4776 }
4777
4778 int
4779 ctl_enable_lun(struct ctl_be_lun *be_lun)
4780 {
4781         struct ctl_softc *ctl_softc;
4782         struct ctl_port *port, *nport;
4783         struct ctl_lun *lun;
4784         int retval;
4785
4786         ctl_softc = control_softc;
4787
4788         lun = (struct ctl_lun *)be_lun->ctl_lun;
4789
4790         mtx_lock(&ctl_softc->ctl_lock);
4791         mtx_lock(&lun->lun_lock);
4792         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4793                 /*
4794                  * eh?  Why did we get called if the LUN is already
4795                  * enabled?
4796                  */
4797                 mtx_unlock(&lun->lun_lock);
4798                 mtx_unlock(&ctl_softc->ctl_lock);
4799                 return (0);
4800         }
4801         lun->flags &= ~CTL_LUN_DISABLED;
4802         mtx_unlock(&lun->lun_lock);
4803
4804         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4805                 nport = STAILQ_NEXT(port, links);
4806
4807                 /*
4808                  * Drop the lock while we call the FETD's enable routine.
4809                  * This can lead to a callback into CTL (at least in the
4810                  * case of the internal initiator frontend.
4811                  */
4812                 mtx_unlock(&ctl_softc->ctl_lock);
4813                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4814                 mtx_lock(&ctl_softc->ctl_lock);
4815                 if (retval != 0) {
4816                         printf("%s: FETD %s port %d returned error "
4817                                "%d for lun_enable on target %ju lun %jd\n",
4818                                __func__, port->port_name, port->targ_port, retval,
4819                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4820                 }
4821 #if 0
4822                  else {
4823             /* NOTE:  TODO:  why does lun enable affect port status? */
4824                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4825                 }
4826 #endif
4827         }
4828
4829         mtx_unlock(&ctl_softc->ctl_lock);
4830
4831         return (0);
4832 }
4833
4834 int
4835 ctl_disable_lun(struct ctl_be_lun *be_lun)
4836 {
4837         struct ctl_softc *ctl_softc;
4838         struct ctl_port *port;
4839         struct ctl_lun *lun;
4840         int retval;
4841
4842         ctl_softc = control_softc;
4843
4844         lun = (struct ctl_lun *)be_lun->ctl_lun;
4845
4846         mtx_lock(&ctl_softc->ctl_lock);
4847         mtx_lock(&lun->lun_lock);
4848         if (lun->flags & CTL_LUN_DISABLED) {
4849                 mtx_unlock(&lun->lun_lock);
4850                 mtx_unlock(&ctl_softc->ctl_lock);
4851                 return (0);
4852         }
4853         lun->flags |= CTL_LUN_DISABLED;
4854         mtx_unlock(&lun->lun_lock);
4855
4856         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4857                 mtx_unlock(&ctl_softc->ctl_lock);
4858                 /*
4859                  * Drop the lock before we call the frontend's disable
4860                  * routine, to avoid lock order reversals.
4861                  *
4862                  * XXX KDM what happens if the frontend list changes while
4863                  * we're traversing it?  It's unlikely, but should be handled.
4864                  */
4865                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4866                                          lun->lun);
4867                 mtx_lock(&ctl_softc->ctl_lock);
4868                 if (retval != 0) {
4869                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4870                                "%d for lun_disable on target %ju lun %jd\n",
4871                                port->port_name, port->targ_port, retval,
4872                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4873                 }
4874         }
4875
4876         mtx_unlock(&ctl_softc->ctl_lock);
4877
4878         return (0);
4879 }
4880
4881 int
4882 ctl_start_lun(struct ctl_be_lun *be_lun)
4883 {
4884         struct ctl_softc *ctl_softc;
4885         struct ctl_lun *lun;
4886
4887         ctl_softc = control_softc;
4888
4889         lun = (struct ctl_lun *)be_lun->ctl_lun;
4890
4891         mtx_lock(&lun->lun_lock);
4892         lun->flags &= ~CTL_LUN_STOPPED;
4893         mtx_unlock(&lun->lun_lock);
4894
4895         return (0);
4896 }
4897
4898 int
4899 ctl_stop_lun(struct ctl_be_lun *be_lun)
4900 {
4901         struct ctl_softc *ctl_softc;
4902         struct ctl_lun *lun;
4903
4904         ctl_softc = control_softc;
4905
4906         lun = (struct ctl_lun *)be_lun->ctl_lun;
4907
4908         mtx_lock(&lun->lun_lock);
4909         lun->flags |= CTL_LUN_STOPPED;
4910         mtx_unlock(&lun->lun_lock);
4911
4912         return (0);
4913 }
4914
4915 int
4916 ctl_lun_offline(struct ctl_be_lun *be_lun)
4917 {
4918         struct ctl_softc *ctl_softc;
4919         struct ctl_lun *lun;
4920
4921         ctl_softc = control_softc;
4922
4923         lun = (struct ctl_lun *)be_lun->ctl_lun;
4924
4925         mtx_lock(&lun->lun_lock);
4926         lun->flags |= CTL_LUN_OFFLINE;
4927         mtx_unlock(&lun->lun_lock);
4928
4929         return (0);
4930 }
4931
4932 int
4933 ctl_lun_online(struct ctl_be_lun *be_lun)
4934 {
4935         struct ctl_softc *ctl_softc;
4936         struct ctl_lun *lun;
4937
4938         ctl_softc = control_softc;
4939
4940         lun = (struct ctl_lun *)be_lun->ctl_lun;
4941
4942         mtx_lock(&lun->lun_lock);
4943         lun->flags &= ~CTL_LUN_OFFLINE;
4944         mtx_unlock(&lun->lun_lock);
4945
4946         return (0);
4947 }
4948
4949 int
4950 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4951 {
4952         struct ctl_softc *ctl_softc;
4953         struct ctl_lun *lun;
4954
4955         ctl_softc = control_softc;
4956
4957         lun = (struct ctl_lun *)be_lun->ctl_lun;
4958
4959         mtx_lock(&lun->lun_lock);
4960
4961         /*
4962          * The LUN needs to be disabled before it can be marked invalid.
4963          */
4964         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4965                 mtx_unlock(&lun->lun_lock);
4966                 return (-1);
4967         }
4968         /*
4969          * Mark the LUN invalid.
4970          */
4971         lun->flags |= CTL_LUN_INVALID;
4972
4973         /*
4974          * If there is nothing in the OOA queue, go ahead and free the LUN.
4975          * If we have something in the OOA queue, we'll free it when the
4976          * last I/O completes.
4977          */
4978         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4979                 mtx_unlock(&lun->lun_lock);
4980                 mtx_lock(&ctl_softc->ctl_lock);
4981                 ctl_free_lun(lun);
4982                 mtx_unlock(&ctl_softc->ctl_lock);
4983         } else
4984                 mtx_unlock(&lun->lun_lock);
4985
4986         return (0);
4987 }
4988
4989 int
4990 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4991 {
4992         struct ctl_softc *ctl_softc;
4993         struct ctl_lun *lun;
4994
4995         ctl_softc = control_softc;
4996         lun = (struct ctl_lun *)be_lun->ctl_lun;
4997
4998         mtx_lock(&lun->lun_lock);
4999         lun->flags |= CTL_LUN_INOPERABLE;
5000         mtx_unlock(&lun->lun_lock);
5001
5002         return (0);
5003 }
5004
5005 int
5006 ctl_lun_operable(struct ctl_be_lun *be_lun)
5007 {
5008         struct ctl_softc *ctl_softc;
5009         struct ctl_lun *lun;
5010
5011         ctl_softc = control_softc;
5012         lun = (struct ctl_lun *)be_lun->ctl_lun;
5013
5014         mtx_lock(&lun->lun_lock);
5015         lun->flags &= ~CTL_LUN_INOPERABLE;
5016         mtx_unlock(&lun->lun_lock);
5017
5018         return (0);
5019 }
5020
5021 void
5022 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5023 {
5024         struct ctl_lun *lun;
5025         struct ctl_softc *softc;
5026         int i;
5027
5028         softc = control_softc;
5029
5030         lun = (struct ctl_lun *)be_lun->ctl_lun;
5031
5032         mtx_lock(&lun->lun_lock);
5033
5034         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5035                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5036
5037         mtx_unlock(&lun->lun_lock);
5038 }
5039
5040 /*
5041  * Backend "memory move is complete" callback for requests that never
5042  * make it down to say RAIDCore's configuration code.
5043  */
5044 int
5045 ctl_config_move_done(union ctl_io *io)
5046 {
5047         int retval;
5048
5049         retval = CTL_RETVAL_COMPLETE;
5050
5051
5052         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5053         /*
5054          * XXX KDM this shouldn't happen, but what if it does?
5055          */
5056         if (io->io_hdr.io_type != CTL_IO_SCSI)
5057                 panic("I/O type isn't CTL_IO_SCSI!");
5058
5059         if ((io->io_hdr.port_status == 0)
5060          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5061          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5062                 io->io_hdr.status = CTL_SUCCESS;
5063         else if ((io->io_hdr.port_status != 0)
5064               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5065               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5066                 /*
5067                  * For hardware error sense keys, the sense key
5068                  * specific value is defined to be a retry count,
5069                  * but we use it to pass back an internal FETD
5070                  * error code.  XXX KDM  Hopefully the FETD is only
5071                  * using 16 bits for an error code, since that's
5072                  * all the space we have in the sks field.
5073                  */
5074                 ctl_set_internal_failure(&io->scsiio,
5075                                          /*sks_valid*/ 1,
5076                                          /*retry_count*/
5077                                          io->io_hdr.port_status);
5078                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5079                         free(io->scsiio.kern_data_ptr, M_CTL);
5080                 ctl_done(io);
5081                 goto bailout;
5082         }
5083
5084         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5085          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5086          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5087                 /*
5088                  * XXX KDM just assuming a single pointer here, and not a
5089                  * S/G list.  If we start using S/G lists for config data,
5090                  * we'll need to know how to clean them up here as well.
5091                  */
5092                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5093                         free(io->scsiio.kern_data_ptr, M_CTL);
5094                 /* Hopefully the user has already set the status... */
5095                 ctl_done(io);
5096         } else {
5097                 /*
5098                  * XXX KDM now we need to continue data movement.  Some
5099                  * options:
5100                  * - call ctl_scsiio() again?  We don't do this for data
5101                  *   writes, because for those at least we know ahead of
5102                  *   time where the write will go and how long it is.  For
5103                  *   config writes, though, that information is largely
5104                  *   contained within the write itself, thus we need to
5105                  *   parse out the data again.
5106                  *
5107                  * - Call some other function once the data is in?
5108                  */
5109                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5110                         ctl_data_print(io);
5111
5112                 /*
5113                  * XXX KDM call ctl_scsiio() again for now, and check flag
5114                  * bits to see whether we're allocated or not.
5115                  */
5116                 retval = ctl_scsiio(&io->scsiio);
5117         }
5118 bailout:
5119         return (retval);
5120 }
5121
5122 /*
5123  * This gets called by a backend driver when it is done with a
5124  * data_submit method.
5125  */
5126 void
5127 ctl_data_submit_done(union ctl_io *io)
5128 {
5129         /*
5130          * If the IO_CONT flag is set, we need to call the supplied
5131          * function to continue processing the I/O, instead of completing
5132          * the I/O just yet.
5133          *
5134          * If there is an error, though, we don't want to keep processing.
5135          * Instead, just send status back to the initiator.
5136          */
5137         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5138             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5139             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5140              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5141                 io->scsiio.io_cont(io);
5142                 return;
5143         }
5144         ctl_done(io);
5145 }
5146
5147 /*
5148  * This gets called by a backend driver when it is done with a
5149  * configuration write.
5150  */
5151 void
5152 ctl_config_write_done(union ctl_io *io)
5153 {
5154         uint8_t *buf;
5155
5156         /*
5157          * If the IO_CONT flag is set, we need to call the supplied
5158          * function to continue processing the I/O, instead of completing
5159          * the I/O just yet.
5160          *
5161          * If there is an error, though, we don't want to keep processing.
5162          * Instead, just send status back to the initiator.
5163          */
5164         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5165             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5166             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5167              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5168                 io->scsiio.io_cont(io);
5169                 return;
5170         }
5171         /*
5172          * Since a configuration write can be done for commands that actually
5173          * have data allocated, like write buffer, and commands that have
5174          * no data, like start/stop unit, we need to check here.
5175          */
5176         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5177                 buf = io->scsiio.kern_data_ptr;
5178         else
5179                 buf = NULL;
5180         ctl_done(io);
5181         if (buf)
5182                 free(buf, M_CTL);
5183 }
5184
5185 /*
5186  * SCSI release command.
5187  */
5188 int
5189 ctl_scsi_release(struct ctl_scsiio *ctsio)
5190 {
5191         int length, longid, thirdparty_id, resv_id;
5192         struct ctl_softc *ctl_softc;
5193         struct ctl_lun *lun;
5194         uint32_t residx;
5195
5196         length = 0;
5197         resv_id = 0;
5198
5199         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5200
5201         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5202         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5203         ctl_softc = control_softc;
5204
5205         switch (ctsio->cdb[0]) {
5206         case RELEASE_10: {
5207                 struct scsi_release_10 *cdb;
5208
5209                 cdb = (struct scsi_release_10 *)ctsio->cdb;
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         /*
5224          * XXX KDM right now, we only support LUN reservation.  We don't
5225          * support 3rd party reservations, or extent reservations, which
5226          * might actually need the parameter list.  If we've gotten this
5227          * far, we've got a LUN reservation.  Anything else got kicked out
5228          * above.  So, according to SPC, ignore the length.
5229          */
5230         length = 0;
5231
5232         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5233          && (length > 0)) {
5234                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5235                 ctsio->kern_data_len = length;
5236                 ctsio->kern_total_len = length;
5237                 ctsio->kern_data_resid = 0;
5238                 ctsio->kern_rel_offset = 0;
5239                 ctsio->kern_sg_entries = 0;
5240                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5241                 ctsio->be_move_done = ctl_config_move_done;
5242                 ctl_datamove((union ctl_io *)ctsio);
5243
5244                 return (CTL_RETVAL_COMPLETE);
5245         }
5246
5247         if (length > 0)
5248                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5249
5250         mtx_lock(&lun->lun_lock);
5251
5252         /*
5253          * According to SPC, it is not an error for an intiator to attempt
5254          * to release a reservation on a LUN that isn't reserved, or that
5255          * is reserved by another initiator.  The reservation can only be
5256          * released, though, by the initiator who made it or by one of
5257          * several reset type events.
5258          */
5259         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5260                         lun->flags &= ~CTL_LUN_RESERVED;
5261
5262         mtx_unlock(&lun->lun_lock);
5263
5264         ctsio->scsi_status = SCSI_STATUS_OK;
5265         ctsio->io_hdr.status = CTL_SUCCESS;
5266
5267         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5268                 free(ctsio->kern_data_ptr, M_CTL);
5269                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5270         }
5271
5272         ctl_done((union ctl_io *)ctsio);
5273         return (CTL_RETVAL_COMPLETE);
5274 }
5275
5276 int
5277 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5278 {
5279         int extent, thirdparty, longid;
5280         int resv_id, length;
5281         uint64_t thirdparty_id;
5282         struct ctl_softc *ctl_softc;
5283         struct ctl_lun *lun;
5284         uint32_t residx;
5285
5286         extent = 0;
5287         thirdparty = 0;
5288         longid = 0;
5289         resv_id = 0;
5290         length = 0;
5291         thirdparty_id = 0;
5292
5293         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5294
5295         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5296         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5297         ctl_softc = control_softc;
5298
5299         switch (ctsio->cdb[0]) {
5300         case RESERVE_10: {
5301                 struct scsi_reserve_10 *cdb;
5302
5303                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5304
5305                 if (cdb->byte2 & SR10_LONGID)
5306                         longid = 1;
5307                 else
5308                         thirdparty_id = cdb->thirdparty_id;
5309
5310                 resv_id = cdb->resv_id;
5311                 length = scsi_2btoul(cdb->length);
5312                 break;
5313         }
5314         }
5315
5316         /*
5317          * XXX KDM right now, we only support LUN reservation.  We don't
5318          * support 3rd party reservations, or extent reservations, which
5319          * might actually need the parameter list.  If we've gotten this
5320          * far, we've got a LUN reservation.  Anything else got kicked out
5321          * above.  So, according to SPC, ignore the length.
5322          */
5323         length = 0;
5324
5325         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5326          && (length > 0)) {
5327                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5328                 ctsio->kern_data_len = length;
5329                 ctsio->kern_total_len = length;
5330                 ctsio->kern_data_resid = 0;
5331                 ctsio->kern_rel_offset = 0;
5332                 ctsio->kern_sg_entries = 0;
5333                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5334                 ctsio->be_move_done = ctl_config_move_done;
5335                 ctl_datamove((union ctl_io *)ctsio);
5336
5337                 return (CTL_RETVAL_COMPLETE);
5338         }
5339
5340         if (length > 0)
5341                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5342
5343         mtx_lock(&lun->lun_lock);
5344         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5345                 ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5346                 ctsio->io_hdr.status = CTL_SCSI_ERROR;
5347                 goto bailout;
5348         }
5349
5350         lun->flags |= CTL_LUN_RESERVED;
5351         lun->res_idx = residx;
5352
5353         ctsio->scsi_status = SCSI_STATUS_OK;
5354         ctsio->io_hdr.status = CTL_SUCCESS;
5355
5356 bailout:
5357         mtx_unlock(&lun->lun_lock);
5358
5359         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5360                 free(ctsio->kern_data_ptr, M_CTL);
5361                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5362         }
5363
5364         ctl_done((union ctl_io *)ctsio);
5365         return (CTL_RETVAL_COMPLETE);
5366 }
5367
5368 int
5369 ctl_start_stop(struct ctl_scsiio *ctsio)
5370 {
5371         struct scsi_start_stop_unit *cdb;
5372         struct ctl_lun *lun;
5373         struct ctl_softc *ctl_softc;
5374         int retval;
5375
5376         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5377
5378         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5379         ctl_softc = control_softc;
5380         retval = 0;
5381
5382         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5383
5384         /*
5385          * XXX KDM
5386          * We don't support the immediate bit on a stop unit.  In order to
5387          * do that, we would need to code up a way to know that a stop is
5388          * pending, and hold off any new commands until it completes, one
5389          * way or another.  Then we could accept or reject those commands
5390          * depending on its status.  We would almost need to do the reverse
5391          * of what we do below for an immediate start -- return the copy of
5392          * the ctl_io to the FETD with status to send to the host (and to
5393          * free the copy!) and then free the original I/O once the stop
5394          * actually completes.  That way, the OOA queue mechanism can work
5395          * to block commands that shouldn't proceed.  Another alternative
5396          * would be to put the copy in the queue in place of the original,
5397          * and return the original back to the caller.  That could be
5398          * slightly safer..
5399          */
5400         if ((cdb->byte2 & SSS_IMMED)
5401          && ((cdb->how & SSS_START) == 0)) {
5402                 ctl_set_invalid_field(ctsio,
5403                                       /*sks_valid*/ 1,
5404                                       /*command*/ 1,
5405                                       /*field*/ 1,
5406                                       /*bit_valid*/ 1,
5407                                       /*bit*/ 0);
5408                 ctl_done((union ctl_io *)ctsio);
5409                 return (CTL_RETVAL_COMPLETE);
5410         }
5411
5412         if ((lun->flags & CTL_LUN_PR_RESERVED)
5413          && ((cdb->how & SSS_START)==0)) {
5414                 uint32_t residx;
5415
5416                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5417                 if (lun->pr_keys[residx] == 0
5418                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5419
5420                         ctl_set_reservation_conflict(ctsio);
5421                         ctl_done((union ctl_io *)ctsio);
5422                         return (CTL_RETVAL_COMPLETE);
5423                 }
5424         }
5425
5426         /*
5427          * If there is no backend on this device, we can't start or stop
5428          * it.  In theory we shouldn't get any start/stop commands in the
5429          * first place at this level if the LUN doesn't have a backend.
5430          * That should get stopped by the command decode code.
5431          */
5432         if (lun->backend == NULL) {
5433                 ctl_set_invalid_opcode(ctsio);
5434                 ctl_done((union ctl_io *)ctsio);
5435                 return (CTL_RETVAL_COMPLETE);
5436         }
5437
5438         /*
5439          * XXX KDM Copan-specific offline behavior.
5440          * Figure out a reasonable way to port this?
5441          */
5442 #ifdef NEEDTOPORT
5443         mtx_lock(&lun->lun_lock);
5444
5445         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5446          && (lun->flags & CTL_LUN_OFFLINE)) {
5447                 /*
5448                  * If the LUN is offline, and the on/offline bit isn't set,
5449                  * reject the start or stop.  Otherwise, let it through.
5450                  */
5451                 mtx_unlock(&lun->lun_lock);
5452                 ctl_set_lun_not_ready(ctsio);
5453                 ctl_done((union ctl_io *)ctsio);
5454         } else {
5455                 mtx_unlock(&lun->lun_lock);
5456 #endif /* NEEDTOPORT */
5457                 /*
5458                  * This could be a start or a stop when we're online,
5459                  * or a stop/offline or start/online.  A start or stop when
5460                  * we're offline is covered in the case above.
5461                  */
5462                 /*
5463                  * In the non-immediate case, we send the request to
5464                  * the backend and return status to the user when
5465                  * it is done.
5466                  *
5467                  * In the immediate case, we allocate a new ctl_io
5468                  * to hold a copy of the request, and send that to
5469                  * the backend.  We then set good status on the
5470                  * user's request and return it immediately.
5471                  */
5472                 if (cdb->byte2 & SSS_IMMED) {
5473                         union ctl_io *new_io;
5474
5475                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5476                         if (new_io == NULL) {
5477                                 ctl_set_busy(ctsio);
5478                                 ctl_done((union ctl_io *)ctsio);
5479                         } else {
5480                                 ctl_copy_io((union ctl_io *)ctsio,
5481                                             new_io);
5482                                 retval = lun->backend->config_write(new_io);
5483                                 ctl_set_success(ctsio);
5484                                 ctl_done((union ctl_io *)ctsio);
5485                         }
5486                 } else {
5487                         retval = lun->backend->config_write(
5488                                 (union ctl_io *)ctsio);
5489                 }
5490 #ifdef NEEDTOPORT
5491         }
5492 #endif
5493         return (retval);
5494 }
5495
5496 /*
5497  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5498  * we don't really do anything with the LBA and length fields if the user
5499  * passes them in.  Instead we'll just flush out the cache for the entire
5500  * LUN.
5501  */
5502 int
5503 ctl_sync_cache(struct ctl_scsiio *ctsio)
5504 {
5505         struct ctl_lun *lun;
5506         struct ctl_softc *ctl_softc;
5507         uint64_t starting_lba;
5508         uint32_t block_count;
5509         int retval;
5510
5511         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5512
5513         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5514         ctl_softc = control_softc;
5515         retval = 0;
5516
5517         switch (ctsio->cdb[0]) {
5518         case SYNCHRONIZE_CACHE: {
5519                 struct scsi_sync_cache *cdb;
5520                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5521
5522                 starting_lba = scsi_4btoul(cdb->begin_lba);
5523                 block_count = scsi_2btoul(cdb->lb_count);
5524                 break;
5525         }
5526         case SYNCHRONIZE_CACHE_16: {
5527                 struct scsi_sync_cache_16 *cdb;
5528                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5529
5530                 starting_lba = scsi_8btou64(cdb->begin_lba);
5531                 block_count = scsi_4btoul(cdb->lb_count);
5532                 break;
5533         }
5534         default:
5535                 ctl_set_invalid_opcode(ctsio);
5536                 ctl_done((union ctl_io *)ctsio);
5537                 goto bailout;
5538                 break; /* NOTREACHED */
5539         }
5540
5541         /*
5542          * We check the LBA and length, but don't do anything with them.
5543          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5544          * get flushed.  This check will just help satisfy anyone who wants
5545          * to see an error for an out of range LBA.
5546          */
5547         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5548                 ctl_set_lba_out_of_range(ctsio);
5549                 ctl_done((union ctl_io *)ctsio);
5550                 goto bailout;
5551         }
5552
5553         /*
5554          * If this LUN has no backend, we can't flush the cache anyway.
5555          */
5556         if (lun->backend == NULL) {
5557                 ctl_set_invalid_opcode(ctsio);
5558                 ctl_done((union ctl_io *)ctsio);
5559                 goto bailout;
5560         }
5561
5562         /*
5563          * Check to see whether we're configured to send the SYNCHRONIZE
5564          * CACHE command directly to the back end.
5565          */
5566         mtx_lock(&lun->lun_lock);
5567         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5568          && (++(lun->sync_count) >= lun->sync_interval)) {
5569                 lun->sync_count = 0;
5570                 mtx_unlock(&lun->lun_lock);
5571                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5572         } else {
5573                 mtx_unlock(&lun->lun_lock);
5574                 ctl_set_success(ctsio);
5575                 ctl_done((union ctl_io *)ctsio);
5576         }
5577
5578 bailout:
5579
5580         return (retval);
5581 }
5582
5583 int
5584 ctl_format(struct ctl_scsiio *ctsio)
5585 {
5586         struct scsi_format *cdb;
5587         struct ctl_lun *lun;
5588         struct ctl_softc *ctl_softc;
5589         int length, defect_list_len;
5590
5591         CTL_DEBUG_PRINT(("ctl_format\n"));
5592
5593         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5594         ctl_softc = control_softc;
5595
5596         cdb = (struct scsi_format *)ctsio->cdb;
5597
5598         length = 0;
5599         if (cdb->byte2 & SF_FMTDATA) {
5600                 if (cdb->byte2 & SF_LONGLIST)
5601                         length = sizeof(struct scsi_format_header_long);
5602                 else
5603                         length = sizeof(struct scsi_format_header_short);
5604         }
5605
5606         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5607          && (length > 0)) {
5608                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5609                 ctsio->kern_data_len = length;
5610                 ctsio->kern_total_len = length;
5611                 ctsio->kern_data_resid = 0;
5612                 ctsio->kern_rel_offset = 0;
5613                 ctsio->kern_sg_entries = 0;
5614                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5615                 ctsio->be_move_done = ctl_config_move_done;
5616                 ctl_datamove((union ctl_io *)ctsio);
5617
5618                 return (CTL_RETVAL_COMPLETE);
5619         }
5620
5621         defect_list_len = 0;
5622
5623         if (cdb->byte2 & SF_FMTDATA) {
5624                 if (cdb->byte2 & SF_LONGLIST) {
5625                         struct scsi_format_header_long *header;
5626
5627                         header = (struct scsi_format_header_long *)
5628                                 ctsio->kern_data_ptr;
5629
5630                         defect_list_len = scsi_4btoul(header->defect_list_len);
5631                         if (defect_list_len != 0) {
5632                                 ctl_set_invalid_field(ctsio,
5633                                                       /*sks_valid*/ 1,
5634                                                       /*command*/ 0,
5635                                                       /*field*/ 2,
5636                                                       /*bit_valid*/ 0,
5637                                                       /*bit*/ 0);
5638                                 goto bailout;
5639                         }
5640                 } else {
5641                         struct scsi_format_header_short *header;
5642
5643                         header = (struct scsi_format_header_short *)
5644                                 ctsio->kern_data_ptr;
5645
5646                         defect_list_len = scsi_2btoul(header->defect_list_len);
5647                         if (defect_list_len != 0) {
5648                                 ctl_set_invalid_field(ctsio,
5649                                                       /*sks_valid*/ 1,
5650                                                       /*command*/ 0,
5651                                                       /*field*/ 2,
5652                                                       /*bit_valid*/ 0,
5653                                                       /*bit*/ 0);
5654                                 goto bailout;
5655                         }
5656                 }
5657         }
5658
5659         /*
5660          * The format command will clear out the "Medium format corrupted"
5661          * status if set by the configuration code.  That status is really
5662          * just a way to notify the host that we have lost the media, and
5663          * get them to issue a command that will basically make them think
5664          * they're blowing away the media.
5665          */
5666         mtx_lock(&lun->lun_lock);
5667         lun->flags &= ~CTL_LUN_INOPERABLE;
5668         mtx_unlock(&lun->lun_lock);
5669
5670         ctsio->scsi_status = SCSI_STATUS_OK;
5671         ctsio->io_hdr.status = CTL_SUCCESS;
5672 bailout:
5673
5674         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5675                 free(ctsio->kern_data_ptr, M_CTL);
5676                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5677         }
5678
5679         ctl_done((union ctl_io *)ctsio);
5680         return (CTL_RETVAL_COMPLETE);
5681 }
5682
5683 int
5684 ctl_read_buffer(struct ctl_scsiio *ctsio)
5685 {
5686         struct scsi_read_buffer *cdb;
5687         struct ctl_lun *lun;
5688         int buffer_offset, len;
5689         static uint8_t descr[4];
5690         static uint8_t echo_descr[4] = { 0 };
5691
5692         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5693
5694         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5695         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5696
5697         if (lun->flags & CTL_LUN_PR_RESERVED) {
5698                 uint32_t residx;
5699
5700                 /*
5701                  * XXX KDM need a lock here.
5702                  */
5703                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5704                 if ((lun->res_type == SPR_TYPE_EX_AC
5705                   && residx != lun->pr_res_idx)
5706                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
5707                    || lun->res_type == SPR_TYPE_EX_AC_AR)
5708                   && lun->pr_keys[residx] == 0)) {
5709                         ctl_set_reservation_conflict(ctsio);
5710                         ctl_done((union ctl_io *)ctsio);
5711                         return (CTL_RETVAL_COMPLETE);
5712                 }
5713         }
5714
5715         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5716             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5717             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5718                 ctl_set_invalid_field(ctsio,
5719                                       /*sks_valid*/ 1,
5720                                       /*command*/ 1,
5721                                       /*field*/ 1,
5722                                       /*bit_valid*/ 1,
5723                                       /*bit*/ 4);
5724                 ctl_done((union ctl_io *)ctsio);
5725                 return (CTL_RETVAL_COMPLETE);
5726         }
5727
5728         len = scsi_3btoul(cdb->length);
5729         buffer_offset = scsi_3btoul(cdb->offset);
5730
5731         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5732                 ctl_set_invalid_field(ctsio,
5733                                       /*sks_valid*/ 1,
5734                                       /*command*/ 1,
5735                                       /*field*/ 6,
5736                                       /*bit_valid*/ 0,
5737                                       /*bit*/ 0);
5738                 ctl_done((union ctl_io *)ctsio);
5739                 return (CTL_RETVAL_COMPLETE);
5740         }
5741
5742         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5743                 descr[0] = 0;
5744                 scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5745                 ctsio->kern_data_ptr = descr;
5746                 len = min(len, sizeof(descr));
5747         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5748                 ctsio->kern_data_ptr = echo_descr;
5749                 len = min(len, sizeof(echo_descr));
5750         } else
5751                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5752         ctsio->kern_data_len = len;
5753         ctsio->kern_total_len = len;
5754         ctsio->kern_data_resid = 0;
5755         ctsio->kern_rel_offset = 0;
5756         ctsio->kern_sg_entries = 0;
5757         ctsio->be_move_done = ctl_config_move_done;
5758         ctl_datamove((union ctl_io *)ctsio);
5759
5760         return (CTL_RETVAL_COMPLETE);
5761 }
5762
5763 int
5764 ctl_write_buffer(struct ctl_scsiio *ctsio)
5765 {
5766         struct scsi_write_buffer *cdb;
5767         struct ctl_lun *lun;
5768         int buffer_offset, len;
5769
5770         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5771
5772         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5773         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5774
5775         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5776                 ctl_set_invalid_field(ctsio,
5777                                       /*sks_valid*/ 1,
5778                                       /*command*/ 1,
5779                                       /*field*/ 1,
5780                                       /*bit_valid*/ 1,
5781                                       /*bit*/ 4);
5782                 ctl_done((union ctl_io *)ctsio);
5783                 return (CTL_RETVAL_COMPLETE);
5784         }
5785
5786         len = scsi_3btoul(cdb->length);
5787         buffer_offset = scsi_3btoul(cdb->offset);
5788
5789         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5790                 ctl_set_invalid_field(ctsio,
5791                                       /*sks_valid*/ 1,
5792                                       /*command*/ 1,
5793                                       /*field*/ 6,
5794                                       /*bit_valid*/ 0,
5795                                       /*bit*/ 0);
5796                 ctl_done((union ctl_io *)ctsio);
5797                 return (CTL_RETVAL_COMPLETE);
5798         }
5799
5800         /*
5801          * If we've got a kernel request that hasn't been malloced yet,
5802          * malloc it and tell the caller the data buffer is here.
5803          */
5804         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5805                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5806                 ctsio->kern_data_len = len;
5807                 ctsio->kern_total_len = len;
5808                 ctsio->kern_data_resid = 0;
5809                 ctsio->kern_rel_offset = 0;
5810                 ctsio->kern_sg_entries = 0;
5811                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5812                 ctsio->be_move_done = ctl_config_move_done;
5813                 ctl_datamove((union ctl_io *)ctsio);
5814
5815                 return (CTL_RETVAL_COMPLETE);
5816         }
5817
5818         ctl_done((union ctl_io *)ctsio);
5819
5820         return (CTL_RETVAL_COMPLETE);
5821 }
5822
5823 int
5824 ctl_write_same(struct ctl_scsiio *ctsio)
5825 {
5826         struct ctl_lun *lun;
5827         struct ctl_lba_len_flags *lbalen;
5828         uint64_t lba;
5829         uint32_t num_blocks;
5830         int len, retval;
5831         uint8_t byte2;
5832
5833         retval = CTL_RETVAL_COMPLETE;
5834
5835         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5836
5837         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5838
5839         switch (ctsio->cdb[0]) {
5840         case WRITE_SAME_10: {
5841                 struct scsi_write_same_10 *cdb;
5842
5843                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5844
5845                 lba = scsi_4btoul(cdb->addr);
5846                 num_blocks = scsi_2btoul(cdb->length);
5847                 byte2 = cdb->byte2;
5848                 break;
5849         }
5850         case WRITE_SAME_16: {
5851                 struct scsi_write_same_16 *cdb;
5852
5853                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5854
5855                 lba = scsi_8btou64(cdb->addr);
5856                 num_blocks = scsi_4btoul(cdb->length);
5857                 byte2 = cdb->byte2;
5858                 break;
5859         }
5860         default:
5861                 /*
5862                  * We got a command we don't support.  This shouldn't
5863                  * happen, commands should be filtered out above us.
5864                  */
5865                 ctl_set_invalid_opcode(ctsio);
5866                 ctl_done((union ctl_io *)ctsio);
5867
5868                 return (CTL_RETVAL_COMPLETE);
5869                 break; /* NOTREACHED */
5870         }
5871
5872         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5873         if ((byte2 & SWS_UNMAP) == 0 &&
5874             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5875                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5876                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5877                 ctl_done((union ctl_io *)ctsio);
5878                 return (CTL_RETVAL_COMPLETE);
5879         }
5880
5881         /*
5882          * The first check is to make sure we're in bounds, the second
5883          * check is to catch wrap-around problems.  If the lba + num blocks
5884          * is less than the lba, then we've wrapped around and the block
5885          * range is invalid anyway.
5886          */
5887         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5888          || ((lba + num_blocks) < lba)) {
5889                 ctl_set_lba_out_of_range(ctsio);
5890                 ctl_done((union ctl_io *)ctsio);
5891                 return (CTL_RETVAL_COMPLETE);
5892         }
5893
5894         /* Zero number of blocks means "to the last logical block" */
5895         if (num_blocks == 0) {
5896                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5897                         ctl_set_invalid_field(ctsio,
5898                                               /*sks_valid*/ 0,
5899                                               /*command*/ 1,
5900                                               /*field*/ 0,
5901                                               /*bit_valid*/ 0,
5902                                               /*bit*/ 0);
5903                         ctl_done((union ctl_io *)ctsio);
5904                         return (CTL_RETVAL_COMPLETE);
5905                 }
5906                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5907         }
5908
5909         len = lun->be_lun->blocksize;
5910
5911         /*
5912          * If we've got a kernel request that hasn't been malloced yet,
5913          * malloc it and tell the caller the data buffer is here.
5914          */
5915         if ((byte2 & SWS_NDOB) == 0 &&
5916             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5917                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5918                 ctsio->kern_data_len = len;
5919                 ctsio->kern_total_len = len;
5920                 ctsio->kern_data_resid = 0;
5921                 ctsio->kern_rel_offset = 0;
5922                 ctsio->kern_sg_entries = 0;
5923                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5924                 ctsio->be_move_done = ctl_config_move_done;
5925                 ctl_datamove((union ctl_io *)ctsio);
5926
5927                 return (CTL_RETVAL_COMPLETE);
5928         }
5929
5930         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5931         lbalen->lba = lba;
5932         lbalen->len = num_blocks;
5933         lbalen->flags = byte2;
5934         retval = lun->backend->config_write((union ctl_io *)ctsio);
5935
5936         return (retval);
5937 }
5938
5939 int
5940 ctl_unmap(struct ctl_scsiio *ctsio)
5941 {
5942         struct ctl_lun *lun;
5943         struct scsi_unmap *cdb;
5944         struct ctl_ptr_len_flags *ptrlen;
5945         struct scsi_unmap_header *hdr;
5946         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5947         uint64_t lba;
5948         uint32_t num_blocks;
5949         int len, retval;
5950         uint8_t byte2;
5951
5952         retval = CTL_RETVAL_COMPLETE;
5953
5954         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5955
5956         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5957         cdb = (struct scsi_unmap *)ctsio->cdb;
5958
5959         len = scsi_2btoul(cdb->length);
5960         byte2 = cdb->byte2;
5961
5962         /*
5963          * If we've got a kernel request that hasn't been malloced yet,
5964          * malloc it and tell the caller the data buffer is here.
5965          */
5966         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5967                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5968                 ctsio->kern_data_len = len;
5969                 ctsio->kern_total_len = len;
5970                 ctsio->kern_data_resid = 0;
5971                 ctsio->kern_rel_offset = 0;
5972                 ctsio->kern_sg_entries = 0;
5973                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5974                 ctsio->be_move_done = ctl_config_move_done;
5975                 ctl_datamove((union ctl_io *)ctsio);
5976
5977                 return (CTL_RETVAL_COMPLETE);
5978         }
5979
5980         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5981         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5982         if (len < sizeof (*hdr) ||
5983             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5984             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5985             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5986                 ctl_set_invalid_field(ctsio,
5987                                       /*sks_valid*/ 0,
5988                                       /*command*/ 0,
5989                                       /*field*/ 0,
5990                                       /*bit_valid*/ 0,
5991                                       /*bit*/ 0);
5992                 ctl_done((union ctl_io *)ctsio);
5993                 return (CTL_RETVAL_COMPLETE);
5994         }
5995         len = scsi_2btoul(hdr->desc_length);
5996         buf = (struct scsi_unmap_desc *)(hdr + 1);
5997         end = buf + len / sizeof(*buf);
5998
5999         endnz = buf;
6000         for (range = buf; range < end; range++) {
6001                 lba = scsi_8btou64(range->lba);
6002                 num_blocks = scsi_4btoul(range->length);
6003                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6004                  || ((lba + num_blocks) < lba)) {
6005                         ctl_set_lba_out_of_range(ctsio);
6006                         ctl_done((union ctl_io *)ctsio);
6007                         return (CTL_RETVAL_COMPLETE);
6008                 }
6009                 if (num_blocks != 0)
6010                         endnz = range + 1;
6011         }
6012
6013         /*
6014          * Block backend can not handle zero last range.
6015          * Filter it out and return if there is nothing left.
6016          */
6017         len = (uint8_t *)endnz - (uint8_t *)buf;
6018         if (len == 0) {
6019                 ctl_set_success(ctsio);
6020                 ctl_done((union ctl_io *)ctsio);
6021                 return (CTL_RETVAL_COMPLETE);
6022         }
6023
6024         mtx_lock(&lun->lun_lock);
6025         ptrlen = (struct ctl_ptr_len_flags *)
6026             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6027         ptrlen->ptr = (void *)buf;
6028         ptrlen->len = len;
6029         ptrlen->flags = byte2;
6030         ctl_check_blocked(lun);
6031         mtx_unlock(&lun->lun_lock);
6032
6033         retval = lun->backend->config_write((union ctl_io *)ctsio);
6034         return (retval);
6035 }
6036
6037 /*
6038  * Note that this function currently doesn't actually do anything inside
6039  * CTL to enforce things if the DQue bit is turned on.
6040  *
6041  * Also note that this function can't be used in the default case, because
6042  * the DQue bit isn't set in the changeable mask for the control mode page
6043  * anyway.  This is just here as an example for how to implement a page
6044  * handler, and a placeholder in case we want to allow the user to turn
6045  * tagged queueing on and off.
6046  *
6047  * The D_SENSE bit handling is functional, however, and will turn
6048  * descriptor sense on and off for a given LUN.
6049  */
6050 int
6051 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6052                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6053 {
6054         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6055         struct ctl_lun *lun;
6056         struct ctl_softc *softc;
6057         int set_ua;
6058         uint32_t initidx;
6059
6060         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6061         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6062         set_ua = 0;
6063
6064         user_cp = (struct scsi_control_page *)page_ptr;
6065         current_cp = (struct scsi_control_page *)
6066                 (page_index->page_data + (page_index->page_len *
6067                 CTL_PAGE_CURRENT));
6068         saved_cp = (struct scsi_control_page *)
6069                 (page_index->page_data + (page_index->page_len *
6070                 CTL_PAGE_SAVED));
6071
6072         softc = control_softc;
6073
6074         mtx_lock(&lun->lun_lock);
6075         if (((current_cp->rlec & SCP_DSENSE) == 0)
6076          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6077                 /*
6078                  * Descriptor sense is currently turned off and the user
6079                  * wants to turn it on.
6080                  */
6081                 current_cp->rlec |= SCP_DSENSE;
6082                 saved_cp->rlec |= SCP_DSENSE;
6083                 lun->flags |= CTL_LUN_SENSE_DESC;
6084                 set_ua = 1;
6085         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6086                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6087                 /*
6088                  * Descriptor sense is currently turned on, and the user
6089                  * wants to turn it off.
6090                  */
6091                 current_cp->rlec &= ~SCP_DSENSE;
6092                 saved_cp->rlec &= ~SCP_DSENSE;
6093                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6094                 set_ua = 1;
6095         }
6096         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6097             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6098                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6099                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6100                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6101                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6102                 set_ua = 1;
6103         }
6104         if ((current_cp->eca_and_aen & SCP_SWP) !=
6105             (user_cp->eca_and_aen & SCP_SWP)) {
6106                 current_cp->eca_and_aen &= ~SCP_SWP;
6107                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6108                 saved_cp->eca_and_aen &= ~SCP_SWP;
6109                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6110                 set_ua = 1;
6111         }
6112         if (set_ua != 0) {
6113                 int i;
6114                 /*
6115                  * Let other initiators know that the mode
6116                  * parameters for this LUN have changed.
6117                  */
6118                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6119                         if (i == initidx)
6120                                 continue;
6121
6122                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6123                 }
6124         }
6125         mtx_unlock(&lun->lun_lock);
6126
6127         return (0);
6128 }
6129
6130 int
6131 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6132                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6133 {
6134         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6135         struct ctl_lun *lun;
6136         int set_ua;
6137         uint32_t initidx;
6138
6139         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6140         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6141         set_ua = 0;
6142
6143         user_cp = (struct scsi_caching_page *)page_ptr;
6144         current_cp = (struct scsi_caching_page *)
6145                 (page_index->page_data + (page_index->page_len *
6146                 CTL_PAGE_CURRENT));
6147         saved_cp = (struct scsi_caching_page *)
6148                 (page_index->page_data + (page_index->page_len *
6149                 CTL_PAGE_SAVED));
6150
6151         mtx_lock(&lun->lun_lock);
6152         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6153             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6154                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6155                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6156                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6157                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6158                 set_ua = 1;
6159         }
6160         if (set_ua != 0) {
6161                 int i;
6162                 /*
6163                  * Let other initiators know that the mode
6164                  * parameters for this LUN have changed.
6165                  */
6166                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6167                         if (i == initidx)
6168                                 continue;
6169
6170                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6171                 }
6172         }
6173         mtx_unlock(&lun->lun_lock);
6174
6175         return (0);
6176 }
6177
6178 int
6179 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6180                                 struct ctl_page_index *page_index,
6181                                 uint8_t *page_ptr)
6182 {
6183         uint8_t *c;
6184         int i;
6185
6186         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6187         ctl_time_io_secs =
6188                 (c[0] << 8) |
6189                 (c[1] << 0) |
6190                 0;
6191         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6192         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6193         printf("page data:");
6194         for (i=0; i<8; i++)
6195                 printf(" %.2x",page_ptr[i]);
6196         printf("\n");
6197         return (0);
6198 }
6199
6200 int
6201 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6202                                struct ctl_page_index *page_index,
6203                                int pc)
6204 {
6205         struct copan_debugconf_subpage *page;
6206
6207         page = (struct copan_debugconf_subpage *)page_index->page_data +
6208                 (page_index->page_len * pc);
6209
6210         switch (pc) {
6211         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6212         case SMS_PAGE_CTRL_DEFAULT >> 6:
6213         case SMS_PAGE_CTRL_SAVED >> 6:
6214                 /*
6215                  * We don't update the changable or default bits for this page.
6216                  */
6217                 break;
6218         case SMS_PAGE_CTRL_CURRENT >> 6:
6219                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6220                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6221                 break;
6222         default:
6223 #ifdef NEEDTOPORT
6224                 EPRINT(0, "Invalid PC %d!!", pc);
6225 #endif /* NEEDTOPORT */
6226                 break;
6227         }
6228         return (0);
6229 }
6230
6231
6232 static int
6233 ctl_do_mode_select(union ctl_io *io)
6234 {
6235         struct scsi_mode_page_header *page_header;
6236         struct ctl_page_index *page_index;
6237         struct ctl_scsiio *ctsio;
6238         int control_dev, page_len;
6239         int page_len_offset, page_len_size;
6240         union ctl_modepage_info *modepage_info;
6241         struct ctl_lun *lun;
6242         int *len_left, *len_used;
6243         int retval, i;
6244
6245         ctsio = &io->scsiio;
6246         page_index = NULL;
6247         page_len = 0;
6248         retval = CTL_RETVAL_COMPLETE;
6249
6250         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6251
6252         if (lun->be_lun->lun_type != T_DIRECT)
6253                 control_dev = 1;
6254         else
6255                 control_dev = 0;
6256
6257         modepage_info = (union ctl_modepage_info *)
6258                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6259         len_left = &modepage_info->header.len_left;
6260         len_used = &modepage_info->header.len_used;
6261
6262 do_next_page:
6263
6264         page_header = (struct scsi_mode_page_header *)
6265                 (ctsio->kern_data_ptr + *len_used);
6266
6267         if (*len_left == 0) {
6268                 free(ctsio->kern_data_ptr, M_CTL);
6269                 ctl_set_success(ctsio);
6270                 ctl_done((union ctl_io *)ctsio);
6271                 return (CTL_RETVAL_COMPLETE);
6272         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6273
6274                 free(ctsio->kern_data_ptr, M_CTL);
6275                 ctl_set_param_len_error(ctsio);
6276                 ctl_done((union ctl_io *)ctsio);
6277                 return (CTL_RETVAL_COMPLETE);
6278
6279         } else if ((page_header->page_code & SMPH_SPF)
6280                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6281
6282                 free(ctsio->kern_data_ptr, M_CTL);
6283                 ctl_set_param_len_error(ctsio);
6284                 ctl_done((union ctl_io *)ctsio);
6285                 return (CTL_RETVAL_COMPLETE);
6286         }
6287
6288
6289         /*
6290          * XXX KDM should we do something with the block descriptor?
6291          */
6292         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6293
6294                 if ((control_dev != 0)
6295                  && (lun->mode_pages.index[i].page_flags &
6296                      CTL_PAGE_FLAG_DISK_ONLY))
6297                         continue;
6298
6299                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6300                     (page_header->page_code & SMPH_PC_MASK))
6301                         continue;
6302
6303                 /*
6304                  * If neither page has a subpage code, then we've got a
6305                  * match.
6306                  */
6307                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6308                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6309                         page_index = &lun->mode_pages.index[i];
6310                         page_len = page_header->page_length;
6311                         break;
6312                 }
6313
6314                 /*
6315                  * If both pages have subpages, then the subpage numbers
6316                  * have to match.
6317                  */
6318                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6319                   && (page_header->page_code & SMPH_SPF)) {
6320                         struct scsi_mode_page_header_sp *sph;
6321
6322                         sph = (struct scsi_mode_page_header_sp *)page_header;
6323
6324                         if (lun->mode_pages.index[i].subpage ==
6325                             sph->subpage) {
6326                                 page_index = &lun->mode_pages.index[i];
6327                                 page_len = scsi_2btoul(sph->page_length);
6328                                 break;
6329                         }
6330                 }
6331         }
6332
6333         /*
6334          * If we couldn't find the page, or if we don't have a mode select
6335          * handler for it, send back an error to the user.
6336          */
6337         if ((page_index == NULL)
6338          || (page_index->select_handler == NULL)) {
6339                 ctl_set_invalid_field(ctsio,
6340                                       /*sks_valid*/ 1,
6341                                       /*command*/ 0,
6342                                       /*field*/ *len_used,
6343                                       /*bit_valid*/ 0,
6344                                       /*bit*/ 0);
6345                 free(ctsio->kern_data_ptr, M_CTL);
6346                 ctl_done((union ctl_io *)ctsio);
6347                 return (CTL_RETVAL_COMPLETE);
6348         }
6349
6350         if (page_index->page_code & SMPH_SPF) {
6351                 page_len_offset = 2;
6352                 page_len_size = 2;
6353         } else {
6354                 page_len_size = 1;
6355                 page_len_offset = 1;
6356         }
6357
6358         /*
6359          * If the length the initiator gives us isn't the one we specify in
6360          * the mode page header, or if they didn't specify enough data in
6361          * the CDB to avoid truncating this page, kick out the request.
6362          */
6363         if ((page_len != (page_index->page_len - page_len_offset -
6364                           page_len_size))
6365          || (*len_left < page_index->page_len)) {
6366
6367
6368                 ctl_set_invalid_field(ctsio,
6369                                       /*sks_valid*/ 1,
6370                                       /*command*/ 0,
6371                                       /*field*/ *len_used + page_len_offset,
6372                                       /*bit_valid*/ 0,
6373                                       /*bit*/ 0);
6374                 free(ctsio->kern_data_ptr, M_CTL);
6375                 ctl_done((union ctl_io *)ctsio);
6376                 return (CTL_RETVAL_COMPLETE);
6377         }
6378
6379         /*
6380          * Run through the mode page, checking to make sure that the bits
6381          * the user changed are actually legal for him to change.
6382          */
6383         for (i = 0; i < page_index->page_len; i++) {
6384                 uint8_t *user_byte, *change_mask, *current_byte;
6385                 int bad_bit;
6386                 int j;
6387
6388                 user_byte = (uint8_t *)page_header + i;
6389                 change_mask = page_index->page_data +
6390                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6391                 current_byte = page_index->page_data +
6392                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6393
6394                 /*
6395                  * Check to see whether the user set any bits in this byte
6396                  * that he is not allowed to set.
6397                  */
6398                 if ((*user_byte & ~(*change_mask)) ==
6399                     (*current_byte & ~(*change_mask)))
6400                         continue;
6401
6402                 /*
6403                  * Go through bit by bit to determine which one is illegal.
6404                  */
6405                 bad_bit = 0;
6406                 for (j = 7; j >= 0; j--) {
6407                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6408                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6409                                 bad_bit = i;
6410                                 break;
6411                         }
6412                 }
6413                 ctl_set_invalid_field(ctsio,
6414                                       /*sks_valid*/ 1,
6415                                       /*command*/ 0,
6416                                       /*field*/ *len_used + i,
6417                                       /*bit_valid*/ 1,
6418                                       /*bit*/ bad_bit);
6419                 free(ctsio->kern_data_ptr, M_CTL);
6420                 ctl_done((union ctl_io *)ctsio);
6421                 return (CTL_RETVAL_COMPLETE);
6422         }
6423
6424         /*
6425          * Decrement these before we call the page handler, since we may
6426          * end up getting called back one way or another before the handler
6427          * returns to this context.
6428          */
6429         *len_left -= page_index->page_len;
6430         *len_used += page_index->page_len;
6431
6432         retval = page_index->select_handler(ctsio, page_index,
6433                                             (uint8_t *)page_header);
6434
6435         /*
6436          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6437          * wait until this queued command completes to finish processing
6438          * the mode page.  If it returns anything other than
6439          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6440          * already set the sense information, freed the data pointer, and
6441          * completed the io for us.
6442          */
6443         if (retval != CTL_RETVAL_COMPLETE)
6444                 goto bailout_no_done;
6445
6446         /*
6447          * If the initiator sent us more than one page, parse the next one.
6448          */
6449         if (*len_left > 0)
6450                 goto do_next_page;
6451
6452         ctl_set_success(ctsio);
6453         free(ctsio->kern_data_ptr, M_CTL);
6454         ctl_done((union ctl_io *)ctsio);
6455
6456 bailout_no_done:
6457
6458         return (CTL_RETVAL_COMPLETE);
6459
6460 }
6461
6462 int
6463 ctl_mode_select(struct ctl_scsiio *ctsio)
6464 {
6465         int param_len, pf, sp;
6466         int header_size, bd_len;
6467         int len_left, len_used;
6468         struct ctl_page_index *page_index;
6469         struct ctl_lun *lun;
6470         int control_dev, page_len;
6471         union ctl_modepage_info *modepage_info;
6472         int retval;
6473
6474         pf = 0;
6475         sp = 0;
6476         page_len = 0;
6477         len_used = 0;
6478         len_left = 0;
6479         retval = 0;
6480         bd_len = 0;
6481         page_index = NULL;
6482
6483         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6484
6485         if (lun->be_lun->lun_type != T_DIRECT)
6486                 control_dev = 1;
6487         else
6488                 control_dev = 0;
6489
6490         switch (ctsio->cdb[0]) {
6491         case MODE_SELECT_6: {
6492                 struct scsi_mode_select_6 *cdb;
6493
6494                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6495
6496                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6497                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6498
6499                 param_len = cdb->length;
6500                 header_size = sizeof(struct scsi_mode_header_6);
6501                 break;
6502         }
6503         case MODE_SELECT_10: {
6504                 struct scsi_mode_select_10 *cdb;
6505
6506                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6507
6508                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6509                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6510
6511                 param_len = scsi_2btoul(cdb->length);
6512                 header_size = sizeof(struct scsi_mode_header_10);
6513                 break;
6514         }
6515         default:
6516                 ctl_set_invalid_opcode(ctsio);
6517                 ctl_done((union ctl_io *)ctsio);
6518                 return (CTL_RETVAL_COMPLETE);
6519                 break; /* NOTREACHED */
6520         }
6521
6522         /*
6523          * From SPC-3:
6524          * "A parameter list length of zero indicates that the Data-Out Buffer
6525          * shall be empty. This condition shall not be considered as an error."
6526          */
6527         if (param_len == 0) {
6528                 ctl_set_success(ctsio);
6529                 ctl_done((union ctl_io *)ctsio);
6530                 return (CTL_RETVAL_COMPLETE);
6531         }
6532
6533         /*
6534          * Since we'll hit this the first time through, prior to
6535          * allocation, we don't need to free a data buffer here.
6536          */
6537         if (param_len < header_size) {
6538                 ctl_set_param_len_error(ctsio);
6539                 ctl_done((union ctl_io *)ctsio);
6540                 return (CTL_RETVAL_COMPLETE);
6541         }
6542
6543         /*
6544          * Allocate the data buffer and grab the user's data.  In theory,
6545          * we shouldn't have to sanity check the parameter list length here
6546          * because the maximum size is 64K.  We should be able to malloc
6547          * that much without too many problems.
6548          */
6549         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6550                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6551                 ctsio->kern_data_len = param_len;
6552                 ctsio->kern_total_len = param_len;
6553                 ctsio->kern_data_resid = 0;
6554                 ctsio->kern_rel_offset = 0;
6555                 ctsio->kern_sg_entries = 0;
6556                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6557                 ctsio->be_move_done = ctl_config_move_done;
6558                 ctl_datamove((union ctl_io *)ctsio);
6559
6560                 return (CTL_RETVAL_COMPLETE);
6561         }
6562
6563         switch (ctsio->cdb[0]) {
6564         case MODE_SELECT_6: {
6565                 struct scsi_mode_header_6 *mh6;
6566
6567                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6568                 bd_len = mh6->blk_desc_len;
6569                 break;
6570         }
6571         case MODE_SELECT_10: {
6572                 struct scsi_mode_header_10 *mh10;
6573
6574                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6575                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6576                 break;
6577         }
6578         default:
6579                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6580                 break;
6581         }
6582
6583         if (param_len < (header_size + bd_len)) {
6584                 free(ctsio->kern_data_ptr, M_CTL);
6585                 ctl_set_param_len_error(ctsio);
6586                 ctl_done((union ctl_io *)ctsio);
6587                 return (CTL_RETVAL_COMPLETE);
6588         }
6589
6590         /*
6591          * Set the IO_CONT flag, so that if this I/O gets passed to
6592          * ctl_config_write_done(), it'll get passed back to
6593          * ctl_do_mode_select() for further processing, or completion if
6594          * we're all done.
6595          */
6596         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6597         ctsio->io_cont = ctl_do_mode_select;
6598
6599         modepage_info = (union ctl_modepage_info *)
6600                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6601
6602         memset(modepage_info, 0, sizeof(*modepage_info));
6603
6604         len_left = param_len - header_size - bd_len;
6605         len_used = header_size + bd_len;
6606
6607         modepage_info->header.len_left = len_left;
6608         modepage_info->header.len_used = len_used;
6609
6610         return (ctl_do_mode_select((union ctl_io *)ctsio));
6611 }
6612
6613 int
6614 ctl_mode_sense(struct ctl_scsiio *ctsio)
6615 {
6616         struct ctl_lun *lun;
6617         int pc, page_code, dbd, llba, subpage;
6618         int alloc_len, page_len, header_len, total_len;
6619         struct scsi_mode_block_descr *block_desc;
6620         struct ctl_page_index *page_index;
6621         int control_dev;
6622
6623         dbd = 0;
6624         llba = 0;
6625         block_desc = NULL;
6626         page_index = NULL;
6627
6628         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6629
6630         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6631
6632         if (lun->be_lun->lun_type != T_DIRECT)
6633                 control_dev = 1;
6634         else
6635                 control_dev = 0;
6636
6637         if (lun->flags & CTL_LUN_PR_RESERVED) {
6638                 uint32_t residx;
6639
6640                 /*
6641                  * XXX KDM need a lock here.
6642                  */
6643                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6644                 if ((lun->res_type == SPR_TYPE_EX_AC
6645                   && residx != lun->pr_res_idx)
6646                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6647                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6648                   && lun->pr_keys[residx] == 0)) {
6649                         ctl_set_reservation_conflict(ctsio);
6650                         ctl_done((union ctl_io *)ctsio);
6651                         return (CTL_RETVAL_COMPLETE);
6652                 }
6653         }
6654
6655         switch (ctsio->cdb[0]) {
6656         case MODE_SENSE_6: {
6657                 struct scsi_mode_sense_6 *cdb;
6658
6659                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6660
6661                 header_len = sizeof(struct scsi_mode_hdr_6);
6662                 if (cdb->byte2 & SMS_DBD)
6663                         dbd = 1;
6664                 else
6665                         header_len += sizeof(struct scsi_mode_block_descr);
6666
6667                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6668                 page_code = cdb->page & SMS_PAGE_CODE;
6669                 subpage = cdb->subpage;
6670                 alloc_len = cdb->length;
6671                 break;
6672         }
6673         case MODE_SENSE_10: {
6674                 struct scsi_mode_sense_10 *cdb;
6675
6676                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6677
6678                 header_len = sizeof(struct scsi_mode_hdr_10);
6679
6680                 if (cdb->byte2 & SMS_DBD)
6681                         dbd = 1;
6682                 else
6683                         header_len += sizeof(struct scsi_mode_block_descr);
6684                 if (cdb->byte2 & SMS10_LLBAA)
6685                         llba = 1;
6686                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6687                 page_code = cdb->page & SMS_PAGE_CODE;
6688                 subpage = cdb->subpage;
6689                 alloc_len = scsi_2btoul(cdb->length);
6690                 break;
6691         }
6692         default:
6693                 ctl_set_invalid_opcode(ctsio);
6694                 ctl_done((union ctl_io *)ctsio);
6695                 return (CTL_RETVAL_COMPLETE);
6696                 break; /* NOTREACHED */
6697         }
6698
6699         /*
6700          * We have to make a first pass through to calculate the size of
6701          * the pages that match the user's query.  Then we allocate enough
6702          * memory to hold it, and actually copy the data into the buffer.
6703          */
6704         switch (page_code) {
6705         case SMS_ALL_PAGES_PAGE: {
6706                 int i;
6707
6708                 page_len = 0;
6709
6710                 /*
6711                  * At the moment, values other than 0 and 0xff here are
6712                  * reserved according to SPC-3.
6713                  */
6714                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6715                  && (subpage != SMS_SUBPAGE_ALL)) {
6716                         ctl_set_invalid_field(ctsio,
6717                                               /*sks_valid*/ 1,
6718                                               /*command*/ 1,
6719                                               /*field*/ 3,
6720                                               /*bit_valid*/ 0,
6721                                               /*bit*/ 0);
6722                         ctl_done((union ctl_io *)ctsio);
6723                         return (CTL_RETVAL_COMPLETE);
6724                 }
6725
6726                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6727                         if ((control_dev != 0)
6728                          && (lun->mode_pages.index[i].page_flags &
6729                              CTL_PAGE_FLAG_DISK_ONLY))
6730                                 continue;
6731
6732                         /*
6733                          * We don't use this subpage if the user didn't
6734                          * request all subpages.
6735                          */
6736                         if ((lun->mode_pages.index[i].subpage != 0)
6737                          && (subpage == SMS_SUBPAGE_PAGE_0))
6738                                 continue;
6739
6740 #if 0
6741                         printf("found page %#x len %d\n",
6742                                lun->mode_pages.index[i].page_code &
6743                                SMPH_PC_MASK,
6744                                lun->mode_pages.index[i].page_len);
6745 #endif
6746                         page_len += lun->mode_pages.index[i].page_len;
6747                 }
6748                 break;
6749         }
6750         default: {
6751                 int i;
6752
6753                 page_len = 0;
6754
6755                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6756                         /* Look for the right page code */
6757                         if ((lun->mode_pages.index[i].page_code &
6758                              SMPH_PC_MASK) != page_code)
6759                                 continue;
6760
6761                         /* Look for the right subpage or the subpage wildcard*/
6762                         if ((lun->mode_pages.index[i].subpage != subpage)
6763                          && (subpage != SMS_SUBPAGE_ALL))
6764                                 continue;
6765
6766                         /* Make sure the page is supported for this dev type */
6767                         if ((control_dev != 0)
6768                          && (lun->mode_pages.index[i].page_flags &
6769                              CTL_PAGE_FLAG_DISK_ONLY))
6770                                 continue;
6771
6772 #if 0
6773                         printf("found page %#x len %d\n",
6774                                lun->mode_pages.index[i].page_code &
6775                                SMPH_PC_MASK,
6776                                lun->mode_pages.index[i].page_len);
6777 #endif
6778
6779                         page_len += lun->mode_pages.index[i].page_len;
6780                 }
6781
6782                 if (page_len == 0) {
6783                         ctl_set_invalid_field(ctsio,
6784                                               /*sks_valid*/ 1,
6785                                               /*command*/ 1,
6786                                               /*field*/ 2,
6787                                               /*bit_valid*/ 1,
6788                                               /*bit*/ 5);
6789                         ctl_done((union ctl_io *)ctsio);
6790                         return (CTL_RETVAL_COMPLETE);
6791                 }
6792                 break;
6793         }
6794         }
6795
6796         total_len = header_len + page_len;
6797 #if 0
6798         printf("header_len = %d, page_len = %d, total_len = %d\n",
6799                header_len, page_len, total_len);
6800 #endif
6801
6802         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6803         ctsio->kern_sg_entries = 0;
6804         ctsio->kern_data_resid = 0;
6805         ctsio->kern_rel_offset = 0;
6806         if (total_len < alloc_len) {
6807                 ctsio->residual = alloc_len - total_len;
6808                 ctsio->kern_data_len = total_len;
6809                 ctsio->kern_total_len = total_len;
6810         } else {
6811                 ctsio->residual = 0;
6812                 ctsio->kern_data_len = alloc_len;
6813                 ctsio->kern_total_len = alloc_len;
6814         }
6815
6816         switch (ctsio->cdb[0]) {
6817         case MODE_SENSE_6: {
6818                 struct scsi_mode_hdr_6 *header;
6819
6820                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6821
6822                 header->datalen = ctl_min(total_len - 1, 254);
6823                 if (control_dev == 0) {
6824                         header->dev_specific = 0x10; /* DPOFUA */
6825                         if ((lun->flags & CTL_LUN_READONLY) ||
6826                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6827                             .eca_and_aen & SCP_SWP) != 0)
6828                                     header->dev_specific |= 0x80; /* WP */
6829                 }
6830                 if (dbd)
6831                         header->block_descr_len = 0;
6832                 else
6833                         header->block_descr_len =
6834                                 sizeof(struct scsi_mode_block_descr);
6835                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6836                 break;
6837         }
6838         case MODE_SENSE_10: {
6839                 struct scsi_mode_hdr_10 *header;
6840                 int datalen;
6841
6842                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6843
6844                 datalen = ctl_min(total_len - 2, 65533);
6845                 scsi_ulto2b(datalen, header->datalen);
6846                 if (control_dev == 0) {
6847                         header->dev_specific = 0x10; /* DPOFUA */
6848                         if ((lun->flags & CTL_LUN_READONLY) ||
6849                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6850                             .eca_and_aen & SCP_SWP) != 0)
6851                                     header->dev_specific |= 0x80; /* WP */
6852                 }
6853                 if (dbd)
6854                         scsi_ulto2b(0, header->block_descr_len);
6855                 else
6856                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6857                                     header->block_descr_len);
6858                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6859                 break;
6860         }
6861         default:
6862                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6863                 break; /* NOTREACHED */
6864         }
6865
6866         /*
6867          * If we've got a disk, use its blocksize in the block
6868          * descriptor.  Otherwise, just set it to 0.
6869          */
6870         if (dbd == 0) {
6871                 if (control_dev == 0)
6872                         scsi_ulto3b(lun->be_lun->blocksize,
6873                                     block_desc->block_len);
6874                 else
6875                         scsi_ulto3b(0, block_desc->block_len);
6876         }
6877
6878         switch (page_code) {
6879         case SMS_ALL_PAGES_PAGE: {
6880                 int i, data_used;
6881
6882                 data_used = header_len;
6883                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6884                         struct ctl_page_index *page_index;
6885
6886                         page_index = &lun->mode_pages.index[i];
6887
6888                         if ((control_dev != 0)
6889                          && (page_index->page_flags &
6890                             CTL_PAGE_FLAG_DISK_ONLY))
6891                                 continue;
6892
6893                         /*
6894                          * We don't use this subpage if the user didn't
6895                          * request all subpages.  We already checked (above)
6896                          * to make sure the user only specified a subpage
6897                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6898                          */
6899                         if ((page_index->subpage != 0)
6900                          && (subpage == SMS_SUBPAGE_PAGE_0))
6901                                 continue;
6902
6903                         /*
6904                          * Call the handler, if it exists, to update the
6905                          * page to the latest values.
6906                          */
6907                         if (page_index->sense_handler != NULL)
6908                                 page_index->sense_handler(ctsio, page_index,pc);
6909
6910                         memcpy(ctsio->kern_data_ptr + data_used,
6911                                page_index->page_data +
6912                                (page_index->page_len * pc),
6913                                page_index->page_len);
6914                         data_used += page_index->page_len;
6915                 }
6916                 break;
6917         }
6918         default: {
6919                 int i, data_used;
6920
6921                 data_used = header_len;
6922
6923                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6924                         struct ctl_page_index *page_index;
6925
6926                         page_index = &lun->mode_pages.index[i];
6927
6928                         /* Look for the right page code */
6929                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6930                                 continue;
6931
6932                         /* Look for the right subpage or the subpage wildcard*/
6933                         if ((page_index->subpage != subpage)
6934                          && (subpage != SMS_SUBPAGE_ALL))
6935                                 continue;
6936
6937                         /* Make sure the page is supported for this dev type */
6938                         if ((control_dev != 0)
6939                          && (page_index->page_flags &
6940                              CTL_PAGE_FLAG_DISK_ONLY))
6941                                 continue;
6942
6943                         /*
6944                          * Call the handler, if it exists, to update the
6945                          * page to the latest values.
6946                          */
6947                         if (page_index->sense_handler != NULL)
6948                                 page_index->sense_handler(ctsio, page_index,pc);
6949
6950                         memcpy(ctsio->kern_data_ptr + data_used,
6951                                page_index->page_data +
6952                                (page_index->page_len * pc),
6953                                page_index->page_len);
6954                         data_used += page_index->page_len;
6955                 }
6956                 break;
6957         }
6958         }
6959
6960         ctsio->scsi_status = SCSI_STATUS_OK;
6961
6962         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6963         ctsio->be_move_done = ctl_config_move_done;
6964         ctl_datamove((union ctl_io *)ctsio);
6965
6966         return (CTL_RETVAL_COMPLETE);
6967 }
6968
6969 int
6970 ctl_log_sense(struct ctl_scsiio *ctsio)
6971 {
6972         struct ctl_lun *lun;
6973         int i, pc, page_code, subpage;
6974         int alloc_len, total_len;
6975         struct ctl_page_index *page_index;
6976         struct scsi_log_sense *cdb;
6977         struct scsi_log_header *header;
6978
6979         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6980
6981         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6982         cdb = (struct scsi_log_sense *)ctsio->cdb;
6983         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6984         page_code = cdb->page & SLS_PAGE_CODE;
6985         subpage = cdb->subpage;
6986         alloc_len = scsi_2btoul(cdb->length);
6987
6988         page_index = NULL;
6989         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6990                 page_index = &lun->log_pages.index[i];
6991
6992                 /* Look for the right page code */
6993                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6994                         continue;
6995
6996                 /* Look for the right subpage or the subpage wildcard*/
6997                 if (page_index->subpage != subpage)
6998                         continue;
6999
7000                 break;
7001         }
7002         if (i >= CTL_NUM_LOG_PAGES) {
7003                 ctl_set_invalid_field(ctsio,
7004                                       /*sks_valid*/ 1,
7005                                       /*command*/ 1,
7006                                       /*field*/ 2,
7007                                       /*bit_valid*/ 0,
7008                                       /*bit*/ 0);
7009                 ctl_done((union ctl_io *)ctsio);
7010                 return (CTL_RETVAL_COMPLETE);
7011         }
7012
7013         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7014
7015         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7016         ctsio->kern_sg_entries = 0;
7017         ctsio->kern_data_resid = 0;
7018         ctsio->kern_rel_offset = 0;
7019         if (total_len < alloc_len) {
7020                 ctsio->residual = alloc_len - total_len;
7021                 ctsio->kern_data_len = total_len;
7022                 ctsio->kern_total_len = total_len;
7023         } else {
7024                 ctsio->residual = 0;
7025                 ctsio->kern_data_len = alloc_len;
7026                 ctsio->kern_total_len = alloc_len;
7027         }
7028
7029         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7030         header->page = page_index->page_code;
7031         if (page_index->subpage) {
7032                 header->page |= SL_SPF;
7033                 header->subpage = page_index->subpage;
7034         }
7035         scsi_ulto2b(page_index->page_len, header->datalen);
7036
7037         /*
7038          * Call the handler, if it exists, to update the
7039          * page to the latest values.
7040          */
7041         if (page_index->sense_handler != NULL)
7042                 page_index->sense_handler(ctsio, page_index, pc);
7043
7044         memcpy(header + 1, page_index->page_data, page_index->page_len);
7045
7046         ctsio->scsi_status = SCSI_STATUS_OK;
7047         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7048         ctsio->be_move_done = ctl_config_move_done;
7049         ctl_datamove((union ctl_io *)ctsio);
7050
7051         return (CTL_RETVAL_COMPLETE);
7052 }
7053
7054 int
7055 ctl_read_capacity(struct ctl_scsiio *ctsio)
7056 {
7057         struct scsi_read_capacity *cdb;
7058         struct scsi_read_capacity_data *data;
7059         struct ctl_lun *lun;
7060         uint32_t lba;
7061
7062         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7063
7064         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7065
7066         lba = scsi_4btoul(cdb->addr);
7067         if (((cdb->pmi & SRC_PMI) == 0)
7068          && (lba != 0)) {
7069                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7070                                       /*sks_valid*/ 1,
7071                                       /*command*/ 1,
7072                                       /*field*/ 2,
7073                                       /*bit_valid*/ 0,
7074                                       /*bit*/ 0);
7075                 ctl_done((union ctl_io *)ctsio);
7076                 return (CTL_RETVAL_COMPLETE);
7077         }
7078
7079         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7080
7081         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7082         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7083         ctsio->residual = 0;
7084         ctsio->kern_data_len = sizeof(*data);
7085         ctsio->kern_total_len = sizeof(*data);
7086         ctsio->kern_data_resid = 0;
7087         ctsio->kern_rel_offset = 0;
7088         ctsio->kern_sg_entries = 0;
7089
7090         /*
7091          * If the maximum LBA is greater than 0xfffffffe, the user must
7092          * issue a SERVICE ACTION IN (16) command, with the read capacity
7093          * serivce action set.
7094          */
7095         if (lun->be_lun->maxlba > 0xfffffffe)
7096                 scsi_ulto4b(0xffffffff, data->addr);
7097         else
7098                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7099
7100         /*
7101          * XXX KDM this may not be 512 bytes...
7102          */
7103         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7104
7105         ctsio->scsi_status = SCSI_STATUS_OK;
7106
7107         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7108         ctsio->be_move_done = ctl_config_move_done;
7109         ctl_datamove((union ctl_io *)ctsio);
7110
7111         return (CTL_RETVAL_COMPLETE);
7112 }
7113
7114 int
7115 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7116 {
7117         struct scsi_read_capacity_16 *cdb;
7118         struct scsi_read_capacity_data_long *data;
7119         struct ctl_lun *lun;
7120         uint64_t lba;
7121         uint32_t alloc_len;
7122
7123         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7124
7125         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7126
7127         alloc_len = scsi_4btoul(cdb->alloc_len);
7128         lba = scsi_8btou64(cdb->addr);
7129
7130         if ((cdb->reladr & SRC16_PMI)
7131          && (lba != 0)) {
7132                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7133                                       /*sks_valid*/ 1,
7134                                       /*command*/ 1,
7135                                       /*field*/ 2,
7136                                       /*bit_valid*/ 0,
7137                                       /*bit*/ 0);
7138                 ctl_done((union ctl_io *)ctsio);
7139                 return (CTL_RETVAL_COMPLETE);
7140         }
7141
7142         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7143
7144         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7145         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7146
7147         if (sizeof(*data) < alloc_len) {
7148                 ctsio->residual = alloc_len - sizeof(*data);
7149                 ctsio->kern_data_len = sizeof(*data);
7150                 ctsio->kern_total_len = sizeof(*data);
7151         } else {
7152                 ctsio->residual = 0;
7153                 ctsio->kern_data_len = alloc_len;
7154                 ctsio->kern_total_len = alloc_len;
7155         }
7156         ctsio->kern_data_resid = 0;
7157         ctsio->kern_rel_offset = 0;
7158         ctsio->kern_sg_entries = 0;
7159
7160         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7161         /* XXX KDM this may not be 512 bytes... */
7162         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7163         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7164         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7165         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7166                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7167
7168         ctsio->scsi_status = SCSI_STATUS_OK;
7169
7170         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7171         ctsio->be_move_done = ctl_config_move_done;
7172         ctl_datamove((union ctl_io *)ctsio);
7173
7174         return (CTL_RETVAL_COMPLETE);
7175 }
7176
7177 int
7178 ctl_read_defect(struct ctl_scsiio *ctsio)
7179 {
7180         struct scsi_read_defect_data_10 *ccb10;
7181         struct scsi_read_defect_data_12 *ccb12;
7182         struct scsi_read_defect_data_hdr_10 *data10;
7183         struct scsi_read_defect_data_hdr_12 *data12;
7184         struct ctl_lun *lun;
7185         uint32_t alloc_len, data_len;
7186         uint8_t format;
7187
7188         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7189
7190         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7191         if (lun->flags & CTL_LUN_PR_RESERVED) {
7192                 uint32_t residx;
7193
7194                 /*
7195                  * XXX KDM need a lock here.
7196                  */
7197                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7198                 if ((lun->res_type == SPR_TYPE_EX_AC
7199                   && residx != lun->pr_res_idx)
7200                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
7201                    || lun->res_type == SPR_TYPE_EX_AC_AR)
7202                   && lun->pr_keys[residx] == 0)) {
7203                         ctl_set_reservation_conflict(ctsio);
7204                         ctl_done((union ctl_io *)ctsio);
7205                         return (CTL_RETVAL_COMPLETE);
7206                 }
7207         }
7208
7209         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7210                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7211                 format = ccb10->format;
7212                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7213                 data_len = sizeof(*data10);
7214         } else {
7215                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7216                 format = ccb12->format;
7217                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7218                 data_len = sizeof(*data12);
7219         }
7220         if (alloc_len == 0) {
7221                 ctl_set_success(ctsio);
7222                 ctl_done((union ctl_io *)ctsio);
7223                 return (CTL_RETVAL_COMPLETE);
7224         }
7225
7226         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7227         if (data_len < alloc_len) {
7228                 ctsio->residual = alloc_len - data_len;
7229                 ctsio->kern_data_len = data_len;
7230                 ctsio->kern_total_len = data_len;
7231         } else {
7232                 ctsio->residual = 0;
7233                 ctsio->kern_data_len = alloc_len;
7234                 ctsio->kern_total_len = alloc_len;
7235         }
7236         ctsio->kern_data_resid = 0;
7237         ctsio->kern_rel_offset = 0;
7238         ctsio->kern_sg_entries = 0;
7239
7240         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7241                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7242                     ctsio->kern_data_ptr;
7243                 data10->format = format;
7244                 scsi_ulto2b(0, data10->length);
7245         } else {
7246                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7247                     ctsio->kern_data_ptr;
7248                 data12->format = format;
7249                 scsi_ulto2b(0, data12->generation);
7250                 scsi_ulto4b(0, data12->length);
7251         }
7252
7253         ctsio->scsi_status = SCSI_STATUS_OK;
7254         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7255         ctsio->be_move_done = ctl_config_move_done;
7256         ctl_datamove((union ctl_io *)ctsio);
7257         return (CTL_RETVAL_COMPLETE);
7258 }
7259
7260 int
7261 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7262 {
7263         struct scsi_maintenance_in *cdb;
7264         int retval;
7265         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7266         int num_target_port_groups, num_target_ports, single;
7267         struct ctl_lun *lun;
7268         struct ctl_softc *softc;
7269         struct ctl_port *port;
7270         struct scsi_target_group_data *rtg_ptr;
7271         struct scsi_target_group_data_extended *rtg_ext_ptr;
7272         struct scsi_target_port_group_descriptor *tpg_desc;
7273
7274         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7275
7276         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7277         softc = control_softc;
7278         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7279
7280         retval = CTL_RETVAL_COMPLETE;
7281
7282         switch (cdb->byte2 & STG_PDF_MASK) {
7283         case STG_PDF_LENGTH:
7284                 ext = 0;
7285                 break;
7286         case STG_PDF_EXTENDED:
7287                 ext = 1;
7288                 break;
7289         default:
7290                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7291                                       /*sks_valid*/ 1,
7292                                       /*command*/ 1,
7293                                       /*field*/ 2,
7294                                       /*bit_valid*/ 1,
7295                                       /*bit*/ 5);
7296                 ctl_done((union ctl_io *)ctsio);
7297                 return(retval);
7298         }
7299
7300         single = ctl_is_single;
7301         if (single)
7302                 num_target_port_groups = 1;
7303         else
7304                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7305         num_target_ports = 0;
7306         mtx_lock(&softc->ctl_lock);
7307         STAILQ_FOREACH(port, &softc->port_list, links) {
7308                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7309                         continue;
7310                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7311                         continue;
7312                 num_target_ports++;
7313         }
7314         mtx_unlock(&softc->ctl_lock);
7315
7316         if (ext)
7317                 total_len = sizeof(struct scsi_target_group_data_extended);
7318         else
7319                 total_len = sizeof(struct scsi_target_group_data);
7320         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7321                 num_target_port_groups +
7322             sizeof(struct scsi_target_port_descriptor) *
7323                 num_target_ports * num_target_port_groups;
7324
7325         alloc_len = scsi_4btoul(cdb->length);
7326
7327         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7328
7329         ctsio->kern_sg_entries = 0;
7330
7331         if (total_len < alloc_len) {
7332                 ctsio->residual = alloc_len - total_len;
7333                 ctsio->kern_data_len = total_len;
7334                 ctsio->kern_total_len = total_len;
7335         } else {
7336                 ctsio->residual = 0;
7337                 ctsio->kern_data_len = alloc_len;
7338                 ctsio->kern_total_len = alloc_len;
7339         }
7340         ctsio->kern_data_resid = 0;
7341         ctsio->kern_rel_offset = 0;
7342
7343         if (ext) {
7344                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7345                     ctsio->kern_data_ptr;
7346                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7347                 rtg_ext_ptr->format_type = 0x10;
7348                 rtg_ext_ptr->implicit_transition_time = 0;
7349                 tpg_desc = &rtg_ext_ptr->groups[0];
7350         } else {
7351                 rtg_ptr = (struct scsi_target_group_data *)
7352                     ctsio->kern_data_ptr;
7353                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7354                 tpg_desc = &rtg_ptr->groups[0];
7355         }
7356
7357         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7358         mtx_lock(&softc->ctl_lock);
7359         for (g = 0; g < num_target_port_groups; g++) {
7360                 if (g == pg)
7361                         tpg_desc->pref_state = TPG_PRIMARY |
7362                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7363                 else
7364                         tpg_desc->pref_state =
7365                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7366                 tpg_desc->support = TPG_AO_SUP;
7367                 if (!single)
7368                         tpg_desc->support |= TPG_AN_SUP;
7369                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7370                 tpg_desc->status = TPG_IMPLICIT;
7371                 pc = 0;
7372                 STAILQ_FOREACH(port, &softc->port_list, links) {
7373                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7374                                 continue;
7375                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7376                             CTL_MAX_LUNS)
7377                                 continue;
7378                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7379                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7380                             relative_target_port_identifier);
7381                         pc++;
7382                 }
7383                 tpg_desc->target_port_count = pc;
7384                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7385                     &tpg_desc->descriptors[pc];
7386         }
7387         mtx_unlock(&softc->ctl_lock);
7388
7389         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7390         ctsio->be_move_done = ctl_config_move_done;
7391
7392         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7393                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7394                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7395                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7396                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7397
7398         ctl_datamove((union ctl_io *)ctsio);
7399         return(retval);
7400 }
7401
7402 int
7403 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7404 {
7405         struct ctl_lun *lun;
7406         struct scsi_report_supported_opcodes *cdb;
7407         const struct ctl_cmd_entry *entry, *sentry;
7408         struct scsi_report_supported_opcodes_all *all;
7409         struct scsi_report_supported_opcodes_descr *descr;
7410         struct scsi_report_supported_opcodes_one *one;
7411         int retval;
7412         int alloc_len, total_len;
7413         int opcode, service_action, i, j, num;
7414
7415         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7416
7417         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7418         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7419
7420         retval = CTL_RETVAL_COMPLETE;
7421
7422         opcode = cdb->requested_opcode;
7423         service_action = scsi_2btoul(cdb->requested_service_action);
7424         switch (cdb->options & RSO_OPTIONS_MASK) {
7425         case RSO_OPTIONS_ALL:
7426                 num = 0;
7427                 for (i = 0; i < 256; i++) {
7428                         entry = &ctl_cmd_table[i];
7429                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7430                                 for (j = 0; j < 32; j++) {
7431                                         sentry = &((const struct ctl_cmd_entry *)
7432                                             entry->execute)[j];
7433                                         if (ctl_cmd_applicable(
7434                                             lun->be_lun->lun_type, sentry))
7435                                                 num++;
7436                                 }
7437                         } else {
7438                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7439                                     entry))
7440                                         num++;
7441                         }
7442                 }
7443                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7444                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7445                 break;
7446         case RSO_OPTIONS_OC:
7447                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7448                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7449                                               /*sks_valid*/ 1,
7450                                               /*command*/ 1,
7451                                               /*field*/ 2,
7452                                               /*bit_valid*/ 1,
7453                                               /*bit*/ 2);
7454                         ctl_done((union ctl_io *)ctsio);
7455                         return (CTL_RETVAL_COMPLETE);
7456                 }
7457                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7458                 break;
7459         case RSO_OPTIONS_OC_SA:
7460                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7461                     service_action >= 32) {
7462                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7463                                               /*sks_valid*/ 1,
7464                                               /*command*/ 1,
7465                                               /*field*/ 2,
7466                                               /*bit_valid*/ 1,
7467                                               /*bit*/ 2);
7468                         ctl_done((union ctl_io *)ctsio);
7469                         return (CTL_RETVAL_COMPLETE);
7470                 }
7471                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7472                 break;
7473         default:
7474                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7475                                       /*sks_valid*/ 1,
7476                                       /*command*/ 1,
7477                                       /*field*/ 2,
7478                                       /*bit_valid*/ 1,
7479                                       /*bit*/ 2);
7480                 ctl_done((union ctl_io *)ctsio);
7481                 return (CTL_RETVAL_COMPLETE);
7482         }
7483
7484         alloc_len = scsi_4btoul(cdb->length);
7485
7486         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7487
7488         ctsio->kern_sg_entries = 0;
7489
7490         if (total_len < alloc_len) {
7491                 ctsio->residual = alloc_len - total_len;
7492                 ctsio->kern_data_len = total_len;
7493                 ctsio->kern_total_len = total_len;
7494         } else {
7495                 ctsio->residual = 0;
7496                 ctsio->kern_data_len = alloc_len;
7497                 ctsio->kern_total_len = alloc_len;
7498         }
7499         ctsio->kern_data_resid = 0;
7500         ctsio->kern_rel_offset = 0;
7501
7502         switch (cdb->options & RSO_OPTIONS_MASK) {
7503         case RSO_OPTIONS_ALL:
7504                 all = (struct scsi_report_supported_opcodes_all *)
7505                     ctsio->kern_data_ptr;
7506                 num = 0;
7507                 for (i = 0; i < 256; i++) {
7508                         entry = &ctl_cmd_table[i];
7509                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7510                                 for (j = 0; j < 32; j++) {
7511                                         sentry = &((const struct ctl_cmd_entry *)
7512                                             entry->execute)[j];
7513                                         if (!ctl_cmd_applicable(
7514                                             lun->be_lun->lun_type, sentry))
7515                                                 continue;
7516                                         descr = &all->descr[num++];
7517                                         descr->opcode = i;
7518                                         scsi_ulto2b(j, descr->service_action);
7519                                         descr->flags = RSO_SERVACTV;
7520                                         scsi_ulto2b(sentry->length,
7521                                             descr->cdb_length);
7522                                 }
7523                         } else {
7524                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7525                                     entry))
7526                                         continue;
7527                                 descr = &all->descr[num++];
7528                                 descr->opcode = i;
7529                                 scsi_ulto2b(0, descr->service_action);
7530                                 descr->flags = 0;
7531                                 scsi_ulto2b(entry->length, descr->cdb_length);
7532                         }
7533                 }
7534                 scsi_ulto4b(
7535                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7536                     all->length);
7537                 break;
7538         case RSO_OPTIONS_OC:
7539                 one = (struct scsi_report_supported_opcodes_one *)
7540                     ctsio->kern_data_ptr;
7541                 entry = &ctl_cmd_table[opcode];
7542                 goto fill_one;
7543         case RSO_OPTIONS_OC_SA:
7544                 one = (struct scsi_report_supported_opcodes_one *)
7545                     ctsio->kern_data_ptr;
7546                 entry = &ctl_cmd_table[opcode];
7547                 entry = &((const struct ctl_cmd_entry *)
7548                     entry->execute)[service_action];
7549 fill_one:
7550                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7551                         one->support = 3;
7552                         scsi_ulto2b(entry->length, one->cdb_length);
7553                         one->cdb_usage[0] = opcode;
7554                         memcpy(&one->cdb_usage[1], entry->usage,
7555                             entry->length - 1);
7556                 } else
7557                         one->support = 1;
7558                 break;
7559         }
7560
7561         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7562         ctsio->be_move_done = ctl_config_move_done;
7563
7564         ctl_datamove((union ctl_io *)ctsio);
7565         return(retval);
7566 }
7567
7568 int
7569 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7570 {
7571         struct ctl_lun *lun;
7572         struct scsi_report_supported_tmf *cdb;
7573         struct scsi_report_supported_tmf_data *data;
7574         int retval;
7575         int alloc_len, total_len;
7576
7577         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7578
7579         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7580         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7581
7582         retval = CTL_RETVAL_COMPLETE;
7583
7584         total_len = sizeof(struct scsi_report_supported_tmf_data);
7585         alloc_len = scsi_4btoul(cdb->length);
7586
7587         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7588
7589         ctsio->kern_sg_entries = 0;
7590
7591         if (total_len < alloc_len) {
7592                 ctsio->residual = alloc_len - total_len;
7593                 ctsio->kern_data_len = total_len;
7594                 ctsio->kern_total_len = total_len;
7595         } else {
7596                 ctsio->residual = 0;
7597                 ctsio->kern_data_len = alloc_len;
7598                 ctsio->kern_total_len = alloc_len;
7599         }
7600         ctsio->kern_data_resid = 0;
7601         ctsio->kern_rel_offset = 0;
7602
7603         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7604         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7605         data->byte2 |= RST_ITNRS;
7606
7607         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7608         ctsio->be_move_done = ctl_config_move_done;
7609
7610         ctl_datamove((union ctl_io *)ctsio);
7611         return (retval);
7612 }
7613
7614 int
7615 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7616 {
7617         struct ctl_lun *lun;
7618         struct scsi_report_timestamp *cdb;
7619         struct scsi_report_timestamp_data *data;
7620         struct timeval tv;
7621         int64_t timestamp;
7622         int retval;
7623         int alloc_len, total_len;
7624
7625         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7626
7627         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7628         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7629
7630         retval = CTL_RETVAL_COMPLETE;
7631
7632         total_len = sizeof(struct scsi_report_timestamp_data);
7633         alloc_len = scsi_4btoul(cdb->length);
7634
7635         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7636
7637         ctsio->kern_sg_entries = 0;
7638
7639         if (total_len < alloc_len) {
7640                 ctsio->residual = alloc_len - total_len;
7641                 ctsio->kern_data_len = total_len;
7642                 ctsio->kern_total_len = total_len;
7643         } else {
7644                 ctsio->residual = 0;
7645                 ctsio->kern_data_len = alloc_len;
7646                 ctsio->kern_total_len = alloc_len;
7647         }
7648         ctsio->kern_data_resid = 0;
7649         ctsio->kern_rel_offset = 0;
7650
7651         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7652         scsi_ulto2b(sizeof(*data) - 2, data->length);
7653         data->origin = RTS_ORIG_OUTSIDE;
7654         getmicrotime(&tv);
7655         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7656         scsi_ulto4b(timestamp >> 16, data->timestamp);
7657         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7658
7659         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7660         ctsio->be_move_done = ctl_config_move_done;
7661
7662         ctl_datamove((union ctl_io *)ctsio);
7663         return (retval);
7664 }
7665
7666 int
7667 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7668 {
7669         struct scsi_per_res_in *cdb;
7670         int alloc_len, total_len = 0;
7671         /* struct scsi_per_res_in_rsrv in_data; */
7672         struct ctl_lun *lun;
7673         struct ctl_softc *softc;
7674
7675         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7676
7677         softc = control_softc;
7678
7679         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7680
7681         alloc_len = scsi_2btoul(cdb->length);
7682
7683         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7684
7685 retry:
7686         mtx_lock(&lun->lun_lock);
7687         switch (cdb->action) {
7688         case SPRI_RK: /* read keys */
7689                 total_len = sizeof(struct scsi_per_res_in_keys) +
7690                         lun->pr_key_count *
7691                         sizeof(struct scsi_per_res_key);
7692                 break;
7693         case SPRI_RR: /* read reservation */
7694                 if (lun->flags & CTL_LUN_PR_RESERVED)
7695                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7696                 else
7697                         total_len = sizeof(struct scsi_per_res_in_header);
7698                 break;
7699         case SPRI_RC: /* report capabilities */
7700                 total_len = sizeof(struct scsi_per_res_cap);
7701                 break;
7702         case SPRI_RS: /* read full status */
7703                 total_len = sizeof(struct scsi_per_res_in_header) +
7704                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7705                     lun->pr_key_count;
7706                 break;
7707         default:
7708                 panic("Invalid PR type %x", cdb->action);
7709         }
7710         mtx_unlock(&lun->lun_lock);
7711
7712         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7713
7714         if (total_len < alloc_len) {
7715                 ctsio->residual = alloc_len - total_len;
7716                 ctsio->kern_data_len = total_len;
7717                 ctsio->kern_total_len = total_len;
7718         } else {
7719                 ctsio->residual = 0;
7720                 ctsio->kern_data_len = alloc_len;
7721                 ctsio->kern_total_len = alloc_len;
7722         }
7723
7724         ctsio->kern_data_resid = 0;
7725         ctsio->kern_rel_offset = 0;
7726         ctsio->kern_sg_entries = 0;
7727
7728         mtx_lock(&lun->lun_lock);
7729         switch (cdb->action) {
7730         case SPRI_RK: { // read keys
7731         struct scsi_per_res_in_keys *res_keys;
7732                 int i, key_count;
7733
7734                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7735
7736                 /*
7737                  * We had to drop the lock to allocate our buffer, which
7738                  * leaves time for someone to come in with another
7739                  * persistent reservation.  (That is unlikely, though,
7740                  * since this should be the only persistent reservation
7741                  * command active right now.)
7742                  */
7743                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7744                     (lun->pr_key_count *
7745                      sizeof(struct scsi_per_res_key)))){
7746                         mtx_unlock(&lun->lun_lock);
7747                         free(ctsio->kern_data_ptr, M_CTL);
7748                         printf("%s: reservation length changed, retrying\n",
7749                                __func__);
7750                         goto retry;
7751                 }
7752
7753                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7754
7755                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7756                              lun->pr_key_count, res_keys->header.length);
7757
7758                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7759                         if (lun->pr_keys[i] == 0)
7760                                 continue;
7761
7762                         /*
7763                          * We used lun->pr_key_count to calculate the
7764                          * size to allocate.  If it turns out the number of
7765                          * initiators with the registered flag set is
7766                          * larger than that (i.e. they haven't been kept in
7767                          * sync), we've got a problem.
7768                          */
7769                         if (key_count >= lun->pr_key_count) {
7770 #ifdef NEEDTOPORT
7771                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7772                                             CTL_PR_ERROR,
7773                                             csevent_LogType_Fault,
7774                                             csevent_AlertLevel_Yellow,
7775                                             csevent_FRU_ShelfController,
7776                                             csevent_FRU_Firmware,
7777                                         csevent_FRU_Unknown,
7778                                             "registered keys %d >= key "
7779                                             "count %d", key_count,
7780                                             lun->pr_key_count);
7781 #endif
7782                                 key_count++;
7783                                 continue;
7784                         }
7785                         scsi_u64to8b(lun->pr_keys[i],
7786                             res_keys->keys[key_count].key);
7787                         key_count++;
7788                 }
7789                 break;
7790         }
7791         case SPRI_RR: { // read reservation
7792                 struct scsi_per_res_in_rsrv *res;
7793                 int tmp_len, header_only;
7794
7795                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7796
7797                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7798
7799                 if (lun->flags & CTL_LUN_PR_RESERVED)
7800                 {
7801                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7802                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7803                                     res->header.length);
7804                         header_only = 0;
7805                 } else {
7806                         tmp_len = sizeof(struct scsi_per_res_in_header);
7807                         scsi_ulto4b(0, res->header.length);
7808                         header_only = 1;
7809                 }
7810
7811                 /*
7812                  * We had to drop the lock to allocate our buffer, which
7813                  * leaves time for someone to come in with another
7814                  * persistent reservation.  (That is unlikely, though,
7815                  * since this should be the only persistent reservation
7816                  * command active right now.)
7817                  */
7818                 if (tmp_len != total_len) {
7819                         mtx_unlock(&lun->lun_lock);
7820                         free(ctsio->kern_data_ptr, M_CTL);
7821                         printf("%s: reservation status changed, retrying\n",
7822                                __func__);
7823                         goto retry;
7824                 }
7825
7826                 /*
7827                  * No reservation held, so we're done.
7828                  */
7829                 if (header_only != 0)
7830                         break;
7831
7832                 /*
7833                  * If the registration is an All Registrants type, the key
7834                  * is 0, since it doesn't really matter.
7835                  */
7836                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7837                         scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7838                             res->data.reservation);
7839                 }
7840                 res->data.scopetype = lun->res_type;
7841                 break;
7842         }
7843         case SPRI_RC:     //report capabilities
7844         {
7845                 struct scsi_per_res_cap *res_cap;
7846                 uint16_t type_mask;
7847
7848                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7849                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7850                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7851                 type_mask = SPRI_TM_WR_EX_AR |
7852                             SPRI_TM_EX_AC_RO |
7853                             SPRI_TM_WR_EX_RO |
7854                             SPRI_TM_EX_AC |
7855                             SPRI_TM_WR_EX |
7856                             SPRI_TM_EX_AC_AR;
7857                 scsi_ulto2b(type_mask, res_cap->type_mask);
7858                 break;
7859         }
7860         case SPRI_RS: { // read full status
7861                 struct scsi_per_res_in_full *res_status;
7862                 struct scsi_per_res_in_full_desc *res_desc;
7863                 struct ctl_port *port;
7864                 int i, len;
7865
7866                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7867
7868                 /*
7869                  * We had to drop the lock to allocate our buffer, which
7870                  * leaves time for someone to come in with another
7871                  * persistent reservation.  (That is unlikely, though,
7872                  * since this should be the only persistent reservation
7873                  * command active right now.)
7874                  */
7875                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7876                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7877                      lun->pr_key_count)){
7878                         mtx_unlock(&lun->lun_lock);
7879                         free(ctsio->kern_data_ptr, M_CTL);
7880                         printf("%s: reservation length changed, retrying\n",
7881                                __func__);
7882                         goto retry;
7883                 }
7884
7885                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7886
7887                 res_desc = &res_status->desc[0];
7888                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7889                         if (lun->pr_keys[i] == 0)
7890                                 continue;
7891
7892                         scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7893                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7894                             (lun->pr_res_idx == i ||
7895                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7896                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7897                                 res_desc->scopetype = lun->res_type;
7898                         }
7899                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7900                             res_desc->rel_trgt_port_id);
7901                         len = 0;
7902                         port = softc->ctl_ports[
7903                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7904                         if (port != NULL)
7905                                 len = ctl_create_iid(port,
7906                                     i % CTL_MAX_INIT_PER_PORT,
7907                                     res_desc->transport_id);
7908                         scsi_ulto4b(len, res_desc->additional_length);
7909                         res_desc = (struct scsi_per_res_in_full_desc *)
7910                             &res_desc->transport_id[len];
7911                 }
7912                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7913                     res_status->header.length);
7914                 break;
7915         }
7916         default:
7917                 /*
7918                  * This is a bug, because we just checked for this above,
7919                  * and should have returned an error.
7920                  */
7921                 panic("Invalid PR type %x", cdb->action);
7922                 break; /* NOTREACHED */
7923         }
7924         mtx_unlock(&lun->lun_lock);
7925
7926         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7927         ctsio->be_move_done = ctl_config_move_done;
7928
7929         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7930                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7931                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7932                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7933                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7934
7935         ctl_datamove((union ctl_io *)ctsio);
7936
7937         return (CTL_RETVAL_COMPLETE);
7938 }
7939
7940 /*
7941  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7942  * it should return.
7943  */
7944 static int
7945 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7946                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7947                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7948                 struct scsi_per_res_out_parms* param)
7949 {
7950         union ctl_ha_msg persis_io;
7951         int retval, i;
7952         int isc_retval;
7953
7954         retval = 0;
7955
7956         mtx_lock(&lun->lun_lock);
7957         if (sa_res_key == 0) {
7958                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7959                         /* validate scope and type */
7960                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7961                              SPR_LU_SCOPE) {
7962                                 mtx_unlock(&lun->lun_lock);
7963                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7964                                                       /*sks_valid*/ 1,
7965                                                       /*command*/ 1,
7966                                                       /*field*/ 2,
7967                                                       /*bit_valid*/ 1,
7968                                                       /*bit*/ 4);
7969                                 ctl_done((union ctl_io *)ctsio);
7970                                 return (1);
7971                         }
7972
7973                         if (type>8 || type==2 || type==4 || type==0) {
7974                                 mtx_unlock(&lun->lun_lock);
7975                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7976                                                       /*sks_valid*/ 1,
7977                                                       /*command*/ 1,
7978                                                       /*field*/ 2,
7979                                                       /*bit_valid*/ 1,
7980                                                       /*bit*/ 0);
7981                                 ctl_done((union ctl_io *)ctsio);
7982                                 return (1);
7983                         }
7984
7985                         /*
7986                          * Unregister everybody else and build UA for
7987                          * them
7988                          */
7989                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7990                                 if (i == residx || lun->pr_keys[i] == 0)
7991                                         continue;
7992
7993                                 if (!persis_offset
7994                                  && i <CTL_MAX_INITIATORS)
7995                                         lun->pending_ua[i] |=
7996                                                 CTL_UA_REG_PREEMPT;
7997                                 else if (persis_offset
7998                                       && i >= persis_offset)
7999                                         lun->pending_ua[i-persis_offset] |=
8000                                                 CTL_UA_REG_PREEMPT;
8001                                 lun->pr_keys[i] = 0;
8002                         }
8003                         lun->pr_key_count = 1;
8004                         lun->res_type = type;
8005                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8006                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8007                                 lun->pr_res_idx = residx;
8008
8009                         /* send msg to other side */
8010                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8011                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8012                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8013                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8014                         persis_io.pr.pr_info.res_type = type;
8015                         memcpy(persis_io.pr.pr_info.sa_res_key,
8016                                param->serv_act_res_key,
8017                                sizeof(param->serv_act_res_key));
8018                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8019                              &persis_io, sizeof(persis_io), 0)) >
8020                              CTL_HA_STATUS_SUCCESS) {
8021                                 printf("CTL:Persis Out error returned "
8022                                        "from ctl_ha_msg_send %d\n",
8023                                        isc_retval);
8024                         }
8025                 } else {
8026                         /* not all registrants */
8027                         mtx_unlock(&lun->lun_lock);
8028                         free(ctsio->kern_data_ptr, M_CTL);
8029                         ctl_set_invalid_field(ctsio,
8030                                               /*sks_valid*/ 1,
8031                                               /*command*/ 0,
8032                                               /*field*/ 8,
8033                                               /*bit_valid*/ 0,
8034                                               /*bit*/ 0);
8035                         ctl_done((union ctl_io *)ctsio);
8036                         return (1);
8037                 }
8038         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8039                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8040                 int found = 0;
8041
8042                 if (res_key == sa_res_key) {
8043                         /* special case */
8044                         /*
8045                          * The spec implies this is not good but doesn't
8046                          * say what to do. There are two choices either
8047                          * generate a res conflict or check condition
8048                          * with illegal field in parameter data. Since
8049                          * that is what is done when the sa_res_key is
8050                          * zero I'll take that approach since this has
8051                          * to do with the sa_res_key.
8052                          */
8053                         mtx_unlock(&lun->lun_lock);
8054                         free(ctsio->kern_data_ptr, M_CTL);
8055                         ctl_set_invalid_field(ctsio,
8056                                               /*sks_valid*/ 1,
8057                                               /*command*/ 0,
8058                                               /*field*/ 8,
8059                                               /*bit_valid*/ 0,
8060                                               /*bit*/ 0);
8061                         ctl_done((union ctl_io *)ctsio);
8062                         return (1);
8063                 }
8064
8065                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8066                         if (lun->pr_keys[i] != sa_res_key)
8067                                 continue;
8068
8069                         found = 1;
8070                         lun->pr_keys[i] = 0;
8071                         lun->pr_key_count--;
8072
8073                         if (!persis_offset && i < CTL_MAX_INITIATORS)
8074                                 lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8075                         else if (persis_offset && i >= persis_offset)
8076                                 lun->pending_ua[i-persis_offset] |=
8077                                         CTL_UA_REG_PREEMPT;
8078                 }
8079                 if (!found) {
8080                         mtx_unlock(&lun->lun_lock);
8081                         free(ctsio->kern_data_ptr, M_CTL);
8082                         ctl_set_reservation_conflict(ctsio);
8083                         ctl_done((union ctl_io *)ctsio);
8084                         return (CTL_RETVAL_COMPLETE);
8085                 }
8086                 /* send msg to other side */
8087                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8088                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8089                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8090                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8091                 persis_io.pr.pr_info.res_type = type;
8092                 memcpy(persis_io.pr.pr_info.sa_res_key,
8093                        param->serv_act_res_key,
8094                        sizeof(param->serv_act_res_key));
8095                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8096                      &persis_io, sizeof(persis_io), 0)) >
8097                      CTL_HA_STATUS_SUCCESS) {
8098                         printf("CTL:Persis Out error returned from "
8099                                "ctl_ha_msg_send %d\n", isc_retval);
8100                 }
8101         } else {
8102                 /* Reserved but not all registrants */
8103                 /* sa_res_key is res holder */
8104                 if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8105                         /* validate scope and type */
8106                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8107                              SPR_LU_SCOPE) {
8108                                 mtx_unlock(&lun->lun_lock);
8109                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8110                                                       /*sks_valid*/ 1,
8111                                                       /*command*/ 1,
8112                                                       /*field*/ 2,
8113                                                       /*bit_valid*/ 1,
8114                                                       /*bit*/ 4);
8115                                 ctl_done((union ctl_io *)ctsio);
8116                                 return (1);
8117                         }
8118
8119                         if (type>8 || type==2 || type==4 || type==0) {
8120                                 mtx_unlock(&lun->lun_lock);
8121                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8122                                                       /*sks_valid*/ 1,
8123                                                       /*command*/ 1,
8124                                                       /*field*/ 2,
8125                                                       /*bit_valid*/ 1,
8126                                                       /*bit*/ 0);
8127                                 ctl_done((union ctl_io *)ctsio);
8128                                 return (1);
8129                         }
8130
8131                         /*
8132                          * Do the following:
8133                          * if sa_res_key != res_key remove all
8134                          * registrants w/sa_res_key and generate UA
8135                          * for these registrants(Registrations
8136                          * Preempted) if it wasn't an exclusive
8137                          * reservation generate UA(Reservations
8138                          * Preempted) for all other registered nexuses
8139                          * if the type has changed. Establish the new
8140                          * reservation and holder. If res_key and
8141                          * sa_res_key are the same do the above
8142                          * except don't unregister the res holder.
8143                          */
8144
8145                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8146                                 if (i == residx || lun->pr_keys[i] == 0)
8147                                         continue;
8148
8149                                 if (sa_res_key == lun->pr_keys[i]) {
8150                                         lun->pr_keys[i] = 0;
8151                                         lun->pr_key_count--;
8152
8153                                         if (!persis_offset
8154                                          && i < CTL_MAX_INITIATORS)
8155                                                 lun->pending_ua[i] |=
8156                                                         CTL_UA_REG_PREEMPT;
8157                                         else if (persis_offset
8158                                               && i >= persis_offset)
8159                                                 lun->pending_ua[i-persis_offset] |=
8160                                                   CTL_UA_REG_PREEMPT;
8161                                 } else if (type != lun->res_type
8162                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8163                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8164                                                 if (!persis_offset
8165                                                  && i < CTL_MAX_INITIATORS)
8166                                                         lun->pending_ua[i] |=
8167                                                         CTL_UA_RES_RELEASE;
8168                                                 else if (persis_offset
8169                                                       && i >= persis_offset)
8170                                                         lun->pending_ua[
8171                                                         i-persis_offset] |=
8172                                                         CTL_UA_RES_RELEASE;
8173                                 }
8174                         }
8175                         lun->res_type = type;
8176                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8177                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8178                                 lun->pr_res_idx = residx;
8179                         else
8180                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8181
8182                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8183                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8184                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8185                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8186                         persis_io.pr.pr_info.res_type = type;
8187                         memcpy(persis_io.pr.pr_info.sa_res_key,
8188                                param->serv_act_res_key,
8189                                sizeof(param->serv_act_res_key));
8190                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8191                              &persis_io, sizeof(persis_io), 0)) >
8192                              CTL_HA_STATUS_SUCCESS) {
8193                                 printf("CTL:Persis Out error returned "
8194                                        "from ctl_ha_msg_send %d\n",
8195                                        isc_retval);
8196                         }
8197                 } else {
8198                         /*
8199                          * sa_res_key is not the res holder just
8200                          * remove registrants
8201                          */
8202                         int found=0;
8203
8204                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8205                                 if (sa_res_key != lun->pr_keys[i])
8206                                         continue;
8207
8208                                 found = 1;
8209                                 lun->pr_keys[i] = 0;
8210                                 lun->pr_key_count--;
8211
8212                                 if (!persis_offset
8213                                  && i < CTL_MAX_INITIATORS)
8214                                         lun->pending_ua[i] |=
8215                                                 CTL_UA_REG_PREEMPT;
8216                                 else if (persis_offset
8217                                       && i >= persis_offset)
8218                                         lun->pending_ua[i-persis_offset] |=
8219                                                 CTL_UA_REG_PREEMPT;
8220                         }
8221
8222                         if (!found) {
8223                                 mtx_unlock(&lun->lun_lock);
8224                                 free(ctsio->kern_data_ptr, M_CTL);
8225                                 ctl_set_reservation_conflict(ctsio);
8226                                 ctl_done((union ctl_io *)ctsio);
8227                                 return (1);
8228                         }
8229                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8230                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8231                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8232                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8233                         persis_io.pr.pr_info.res_type = type;
8234                         memcpy(persis_io.pr.pr_info.sa_res_key,
8235                                param->serv_act_res_key,
8236                                sizeof(param->serv_act_res_key));
8237                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8238                              &persis_io, sizeof(persis_io), 0)) >
8239                              CTL_HA_STATUS_SUCCESS) {
8240                                 printf("CTL:Persis Out error returned "
8241                                        "from ctl_ha_msg_send %d\n",
8242                                 isc_retval);
8243                         }
8244                 }
8245         }
8246
8247         lun->PRGeneration++;
8248         mtx_unlock(&lun->lun_lock);
8249
8250         return (retval);
8251 }
8252
8253 static void
8254 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8255 {
8256         uint64_t sa_res_key;
8257         int i;
8258
8259         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8260
8261         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8262          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8263          || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8264                 if (sa_res_key == 0) {
8265                         /*
8266                          * Unregister everybody else and build UA for
8267                          * them
8268                          */
8269                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8270                                 if (i == msg->pr.pr_info.residx ||
8271                                     lun->pr_keys[i] == 0)
8272                                         continue;
8273
8274                                 if (!persis_offset
8275                                  && i < CTL_MAX_INITIATORS)
8276                                         lun->pending_ua[i] |=
8277                                                 CTL_UA_REG_PREEMPT;
8278                                 else if (persis_offset && i >= persis_offset)
8279                                         lun->pending_ua[i - persis_offset] |=
8280                                                 CTL_UA_REG_PREEMPT;
8281                                 lun->pr_keys[i] = 0;
8282                         }
8283
8284                         lun->pr_key_count = 1;
8285                         lun->res_type = msg->pr.pr_info.res_type;
8286                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8287                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8288                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8289                 } else {
8290                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8291                                 if (sa_res_key == lun->pr_keys[i])
8292                                         continue;
8293
8294                                 lun->pr_keys[i] = 0;
8295                                 lun->pr_key_count--;
8296
8297                                 if (!persis_offset
8298                                  && i < persis_offset)
8299                                         lun->pending_ua[i] |=
8300                                                 CTL_UA_REG_PREEMPT;
8301                                 else if (persis_offset
8302                                       && i >= persis_offset)
8303                                         lun->pending_ua[i - persis_offset] |=
8304                                                 CTL_UA_REG_PREEMPT;
8305                         }
8306                 }
8307         } else {
8308                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8309                         if (i == msg->pr.pr_info.residx ||
8310                             lun->pr_keys[i] == 0)
8311                                 continue;
8312
8313                         if (sa_res_key == lun->pr_keys[i]) {
8314                                 lun->pr_keys[i] = 0;
8315                                 lun->pr_key_count--;
8316                                 if (!persis_offset
8317                                  && i < CTL_MAX_INITIATORS)
8318                                         lun->pending_ua[i] |=
8319                                                 CTL_UA_REG_PREEMPT;
8320                                 else if (persis_offset
8321                                       && i >= persis_offset)
8322                                         lun->pending_ua[i - persis_offset] |=
8323                                                 CTL_UA_REG_PREEMPT;
8324                         } else if (msg->pr.pr_info.res_type != lun->res_type
8325                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8326                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8327                                         if (!persis_offset
8328                                          && i < persis_offset)
8329                                                 lun->pending_ua[i] |=
8330                                                         CTL_UA_RES_RELEASE;
8331                                         else if (persis_offset
8332                                               && i >= persis_offset)
8333                                         lun->pending_ua[i - persis_offset] |=
8334                                                 CTL_UA_RES_RELEASE;
8335                         }
8336                 }
8337                 lun->res_type = msg->pr.pr_info.res_type;
8338                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8339                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8340                         lun->pr_res_idx = msg->pr.pr_info.residx;
8341                 else
8342                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8343         }
8344         lun->PRGeneration++;
8345
8346 }
8347
8348
8349 int
8350 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8351 {
8352         int retval;
8353         int isc_retval;
8354         u_int32_t param_len;
8355         struct scsi_per_res_out *cdb;
8356         struct ctl_lun *lun;
8357         struct scsi_per_res_out_parms* param;
8358         struct ctl_softc *softc;
8359         uint32_t residx;
8360         uint64_t res_key, sa_res_key;
8361         uint8_t type;
8362         union ctl_ha_msg persis_io;
8363         int    i;
8364
8365         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8366
8367         retval = CTL_RETVAL_COMPLETE;
8368
8369         softc = control_softc;
8370
8371         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8372         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8373
8374         /*
8375          * We only support whole-LUN scope.  The scope & type are ignored for
8376          * register, register and ignore existing key and clear.
8377          * We sometimes ignore scope and type on preempts too!!
8378          * Verify reservation type here as well.
8379          */
8380         type = cdb->scope_type & SPR_TYPE_MASK;
8381         if ((cdb->action == SPRO_RESERVE)
8382          || (cdb->action == SPRO_RELEASE)) {
8383                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8384                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8385                                               /*sks_valid*/ 1,
8386                                               /*command*/ 1,
8387                                               /*field*/ 2,
8388                                               /*bit_valid*/ 1,
8389                                               /*bit*/ 4);
8390                         ctl_done((union ctl_io *)ctsio);
8391                         return (CTL_RETVAL_COMPLETE);
8392                 }
8393
8394                 if (type>8 || type==2 || type==4 || type==0) {
8395                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8396                                               /*sks_valid*/ 1,
8397                                               /*command*/ 1,
8398                                               /*field*/ 2,
8399                                               /*bit_valid*/ 1,
8400                                               /*bit*/ 0);
8401                         ctl_done((union ctl_io *)ctsio);
8402                         return (CTL_RETVAL_COMPLETE);
8403                 }
8404         }
8405
8406         param_len = scsi_4btoul(cdb->length);
8407
8408         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8409                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8410                 ctsio->kern_data_len = param_len;
8411                 ctsio->kern_total_len = param_len;
8412                 ctsio->kern_data_resid = 0;
8413                 ctsio->kern_rel_offset = 0;
8414                 ctsio->kern_sg_entries = 0;
8415                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8416                 ctsio->be_move_done = ctl_config_move_done;
8417                 ctl_datamove((union ctl_io *)ctsio);
8418
8419                 return (CTL_RETVAL_COMPLETE);
8420         }
8421
8422         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8423
8424         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8425         res_key = scsi_8btou64(param->res_key.key);
8426         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8427
8428         /*
8429          * Validate the reservation key here except for SPRO_REG_IGNO
8430          * This must be done for all other service actions
8431          */
8432         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8433                 mtx_lock(&lun->lun_lock);
8434                 if (lun->pr_keys[residx] != 0) {
8435                     if (res_key != lun->pr_keys[residx]) {
8436                                 /*
8437                                  * The current key passed in doesn't match
8438                                  * the one the initiator previously
8439                                  * registered.
8440                                  */
8441                                 mtx_unlock(&lun->lun_lock);
8442                                 free(ctsio->kern_data_ptr, M_CTL);
8443                                 ctl_set_reservation_conflict(ctsio);
8444                                 ctl_done((union ctl_io *)ctsio);
8445                                 return (CTL_RETVAL_COMPLETE);
8446                         }
8447                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8448                         /*
8449                          * We are not registered
8450                          */
8451                         mtx_unlock(&lun->lun_lock);
8452                         free(ctsio->kern_data_ptr, M_CTL);
8453                         ctl_set_reservation_conflict(ctsio);
8454                         ctl_done((union ctl_io *)ctsio);
8455                         return (CTL_RETVAL_COMPLETE);
8456                 } else if (res_key != 0) {
8457                         /*
8458                          * We are not registered and trying to register but
8459                          * the register key isn't zero.
8460                          */
8461                         mtx_unlock(&lun->lun_lock);
8462                         free(ctsio->kern_data_ptr, M_CTL);
8463                         ctl_set_reservation_conflict(ctsio);
8464                         ctl_done((union ctl_io *)ctsio);
8465                         return (CTL_RETVAL_COMPLETE);
8466                 }
8467                 mtx_unlock(&lun->lun_lock);
8468         }
8469
8470         switch (cdb->action & SPRO_ACTION_MASK) {
8471         case SPRO_REGISTER:
8472         case SPRO_REG_IGNO: {
8473
8474 #if 0
8475                 printf("Registration received\n");
8476 #endif
8477
8478                 /*
8479                  * We don't support any of these options, as we report in
8480                  * the read capabilities request (see
8481                  * ctl_persistent_reserve_in(), above).
8482                  */
8483                 if ((param->flags & SPR_SPEC_I_PT)
8484                  || (param->flags & SPR_ALL_TG_PT)
8485                  || (param->flags & SPR_APTPL)) {
8486                         int bit_ptr;
8487
8488                         if (param->flags & SPR_APTPL)
8489                                 bit_ptr = 0;
8490                         else if (param->flags & SPR_ALL_TG_PT)
8491                                 bit_ptr = 2;
8492                         else /* SPR_SPEC_I_PT */
8493                                 bit_ptr = 3;
8494
8495                         free(ctsio->kern_data_ptr, M_CTL);
8496                         ctl_set_invalid_field(ctsio,
8497                                               /*sks_valid*/ 1,
8498                                               /*command*/ 0,
8499                                               /*field*/ 20,
8500                                               /*bit_valid*/ 1,
8501                                               /*bit*/ bit_ptr);
8502                         ctl_done((union ctl_io *)ctsio);
8503                         return (CTL_RETVAL_COMPLETE);
8504                 }
8505
8506                 mtx_lock(&lun->lun_lock);
8507
8508                 /*
8509                  * The initiator wants to clear the
8510                  * key/unregister.
8511                  */
8512                 if (sa_res_key == 0) {
8513                         if ((res_key == 0
8514                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8515                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8516                           && lun->pr_keys[residx] == 0)) {
8517                                 mtx_unlock(&lun->lun_lock);
8518                                 goto done;
8519                         }
8520
8521                         lun->pr_keys[residx] = 0;
8522                         lun->pr_key_count--;
8523
8524                         if (residx == lun->pr_res_idx) {
8525                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8526                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8527
8528                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8529                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8530                                  && lun->pr_key_count) {
8531                                         /*
8532                                          * If the reservation is a registrants
8533                                          * only type we need to generate a UA
8534                                          * for other registered inits.  The
8535                                          * sense code should be RESERVATIONS
8536                                          * RELEASED
8537                                          */
8538
8539                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8540                                                 if (lun->pr_keys[
8541                                                     i + persis_offset] == 0)
8542                                                         continue;
8543                                                 lun->pending_ua[i] |=
8544                                                         CTL_UA_RES_RELEASE;
8545                                         }
8546                                 }
8547                                 lun->res_type = 0;
8548                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8549                                 if (lun->pr_key_count==0) {
8550                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8551                                         lun->res_type = 0;
8552                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8553                                 }
8554                         }
8555                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8556                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8557                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8558                         persis_io.pr.pr_info.residx = residx;
8559                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8560                              &persis_io, sizeof(persis_io), 0 )) >
8561                              CTL_HA_STATUS_SUCCESS) {
8562                                 printf("CTL:Persis Out error returned from "
8563                                        "ctl_ha_msg_send %d\n", isc_retval);
8564                         }
8565                 } else /* sa_res_key != 0 */ {
8566
8567                         /*
8568                          * If we aren't registered currently then increment
8569                          * the key count and set the registered flag.
8570                          */
8571                         if (lun->pr_keys[residx] == 0)
8572                                 lun->pr_key_count++;
8573                         lun->pr_keys[residx] = sa_res_key;
8574
8575                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8576                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8577                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8578                         persis_io.pr.pr_info.residx = residx;
8579                         memcpy(persis_io.pr.pr_info.sa_res_key,
8580                                param->serv_act_res_key,
8581                                sizeof(param->serv_act_res_key));
8582                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8583                              &persis_io, sizeof(persis_io), 0)) >
8584                              CTL_HA_STATUS_SUCCESS) {
8585                                 printf("CTL:Persis Out error returned from "
8586                                        "ctl_ha_msg_send %d\n", isc_retval);
8587                         }
8588                 }
8589                 lun->PRGeneration++;
8590                 mtx_unlock(&lun->lun_lock);
8591
8592                 break;
8593         }
8594         case SPRO_RESERVE:
8595 #if 0
8596                 printf("Reserve executed type %d\n", type);
8597 #endif
8598                 mtx_lock(&lun->lun_lock);
8599                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8600                         /*
8601                          * if this isn't the reservation holder and it's
8602                          * not a "all registrants" type or if the type is
8603                          * different then we have a conflict
8604                          */
8605                         if ((lun->pr_res_idx != residx
8606                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8607                          || lun->res_type != type) {
8608                                 mtx_unlock(&lun->lun_lock);
8609                                 free(ctsio->kern_data_ptr, M_CTL);
8610                                 ctl_set_reservation_conflict(ctsio);
8611                                 ctl_done((union ctl_io *)ctsio);
8612                                 return (CTL_RETVAL_COMPLETE);
8613                         }
8614                         mtx_unlock(&lun->lun_lock);
8615                 } else /* create a reservation */ {
8616                         /*
8617                          * If it's not an "all registrants" type record
8618                          * reservation holder
8619                          */
8620                         if (type != SPR_TYPE_WR_EX_AR
8621                          && type != SPR_TYPE_EX_AC_AR)
8622                                 lun->pr_res_idx = residx; /* Res holder */
8623                         else
8624                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8625
8626                         lun->flags |= CTL_LUN_PR_RESERVED;
8627                         lun->res_type = type;
8628
8629                         mtx_unlock(&lun->lun_lock);
8630
8631                         /* send msg to other side */
8632                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8633                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8634                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8635                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8636                         persis_io.pr.pr_info.res_type = type;
8637                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8638                              &persis_io, sizeof(persis_io), 0)) >
8639                              CTL_HA_STATUS_SUCCESS) {
8640                                 printf("CTL:Persis Out error returned from "
8641                                        "ctl_ha_msg_send %d\n", isc_retval);
8642                         }
8643                 }
8644                 break;
8645
8646         case SPRO_RELEASE:
8647                 mtx_lock(&lun->lun_lock);
8648                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8649                         /* No reservation exists return good status */
8650                         mtx_unlock(&lun->lun_lock);
8651                         goto done;
8652                 }
8653                 /*
8654                  * Is this nexus a reservation holder?
8655                  */
8656                 if (lun->pr_res_idx != residx
8657                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8658                         /*
8659                          * not a res holder return good status but
8660                          * do nothing
8661                          */
8662                         mtx_unlock(&lun->lun_lock);
8663                         goto done;
8664                 }
8665
8666                 if (lun->res_type != type) {
8667                         mtx_unlock(&lun->lun_lock);
8668                         free(ctsio->kern_data_ptr, M_CTL);
8669                         ctl_set_illegal_pr_release(ctsio);
8670                         ctl_done((union ctl_io *)ctsio);
8671                         return (CTL_RETVAL_COMPLETE);
8672                 }
8673
8674                 /* okay to release */
8675                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8676                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8677                 lun->res_type = 0;
8678
8679                 /*
8680                  * if this isn't an exclusive access
8681                  * res generate UA for all other
8682                  * registrants.
8683                  */
8684                 if (type != SPR_TYPE_EX_AC
8685                  && type != SPR_TYPE_WR_EX) {
8686                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8687                                 if (i == residx ||
8688                                     lun->pr_keys[i + persis_offset] == 0)
8689                                         continue;
8690                                 lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8691                         }
8692                 }
8693                 mtx_unlock(&lun->lun_lock);
8694                 /* Send msg to other side */
8695                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8696                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8697                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8698                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8699                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8700                         printf("CTL:Persis Out error returned from "
8701                                "ctl_ha_msg_send %d\n", isc_retval);
8702                 }
8703                 break;
8704
8705         case SPRO_CLEAR:
8706                 /* send msg to other side */
8707
8708                 mtx_lock(&lun->lun_lock);
8709                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8710                 lun->res_type = 0;
8711                 lun->pr_key_count = 0;
8712                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8713
8714                 lun->pr_keys[residx] = 0;
8715
8716                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8717                         if (lun->pr_keys[i] != 0) {
8718                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8719                                         lun->pending_ua[i] |=
8720                                                 CTL_UA_RES_PREEMPT;
8721                                 else if (persis_offset && i >= persis_offset)
8722                                         lun->pending_ua[i-persis_offset] |=
8723                                             CTL_UA_RES_PREEMPT;
8724
8725                                 lun->pr_keys[i] = 0;
8726                         }
8727                 lun->PRGeneration++;
8728                 mtx_unlock(&lun->lun_lock);
8729                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8730                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8731                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8732                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8733                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8734                         printf("CTL:Persis Out error returned from "
8735                                "ctl_ha_msg_send %d\n", isc_retval);
8736                 }
8737                 break;
8738
8739         case SPRO_PREEMPT: {
8740                 int nretval;
8741
8742                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8743                                           residx, ctsio, cdb, param);
8744                 if (nretval != 0)
8745                         return (CTL_RETVAL_COMPLETE);
8746                 break;
8747         }
8748         default:
8749                 panic("Invalid PR type %x", cdb->action);
8750         }
8751
8752 done:
8753         free(ctsio->kern_data_ptr, M_CTL);
8754         ctl_set_success(ctsio);
8755         ctl_done((union ctl_io *)ctsio);
8756
8757         return (retval);
8758 }
8759
8760 /*
8761  * This routine is for handling a message from the other SC pertaining to
8762  * persistent reserve out. All the error checking will have been done
8763  * so only perorming the action need be done here to keep the two
8764  * in sync.
8765  */
8766 static void
8767 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8768 {
8769         struct ctl_lun *lun;
8770         struct ctl_softc *softc;
8771         int i;
8772         uint32_t targ_lun;
8773
8774         softc = control_softc;
8775
8776         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8777         lun = softc->ctl_luns[targ_lun];
8778         mtx_lock(&lun->lun_lock);
8779         switch(msg->pr.pr_info.action) {
8780         case CTL_PR_REG_KEY:
8781                 if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8782                         lun->pr_key_count++;
8783                 lun->pr_keys[msg->pr.pr_info.residx] =
8784                     scsi_8btou64(msg->pr.pr_info.sa_res_key);
8785                 lun->PRGeneration++;
8786                 break;
8787
8788         case CTL_PR_UNREG_KEY:
8789                 lun->pr_keys[msg->pr.pr_info.residx] = 0;
8790                 lun->pr_key_count--;
8791
8792                 /* XXX Need to see if the reservation has been released */
8793                 /* if so do we need to generate UA? */
8794                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8795                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8796                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8797
8798                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8799                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8800                          && lun->pr_key_count) {
8801                                 /*
8802                                  * If the reservation is a registrants
8803                                  * only type we need to generate a UA
8804                                  * for other registered inits.  The
8805                                  * sense code should be RESERVATIONS
8806                                  * RELEASED
8807                                  */
8808
8809                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8810                                         if (lun->pr_keys[i+
8811                                             persis_offset] == 0)
8812                                                 continue;
8813
8814                                         lun->pending_ua[i] |=
8815                                                 CTL_UA_RES_RELEASE;
8816                                 }
8817                         }
8818                         lun->res_type = 0;
8819                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8820                         if (lun->pr_key_count==0) {
8821                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8822                                 lun->res_type = 0;
8823                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8824                         }
8825                 }
8826                 lun->PRGeneration++;
8827                 break;
8828
8829         case CTL_PR_RESERVE:
8830                 lun->flags |= CTL_LUN_PR_RESERVED;
8831                 lun->res_type = msg->pr.pr_info.res_type;
8832                 lun->pr_res_idx = msg->pr.pr_info.residx;
8833
8834                 break;
8835
8836         case CTL_PR_RELEASE:
8837                 /*
8838                  * if this isn't an exclusive access res generate UA for all
8839                  * other registrants.
8840                  */
8841                 if (lun->res_type != SPR_TYPE_EX_AC
8842                  && lun->res_type != SPR_TYPE_WR_EX) {
8843                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8844                                 if (lun->pr_keys[i+persis_offset] != 0)
8845                                         lun->pending_ua[i] |=
8846                                                 CTL_UA_RES_RELEASE;
8847                 }
8848
8849                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8850                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8851                 lun->res_type = 0;
8852                 break;
8853
8854         case CTL_PR_PREEMPT:
8855                 ctl_pro_preempt_other(lun, msg);
8856                 break;
8857         case CTL_PR_CLEAR:
8858                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8859                 lun->res_type = 0;
8860                 lun->pr_key_count = 0;
8861                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8862
8863                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8864                         if (lun->pr_keys[i] == 0)
8865                                 continue;
8866                         if (!persis_offset
8867                          && i < CTL_MAX_INITIATORS)
8868                                 lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8869                         else if (persis_offset
8870                               && i >= persis_offset)
8871                                 lun->pending_ua[i-persis_offset] |=
8872                                         CTL_UA_RES_PREEMPT;
8873                         lun->pr_keys[i] = 0;
8874                 }
8875                 lun->PRGeneration++;
8876                 break;
8877         }
8878
8879         mtx_unlock(&lun->lun_lock);
8880 }
8881
8882 int
8883 ctl_read_write(struct ctl_scsiio *ctsio)
8884 {
8885         struct ctl_lun *lun;
8886         struct ctl_lba_len_flags *lbalen;
8887         uint64_t lba;
8888         uint32_t num_blocks;
8889         int flags, retval;
8890         int isread;
8891
8892         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8893
8894         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8895
8896         flags = 0;
8897         retval = CTL_RETVAL_COMPLETE;
8898
8899         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8900               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8901         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8902                 uint32_t residx;
8903
8904                 /*
8905                  * XXX KDM need a lock here.
8906                  */
8907                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8908                 if ((lun->res_type == SPR_TYPE_EX_AC
8909                   && residx != lun->pr_res_idx)
8910                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
8911                    || lun->res_type == SPR_TYPE_EX_AC_AR)
8912                   && lun->pr_keys[residx] == 0)) {
8913                         ctl_set_reservation_conflict(ctsio);
8914                         ctl_done((union ctl_io *)ctsio);
8915                         return (CTL_RETVAL_COMPLETE);
8916                 }
8917         }
8918
8919         switch (ctsio->cdb[0]) {
8920         case READ_6:
8921         case WRITE_6: {
8922                 struct scsi_rw_6 *cdb;
8923
8924                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8925
8926                 lba = scsi_3btoul(cdb->addr);
8927                 /* only 5 bits are valid in the most significant address byte */
8928                 lba &= 0x1fffff;
8929                 num_blocks = cdb->length;
8930                 /*
8931                  * This is correct according to SBC-2.
8932                  */
8933                 if (num_blocks == 0)
8934                         num_blocks = 256;
8935                 break;
8936         }
8937         case READ_10:
8938         case WRITE_10: {
8939                 struct scsi_rw_10 *cdb;
8940
8941                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8942                 if (cdb->byte2 & SRW10_FUA)
8943                         flags |= CTL_LLF_FUA;
8944                 if (cdb->byte2 & SRW10_DPO)
8945                         flags |= CTL_LLF_DPO;
8946                 lba = scsi_4btoul(cdb->addr);
8947                 num_blocks = scsi_2btoul(cdb->length);
8948                 break;
8949         }
8950         case WRITE_VERIFY_10: {
8951                 struct scsi_write_verify_10 *cdb;
8952
8953                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8954                 flags |= CTL_LLF_FUA;
8955                 if (cdb->byte2 & SWV_DPO)
8956                         flags |= CTL_LLF_DPO;
8957                 lba = scsi_4btoul(cdb->addr);
8958                 num_blocks = scsi_2btoul(cdb->length);
8959                 break;
8960         }
8961         case READ_12:
8962         case WRITE_12: {
8963                 struct scsi_rw_12 *cdb;
8964
8965                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8966                 if (cdb->byte2 & SRW12_FUA)
8967                         flags |= CTL_LLF_FUA;
8968                 if (cdb->byte2 & SRW12_DPO)
8969                         flags |= CTL_LLF_DPO;
8970                 lba = scsi_4btoul(cdb->addr);
8971                 num_blocks = scsi_4btoul(cdb->length);
8972                 break;
8973         }
8974         case WRITE_VERIFY_12: {
8975                 struct scsi_write_verify_12 *cdb;
8976
8977                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8978                 flags |= CTL_LLF_FUA;
8979                 if (cdb->byte2 & SWV_DPO)
8980                         flags |= CTL_LLF_DPO;
8981                 lba = scsi_4btoul(cdb->addr);
8982                 num_blocks = scsi_4btoul(cdb->length);
8983                 break;
8984         }
8985         case READ_16:
8986         case WRITE_16: {
8987                 struct scsi_rw_16 *cdb;
8988
8989                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8990                 if (cdb->byte2 & SRW12_FUA)
8991                         flags |= CTL_LLF_FUA;
8992                 if (cdb->byte2 & SRW12_DPO)
8993                         flags |= CTL_LLF_DPO;
8994                 lba = scsi_8btou64(cdb->addr);
8995                 num_blocks = scsi_4btoul(cdb->length);
8996                 break;
8997         }
8998         case WRITE_ATOMIC_16: {
8999                 struct scsi_rw_16 *cdb;
9000
9001                 if (lun->be_lun->atomicblock == 0) {
9002                         ctl_set_invalid_opcode(ctsio);
9003                         ctl_done((union ctl_io *)ctsio);
9004                         return (CTL_RETVAL_COMPLETE);
9005                 }
9006
9007                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9008                 if (cdb->byte2 & SRW12_FUA)
9009                         flags |= CTL_LLF_FUA;
9010                 if (cdb->byte2 & SRW12_DPO)
9011                         flags |= CTL_LLF_DPO;
9012                 lba = scsi_8btou64(cdb->addr);
9013                 num_blocks = scsi_4btoul(cdb->length);
9014                 if (num_blocks > lun->be_lun->atomicblock) {
9015                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9016                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9017                             /*bit*/ 0);
9018                         ctl_done((union ctl_io *)ctsio);
9019                         return (CTL_RETVAL_COMPLETE);
9020                 }
9021                 break;
9022         }
9023         case WRITE_VERIFY_16: {
9024                 struct scsi_write_verify_16 *cdb;
9025
9026                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9027                 flags |= CTL_LLF_FUA;
9028                 if (cdb->byte2 & SWV_DPO)
9029                         flags |= CTL_LLF_DPO;
9030                 lba = scsi_8btou64(cdb->addr);
9031                 num_blocks = scsi_4btoul(cdb->length);
9032                 break;
9033         }
9034         default:
9035                 /*
9036                  * We got a command we don't support.  This shouldn't
9037                  * happen, commands should be filtered out above us.
9038                  */
9039                 ctl_set_invalid_opcode(ctsio);
9040                 ctl_done((union ctl_io *)ctsio);
9041
9042                 return (CTL_RETVAL_COMPLETE);
9043                 break; /* NOTREACHED */
9044         }
9045
9046         /*
9047          * The first check is to make sure we're in bounds, the second
9048          * check is to catch wrap-around problems.  If the lba + num blocks
9049          * is less than the lba, then we've wrapped around and the block
9050          * range is invalid anyway.
9051          */
9052         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9053          || ((lba + num_blocks) < lba)) {
9054                 ctl_set_lba_out_of_range(ctsio);
9055                 ctl_done((union ctl_io *)ctsio);
9056                 return (CTL_RETVAL_COMPLETE);
9057         }
9058
9059         /*
9060          * According to SBC-3, a transfer length of 0 is not an error.
9061          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9062          * translates to 256 blocks for those commands.
9063          */
9064         if (num_blocks == 0) {
9065                 ctl_set_success(ctsio);
9066                 ctl_done((union ctl_io *)ctsio);
9067                 return (CTL_RETVAL_COMPLETE);
9068         }
9069
9070         /* Set FUA and/or DPO if caches are disabled. */
9071         if (isread) {
9072                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9073                     SCP_RCD) != 0)
9074                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9075         } else {
9076                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9077                     SCP_WCE) == 0)
9078                         flags |= CTL_LLF_FUA;
9079         }
9080
9081         lbalen = (struct ctl_lba_len_flags *)
9082             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9083         lbalen->lba = lba;
9084         lbalen->len = num_blocks;
9085         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9086
9087         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9088         ctsio->kern_rel_offset = 0;
9089
9090         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9091
9092         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9093
9094         return (retval);
9095 }
9096
9097 static int
9098 ctl_cnw_cont(union ctl_io *io)
9099 {
9100         struct ctl_scsiio *ctsio;
9101         struct ctl_lun *lun;
9102         struct ctl_lba_len_flags *lbalen;
9103         int retval;
9104
9105         ctsio = &io->scsiio;
9106         ctsio->io_hdr.status = CTL_STATUS_NONE;
9107         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9108         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9109         lbalen = (struct ctl_lba_len_flags *)
9110             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9111         lbalen->flags &= ~CTL_LLF_COMPARE;
9112         lbalen->flags |= CTL_LLF_WRITE;
9113
9114         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9115         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9116         return (retval);
9117 }
9118
9119 int
9120 ctl_cnw(struct ctl_scsiio *ctsio)
9121 {
9122         struct ctl_lun *lun;
9123         struct ctl_lba_len_flags *lbalen;
9124         uint64_t lba;
9125         uint32_t num_blocks;
9126         int flags, retval;
9127
9128         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9129
9130         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9131
9132         flags = 0;
9133         retval = CTL_RETVAL_COMPLETE;
9134
9135         switch (ctsio->cdb[0]) {
9136         case COMPARE_AND_WRITE: {
9137                 struct scsi_compare_and_write *cdb;
9138
9139                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9140                 if (cdb->byte2 & SRW10_FUA)
9141                         flags |= CTL_LLF_FUA;
9142                 if (cdb->byte2 & SRW10_DPO)
9143                         flags |= CTL_LLF_DPO;
9144                 lba = scsi_8btou64(cdb->addr);
9145                 num_blocks = cdb->length;
9146                 break;
9147         }
9148         default:
9149                 /*
9150                  * We got a command we don't support.  This shouldn't
9151                  * happen, commands should be filtered out above us.
9152                  */
9153                 ctl_set_invalid_opcode(ctsio);
9154                 ctl_done((union ctl_io *)ctsio);
9155
9156                 return (CTL_RETVAL_COMPLETE);
9157                 break; /* NOTREACHED */
9158         }
9159
9160         /*
9161          * The first check is to make sure we're in bounds, the second
9162          * check is to catch wrap-around problems.  If the lba + num blocks
9163          * is less than the lba, then we've wrapped around and the block
9164          * range is invalid anyway.
9165          */
9166         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9167          || ((lba + num_blocks) < lba)) {
9168                 ctl_set_lba_out_of_range(ctsio);
9169                 ctl_done((union ctl_io *)ctsio);
9170                 return (CTL_RETVAL_COMPLETE);
9171         }
9172
9173         /*
9174          * According to SBC-3, a transfer length of 0 is not an error.
9175          */
9176         if (num_blocks == 0) {
9177                 ctl_set_success(ctsio);
9178                 ctl_done((union ctl_io *)ctsio);
9179                 return (CTL_RETVAL_COMPLETE);
9180         }
9181
9182         /* Set FUA if write cache is disabled. */
9183         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9184             SCP_WCE) == 0)
9185                 flags |= CTL_LLF_FUA;
9186
9187         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9188         ctsio->kern_rel_offset = 0;
9189
9190         /*
9191          * Set the IO_CONT flag, so that if this I/O gets passed to
9192          * ctl_data_submit_done(), it'll get passed back to
9193          * ctl_ctl_cnw_cont() for further processing.
9194          */
9195         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9196         ctsio->io_cont = ctl_cnw_cont;
9197
9198         lbalen = (struct ctl_lba_len_flags *)
9199             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9200         lbalen->lba = lba;
9201         lbalen->len = num_blocks;
9202         lbalen->flags = CTL_LLF_COMPARE | flags;
9203
9204         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9205         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9206         return (retval);
9207 }
9208
9209 int
9210 ctl_verify(struct ctl_scsiio *ctsio)
9211 {
9212         struct ctl_lun *lun;
9213         struct ctl_lba_len_flags *lbalen;
9214         uint64_t lba;
9215         uint32_t num_blocks;
9216         int bytchk, flags;
9217         int retval;
9218
9219         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9220
9221         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9222
9223         bytchk = 0;
9224         flags = CTL_LLF_FUA;
9225         retval = CTL_RETVAL_COMPLETE;
9226
9227         switch (ctsio->cdb[0]) {
9228         case VERIFY_10: {
9229                 struct scsi_verify_10 *cdb;
9230
9231                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9232                 if (cdb->byte2 & SVFY_BYTCHK)
9233                         bytchk = 1;
9234                 if (cdb->byte2 & SVFY_DPO)
9235                         flags |= CTL_LLF_DPO;
9236                 lba = scsi_4btoul(cdb->addr);
9237                 num_blocks = scsi_2btoul(cdb->length);
9238                 break;
9239         }
9240         case VERIFY_12: {
9241                 struct scsi_verify_12 *cdb;
9242
9243                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9244                 if (cdb->byte2 & SVFY_BYTCHK)
9245                         bytchk = 1;
9246                 if (cdb->byte2 & SVFY_DPO)
9247                         flags |= CTL_LLF_DPO;
9248                 lba = scsi_4btoul(cdb->addr);
9249                 num_blocks = scsi_4btoul(cdb->length);
9250                 break;
9251         }
9252         case VERIFY_16: {
9253                 struct scsi_rw_16 *cdb;
9254
9255                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9256                 if (cdb->byte2 & SVFY_BYTCHK)
9257                         bytchk = 1;
9258                 if (cdb->byte2 & SVFY_DPO)
9259                         flags |= CTL_LLF_DPO;
9260                 lba = scsi_8btou64(cdb->addr);
9261                 num_blocks = scsi_4btoul(cdb->length);
9262                 break;
9263         }
9264         default:
9265                 /*
9266                  * We got a command we don't support.  This shouldn't
9267                  * happen, commands should be filtered out above us.
9268                  */
9269                 ctl_set_invalid_opcode(ctsio);
9270                 ctl_done((union ctl_io *)ctsio);
9271                 return (CTL_RETVAL_COMPLETE);
9272         }
9273
9274         /*
9275          * The first check is to make sure we're in bounds, the second
9276          * check is to catch wrap-around problems.  If the lba + num blocks
9277          * is less than the lba, then we've wrapped around and the block
9278          * range is invalid anyway.
9279          */
9280         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9281          || ((lba + num_blocks) < lba)) {
9282                 ctl_set_lba_out_of_range(ctsio);
9283                 ctl_done((union ctl_io *)ctsio);
9284                 return (CTL_RETVAL_COMPLETE);
9285         }
9286
9287         /*
9288          * According to SBC-3, a transfer length of 0 is not an error.
9289          */
9290         if (num_blocks == 0) {
9291                 ctl_set_success(ctsio);
9292                 ctl_done((union ctl_io *)ctsio);
9293                 return (CTL_RETVAL_COMPLETE);
9294         }
9295
9296         lbalen = (struct ctl_lba_len_flags *)
9297             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9298         lbalen->lba = lba;
9299         lbalen->len = num_blocks;
9300         if (bytchk) {
9301                 lbalen->flags = CTL_LLF_COMPARE | flags;
9302                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9303         } else {
9304                 lbalen->flags = CTL_LLF_VERIFY | flags;
9305                 ctsio->kern_total_len = 0;
9306         }
9307         ctsio->kern_rel_offset = 0;
9308
9309         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9310         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9311         return (retval);
9312 }
9313
9314 int
9315 ctl_report_luns(struct ctl_scsiio *ctsio)
9316 {
9317         struct scsi_report_luns *cdb;
9318         struct scsi_report_luns_data *lun_data;
9319         struct ctl_lun *lun, *request_lun;
9320         int num_luns, retval;
9321         uint32_t alloc_len, lun_datalen;
9322         int num_filled, well_known;
9323         uint32_t initidx, targ_lun_id, lun_id;
9324
9325         retval = CTL_RETVAL_COMPLETE;
9326         well_known = 0;
9327
9328         cdb = (struct scsi_report_luns *)ctsio->cdb;
9329
9330         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9331
9332         mtx_lock(&control_softc->ctl_lock);
9333         num_luns = control_softc->num_luns;
9334         mtx_unlock(&control_softc->ctl_lock);
9335
9336         switch (cdb->select_report) {
9337         case RPL_REPORT_DEFAULT:
9338         case RPL_REPORT_ALL:
9339                 break;
9340         case RPL_REPORT_WELLKNOWN:
9341                 well_known = 1;
9342                 num_luns = 0;
9343                 break;
9344         default:
9345                 ctl_set_invalid_field(ctsio,
9346                                       /*sks_valid*/ 1,
9347                                       /*command*/ 1,
9348                                       /*field*/ 2,
9349                                       /*bit_valid*/ 0,
9350                                       /*bit*/ 0);
9351                 ctl_done((union ctl_io *)ctsio);
9352                 return (retval);
9353                 break; /* NOTREACHED */
9354         }
9355
9356         alloc_len = scsi_4btoul(cdb->length);
9357         /*
9358          * The initiator has to allocate at least 16 bytes for this request,
9359          * so he can at least get the header and the first LUN.  Otherwise
9360          * we reject the request (per SPC-3 rev 14, section 6.21).
9361          */
9362         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9363             sizeof(struct scsi_report_luns_lundata))) {
9364                 ctl_set_invalid_field(ctsio,
9365                                       /*sks_valid*/ 1,
9366                                       /*command*/ 1,
9367                                       /*field*/ 6,
9368                                       /*bit_valid*/ 0,
9369                                       /*bit*/ 0);
9370                 ctl_done((union ctl_io *)ctsio);
9371                 return (retval);
9372         }
9373
9374         request_lun = (struct ctl_lun *)
9375                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9376
9377         lun_datalen = sizeof(*lun_data) +
9378                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9379
9380         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9381         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9382         ctsio->kern_sg_entries = 0;
9383
9384         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9385
9386         mtx_lock(&control_softc->ctl_lock);
9387         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9388                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9389                 if (lun_id >= CTL_MAX_LUNS)
9390                         continue;
9391                 lun = control_softc->ctl_luns[lun_id];
9392                 if (lun == NULL)
9393                         continue;
9394
9395                 if (targ_lun_id <= 0xff) {
9396                         /*
9397                          * Peripheral addressing method, bus number 0.
9398                          */
9399                         lun_data->luns[num_filled].lundata[0] =
9400                                 RPL_LUNDATA_ATYP_PERIPH;
9401                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9402                         num_filled++;
9403                 } else if (targ_lun_id <= 0x3fff) {
9404                         /*
9405                          * Flat addressing method.
9406                          */
9407                         lun_data->luns[num_filled].lundata[0] =
9408                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9409                         lun_data->luns[num_filled].lundata[1] =
9410                                 (targ_lun_id & 0xff);
9411                         num_filled++;
9412                 } else if (targ_lun_id <= 0xffffff) {
9413                         /*
9414                          * Extended flat addressing method.
9415                          */
9416                         lun_data->luns[num_filled].lundata[0] =
9417                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9418                         scsi_ulto3b(targ_lun_id,
9419                             &lun_data->luns[num_filled].lundata[1]);
9420                         num_filled++;
9421                 } else {
9422                         printf("ctl_report_luns: bogus LUN number %jd, "
9423                                "skipping\n", (intmax_t)targ_lun_id);
9424                 }
9425                 /*
9426                  * According to SPC-3, rev 14 section 6.21:
9427                  *
9428                  * "The execution of a REPORT LUNS command to any valid and
9429                  * installed logical unit shall clear the REPORTED LUNS DATA
9430                  * HAS CHANGED unit attention condition for all logical
9431                  * units of that target with respect to the requesting
9432                  * initiator. A valid and installed logical unit is one
9433                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9434                  * INQUIRY data (see 6.4.2)."
9435                  *
9436                  * If request_lun is NULL, the LUN this report luns command
9437                  * was issued to is either disabled or doesn't exist. In that
9438                  * case, we shouldn't clear any pending lun change unit
9439                  * attention.
9440                  */
9441                 if (request_lun != NULL) {
9442                         mtx_lock(&lun->lun_lock);
9443                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9444                         mtx_unlock(&lun->lun_lock);
9445                 }
9446         }
9447         mtx_unlock(&control_softc->ctl_lock);
9448
9449         /*
9450          * It's quite possible that we've returned fewer LUNs than we allocated
9451          * space for.  Trim it.
9452          */
9453         lun_datalen = sizeof(*lun_data) +
9454                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9455
9456         if (lun_datalen < alloc_len) {
9457                 ctsio->residual = alloc_len - lun_datalen;
9458                 ctsio->kern_data_len = lun_datalen;
9459                 ctsio->kern_total_len = lun_datalen;
9460         } else {
9461                 ctsio->residual = 0;
9462                 ctsio->kern_data_len = alloc_len;
9463                 ctsio->kern_total_len = alloc_len;
9464         }
9465         ctsio->kern_data_resid = 0;
9466         ctsio->kern_rel_offset = 0;
9467         ctsio->kern_sg_entries = 0;
9468
9469         /*
9470          * We set this to the actual data length, regardless of how much
9471          * space we actually have to return results.  If the user looks at
9472          * this value, he'll know whether or not he allocated enough space
9473          * and reissue the command if necessary.  We don't support well
9474          * known logical units, so if the user asks for that, return none.
9475          */
9476         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9477
9478         /*
9479          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9480          * this request.
9481          */
9482         ctsio->scsi_status = SCSI_STATUS_OK;
9483
9484         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9485         ctsio->be_move_done = ctl_config_move_done;
9486         ctl_datamove((union ctl_io *)ctsio);
9487
9488         return (retval);
9489 }
9490
9491 int
9492 ctl_request_sense(struct ctl_scsiio *ctsio)
9493 {
9494         struct scsi_request_sense *cdb;
9495         struct scsi_sense_data *sense_ptr;
9496         struct ctl_lun *lun;
9497         uint32_t initidx;
9498         int have_error;
9499         scsi_sense_data_type sense_format;
9500
9501         cdb = (struct scsi_request_sense *)ctsio->cdb;
9502
9503         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9504
9505         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9506
9507         /*
9508          * Determine which sense format the user wants.
9509          */
9510         if (cdb->byte2 & SRS_DESC)
9511                 sense_format = SSD_TYPE_DESC;
9512         else
9513                 sense_format = SSD_TYPE_FIXED;
9514
9515         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9516         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9517         ctsio->kern_sg_entries = 0;
9518
9519         /*
9520          * struct scsi_sense_data, which is currently set to 256 bytes, is
9521          * larger than the largest allowed value for the length field in the
9522          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9523          */
9524         ctsio->residual = 0;
9525         ctsio->kern_data_len = cdb->length;
9526         ctsio->kern_total_len = cdb->length;
9527
9528         ctsio->kern_data_resid = 0;
9529         ctsio->kern_rel_offset = 0;
9530         ctsio->kern_sg_entries = 0;
9531
9532         /*
9533          * If we don't have a LUN, we don't have any pending sense.
9534          */
9535         if (lun == NULL)
9536                 goto no_sense;
9537
9538         have_error = 0;
9539         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9540         /*
9541          * Check for pending sense, and then for pending unit attentions.
9542          * Pending sense gets returned first, then pending unit attentions.
9543          */
9544         mtx_lock(&lun->lun_lock);
9545 #ifdef CTL_WITH_CA
9546         if (ctl_is_set(lun->have_ca, initidx)) {
9547                 scsi_sense_data_type stored_format;
9548
9549                 /*
9550                  * Check to see which sense format was used for the stored
9551                  * sense data.
9552                  */
9553                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9554
9555                 /*
9556                  * If the user requested a different sense format than the
9557                  * one we stored, then we need to convert it to the other
9558                  * format.  If we're going from descriptor to fixed format
9559                  * sense data, we may lose things in translation, depending
9560                  * on what options were used.
9561                  *
9562                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9563                  * for some reason we'll just copy it out as-is.
9564                  */
9565                 if ((stored_format == SSD_TYPE_FIXED)
9566                  && (sense_format == SSD_TYPE_DESC))
9567                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9568                             &lun->pending_sense[initidx],
9569                             (struct scsi_sense_data_desc *)sense_ptr);
9570                 else if ((stored_format == SSD_TYPE_DESC)
9571                       && (sense_format == SSD_TYPE_FIXED))
9572                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9573                             &lun->pending_sense[initidx],
9574                             (struct scsi_sense_data_fixed *)sense_ptr);
9575                 else
9576                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9577                                ctl_min(sizeof(*sense_ptr),
9578                                sizeof(lun->pending_sense[initidx])));
9579
9580                 ctl_clear_mask(lun->have_ca, initidx);
9581                 have_error = 1;
9582         } else
9583 #endif
9584         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9585                 ctl_ua_type ua_type;
9586
9587                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9588                                        sense_ptr, sense_format);
9589                 if (ua_type != CTL_UA_NONE)
9590                         have_error = 1;
9591         }
9592         mtx_unlock(&lun->lun_lock);
9593
9594         /*
9595          * We already have a pending error, return it.
9596          */
9597         if (have_error != 0) {
9598                 /*
9599                  * We report the SCSI status as OK, since the status of the
9600                  * request sense command itself is OK.
9601                  */
9602                 ctsio->scsi_status = SCSI_STATUS_OK;
9603
9604                 /*
9605                  * We report 0 for the sense length, because we aren't doing
9606                  * autosense in this case.  We're reporting sense as
9607                  * parameter data.
9608                  */
9609                 ctsio->sense_len = 0;
9610                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9611                 ctsio->be_move_done = ctl_config_move_done;
9612                 ctl_datamove((union ctl_io *)ctsio);
9613
9614                 return (CTL_RETVAL_COMPLETE);
9615         }
9616
9617 no_sense:
9618
9619         /*
9620          * No sense information to report, so we report that everything is
9621          * okay.
9622          */
9623         ctl_set_sense_data(sense_ptr,
9624                            lun,
9625                            sense_format,
9626                            /*current_error*/ 1,
9627                            /*sense_key*/ SSD_KEY_NO_SENSE,
9628                            /*asc*/ 0x00,
9629                            /*ascq*/ 0x00,
9630                            SSD_ELEM_NONE);
9631
9632         ctsio->scsi_status = SCSI_STATUS_OK;
9633
9634         /*
9635          * We report 0 for the sense length, because we aren't doing
9636          * autosense in this case.  We're reporting sense as parameter data.
9637          */
9638         ctsio->sense_len = 0;
9639         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9640         ctsio->be_move_done = ctl_config_move_done;
9641         ctl_datamove((union ctl_io *)ctsio);
9642
9643         return (CTL_RETVAL_COMPLETE);
9644 }
9645
9646 int
9647 ctl_tur(struct ctl_scsiio *ctsio)
9648 {
9649         struct ctl_lun *lun;
9650
9651         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9652
9653         CTL_DEBUG_PRINT(("ctl_tur\n"));
9654
9655         if (lun == NULL)
9656                 return (EINVAL);
9657
9658         ctsio->scsi_status = SCSI_STATUS_OK;
9659         ctsio->io_hdr.status = CTL_SUCCESS;
9660
9661         ctl_done((union ctl_io *)ctsio);
9662
9663         return (CTL_RETVAL_COMPLETE);
9664 }
9665
9666 #ifdef notyet
9667 static int
9668 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9669 {
9670
9671 }
9672 #endif
9673
9674 static int
9675 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9676 {
9677         struct scsi_vpd_supported_pages *pages;
9678         int sup_page_size;
9679         struct ctl_lun *lun;
9680
9681         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9682
9683         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9684             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9685         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9686         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9687         ctsio->kern_sg_entries = 0;
9688
9689         if (sup_page_size < alloc_len) {
9690                 ctsio->residual = alloc_len - sup_page_size;
9691                 ctsio->kern_data_len = sup_page_size;
9692                 ctsio->kern_total_len = sup_page_size;
9693         } else {
9694                 ctsio->residual = 0;
9695                 ctsio->kern_data_len = alloc_len;
9696                 ctsio->kern_total_len = alloc_len;
9697         }
9698         ctsio->kern_data_resid = 0;
9699         ctsio->kern_rel_offset = 0;
9700         ctsio->kern_sg_entries = 0;
9701
9702         /*
9703          * The control device is always connected.  The disk device, on the
9704          * other hand, may not be online all the time.  Need to change this
9705          * to figure out whether the disk device is actually online or not.
9706          */
9707         if (lun != NULL)
9708                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9709                                 lun->be_lun->lun_type;
9710         else
9711                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9712
9713         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9714         /* Supported VPD pages */
9715         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9716         /* Serial Number */
9717         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9718         /* Device Identification */
9719         pages->page_list[2] = SVPD_DEVICE_ID;
9720         /* Extended INQUIRY Data */
9721         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9722         /* Mode Page Policy */
9723         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9724         /* SCSI Ports */
9725         pages->page_list[5] = SVPD_SCSI_PORTS;
9726         /* Third-party Copy */
9727         pages->page_list[6] = SVPD_SCSI_TPC;
9728         /* Block limits */
9729         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9730         /* Block Device Characteristics */
9731         pages->page_list[8] = SVPD_BDC;
9732         /* Logical Block Provisioning */
9733         pages->page_list[9] = SVPD_LBP;
9734
9735         ctsio->scsi_status = SCSI_STATUS_OK;
9736
9737         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9738         ctsio->be_move_done = ctl_config_move_done;
9739         ctl_datamove((union ctl_io *)ctsio);
9740
9741         return (CTL_RETVAL_COMPLETE);
9742 }
9743
9744 static int
9745 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9746 {
9747         struct scsi_vpd_unit_serial_number *sn_ptr;
9748         struct ctl_lun *lun;
9749         int data_len;
9750
9751         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9752
9753         data_len = 4 + CTL_SN_LEN;
9754         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9755         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9756         if (data_len < alloc_len) {
9757                 ctsio->residual = alloc_len - data_len;
9758                 ctsio->kern_data_len = data_len;
9759                 ctsio->kern_total_len = data_len;
9760         } else {
9761                 ctsio->residual = 0;
9762                 ctsio->kern_data_len = alloc_len;
9763                 ctsio->kern_total_len = alloc_len;
9764         }
9765         ctsio->kern_data_resid = 0;
9766         ctsio->kern_rel_offset = 0;
9767         ctsio->kern_sg_entries = 0;
9768
9769         /*
9770          * The control device is always connected.  The disk device, on the
9771          * other hand, may not be online all the time.  Need to change this
9772          * to figure out whether the disk device is actually online or not.
9773          */
9774         if (lun != NULL)
9775                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9776                                   lun->be_lun->lun_type;
9777         else
9778                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9779
9780         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9781         sn_ptr->length = CTL_SN_LEN;
9782         /*
9783          * If we don't have a LUN, we just leave the serial number as
9784          * all spaces.
9785          */
9786         if (lun != NULL) {
9787                 strncpy((char *)sn_ptr->serial_num,
9788                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9789         } else
9790                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9791         ctsio->scsi_status = SCSI_STATUS_OK;
9792
9793         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9794         ctsio->be_move_done = ctl_config_move_done;
9795         ctl_datamove((union ctl_io *)ctsio);
9796
9797         return (CTL_RETVAL_COMPLETE);
9798 }
9799
9800
9801 static int
9802 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9803 {
9804         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9805         struct ctl_lun *lun;
9806         int data_len;
9807
9808         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9809
9810         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9811         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9812         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9813         ctsio->kern_sg_entries = 0;
9814
9815         if (data_len < alloc_len) {
9816                 ctsio->residual = alloc_len - data_len;
9817                 ctsio->kern_data_len = data_len;
9818                 ctsio->kern_total_len = data_len;
9819         } else {
9820                 ctsio->residual = 0;
9821                 ctsio->kern_data_len = alloc_len;
9822                 ctsio->kern_total_len = alloc_len;
9823         }
9824         ctsio->kern_data_resid = 0;
9825         ctsio->kern_rel_offset = 0;
9826         ctsio->kern_sg_entries = 0;
9827
9828         /*
9829          * The control device is always connected.  The disk device, on the
9830          * other hand, may not be online all the time.
9831          */
9832         if (lun != NULL)
9833                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9834                                      lun->be_lun->lun_type;
9835         else
9836                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9837         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9838         eid_ptr->page_length = data_len - 4;
9839         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9840         eid_ptr->flags3 = SVPD_EID_V_SUP;
9841
9842         ctsio->scsi_status = SCSI_STATUS_OK;
9843         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9844         ctsio->be_move_done = ctl_config_move_done;
9845         ctl_datamove((union ctl_io *)ctsio);
9846
9847         return (CTL_RETVAL_COMPLETE);
9848 }
9849
9850 static int
9851 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9852 {
9853         struct scsi_vpd_mode_page_policy *mpp_ptr;
9854         struct ctl_lun *lun;
9855         int data_len;
9856
9857         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9858
9859         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9860             sizeof(struct scsi_vpd_mode_page_policy_descr);
9861
9862         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9863         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9864         ctsio->kern_sg_entries = 0;
9865
9866         if (data_len < alloc_len) {
9867                 ctsio->residual = alloc_len - data_len;
9868                 ctsio->kern_data_len = data_len;
9869                 ctsio->kern_total_len = data_len;
9870         } else {
9871                 ctsio->residual = 0;
9872                 ctsio->kern_data_len = alloc_len;
9873                 ctsio->kern_total_len = alloc_len;
9874         }
9875         ctsio->kern_data_resid = 0;
9876         ctsio->kern_rel_offset = 0;
9877         ctsio->kern_sg_entries = 0;
9878
9879         /*
9880          * The control device is always connected.  The disk device, on the
9881          * other hand, may not be online all the time.
9882          */
9883         if (lun != NULL)
9884                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9885                                      lun->be_lun->lun_type;
9886         else
9887                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9888         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9889         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9890         mpp_ptr->descr[0].page_code = 0x3f;
9891         mpp_ptr->descr[0].subpage_code = 0xff;
9892         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9893
9894         ctsio->scsi_status = SCSI_STATUS_OK;
9895         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9896         ctsio->be_move_done = ctl_config_move_done;
9897         ctl_datamove((union ctl_io *)ctsio);
9898
9899         return (CTL_RETVAL_COMPLETE);
9900 }
9901
9902 static int
9903 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9904 {
9905         struct scsi_vpd_device_id *devid_ptr;
9906         struct scsi_vpd_id_descriptor *desc;
9907         struct ctl_softc *ctl_softc;
9908         struct ctl_lun *lun;
9909         struct ctl_port *port;
9910         int data_len;
9911         uint8_t proto;
9912
9913         ctl_softc = control_softc;
9914
9915         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9916         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9917
9918         data_len = sizeof(struct scsi_vpd_device_id) +
9919             sizeof(struct scsi_vpd_id_descriptor) +
9920                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9921             sizeof(struct scsi_vpd_id_descriptor) +
9922                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9923         if (lun && lun->lun_devid)
9924                 data_len += lun->lun_devid->len;
9925         if (port->port_devid)
9926                 data_len += port->port_devid->len;
9927         if (port->target_devid)
9928                 data_len += port->target_devid->len;
9929
9930         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9931         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9932         ctsio->kern_sg_entries = 0;
9933
9934         if (data_len < alloc_len) {
9935                 ctsio->residual = alloc_len - data_len;
9936                 ctsio->kern_data_len = data_len;
9937                 ctsio->kern_total_len = data_len;
9938         } else {
9939                 ctsio->residual = 0;
9940                 ctsio->kern_data_len = alloc_len;
9941                 ctsio->kern_total_len = alloc_len;
9942         }
9943         ctsio->kern_data_resid = 0;
9944         ctsio->kern_rel_offset = 0;
9945         ctsio->kern_sg_entries = 0;
9946
9947         /*
9948          * The control device is always connected.  The disk device, on the
9949          * other hand, may not be online all the time.
9950          */
9951         if (lun != NULL)
9952                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9953                                      lun->be_lun->lun_type;
9954         else
9955                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9956         devid_ptr->page_code = SVPD_DEVICE_ID;
9957         scsi_ulto2b(data_len - 4, devid_ptr->length);
9958
9959         if (port->port_type == CTL_PORT_FC)
9960                 proto = SCSI_PROTO_FC << 4;
9961         else if (port->port_type == CTL_PORT_ISCSI)
9962                 proto = SCSI_PROTO_ISCSI << 4;
9963         else
9964                 proto = SCSI_PROTO_SPI << 4;
9965         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9966
9967         /*
9968          * We're using a LUN association here.  i.e., this device ID is a
9969          * per-LUN identifier.
9970          */
9971         if (lun && lun->lun_devid) {
9972                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9973                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9974                     lun->lun_devid->len);
9975         }
9976
9977         /*
9978          * This is for the WWPN which is a port association.
9979          */
9980         if (port->port_devid) {
9981                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9982                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9983                     port->port_devid->len);
9984         }
9985
9986         /*
9987          * This is for the Relative Target Port(type 4h) identifier
9988          */
9989         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9990         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9991             SVPD_ID_TYPE_RELTARG;
9992         desc->length = 4;
9993         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9994         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9995             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9996
9997         /*
9998          * This is for the Target Port Group(type 5h) identifier
9999          */
10000         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10001         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10002             SVPD_ID_TYPE_TPORTGRP;
10003         desc->length = 4;
10004         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10005             &desc->identifier[2]);
10006         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10007             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10008
10009         /*
10010          * This is for the Target identifier
10011          */
10012         if (port->target_devid) {
10013                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10014         }
10015
10016         ctsio->scsi_status = SCSI_STATUS_OK;
10017         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10018         ctsio->be_move_done = ctl_config_move_done;
10019         ctl_datamove((union ctl_io *)ctsio);
10020
10021         return (CTL_RETVAL_COMPLETE);
10022 }
10023
10024 static int
10025 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10026 {
10027         struct ctl_softc *softc = control_softc;
10028         struct scsi_vpd_scsi_ports *sp;
10029         struct scsi_vpd_port_designation *pd;
10030         struct scsi_vpd_port_designation_cont *pdc;
10031         struct ctl_lun *lun;
10032         struct ctl_port *port;
10033         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10034         int num_target_port_groups, single;
10035
10036         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10037
10038         single = ctl_is_single;
10039         if (single)
10040                 num_target_port_groups = 1;
10041         else
10042                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10043         num_target_ports = 0;
10044         iid_len = 0;
10045         id_len = 0;
10046         mtx_lock(&softc->ctl_lock);
10047         STAILQ_FOREACH(port, &softc->port_list, links) {
10048                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10049                         continue;
10050                 if (lun != NULL &&
10051                     ctl_map_lun_back(port->targ_port, lun->lun) >=
10052                     CTL_MAX_LUNS)
10053                         continue;
10054                 num_target_ports++;
10055                 if (port->init_devid)
10056                         iid_len += port->init_devid->len;
10057                 if (port->port_devid)
10058                         id_len += port->port_devid->len;
10059         }
10060         mtx_unlock(&softc->ctl_lock);
10061
10062         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10063             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10064              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10065         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10066         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10067         ctsio->kern_sg_entries = 0;
10068
10069         if (data_len < alloc_len) {
10070                 ctsio->residual = alloc_len - data_len;
10071                 ctsio->kern_data_len = data_len;
10072                 ctsio->kern_total_len = data_len;
10073         } else {
10074                 ctsio->residual = 0;
10075                 ctsio->kern_data_len = alloc_len;
10076                 ctsio->kern_total_len = alloc_len;
10077         }
10078         ctsio->kern_data_resid = 0;
10079         ctsio->kern_rel_offset = 0;
10080         ctsio->kern_sg_entries = 0;
10081
10082         /*
10083          * The control device is always connected.  The disk device, on the
10084          * other hand, may not be online all the time.  Need to change this
10085          * to figure out whether the disk device is actually online or not.
10086          */
10087         if (lun != NULL)
10088                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10089                                   lun->be_lun->lun_type;
10090         else
10091                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10092
10093         sp->page_code = SVPD_SCSI_PORTS;
10094         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10095             sp->page_length);
10096         pd = &sp->design[0];
10097
10098         mtx_lock(&softc->ctl_lock);
10099         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10100                 pg = 0;
10101         else
10102                 pg = 1;
10103         for (g = 0; g < num_target_port_groups; g++) {
10104                 STAILQ_FOREACH(port, &softc->port_list, links) {
10105                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10106                                 continue;
10107                         if (lun != NULL &&
10108                             ctl_map_lun_back(port->targ_port, lun->lun) >=
10109                             CTL_MAX_LUNS)
10110                                 continue;
10111                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10112                         scsi_ulto2b(p, pd->relative_port_id);
10113                         if (port->init_devid && g == pg) {
10114                                 iid_len = port->init_devid->len;
10115                                 memcpy(pd->initiator_transportid,
10116                                     port->init_devid->data, port->init_devid->len);
10117                         } else
10118                                 iid_len = 0;
10119                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10120                         pdc = (struct scsi_vpd_port_designation_cont *)
10121                             (&pd->initiator_transportid[iid_len]);
10122                         if (port->port_devid && g == pg) {
10123                                 id_len = port->port_devid->len;
10124                                 memcpy(pdc->target_port_descriptors,
10125                                     port->port_devid->data, port->port_devid->len);
10126                         } else
10127                                 id_len = 0;
10128                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10129                         pd = (struct scsi_vpd_port_designation *)
10130                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10131                 }
10132         }
10133         mtx_unlock(&softc->ctl_lock);
10134
10135         ctsio->scsi_status = SCSI_STATUS_OK;
10136         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10137         ctsio->be_move_done = ctl_config_move_done;
10138         ctl_datamove((union ctl_io *)ctsio);
10139
10140         return (CTL_RETVAL_COMPLETE);
10141 }
10142
10143 static int
10144 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10145 {
10146         struct scsi_vpd_block_limits *bl_ptr;
10147         struct ctl_lun *lun;
10148         int bs;
10149
10150         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10151
10152         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10153         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10154         ctsio->kern_sg_entries = 0;
10155
10156         if (sizeof(*bl_ptr) < alloc_len) {
10157                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10158                 ctsio->kern_data_len = sizeof(*bl_ptr);
10159                 ctsio->kern_total_len = sizeof(*bl_ptr);
10160         } else {
10161                 ctsio->residual = 0;
10162                 ctsio->kern_data_len = alloc_len;
10163                 ctsio->kern_total_len = alloc_len;
10164         }
10165         ctsio->kern_data_resid = 0;
10166         ctsio->kern_rel_offset = 0;
10167         ctsio->kern_sg_entries = 0;
10168
10169         /*
10170          * The control device is always connected.  The disk device, on the
10171          * other hand, may not be online all the time.  Need to change this
10172          * to figure out whether the disk device is actually online or not.
10173          */
10174         if (lun != NULL)
10175                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10176                                   lun->be_lun->lun_type;
10177         else
10178                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10179
10180         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10181         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10182         bl_ptr->max_cmp_write_len = 0xff;
10183         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10184         if (lun != NULL) {
10185                 bs = lun->be_lun->blocksize;
10186                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10187                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10188                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10189                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10190                         if (lun->be_lun->pblockexp != 0) {
10191                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10192                                     bl_ptr->opt_unmap_grain);
10193                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10194                                     bl_ptr->unmap_grain_align);
10195                         }
10196                 }
10197                 scsi_ulto4b(lun->be_lun->atomicblock,
10198                     bl_ptr->max_atomic_transfer_length);
10199                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10200                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10201         }
10202         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10203
10204         ctsio->scsi_status = SCSI_STATUS_OK;
10205         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10206         ctsio->be_move_done = ctl_config_move_done;
10207         ctl_datamove((union ctl_io *)ctsio);
10208
10209         return (CTL_RETVAL_COMPLETE);
10210 }
10211
10212 static int
10213 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10214 {
10215         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10216         struct ctl_lun *lun;
10217         const char *value;
10218         u_int i;
10219
10220         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10221
10222         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10223         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10224         ctsio->kern_sg_entries = 0;
10225
10226         if (sizeof(*bdc_ptr) < alloc_len) {
10227                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10228                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10229                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10230         } else {
10231                 ctsio->residual = 0;
10232                 ctsio->kern_data_len = alloc_len;
10233                 ctsio->kern_total_len = alloc_len;
10234         }
10235         ctsio->kern_data_resid = 0;
10236         ctsio->kern_rel_offset = 0;
10237         ctsio->kern_sg_entries = 0;
10238
10239         /*
10240          * The control device is always connected.  The disk device, on the
10241          * other hand, may not be online all the time.  Need to change this
10242          * to figure out whether the disk device is actually online or not.
10243          */
10244         if (lun != NULL)
10245                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10246                                   lun->be_lun->lun_type;
10247         else
10248                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10249         bdc_ptr->page_code = SVPD_BDC;
10250         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10251         if (lun != NULL &&
10252             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10253                 i = strtol(value, NULL, 0);
10254         else
10255                 i = SVPD_NON_ROTATING;
10256         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10257         if (lun != NULL &&
10258             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10259                 i = strtol(value, NULL, 0);
10260         else
10261                 i = 0;
10262         bdc_ptr->wab_wac_ff = (i & 0x0f);
10263         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10264
10265         ctsio->scsi_status = SCSI_STATUS_OK;
10266         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10267         ctsio->be_move_done = ctl_config_move_done;
10268         ctl_datamove((union ctl_io *)ctsio);
10269
10270         return (CTL_RETVAL_COMPLETE);
10271 }
10272
10273 static int
10274 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10275 {
10276         struct scsi_vpd_logical_block_prov *lbp_ptr;
10277         struct ctl_lun *lun;
10278
10279         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10280
10281         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10282         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10283         ctsio->kern_sg_entries = 0;
10284
10285         if (sizeof(*lbp_ptr) < alloc_len) {
10286                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10287                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10288                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10289         } else {
10290                 ctsio->residual = 0;
10291                 ctsio->kern_data_len = alloc_len;
10292                 ctsio->kern_total_len = alloc_len;
10293         }
10294         ctsio->kern_data_resid = 0;
10295         ctsio->kern_rel_offset = 0;
10296         ctsio->kern_sg_entries = 0;
10297
10298         /*
10299          * The control device is always connected.  The disk device, on the
10300          * other hand, may not be online all the time.  Need to change this
10301          * to figure out whether the disk device is actually online or not.
10302          */
10303         if (lun != NULL)
10304                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10305                                   lun->be_lun->lun_type;
10306         else
10307                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10308
10309         lbp_ptr->page_code = SVPD_LBP;
10310         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10311         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10312                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10313                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10314                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10315         }
10316
10317         ctsio->scsi_status = SCSI_STATUS_OK;
10318         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10319         ctsio->be_move_done = ctl_config_move_done;
10320         ctl_datamove((union ctl_io *)ctsio);
10321
10322         return (CTL_RETVAL_COMPLETE);
10323 }
10324
10325 static int
10326 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10327 {
10328         struct scsi_inquiry *cdb;
10329         struct ctl_lun *lun;
10330         int alloc_len, retval;
10331
10332         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10333         cdb = (struct scsi_inquiry *)ctsio->cdb;
10334
10335         retval = CTL_RETVAL_COMPLETE;
10336
10337         alloc_len = scsi_2btoul(cdb->length);
10338
10339         switch (cdb->page_code) {
10340         case SVPD_SUPPORTED_PAGES:
10341                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10342                 break;
10343         case SVPD_UNIT_SERIAL_NUMBER:
10344                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10345                 break;
10346         case SVPD_DEVICE_ID:
10347                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10348                 break;
10349         case SVPD_EXTENDED_INQUIRY_DATA:
10350                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10351                 break;
10352         case SVPD_MODE_PAGE_POLICY:
10353                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10354                 break;
10355         case SVPD_SCSI_PORTS:
10356                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10357                 break;
10358         case SVPD_SCSI_TPC:
10359                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10360                 break;
10361         case SVPD_BLOCK_LIMITS:
10362                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10363                 break;
10364         case SVPD_BDC:
10365                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10366                 break;
10367         case SVPD_LBP:
10368                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10369                 break;
10370         default:
10371                 ctl_set_invalid_field(ctsio,
10372                                       /*sks_valid*/ 1,
10373                                       /*command*/ 1,
10374                                       /*field*/ 2,
10375                                       /*bit_valid*/ 0,
10376                                       /*bit*/ 0);
10377                 ctl_done((union ctl_io *)ctsio);
10378                 retval = CTL_RETVAL_COMPLETE;
10379                 break;
10380         }
10381
10382         return (retval);
10383 }
10384
10385 static int
10386 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10387 {
10388         struct scsi_inquiry_data *inq_ptr;
10389         struct scsi_inquiry *cdb;
10390         struct ctl_softc *ctl_softc;
10391         struct ctl_lun *lun;
10392         char *val;
10393         uint32_t alloc_len, data_len;
10394         ctl_port_type port_type;
10395
10396         ctl_softc = control_softc;
10397
10398         /*
10399          * Figure out whether we're talking to a Fibre Channel port or not.
10400          * We treat the ioctl front end, and any SCSI adapters, as packetized
10401          * SCSI front ends.
10402          */
10403         port_type = ctl_softc->ctl_ports[
10404             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10405         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10406                 port_type = CTL_PORT_SCSI;
10407
10408         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10409         cdb = (struct scsi_inquiry *)ctsio->cdb;
10410         alloc_len = scsi_2btoul(cdb->length);
10411
10412         /*
10413          * We malloc the full inquiry data size here and fill it
10414          * in.  If the user only asks for less, we'll give him
10415          * that much.
10416          */
10417         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10418         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10419         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10420         ctsio->kern_sg_entries = 0;
10421         ctsio->kern_data_resid = 0;
10422         ctsio->kern_rel_offset = 0;
10423
10424         if (data_len < alloc_len) {
10425                 ctsio->residual = alloc_len - data_len;
10426                 ctsio->kern_data_len = data_len;
10427                 ctsio->kern_total_len = data_len;
10428         } else {
10429                 ctsio->residual = 0;
10430                 ctsio->kern_data_len = alloc_len;
10431                 ctsio->kern_total_len = alloc_len;
10432         }
10433
10434         /*
10435          * If we have a LUN configured, report it as connected.  Otherwise,
10436          * report that it is offline or no device is supported, depending 
10437          * on the value of inquiry_pq_no_lun.
10438          *
10439          * According to the spec (SPC-4 r34), the peripheral qualifier
10440          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10441          *
10442          * "A peripheral device having the specified peripheral device type 
10443          * is not connected to this logical unit. However, the device
10444          * server is capable of supporting the specified peripheral device
10445          * type on this logical unit."
10446          *
10447          * According to the same spec, the peripheral qualifier
10448          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10449          *
10450          * "The device server is not capable of supporting a peripheral
10451          * device on this logical unit. For this peripheral qualifier the
10452          * peripheral device type shall be set to 1Fh. All other peripheral
10453          * device type values are reserved for this peripheral qualifier."
10454          *
10455          * Given the text, it would seem that we probably want to report that
10456          * the LUN is offline here.  There is no LUN connected, but we can
10457          * support a LUN at the given LUN number.
10458          *
10459          * In the real world, though, it sounds like things are a little
10460          * different:
10461          *
10462          * - Linux, when presented with a LUN with the offline peripheral
10463          *   qualifier, will create an sg driver instance for it.  So when
10464          *   you attach it to CTL, you wind up with a ton of sg driver
10465          *   instances.  (One for every LUN that Linux bothered to probe.)
10466          *   Linux does this despite the fact that it issues a REPORT LUNs
10467          *   to LUN 0 to get the inventory of supported LUNs.
10468          *
10469          * - There is other anecdotal evidence (from Emulex folks) about
10470          *   arrays that use the offline peripheral qualifier for LUNs that
10471          *   are on the "passive" path in an active/passive array.
10472          *
10473          * So the solution is provide a hopefully reasonable default
10474          * (return bad/no LUN) and allow the user to change the behavior
10475          * with a tunable/sysctl variable.
10476          */
10477         if (lun != NULL)
10478                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10479                                   lun->be_lun->lun_type;
10480         else if (ctl_softc->inquiry_pq_no_lun == 0)
10481                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10482         else
10483                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10484
10485         /* RMB in byte 2 is 0 */
10486         inq_ptr->version = SCSI_REV_SPC4;
10487
10488         /*
10489          * According to SAM-3, even if a device only supports a single
10490          * level of LUN addressing, it should still set the HISUP bit:
10491          *
10492          * 4.9.1 Logical unit numbers overview
10493          *
10494          * All logical unit number formats described in this standard are
10495          * hierarchical in structure even when only a single level in that
10496          * hierarchy is used. The HISUP bit shall be set to one in the
10497          * standard INQUIRY data (see SPC-2) when any logical unit number
10498          * format described in this standard is used.  Non-hierarchical
10499          * formats are outside the scope of this standard.
10500          *
10501          * Therefore we set the HiSup bit here.
10502          *
10503          * The reponse format is 2, per SPC-3.
10504          */
10505         inq_ptr->response_format = SID_HiSup | 2;
10506
10507         inq_ptr->additional_length = data_len -
10508             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10509         CTL_DEBUG_PRINT(("additional_length = %d\n",
10510                          inq_ptr->additional_length));
10511
10512         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10513         /* 16 bit addressing */
10514         if (port_type == CTL_PORT_SCSI)
10515                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10516         /* XXX set the SID_MultiP bit here if we're actually going to
10517            respond on multiple ports */
10518         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10519
10520         /* 16 bit data bus, synchronous transfers */
10521         if (port_type == CTL_PORT_SCSI)
10522                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10523         /*
10524          * XXX KDM do we want to support tagged queueing on the control
10525          * device at all?
10526          */
10527         if ((lun == NULL)
10528          || (lun->be_lun->lun_type != T_PROCESSOR))
10529                 inq_ptr->flags |= SID_CmdQue;
10530         /*
10531          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10532          * We have 8 bytes for the vendor name, and 16 bytes for the device
10533          * name and 4 bytes for the revision.
10534          */
10535         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10536             "vendor")) == NULL) {
10537                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10538         } else {
10539                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10540                 strncpy(inq_ptr->vendor, val,
10541                     min(sizeof(inq_ptr->vendor), strlen(val)));
10542         }
10543         if (lun == NULL) {
10544                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10545                     sizeof(inq_ptr->product));
10546         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10547                 switch (lun->be_lun->lun_type) {
10548                 case T_DIRECT:
10549                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10550                             sizeof(inq_ptr->product));
10551                         break;
10552                 case T_PROCESSOR:
10553                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10554                             sizeof(inq_ptr->product));
10555                         break;
10556                 default:
10557                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10558                             sizeof(inq_ptr->product));
10559                         break;
10560                 }
10561         } else {
10562                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10563                 strncpy(inq_ptr->product, val,
10564                     min(sizeof(inq_ptr->product), strlen(val)));
10565         }
10566
10567         /*
10568          * XXX make this a macro somewhere so it automatically gets
10569          * incremented when we make changes.
10570          */
10571         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10572             "revision")) == NULL) {
10573                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10574         } else {
10575                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10576                 strncpy(inq_ptr->revision, val,
10577                     min(sizeof(inq_ptr->revision), strlen(val)));
10578         }
10579
10580         /*
10581          * For parallel SCSI, we support double transition and single
10582          * transition clocking.  We also support QAS (Quick Arbitration
10583          * and Selection) and Information Unit transfers on both the
10584          * control and array devices.
10585          */
10586         if (port_type == CTL_PORT_SCSI)
10587                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10588                                     SID_SPI_IUS;
10589
10590         /* SAM-5 (no version claimed) */
10591         scsi_ulto2b(0x00A0, inq_ptr->version1);
10592         /* SPC-4 (no version claimed) */
10593         scsi_ulto2b(0x0460, inq_ptr->version2);
10594         if (port_type == CTL_PORT_FC) {
10595                 /* FCP-2 ANSI INCITS.350:2003 */
10596                 scsi_ulto2b(0x0917, inq_ptr->version3);
10597         } else if (port_type == CTL_PORT_SCSI) {
10598                 /* SPI-4 ANSI INCITS.362:200x */
10599                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10600         } else if (port_type == CTL_PORT_ISCSI) {
10601                 /* iSCSI (no version claimed) */
10602                 scsi_ulto2b(0x0960, inq_ptr->version3);
10603         } else if (port_type == CTL_PORT_SAS) {
10604                 /* SAS (no version claimed) */
10605                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10606         }
10607
10608         if (lun == NULL) {
10609                 /* SBC-4 (no version claimed) */
10610                 scsi_ulto2b(0x0600, inq_ptr->version4);
10611         } else {
10612                 switch (lun->be_lun->lun_type) {
10613                 case T_DIRECT:
10614                         /* SBC-4 (no version claimed) */
10615                         scsi_ulto2b(0x0600, inq_ptr->version4);
10616                         break;
10617                 case T_PROCESSOR:
10618                 default:
10619                         break;
10620                 }
10621         }
10622
10623         ctsio->scsi_status = SCSI_STATUS_OK;
10624         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10625         ctsio->be_move_done = ctl_config_move_done;
10626         ctl_datamove((union ctl_io *)ctsio);
10627         return (CTL_RETVAL_COMPLETE);
10628 }
10629
10630 int
10631 ctl_inquiry(struct ctl_scsiio *ctsio)
10632 {
10633         struct scsi_inquiry *cdb;
10634         int retval;
10635
10636         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10637
10638         cdb = (struct scsi_inquiry *)ctsio->cdb;
10639         if (cdb->byte2 & SI_EVPD)
10640                 retval = ctl_inquiry_evpd(ctsio);
10641         else if (cdb->page_code == 0)
10642                 retval = ctl_inquiry_std(ctsio);
10643         else {
10644                 ctl_set_invalid_field(ctsio,
10645                                       /*sks_valid*/ 1,
10646                                       /*command*/ 1,
10647                                       /*field*/ 2,
10648                                       /*bit_valid*/ 0,
10649                                       /*bit*/ 0);
10650                 ctl_done((union ctl_io *)ctsio);
10651                 return (CTL_RETVAL_COMPLETE);
10652         }
10653
10654         return (retval);
10655 }
10656
10657 /*
10658  * For known CDB types, parse the LBA and length.
10659  */
10660 static int
10661 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10662 {
10663         if (io->io_hdr.io_type != CTL_IO_SCSI)
10664                 return (1);
10665
10666         switch (io->scsiio.cdb[0]) {
10667         case COMPARE_AND_WRITE: {
10668                 struct scsi_compare_and_write *cdb;
10669
10670                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10671
10672                 *lba = scsi_8btou64(cdb->addr);
10673                 *len = cdb->length;
10674                 break;
10675         }
10676         case READ_6:
10677         case WRITE_6: {
10678                 struct scsi_rw_6 *cdb;
10679
10680                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10681
10682                 *lba = scsi_3btoul(cdb->addr);
10683                 /* only 5 bits are valid in the most significant address byte */
10684                 *lba &= 0x1fffff;
10685                 *len = cdb->length;
10686                 break;
10687         }
10688         case READ_10:
10689         case WRITE_10: {
10690                 struct scsi_rw_10 *cdb;
10691
10692                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10693
10694                 *lba = scsi_4btoul(cdb->addr);
10695                 *len = scsi_2btoul(cdb->length);
10696                 break;
10697         }
10698         case WRITE_VERIFY_10: {
10699                 struct scsi_write_verify_10 *cdb;
10700
10701                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10702
10703                 *lba = scsi_4btoul(cdb->addr);
10704                 *len = scsi_2btoul(cdb->length);
10705                 break;
10706         }
10707         case READ_12:
10708         case WRITE_12: {
10709                 struct scsi_rw_12 *cdb;
10710
10711                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10712
10713                 *lba = scsi_4btoul(cdb->addr);
10714                 *len = scsi_4btoul(cdb->length);
10715                 break;
10716         }
10717         case WRITE_VERIFY_12: {
10718                 struct scsi_write_verify_12 *cdb;
10719
10720                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10721
10722                 *lba = scsi_4btoul(cdb->addr);
10723                 *len = scsi_4btoul(cdb->length);
10724                 break;
10725         }
10726         case READ_16:
10727         case WRITE_16:
10728         case WRITE_ATOMIC_16: {
10729                 struct scsi_rw_16 *cdb;
10730
10731                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10732
10733                 *lba = scsi_8btou64(cdb->addr);
10734                 *len = scsi_4btoul(cdb->length);
10735                 break;
10736         }
10737         case WRITE_VERIFY_16: {
10738                 struct scsi_write_verify_16 *cdb;
10739
10740                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10741
10742                 *lba = scsi_8btou64(cdb->addr);
10743                 *len = scsi_4btoul(cdb->length);
10744                 break;
10745         }
10746         case WRITE_SAME_10: {
10747                 struct scsi_write_same_10 *cdb;
10748
10749                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10750
10751                 *lba = scsi_4btoul(cdb->addr);
10752                 *len = scsi_2btoul(cdb->length);
10753                 break;
10754         }
10755         case WRITE_SAME_16: {
10756                 struct scsi_write_same_16 *cdb;
10757
10758                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10759
10760                 *lba = scsi_8btou64(cdb->addr);
10761                 *len = scsi_4btoul(cdb->length);
10762                 break;
10763         }
10764         case VERIFY_10: {
10765                 struct scsi_verify_10 *cdb;
10766
10767                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10768
10769                 *lba = scsi_4btoul(cdb->addr);
10770                 *len = scsi_2btoul(cdb->length);
10771                 break;
10772         }
10773         case VERIFY_12: {
10774                 struct scsi_verify_12 *cdb;
10775
10776                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10777
10778                 *lba = scsi_4btoul(cdb->addr);
10779                 *len = scsi_4btoul(cdb->length);
10780                 break;
10781         }
10782         case VERIFY_16: {
10783                 struct scsi_verify_16 *cdb;
10784
10785                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10786
10787                 *lba = scsi_8btou64(cdb->addr);
10788                 *len = scsi_4btoul(cdb->length);
10789                 break;
10790         }
10791         case UNMAP: {
10792                 *lba = 0;
10793                 *len = UINT64_MAX;
10794                 break;
10795         }
10796         default:
10797                 return (1);
10798                 break; /* NOTREACHED */
10799         }
10800
10801         return (0);
10802 }
10803
10804 static ctl_action
10805 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10806 {
10807         uint64_t endlba1, endlba2;
10808
10809         endlba1 = lba1 + len1 - 1;
10810         endlba2 = lba2 + len2 - 1;
10811
10812         if ((endlba1 < lba2)
10813          || (endlba2 < lba1))
10814                 return (CTL_ACTION_PASS);
10815         else
10816                 return (CTL_ACTION_BLOCK);
10817 }
10818
10819 static int
10820 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10821 {
10822         struct ctl_ptr_len_flags *ptrlen;
10823         struct scsi_unmap_desc *buf, *end, *range;
10824         uint64_t lba;
10825         uint32_t len;
10826
10827         /* If not UNMAP -- go other way. */
10828         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10829             io->scsiio.cdb[0] != UNMAP)
10830                 return (CTL_ACTION_ERROR);
10831
10832         /* If UNMAP without data -- block and wait for data. */
10833         ptrlen = (struct ctl_ptr_len_flags *)
10834             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10835         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10836             ptrlen->ptr == NULL)
10837                 return (CTL_ACTION_BLOCK);
10838
10839         /* UNMAP with data -- check for collision. */
10840         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10841         end = buf + ptrlen->len / sizeof(*buf);
10842         for (range = buf; range < end; range++) {
10843                 lba = scsi_8btou64(range->lba);
10844                 len = scsi_4btoul(range->length);
10845                 if ((lba < lba2 + len2) && (lba + len > lba2))
10846                         return (CTL_ACTION_BLOCK);
10847         }
10848         return (CTL_ACTION_PASS);
10849 }
10850
10851 static ctl_action
10852 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10853 {
10854         uint64_t lba1, lba2;
10855         uint64_t len1, len2;
10856         int retval;
10857
10858         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10859                 return (CTL_ACTION_ERROR);
10860
10861         retval = ctl_extent_check_unmap(io2, lba1, len1);
10862         if (retval != CTL_ACTION_ERROR)
10863                 return (retval);
10864
10865         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10866                 return (CTL_ACTION_ERROR);
10867
10868         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10869 }
10870
10871 static ctl_action
10872 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10873     union ctl_io *ooa_io)
10874 {
10875         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10876         ctl_serialize_action *serialize_row;
10877
10878         /*
10879          * The initiator attempted multiple untagged commands at the same
10880          * time.  Can't do that.
10881          */
10882         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10883          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10884          && ((pending_io->io_hdr.nexus.targ_port ==
10885               ooa_io->io_hdr.nexus.targ_port)
10886           && (pending_io->io_hdr.nexus.initid.id ==
10887               ooa_io->io_hdr.nexus.initid.id))
10888          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10889                 return (CTL_ACTION_OVERLAP);
10890
10891         /*
10892          * The initiator attempted to send multiple tagged commands with
10893          * the same ID.  (It's fine if different initiators have the same
10894          * tag ID.)
10895          *
10896          * Even if all of those conditions are true, we don't kill the I/O
10897          * if the command ahead of us has been aborted.  We won't end up
10898          * sending it to the FETD, and it's perfectly legal to resend a
10899          * command with the same tag number as long as the previous
10900          * instance of this tag number has been aborted somehow.
10901          */
10902         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10903          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10904          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10905          && ((pending_io->io_hdr.nexus.targ_port ==
10906               ooa_io->io_hdr.nexus.targ_port)
10907           && (pending_io->io_hdr.nexus.initid.id ==
10908               ooa_io->io_hdr.nexus.initid.id))
10909          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10910                 return (CTL_ACTION_OVERLAP_TAG);
10911
10912         /*
10913          * If we get a head of queue tag, SAM-3 says that we should
10914          * immediately execute it.
10915          *
10916          * What happens if this command would normally block for some other
10917          * reason?  e.g. a request sense with a head of queue tag
10918          * immediately after a write.  Normally that would block, but this
10919          * will result in its getting executed immediately...
10920          *
10921          * We currently return "pass" instead of "skip", so we'll end up
10922          * going through the rest of the queue to check for overlapped tags.
10923          *
10924          * XXX KDM check for other types of blockage first??
10925          */
10926         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10927                 return (CTL_ACTION_PASS);
10928
10929         /*
10930          * Ordered tags have to block until all items ahead of them
10931          * have completed.  If we get called with an ordered tag, we always
10932          * block, if something else is ahead of us in the queue.
10933          */
10934         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10935                 return (CTL_ACTION_BLOCK);
10936
10937         /*
10938          * Simple tags get blocked until all head of queue and ordered tags
10939          * ahead of them have completed.  I'm lumping untagged commands in
10940          * with simple tags here.  XXX KDM is that the right thing to do?
10941          */
10942         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10943           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10944          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10945           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10946                 return (CTL_ACTION_BLOCK);
10947
10948         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10949         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10950
10951         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10952
10953         switch (serialize_row[pending_entry->seridx]) {
10954         case CTL_SER_BLOCK:
10955                 return (CTL_ACTION_BLOCK);
10956         case CTL_SER_EXTENT:
10957                 return (ctl_extent_check(pending_io, ooa_io));
10958         case CTL_SER_EXTENTOPT:
10959                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10960                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10961                         return (ctl_extent_check(pending_io, ooa_io));
10962                 /* FALLTHROUGH */
10963         case CTL_SER_PASS:
10964                 return (CTL_ACTION_PASS);
10965         case CTL_SER_BLOCKOPT:
10966                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10967                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10968                         return (CTL_ACTION_BLOCK);
10969                 return (CTL_ACTION_PASS);
10970         case CTL_SER_SKIP:
10971                 return (CTL_ACTION_SKIP);
10972         default:
10973                 panic("invalid serialization value %d",
10974                       serialize_row[pending_entry->seridx]);
10975         }
10976
10977         return (CTL_ACTION_ERROR);
10978 }
10979
10980 /*
10981  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10982  * Assumptions:
10983  * - pending_io is generally either incoming, or on the blocked queue
10984  * - starting I/O is the I/O we want to start the check with.
10985  */
10986 static ctl_action
10987 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10988               union ctl_io *starting_io)
10989 {
10990         union ctl_io *ooa_io;
10991         ctl_action action;
10992
10993         mtx_assert(&lun->lun_lock, MA_OWNED);
10994
10995         /*
10996          * Run back along the OOA queue, starting with the current
10997          * blocked I/O and going through every I/O before it on the
10998          * queue.  If starting_io is NULL, we'll just end up returning
10999          * CTL_ACTION_PASS.
11000          */
11001         for (ooa_io = starting_io; ooa_io != NULL;
11002              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11003              ooa_links)){
11004
11005                 /*
11006                  * This routine just checks to see whether
11007                  * cur_blocked is blocked by ooa_io, which is ahead
11008                  * of it in the queue.  It doesn't queue/dequeue
11009                  * cur_blocked.
11010                  */
11011                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11012                 switch (action) {
11013                 case CTL_ACTION_BLOCK:
11014                 case CTL_ACTION_OVERLAP:
11015                 case CTL_ACTION_OVERLAP_TAG:
11016                 case CTL_ACTION_SKIP:
11017                 case CTL_ACTION_ERROR:
11018                         return (action);
11019                         break; /* NOTREACHED */
11020                 case CTL_ACTION_PASS:
11021                         break;
11022                 default:
11023                         panic("invalid action %d", action);
11024                         break;  /* NOTREACHED */
11025                 }
11026         }
11027
11028         return (CTL_ACTION_PASS);
11029 }
11030
11031 /*
11032  * Assumptions:
11033  * - An I/O has just completed, and has been removed from the per-LUN OOA
11034  *   queue, so some items on the blocked queue may now be unblocked.
11035  */
11036 static int
11037 ctl_check_blocked(struct ctl_lun *lun)
11038 {
11039         union ctl_io *cur_blocked, *next_blocked;
11040
11041         mtx_assert(&lun->lun_lock, MA_OWNED);
11042
11043         /*
11044          * Run forward from the head of the blocked queue, checking each
11045          * entry against the I/Os prior to it on the OOA queue to see if
11046          * there is still any blockage.
11047          *
11048          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11049          * with our removing a variable on it while it is traversing the
11050          * list.
11051          */
11052         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11053              cur_blocked != NULL; cur_blocked = next_blocked) {
11054                 union ctl_io *prev_ooa;
11055                 ctl_action action;
11056
11057                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11058                                                           blocked_links);
11059
11060                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11061                                                       ctl_ooaq, ooa_links);
11062
11063                 /*
11064                  * If cur_blocked happens to be the first item in the OOA
11065                  * queue now, prev_ooa will be NULL, and the action
11066                  * returned will just be CTL_ACTION_PASS.
11067                  */
11068                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11069
11070                 switch (action) {
11071                 case CTL_ACTION_BLOCK:
11072                         /* Nothing to do here, still blocked */
11073                         break;
11074                 case CTL_ACTION_OVERLAP:
11075                 case CTL_ACTION_OVERLAP_TAG:
11076                         /*
11077                          * This shouldn't happen!  In theory we've already
11078                          * checked this command for overlap...
11079                          */
11080                         break;
11081                 case CTL_ACTION_PASS:
11082                 case CTL_ACTION_SKIP: {
11083                         struct ctl_softc *softc;
11084                         const struct ctl_cmd_entry *entry;
11085                         uint32_t initidx;
11086                         int isc_retval;
11087
11088                         /*
11089                          * The skip case shouldn't happen, this transaction
11090                          * should have never made it onto the blocked queue.
11091                          */
11092                         /*
11093                          * This I/O is no longer blocked, we can remove it
11094                          * from the blocked queue.  Since this is a TAILQ
11095                          * (doubly linked list), we can do O(1) removals
11096                          * from any place on the list.
11097                          */
11098                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11099                                      blocked_links);
11100                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11101
11102                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11103                                 /*
11104                                  * Need to send IO back to original side to
11105                                  * run
11106                                  */
11107                                 union ctl_ha_msg msg_info;
11108
11109                                 msg_info.hdr.original_sc =
11110                                         cur_blocked->io_hdr.original_sc;
11111                                 msg_info.hdr.serializing_sc = cur_blocked;
11112                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11113                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11114                                      &msg_info, sizeof(msg_info), 0)) >
11115                                      CTL_HA_STATUS_SUCCESS) {
11116                                         printf("CTL:Check Blocked error from "
11117                                                "ctl_ha_msg_send %d\n",
11118                                                isc_retval);
11119                                 }
11120                                 break;
11121                         }
11122                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11123                         softc = control_softc;
11124
11125                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11126
11127                         /*
11128                          * Check this I/O for LUN state changes that may
11129                          * have happened while this command was blocked.
11130                          * The LUN state may have been changed by a command
11131                          * ahead of us in the queue, so we need to re-check
11132                          * for any states that can be caused by SCSI
11133                          * commands.
11134                          */
11135                         if (ctl_scsiio_lun_check(softc, lun, entry,
11136                                                  &cur_blocked->scsiio) == 0) {
11137                                 cur_blocked->io_hdr.flags |=
11138                                                       CTL_FLAG_IS_WAS_ON_RTR;
11139                                 ctl_enqueue_rtr(cur_blocked);
11140                         } else
11141                                 ctl_done(cur_blocked);
11142                         break;
11143                 }
11144                 default:
11145                         /*
11146                          * This probably shouldn't happen -- we shouldn't
11147                          * get CTL_ACTION_ERROR, or anything else.
11148                          */
11149                         break;
11150                 }
11151         }
11152
11153         return (CTL_RETVAL_COMPLETE);
11154 }
11155
11156 /*
11157  * This routine (with one exception) checks LUN flags that can be set by
11158  * commands ahead of us in the OOA queue.  These flags have to be checked
11159  * when a command initially comes in, and when we pull a command off the
11160  * blocked queue and are preparing to execute it.  The reason we have to
11161  * check these flags for commands on the blocked queue is that the LUN
11162  * state may have been changed by a command ahead of us while we're on the
11163  * blocked queue.
11164  *
11165  * Ordering is somewhat important with these checks, so please pay
11166  * careful attention to the placement of any new checks.
11167  */
11168 static int
11169 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11170     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11171 {
11172         int retval;
11173         uint32_t residx;
11174
11175         retval = 0;
11176
11177         mtx_assert(&lun->lun_lock, MA_OWNED);
11178
11179         /*
11180          * If this shelf is a secondary shelf controller, we have to reject
11181          * any media access commands.
11182          */
11183 #if 0
11184         /* No longer needed for HA */
11185         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11186          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11187                 ctl_set_lun_standby(ctsio);
11188                 retval = 1;
11189                 goto bailout;
11190         }
11191 #endif
11192
11193         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11194                 if (lun->flags & CTL_LUN_READONLY) {
11195                         ctl_set_sense(ctsio, /*current_error*/ 1,
11196                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11197                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11198                         retval = 1;
11199                         goto bailout;
11200                 }
11201                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11202                     .eca_and_aen & SCP_SWP) != 0) {
11203                         ctl_set_sense(ctsio, /*current_error*/ 1,
11204                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11205                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11206                         retval = 1;
11207                         goto bailout;
11208                 }
11209         }
11210
11211         /*
11212          * Check for a reservation conflict.  If this command isn't allowed
11213          * even on reserved LUNs, and if this initiator isn't the one who
11214          * reserved us, reject the command with a reservation conflict.
11215          */
11216         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11217         if ((lun->flags & CTL_LUN_RESERVED)
11218          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11219                 if (lun->res_idx != residx) {
11220                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11221                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11222                         retval = 1;
11223                         goto bailout;
11224                 }
11225         }
11226
11227         if ((lun->flags & CTL_LUN_PR_RESERVED)
11228          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11229                 /*
11230                  * if we aren't registered or it's a res holder type
11231                  * reservation and this isn't the res holder then set a
11232                  * conflict.
11233                  * NOTE: Commands which might be allowed on write exclusive
11234                  * type reservations are checked in the particular command
11235                  * for a conflict. Read and SSU are the only ones.
11236                  */
11237                 if (lun->pr_keys[residx] == 0
11238                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11239                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11240                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11241                         retval = 1;
11242                         goto bailout;
11243                 }
11244
11245         }
11246
11247         if ((lun->flags & CTL_LUN_OFFLINE)
11248          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11249                 ctl_set_lun_not_ready(ctsio);
11250                 retval = 1;
11251                 goto bailout;
11252         }
11253
11254         /*
11255          * If the LUN is stopped, see if this particular command is allowed
11256          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11257          */
11258         if ((lun->flags & CTL_LUN_STOPPED)
11259          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11260                 /* "Logical unit not ready, initializing cmd. required" */
11261                 ctl_set_lun_stopped(ctsio);
11262                 retval = 1;
11263                 goto bailout;
11264         }
11265
11266         if ((lun->flags & CTL_LUN_INOPERABLE)
11267          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11268                 /* "Medium format corrupted" */
11269                 ctl_set_medium_format_corrupted(ctsio);
11270                 retval = 1;
11271                 goto bailout;
11272         }
11273
11274 bailout:
11275         return (retval);
11276
11277 }
11278
11279 static void
11280 ctl_failover_io(union ctl_io *io, int have_lock)
11281 {
11282         ctl_set_busy(&io->scsiio);
11283         ctl_done(io);
11284 }
11285
11286 static void
11287 ctl_failover(void)
11288 {
11289         struct ctl_lun *lun;
11290         struct ctl_softc *ctl_softc;
11291         union ctl_io *next_io, *pending_io;
11292         union ctl_io *io;
11293         int lun_idx;
11294         int i;
11295
11296         ctl_softc = control_softc;
11297
11298         mtx_lock(&ctl_softc->ctl_lock);
11299         /*
11300          * Remove any cmds from the other SC from the rtr queue.  These
11301          * will obviously only be for LUNs for which we're the primary.
11302          * We can't send status or get/send data for these commands.
11303          * Since they haven't been executed yet, we can just remove them.
11304          * We'll either abort them or delete them below, depending on
11305          * which HA mode we're in.
11306          */
11307 #ifdef notyet
11308         mtx_lock(&ctl_softc->queue_lock);
11309         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11310              io != NULL; io = next_io) {
11311                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11312                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11313                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11314                                       ctl_io_hdr, links);
11315         }
11316         mtx_unlock(&ctl_softc->queue_lock);
11317 #endif
11318
11319         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11320                 lun = ctl_softc->ctl_luns[lun_idx];
11321                 if (lun==NULL)
11322                         continue;
11323
11324                 /*
11325                  * Processor LUNs are primary on both sides.
11326                  * XXX will this always be true?
11327                  */
11328                 if (lun->be_lun->lun_type == T_PROCESSOR)
11329                         continue;
11330
11331                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11332                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11333                         printf("FAILOVER: primary lun %d\n", lun_idx);
11334                         /*
11335                          * Remove all commands from the other SC. First from the
11336                          * blocked queue then from the ooa queue. Once we have
11337                          * removed them. Call ctl_check_blocked to see if there
11338                          * is anything that can run.
11339                          */
11340                         for (io = (union ctl_io *)TAILQ_FIRST(
11341                              &lun->blocked_queue); io != NULL; io = next_io) {
11342
11343                                 next_io = (union ctl_io *)TAILQ_NEXT(
11344                                     &io->io_hdr, blocked_links);
11345
11346                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11347                                         TAILQ_REMOVE(&lun->blocked_queue,
11348                                                      &io->io_hdr,blocked_links);
11349                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11350                                         TAILQ_REMOVE(&lun->ooa_queue,
11351                                                      &io->io_hdr, ooa_links);
11352
11353                                         ctl_free_io(io);
11354                                 }
11355                         }
11356
11357                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11358                              io != NULL; io = next_io) {
11359
11360                                 next_io = (union ctl_io *)TAILQ_NEXT(
11361                                     &io->io_hdr, ooa_links);
11362
11363                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11364
11365                                         TAILQ_REMOVE(&lun->ooa_queue,
11366                                                 &io->io_hdr,
11367                                                 ooa_links);
11368
11369                                         ctl_free_io(io);
11370                                 }
11371                         }
11372                         ctl_check_blocked(lun);
11373                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11374                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11375
11376                         printf("FAILOVER: primary lun %d\n", lun_idx);
11377                         /*
11378                          * Abort all commands from the other SC.  We can't
11379                          * send status back for them now.  These should get
11380                          * cleaned up when they are completed or come out
11381                          * for a datamove operation.
11382                          */
11383                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11384                              io != NULL; io = next_io) {
11385                                 next_io = (union ctl_io *)TAILQ_NEXT(
11386                                         &io->io_hdr, ooa_links);
11387
11388                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11389                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11390                         }
11391                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11392                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11393
11394                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11395
11396                         lun->flags |= CTL_LUN_PRIMARY_SC;
11397
11398                         /*
11399                          * We send all I/O that was sent to this controller
11400                          * and redirected to the other side back with
11401                          * busy status, and have the initiator retry it.
11402                          * Figuring out how much data has been transferred,
11403                          * etc. and picking up where we left off would be 
11404                          * very tricky.
11405                          *
11406                          * XXX KDM need to remove I/O from the blocked
11407                          * queue as well!
11408                          */
11409                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11410                              &lun->ooa_queue); pending_io != NULL;
11411                              pending_io = next_io) {
11412
11413                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11414                                         &pending_io->io_hdr, ooa_links);
11415
11416                                 pending_io->io_hdr.flags &=
11417                                         ~CTL_FLAG_SENT_2OTHER_SC;
11418
11419                                 if (pending_io->io_hdr.flags &
11420                                     CTL_FLAG_IO_ACTIVE) {
11421                                         pending_io->io_hdr.flags |=
11422                                                 CTL_FLAG_FAILOVER;
11423                                 } else {
11424                                         ctl_set_busy(&pending_io->scsiio);
11425                                         ctl_done(pending_io);
11426                                 }
11427                         }
11428
11429                         /*
11430                          * Build Unit Attention
11431                          */
11432                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11433                                 lun->pending_ua[i] |=
11434                                                      CTL_UA_ASYM_ACC_CHANGE;
11435                         }
11436                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11437                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11438                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11439                         /*
11440                          * if the first io on the OOA is not on the RtR queue
11441                          * add it.
11442                          */
11443                         lun->flags |= CTL_LUN_PRIMARY_SC;
11444
11445                         pending_io = (union ctl_io *)TAILQ_FIRST(
11446                             &lun->ooa_queue);
11447                         if (pending_io==NULL) {
11448                                 printf("Nothing on OOA queue\n");
11449                                 continue;
11450                         }
11451
11452                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11453                         if ((pending_io->io_hdr.flags &
11454                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11455                                 pending_io->io_hdr.flags |=
11456                                     CTL_FLAG_IS_WAS_ON_RTR;
11457                                 ctl_enqueue_rtr(pending_io);
11458                         }
11459 #if 0
11460                         else
11461                         {
11462                                 printf("Tag 0x%04x is running\n",
11463                                       pending_io->scsiio.tag_num);
11464                         }
11465 #endif
11466
11467                         next_io = (union ctl_io *)TAILQ_NEXT(
11468                             &pending_io->io_hdr, ooa_links);
11469                         for (pending_io=next_io; pending_io != NULL;
11470                              pending_io = next_io) {
11471                                 pending_io->io_hdr.flags &=
11472                                     ~CTL_FLAG_SENT_2OTHER_SC;
11473                                 next_io = (union ctl_io *)TAILQ_NEXT(
11474                                         &pending_io->io_hdr, ooa_links);
11475                                 if (pending_io->io_hdr.flags &
11476                                     CTL_FLAG_IS_WAS_ON_RTR) {
11477 #if 0
11478                                         printf("Tag 0x%04x is running\n",
11479                                                 pending_io->scsiio.tag_num);
11480 #endif
11481                                         continue;
11482                                 }
11483
11484                                 switch (ctl_check_ooa(lun, pending_io,
11485                                     (union ctl_io *)TAILQ_PREV(
11486                                     &pending_io->io_hdr, ctl_ooaq,
11487                                     ooa_links))) {
11488
11489                                 case CTL_ACTION_BLOCK:
11490                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11491                                                           &pending_io->io_hdr,
11492                                                           blocked_links);
11493                                         pending_io->io_hdr.flags |=
11494                                             CTL_FLAG_BLOCKED;
11495                                         break;
11496                                 case CTL_ACTION_PASS:
11497                                 case CTL_ACTION_SKIP:
11498                                         pending_io->io_hdr.flags |=
11499                                             CTL_FLAG_IS_WAS_ON_RTR;
11500                                         ctl_enqueue_rtr(pending_io);
11501                                         break;
11502                                 case CTL_ACTION_OVERLAP:
11503                                         ctl_set_overlapped_cmd(
11504                                             (struct ctl_scsiio *)pending_io);
11505                                         ctl_done(pending_io);
11506                                         break;
11507                                 case CTL_ACTION_OVERLAP_TAG:
11508                                         ctl_set_overlapped_tag(
11509                                             (struct ctl_scsiio *)pending_io,
11510                                             pending_io->scsiio.tag_num & 0xff);
11511                                         ctl_done(pending_io);
11512                                         break;
11513                                 case CTL_ACTION_ERROR:
11514                                 default:
11515                                         ctl_set_internal_failure(
11516                                                 (struct ctl_scsiio *)pending_io,
11517                                                 0,  // sks_valid
11518                                                 0); //retry count
11519                                         ctl_done(pending_io);
11520                                         break;
11521                                 }
11522                         }
11523
11524                         /*
11525                          * Build Unit Attention
11526                          */
11527                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11528                                 lun->pending_ua[i] |=
11529                                                      CTL_UA_ASYM_ACC_CHANGE;
11530                         }
11531                 } else {
11532                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11533                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11534                 }
11535         }
11536         ctl_pause_rtr = 0;
11537         mtx_unlock(&ctl_softc->ctl_lock);
11538 }
11539
11540 static int
11541 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11542 {
11543         struct ctl_lun *lun;
11544         const struct ctl_cmd_entry *entry;
11545         uint32_t initidx, targ_lun;
11546         int retval;
11547
11548         retval = 0;
11549
11550         lun = NULL;
11551
11552         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11553         if ((targ_lun < CTL_MAX_LUNS)
11554          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11555                 lun = ctl_softc->ctl_luns[targ_lun];
11556                 /*
11557                  * If the LUN is invalid, pretend that it doesn't exist.
11558                  * It will go away as soon as all pending I/O has been
11559                  * completed.
11560                  */
11561                 if (lun->flags & CTL_LUN_DISABLED) {
11562                         lun = NULL;
11563                 } else {
11564                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11565                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11566                                 lun->be_lun;
11567                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11568                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11569                         }
11570
11571                         /*
11572                          * Every I/O goes into the OOA queue for a
11573                          * particular LUN, and stays there until completion.
11574                          */
11575                         mtx_lock(&lun->lun_lock);
11576                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11577                             ooa_links);
11578                 }
11579         } else {
11580                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11581                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11582         }
11583
11584         /* Get command entry and return error if it is unsuppotyed. */
11585         entry = ctl_validate_command(ctsio);
11586         if (entry == NULL) {
11587                 if (lun)
11588                         mtx_unlock(&lun->lun_lock);
11589                 return (retval);
11590         }
11591
11592         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11593         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11594
11595         /*
11596          * Check to see whether we can send this command to LUNs that don't
11597          * exist.  This should pretty much only be the case for inquiry
11598          * and request sense.  Further checks, below, really require having
11599          * a LUN, so we can't really check the command anymore.  Just put
11600          * it on the rtr queue.
11601          */
11602         if (lun == NULL) {
11603                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11604                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11605                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11606                         return (retval);
11607                 }
11608
11609                 ctl_set_unsupported_lun(ctsio);
11610                 ctl_done((union ctl_io *)ctsio);
11611                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11612                 return (retval);
11613         } else {
11614                 /*
11615                  * Make sure we support this particular command on this LUN.
11616                  * e.g., we don't support writes to the control LUN.
11617                  */
11618                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11619                         mtx_unlock(&lun->lun_lock);
11620                         ctl_set_invalid_opcode(ctsio);
11621                         ctl_done((union ctl_io *)ctsio);
11622                         return (retval);
11623                 }
11624         }
11625
11626         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11627
11628 #ifdef CTL_WITH_CA
11629         /*
11630          * If we've got a request sense, it'll clear the contingent
11631          * allegiance condition.  Otherwise, if we have a CA condition for
11632          * this initiator, clear it, because it sent down a command other
11633          * than request sense.
11634          */
11635         if ((ctsio->cdb[0] != REQUEST_SENSE)
11636          && (ctl_is_set(lun->have_ca, initidx)))
11637                 ctl_clear_mask(lun->have_ca, initidx);
11638 #endif
11639
11640         /*
11641          * If the command has this flag set, it handles its own unit
11642          * attention reporting, we shouldn't do anything.  Otherwise we
11643          * check for any pending unit attentions, and send them back to the
11644          * initiator.  We only do this when a command initially comes in,
11645          * not when we pull it off the blocked queue.
11646          *
11647          * According to SAM-3, section 5.3.2, the order that things get
11648          * presented back to the host is basically unit attentions caused
11649          * by some sort of reset event, busy status, reservation conflicts
11650          * or task set full, and finally any other status.
11651          *
11652          * One issue here is that some of the unit attentions we report
11653          * don't fall into the "reset" category (e.g. "reported luns data
11654          * has changed").  So reporting it here, before the reservation
11655          * check, may be technically wrong.  I guess the only thing to do
11656          * would be to check for and report the reset events here, and then
11657          * check for the other unit attention types after we check for a
11658          * reservation conflict.
11659          *
11660          * XXX KDM need to fix this
11661          */
11662         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11663                 ctl_ua_type ua_type;
11664
11665                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11666                         scsi_sense_data_type sense_format;
11667
11668                         if (lun != NULL)
11669                                 sense_format = (lun->flags &
11670                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11671                                     SSD_TYPE_FIXED;
11672                         else
11673                                 sense_format = SSD_TYPE_FIXED;
11674
11675                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11676                             &ctsio->sense_data, sense_format);
11677                         if (ua_type != CTL_UA_NONE) {
11678                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11679                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11680                                                        CTL_AUTOSENSE;
11681                                 ctsio->sense_len = SSD_FULL_SIZE;
11682                                 mtx_unlock(&lun->lun_lock);
11683                                 ctl_done((union ctl_io *)ctsio);
11684                                 return (retval);
11685                         }
11686                 }
11687         }
11688
11689
11690         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11691                 mtx_unlock(&lun->lun_lock);
11692                 ctl_done((union ctl_io *)ctsio);
11693                 return (retval);
11694         }
11695
11696         /*
11697          * XXX CHD this is where we want to send IO to other side if
11698          * this LUN is secondary on this SC. We will need to make a copy
11699          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11700          * the copy we send as FROM_OTHER.
11701          * We also need to stuff the address of the original IO so we can
11702          * find it easily. Something similar will need be done on the other
11703          * side so when we are done we can find the copy.
11704          */
11705         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11706                 union ctl_ha_msg msg_info;
11707                 int isc_retval;
11708
11709                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11710
11711                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11712                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11713 #if 0
11714                 printf("1. ctsio %p\n", ctsio);
11715 #endif
11716                 msg_info.hdr.serializing_sc = NULL;
11717                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11718                 msg_info.scsi.tag_num = ctsio->tag_num;
11719                 msg_info.scsi.tag_type = ctsio->tag_type;
11720                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11721
11722                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11723
11724                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11725                     (void *)&msg_info, sizeof(msg_info), 0)) >
11726                     CTL_HA_STATUS_SUCCESS) {
11727                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11728                                isc_retval);
11729                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11730                 } else {
11731 #if 0
11732                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11733 #endif
11734                 }
11735
11736                 /*
11737                  * XXX KDM this I/O is off the incoming queue, but hasn't
11738                  * been inserted on any other queue.  We may need to come
11739                  * up with a holding queue while we wait for serialization
11740                  * so that we have an idea of what we're waiting for from
11741                  * the other side.
11742                  */
11743                 mtx_unlock(&lun->lun_lock);
11744                 return (retval);
11745         }
11746
11747         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11748                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11749                               ctl_ooaq, ooa_links))) {
11750         case CTL_ACTION_BLOCK:
11751                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11752                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11753                                   blocked_links);
11754                 mtx_unlock(&lun->lun_lock);
11755                 return (retval);
11756         case CTL_ACTION_PASS:
11757         case CTL_ACTION_SKIP:
11758                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11759                 mtx_unlock(&lun->lun_lock);
11760                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11761                 break;
11762         case CTL_ACTION_OVERLAP:
11763                 mtx_unlock(&lun->lun_lock);
11764                 ctl_set_overlapped_cmd(ctsio);
11765                 ctl_done((union ctl_io *)ctsio);
11766                 break;
11767         case CTL_ACTION_OVERLAP_TAG:
11768                 mtx_unlock(&lun->lun_lock);
11769                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11770                 ctl_done((union ctl_io *)ctsio);
11771                 break;
11772         case CTL_ACTION_ERROR:
11773         default:
11774                 mtx_unlock(&lun->lun_lock);
11775                 ctl_set_internal_failure(ctsio,
11776                                          /*sks_valid*/ 0,
11777                                          /*retry_count*/ 0);
11778                 ctl_done((union ctl_io *)ctsio);
11779                 break;
11780         }
11781         return (retval);
11782 }
11783
11784 const struct ctl_cmd_entry *
11785 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11786 {
11787         const struct ctl_cmd_entry *entry;
11788         int service_action;
11789
11790         entry = &ctl_cmd_table[ctsio->cdb[0]];
11791         if (sa)
11792                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11793         if (entry->flags & CTL_CMD_FLAG_SA5) {
11794                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11795                 entry = &((const struct ctl_cmd_entry *)
11796                     entry->execute)[service_action];
11797         }
11798         return (entry);
11799 }
11800
11801 const struct ctl_cmd_entry *
11802 ctl_validate_command(struct ctl_scsiio *ctsio)
11803 {
11804         const struct ctl_cmd_entry *entry;
11805         int i, sa;
11806         uint8_t diff;
11807
11808         entry = ctl_get_cmd_entry(ctsio, &sa);
11809         if (entry->execute == NULL) {
11810                 if (sa)
11811                         ctl_set_invalid_field(ctsio,
11812                                               /*sks_valid*/ 1,
11813                                               /*command*/ 1,
11814                                               /*field*/ 1,
11815                                               /*bit_valid*/ 1,
11816                                               /*bit*/ 4);
11817                 else
11818                         ctl_set_invalid_opcode(ctsio);
11819                 ctl_done((union ctl_io *)ctsio);
11820                 return (NULL);
11821         }
11822         KASSERT(entry->length > 0,
11823             ("Not defined length for command 0x%02x/0x%02x",
11824              ctsio->cdb[0], ctsio->cdb[1]));
11825         for (i = 1; i < entry->length; i++) {
11826                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11827                 if (diff == 0)
11828                         continue;
11829                 ctl_set_invalid_field(ctsio,
11830                                       /*sks_valid*/ 1,
11831                                       /*command*/ 1,
11832                                       /*field*/ i,
11833                                       /*bit_valid*/ 1,
11834                                       /*bit*/ fls(diff) - 1);
11835                 ctl_done((union ctl_io *)ctsio);
11836                 return (NULL);
11837         }
11838         return (entry);
11839 }
11840
11841 static int
11842 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11843 {
11844
11845         switch (lun_type) {
11846         case T_PROCESSOR:
11847                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11848                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11849                         return (0);
11850                 break;
11851         case T_DIRECT:
11852                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11853                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11854                         return (0);
11855                 break;
11856         default:
11857                 return (0);
11858         }
11859         return (1);
11860 }
11861
11862 static int
11863 ctl_scsiio(struct ctl_scsiio *ctsio)
11864 {
11865         int retval;
11866         const struct ctl_cmd_entry *entry;
11867
11868         retval = CTL_RETVAL_COMPLETE;
11869
11870         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11871
11872         entry = ctl_get_cmd_entry(ctsio, NULL);
11873
11874         /*
11875          * If this I/O has been aborted, just send it straight to
11876          * ctl_done() without executing it.
11877          */
11878         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11879                 ctl_done((union ctl_io *)ctsio);
11880                 goto bailout;
11881         }
11882
11883         /*
11884          * All the checks should have been handled by ctl_scsiio_precheck().
11885          * We should be clear now to just execute the I/O.
11886          */
11887         retval = entry->execute(ctsio);
11888
11889 bailout:
11890         return (retval);
11891 }
11892
11893 /*
11894  * Since we only implement one target right now, a bus reset simply resets
11895  * our single target.
11896  */
11897 static int
11898 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11899 {
11900         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11901 }
11902
11903 static int
11904 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11905                  ctl_ua_type ua_type)
11906 {
11907         struct ctl_lun *lun;
11908         int retval;
11909
11910         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11911                 union ctl_ha_msg msg_info;
11912
11913                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11914                 msg_info.hdr.nexus = io->io_hdr.nexus;
11915                 if (ua_type==CTL_UA_TARG_RESET)
11916                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11917                 else
11918                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11919                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11920                 msg_info.hdr.original_sc = NULL;
11921                 msg_info.hdr.serializing_sc = NULL;
11922                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11923                     (void *)&msg_info, sizeof(msg_info), 0)) {
11924                 }
11925         }
11926         retval = 0;
11927
11928         mtx_lock(&ctl_softc->ctl_lock);
11929         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11930                 retval += ctl_lun_reset(lun, io, ua_type);
11931         mtx_unlock(&ctl_softc->ctl_lock);
11932
11933         return (retval);
11934 }
11935
11936 /*
11937  * The LUN should always be set.  The I/O is optional, and is used to
11938  * distinguish between I/Os sent by this initiator, and by other
11939  * initiators.  We set unit attention for initiators other than this one.
11940  * SAM-3 is vague on this point.  It does say that a unit attention should
11941  * be established for other initiators when a LUN is reset (see section
11942  * 5.7.3), but it doesn't specifically say that the unit attention should
11943  * be established for this particular initiator when a LUN is reset.  Here
11944  * is the relevant text, from SAM-3 rev 8:
11945  *
11946  * 5.7.2 When a SCSI initiator port aborts its own tasks
11947  *
11948  * When a SCSI initiator port causes its own task(s) to be aborted, no
11949  * notification that the task(s) have been aborted shall be returned to
11950  * the SCSI initiator port other than the completion response for the
11951  * command or task management function action that caused the task(s) to
11952  * be aborted and notification(s) associated with related effects of the
11953  * action (e.g., a reset unit attention condition).
11954  *
11955  * XXX KDM for now, we're setting unit attention for all initiators.
11956  */
11957 static int
11958 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11959 {
11960         union ctl_io *xio;
11961 #if 0
11962         uint32_t initindex;
11963 #endif
11964         int i;
11965
11966         mtx_lock(&lun->lun_lock);
11967         /*
11968          * Run through the OOA queue and abort each I/O.
11969          */
11970 #if 0
11971         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11972 #endif
11973         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11974              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11975                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11976         }
11977
11978         /*
11979          * This version sets unit attention for every
11980          */
11981 #if 0
11982         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11983         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11984                 if (initindex == i)
11985                         continue;
11986                 lun->pending_ua[i] |= ua_type;
11987         }
11988 #endif
11989
11990         /*
11991          * A reset (any kind, really) clears reservations established with
11992          * RESERVE/RELEASE.  It does not clear reservations established
11993          * with PERSISTENT RESERVE OUT, but we don't support that at the
11994          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11995          * reservations made with the RESERVE/RELEASE commands, because
11996          * those commands are obsolete in SPC-3.
11997          */
11998         lun->flags &= ~CTL_LUN_RESERVED;
11999
12000         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12001 #ifdef CTL_WITH_CA
12002                 ctl_clear_mask(lun->have_ca, i);
12003 #endif
12004                 lun->pending_ua[i] |= ua_type;
12005         }
12006         mtx_unlock(&lun->lun_lock);
12007
12008         return (0);
12009 }
12010
12011 static void
12012 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12013     int other_sc)
12014 {
12015         union ctl_io *xio;
12016
12017         mtx_assert(&lun->lun_lock, MA_OWNED);
12018
12019         /*
12020          * Run through the OOA queue and attempt to find the given I/O.
12021          * The target port, initiator ID, tag type and tag number have to
12022          * match the values that we got from the initiator.  If we have an
12023          * untagged command to abort, simply abort the first untagged command
12024          * we come to.  We only allow one untagged command at a time of course.
12025          */
12026         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12027              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12028
12029                 if ((targ_port == UINT32_MAX ||
12030                      targ_port == xio->io_hdr.nexus.targ_port) &&
12031                     (init_id == UINT32_MAX ||
12032                      init_id == xio->io_hdr.nexus.initid.id)) {
12033                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12034                             init_id != xio->io_hdr.nexus.initid.id)
12035                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12036                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12037                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12038                                 union ctl_ha_msg msg_info;
12039
12040                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12041                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12042                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12043                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12044                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12045                                 msg_info.hdr.original_sc = NULL;
12046                                 msg_info.hdr.serializing_sc = NULL;
12047                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12048                                     (void *)&msg_info, sizeof(msg_info), 0);
12049                         }
12050                 }
12051         }
12052 }
12053
12054 static int
12055 ctl_abort_task_set(union ctl_io *io)
12056 {
12057         struct ctl_softc *softc = control_softc;
12058         struct ctl_lun *lun;
12059         uint32_t targ_lun;
12060
12061         /*
12062          * Look up the LUN.
12063          */
12064         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12065         mtx_lock(&softc->ctl_lock);
12066         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12067                 lun = softc->ctl_luns[targ_lun];
12068         else {
12069                 mtx_unlock(&softc->ctl_lock);
12070                 return (1);
12071         }
12072
12073         mtx_lock(&lun->lun_lock);
12074         mtx_unlock(&softc->ctl_lock);
12075         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12076                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12077                     io->io_hdr.nexus.initid.id,
12078                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12079         } else { /* CTL_TASK_CLEAR_TASK_SET */
12080                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12081                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12082         }
12083         mtx_unlock(&lun->lun_lock);
12084         return (0);
12085 }
12086
12087 static int
12088 ctl_i_t_nexus_reset(union ctl_io *io)
12089 {
12090         struct ctl_softc *softc = control_softc;
12091         struct ctl_lun *lun;
12092         uint32_t initindex, residx;
12093
12094         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12095         residx = ctl_get_resindex(&io->io_hdr.nexus);
12096         mtx_lock(&softc->ctl_lock);
12097         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12098                 mtx_lock(&lun->lun_lock);
12099                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12100                     io->io_hdr.nexus.initid.id,
12101                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12102 #ifdef CTL_WITH_CA
12103                 ctl_clear_mask(lun->have_ca, initindex);
12104 #endif
12105                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12106                         lun->flags &= ~CTL_LUN_RESERVED;
12107                 lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12108                 mtx_unlock(&lun->lun_lock);
12109         }
12110         mtx_unlock(&softc->ctl_lock);
12111         return (0);
12112 }
12113
12114 static int
12115 ctl_abort_task(union ctl_io *io)
12116 {
12117         union ctl_io *xio;
12118         struct ctl_lun *lun;
12119         struct ctl_softc *ctl_softc;
12120 #if 0
12121         struct sbuf sb;
12122         char printbuf[128];
12123 #endif
12124         int found;
12125         uint32_t targ_lun;
12126
12127         ctl_softc = control_softc;
12128         found = 0;
12129
12130         /*
12131          * Look up the LUN.
12132          */
12133         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12134         mtx_lock(&ctl_softc->ctl_lock);
12135         if ((targ_lun < CTL_MAX_LUNS)
12136          && (ctl_softc->ctl_luns[targ_lun] != NULL))
12137                 lun = ctl_softc->ctl_luns[targ_lun];
12138         else {
12139                 mtx_unlock(&ctl_softc->ctl_lock);
12140                 return (1);
12141         }
12142
12143 #if 0
12144         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12145                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12146 #endif
12147
12148         mtx_lock(&lun->lun_lock);
12149         mtx_unlock(&ctl_softc->ctl_lock);
12150         /*
12151          * Run through the OOA queue and attempt to find the given I/O.
12152          * The target port, initiator ID, tag type and tag number have to
12153          * match the values that we got from the initiator.  If we have an
12154          * untagged command to abort, simply abort the first untagged command
12155          * we come to.  We only allow one untagged command at a time of course.
12156          */
12157 #if 0
12158         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12159 #endif
12160         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12161              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12162 #if 0
12163                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12164
12165                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12166                             lun->lun, xio->scsiio.tag_num,
12167                             xio->scsiio.tag_type,
12168                             (xio->io_hdr.blocked_links.tqe_prev
12169                             == NULL) ? "" : " BLOCKED",
12170                             (xio->io_hdr.flags &
12171                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12172                             (xio->io_hdr.flags &
12173                             CTL_FLAG_ABORT) ? " ABORT" : "",
12174                             (xio->io_hdr.flags &
12175                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12176                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12177                 sbuf_finish(&sb);
12178                 printf("%s\n", sbuf_data(&sb));
12179 #endif
12180
12181                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12182                  && (xio->io_hdr.nexus.initid.id ==
12183                      io->io_hdr.nexus.initid.id)) {
12184                         /*
12185                          * If the abort says that the task is untagged, the
12186                          * task in the queue must be untagged.  Otherwise,
12187                          * we just check to see whether the tag numbers
12188                          * match.  This is because the QLogic firmware
12189                          * doesn't pass back the tag type in an abort
12190                          * request.
12191                          */
12192 #if 0
12193                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12194                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12195                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12196 #endif
12197                         /*
12198                          * XXX KDM we've got problems with FC, because it
12199                          * doesn't send down a tag type with aborts.  So we
12200                          * can only really go by the tag number...
12201                          * This may cause problems with parallel SCSI.
12202                          * Need to figure that out!!
12203                          */
12204                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12205                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12206                                 found = 1;
12207                                 if ((io->io_hdr.flags &
12208                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12209                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12210                                         union ctl_ha_msg msg_info;
12211
12212                                         io->io_hdr.flags |=
12213                                                         CTL_FLAG_SENT_2OTHER_SC;
12214                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12215                                         msg_info.task.task_action =
12216                                                 CTL_TASK_ABORT_TASK;
12217                                         msg_info.task.tag_num =
12218                                                 io->taskio.tag_num;
12219                                         msg_info.task.tag_type =
12220                                                 io->taskio.tag_type;
12221                                         msg_info.hdr.msg_type =
12222                                                 CTL_MSG_MANAGE_TASKS;
12223                                         msg_info.hdr.original_sc = NULL;
12224                                         msg_info.hdr.serializing_sc = NULL;
12225 #if 0
12226                                         printf("Sent Abort to other side\n");
12227 #endif
12228                                         if (CTL_HA_STATUS_SUCCESS !=
12229                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12230                                                 (void *)&msg_info,
12231                                                 sizeof(msg_info), 0)) {
12232                                         }
12233                                 }
12234 #if 0
12235                                 printf("ctl_abort_task: found I/O to abort\n");
12236 #endif
12237                                 break;
12238                         }
12239                 }
12240         }
12241         mtx_unlock(&lun->lun_lock);
12242
12243         if (found == 0) {
12244                 /*
12245                  * This isn't really an error.  It's entirely possible for
12246                  * the abort and command completion to cross on the wire.
12247                  * This is more of an informative/diagnostic error.
12248                  */
12249 #if 0
12250                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12251                        "%d:%d:%d:%d tag %d type %d\n",
12252                        io->io_hdr.nexus.initid.id,
12253                        io->io_hdr.nexus.targ_port,
12254                        io->io_hdr.nexus.targ_target.id,
12255                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12256                        io->taskio.tag_type);
12257 #endif
12258         }
12259         return (0);
12260 }
12261
12262 static void
12263 ctl_run_task(union ctl_io *io)
12264 {
12265         struct ctl_softc *ctl_softc = control_softc;
12266         int retval = 1;
12267         const char *task_desc;
12268
12269         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12270
12271         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12272             ("ctl_run_task: Unextected io_type %d\n",
12273              io->io_hdr.io_type));
12274
12275         task_desc = ctl_scsi_task_string(&io->taskio);
12276         if (task_desc != NULL) {
12277 #ifdef NEEDTOPORT
12278                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12279                             CTL_TASK_REPORT,
12280                             csevent_LogType_Trace,
12281                             csevent_Severity_Information,
12282                             csevent_AlertLevel_Green,
12283                             csevent_FRU_Firmware,
12284                             csevent_FRU_Unknown,
12285                             "CTL: received task: %s",task_desc);
12286 #endif
12287         } else {
12288 #ifdef NEEDTOPORT
12289                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12290                             CTL_TASK_REPORT,
12291                             csevent_LogType_Trace,
12292                             csevent_Severity_Information,
12293                             csevent_AlertLevel_Green,
12294                             csevent_FRU_Firmware,
12295                             csevent_FRU_Unknown,
12296                             "CTL: received unknown task "
12297                             "type: %d (%#x)",
12298                             io->taskio.task_action,
12299                             io->taskio.task_action);
12300 #endif
12301         }
12302         switch (io->taskio.task_action) {
12303         case CTL_TASK_ABORT_TASK:
12304                 retval = ctl_abort_task(io);
12305                 break;
12306         case CTL_TASK_ABORT_TASK_SET:
12307         case CTL_TASK_CLEAR_TASK_SET:
12308                 retval = ctl_abort_task_set(io);
12309                 break;
12310         case CTL_TASK_CLEAR_ACA:
12311                 break;
12312         case CTL_TASK_I_T_NEXUS_RESET:
12313                 retval = ctl_i_t_nexus_reset(io);
12314                 break;
12315         case CTL_TASK_LUN_RESET: {
12316                 struct ctl_lun *lun;
12317                 uint32_t targ_lun;
12318
12319                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12320                 mtx_lock(&ctl_softc->ctl_lock);
12321                 if ((targ_lun < CTL_MAX_LUNS)
12322                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12323                         lun = ctl_softc->ctl_luns[targ_lun];
12324                 else {
12325                         mtx_unlock(&ctl_softc->ctl_lock);
12326                         retval = 1;
12327                         break;
12328                 }
12329
12330                 if (!(io->io_hdr.flags &
12331                     CTL_FLAG_FROM_OTHER_SC)) {
12332                         union ctl_ha_msg msg_info;
12333
12334                         io->io_hdr.flags |=
12335                                 CTL_FLAG_SENT_2OTHER_SC;
12336                         msg_info.hdr.msg_type =
12337                                 CTL_MSG_MANAGE_TASKS;
12338                         msg_info.hdr.nexus = io->io_hdr.nexus;
12339                         msg_info.task.task_action =
12340                                 CTL_TASK_LUN_RESET;
12341                         msg_info.hdr.original_sc = NULL;
12342                         msg_info.hdr.serializing_sc = NULL;
12343                         if (CTL_HA_STATUS_SUCCESS !=
12344                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12345                             (void *)&msg_info,
12346                             sizeof(msg_info), 0)) {
12347                         }
12348                 }
12349
12350                 retval = ctl_lun_reset(lun, io,
12351                                        CTL_UA_LUN_RESET);
12352                 mtx_unlock(&ctl_softc->ctl_lock);
12353                 break;
12354         }
12355         case CTL_TASK_TARGET_RESET:
12356                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12357                 break;
12358         case CTL_TASK_BUS_RESET:
12359                 retval = ctl_bus_reset(ctl_softc, io);
12360                 break;
12361         case CTL_TASK_PORT_LOGIN:
12362                 break;
12363         case CTL_TASK_PORT_LOGOUT:
12364                 break;
12365         default:
12366                 printf("ctl_run_task: got unknown task management event %d\n",
12367                        io->taskio.task_action);
12368                 break;
12369         }
12370         if (retval == 0)
12371                 io->io_hdr.status = CTL_SUCCESS;
12372         else
12373                 io->io_hdr.status = CTL_ERROR;
12374         ctl_done(io);
12375 }
12376
12377 /*
12378  * For HA operation.  Handle commands that come in from the other
12379  * controller.
12380  */
12381 static void
12382 ctl_handle_isc(union ctl_io *io)
12383 {
12384         int free_io;
12385         struct ctl_lun *lun;
12386         struct ctl_softc *ctl_softc;
12387         uint32_t targ_lun;
12388
12389         ctl_softc = control_softc;
12390
12391         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12392         lun = ctl_softc->ctl_luns[targ_lun];
12393
12394         switch (io->io_hdr.msg_type) {
12395         case CTL_MSG_SERIALIZE:
12396                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12397                 break;
12398         case CTL_MSG_R2R: {
12399                 const struct ctl_cmd_entry *entry;
12400
12401                 /*
12402                  * This is only used in SER_ONLY mode.
12403                  */
12404                 free_io = 0;
12405                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12406                 mtx_lock(&lun->lun_lock);
12407                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12408                     entry, (struct ctl_scsiio *)io) != 0) {
12409                         mtx_unlock(&lun->lun_lock);
12410                         ctl_done(io);
12411                         break;
12412                 }
12413                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12414                 mtx_unlock(&lun->lun_lock);
12415                 ctl_enqueue_rtr(io);
12416                 break;
12417         }
12418         case CTL_MSG_FINISH_IO:
12419                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12420                         free_io = 0;
12421                         ctl_done(io);
12422                 } else {
12423                         free_io = 1;
12424                         mtx_lock(&lun->lun_lock);
12425                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12426                                      ooa_links);
12427                         ctl_check_blocked(lun);
12428                         mtx_unlock(&lun->lun_lock);
12429                 }
12430                 break;
12431         case CTL_MSG_PERS_ACTION:
12432                 ctl_hndl_per_res_out_on_other_sc(
12433                         (union ctl_ha_msg *)&io->presio.pr_msg);
12434                 free_io = 1;
12435                 break;
12436         case CTL_MSG_BAD_JUJU:
12437                 free_io = 0;
12438                 ctl_done(io);
12439                 break;
12440         case CTL_MSG_DATAMOVE:
12441                 /* Only used in XFER mode */
12442                 free_io = 0;
12443                 ctl_datamove_remote(io);
12444                 break;
12445         case CTL_MSG_DATAMOVE_DONE:
12446                 /* Only used in XFER mode */
12447                 free_io = 0;
12448                 io->scsiio.be_move_done(io);
12449                 break;
12450         default:
12451                 free_io = 1;
12452                 printf("%s: Invalid message type %d\n",
12453                        __func__, io->io_hdr.msg_type);
12454                 break;
12455         }
12456         if (free_io)
12457                 ctl_free_io(io);
12458
12459 }
12460
12461
12462 /*
12463  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12464  * there is no match.
12465  */
12466 static ctl_lun_error_pattern
12467 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12468 {
12469         const struct ctl_cmd_entry *entry;
12470         ctl_lun_error_pattern filtered_pattern, pattern;
12471
12472         pattern = desc->error_pattern;
12473
12474         /*
12475          * XXX KDM we need more data passed into this function to match a
12476          * custom pattern, and we actually need to implement custom pattern
12477          * matching.
12478          */
12479         if (pattern & CTL_LUN_PAT_CMD)
12480                 return (CTL_LUN_PAT_CMD);
12481
12482         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12483                 return (CTL_LUN_PAT_ANY);
12484
12485         entry = ctl_get_cmd_entry(ctsio, NULL);
12486
12487         filtered_pattern = entry->pattern & pattern;
12488
12489         /*
12490          * If the user requested specific flags in the pattern (e.g.
12491          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12492          * flags.
12493          *
12494          * If the user did not specify any flags, it doesn't matter whether
12495          * or not the command supports the flags.
12496          */
12497         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12498              (pattern & ~CTL_LUN_PAT_MASK))
12499                 return (CTL_LUN_PAT_NONE);
12500
12501         /*
12502          * If the user asked for a range check, see if the requested LBA
12503          * range overlaps with this command's LBA range.
12504          */
12505         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12506                 uint64_t lba1;
12507                 uint64_t len1;
12508                 ctl_action action;
12509                 int retval;
12510
12511                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12512                 if (retval != 0)
12513                         return (CTL_LUN_PAT_NONE);
12514
12515                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12516                                               desc->lba_range.len);
12517                 /*
12518                  * A "pass" means that the LBA ranges don't overlap, so
12519                  * this doesn't match the user's range criteria.
12520                  */
12521                 if (action == CTL_ACTION_PASS)
12522                         return (CTL_LUN_PAT_NONE);
12523         }
12524
12525         return (filtered_pattern);
12526 }
12527
12528 static void
12529 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12530 {
12531         struct ctl_error_desc *desc, *desc2;
12532
12533         mtx_assert(&lun->lun_lock, MA_OWNED);
12534
12535         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12536                 ctl_lun_error_pattern pattern;
12537                 /*
12538                  * Check to see whether this particular command matches
12539                  * the pattern in the descriptor.
12540                  */
12541                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12542                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12543                         continue;
12544
12545                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12546                 case CTL_LUN_INJ_ABORTED:
12547                         ctl_set_aborted(&io->scsiio);
12548                         break;
12549                 case CTL_LUN_INJ_MEDIUM_ERR:
12550                         ctl_set_medium_error(&io->scsiio);
12551                         break;
12552                 case CTL_LUN_INJ_UA:
12553                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12554                          * OCCURRED */
12555                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12556                         break;
12557                 case CTL_LUN_INJ_CUSTOM:
12558                         /*
12559                          * We're assuming the user knows what he is doing.
12560                          * Just copy the sense information without doing
12561                          * checks.
12562                          */
12563                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12564                               ctl_min(sizeof(desc->custom_sense),
12565                                       sizeof(io->scsiio.sense_data)));
12566                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12567                         io->scsiio.sense_len = SSD_FULL_SIZE;
12568                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12569                         break;
12570                 case CTL_LUN_INJ_NONE:
12571                 default:
12572                         /*
12573                          * If this is an error injection type we don't know
12574                          * about, clear the continuous flag (if it is set)
12575                          * so it will get deleted below.
12576                          */
12577                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12578                         break;
12579                 }
12580                 /*
12581                  * By default, each error injection action is a one-shot
12582                  */
12583                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12584                         continue;
12585
12586                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12587
12588                 free(desc, M_CTL);
12589         }
12590 }
12591
12592 #ifdef CTL_IO_DELAY
12593 static void
12594 ctl_datamove_timer_wakeup(void *arg)
12595 {
12596         union ctl_io *io;
12597
12598         io = (union ctl_io *)arg;
12599
12600         ctl_datamove(io);
12601 }
12602 #endif /* CTL_IO_DELAY */
12603
12604 void
12605 ctl_datamove(union ctl_io *io)
12606 {
12607         void (*fe_datamove)(union ctl_io *io);
12608
12609         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12610
12611         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12612
12613 #ifdef CTL_TIME_IO
12614         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12615                 char str[256];
12616                 char path_str[64];
12617                 struct sbuf sb;
12618
12619                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12620                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12621
12622                 sbuf_cat(&sb, path_str);
12623                 switch (io->io_hdr.io_type) {
12624                 case CTL_IO_SCSI:
12625                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12626                         sbuf_printf(&sb, "\n");
12627                         sbuf_cat(&sb, path_str);
12628                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12629                                     io->scsiio.tag_num, io->scsiio.tag_type);
12630                         break;
12631                 case CTL_IO_TASK:
12632                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12633                                     "Tag Type: %d\n", io->taskio.task_action,
12634                                     io->taskio.tag_num, io->taskio.tag_type);
12635                         break;
12636                 default:
12637                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12638                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12639                         break;
12640                 }
12641                 sbuf_cat(&sb, path_str);
12642                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12643                             (intmax_t)time_uptime - io->io_hdr.start_time);
12644                 sbuf_finish(&sb);
12645                 printf("%s", sbuf_data(&sb));
12646         }
12647 #endif /* CTL_TIME_IO */
12648
12649 #ifdef CTL_IO_DELAY
12650         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12651                 struct ctl_lun *lun;
12652
12653                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12654
12655                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12656         } else {
12657                 struct ctl_lun *lun;
12658
12659                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12660                 if ((lun != NULL)
12661                  && (lun->delay_info.datamove_delay > 0)) {
12662                         struct callout *callout;
12663
12664                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12665                         callout_init(callout, /*mpsafe*/ 1);
12666                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12667                         callout_reset(callout,
12668                                       lun->delay_info.datamove_delay * hz,
12669                                       ctl_datamove_timer_wakeup, io);
12670                         if (lun->delay_info.datamove_type ==
12671                             CTL_DELAY_TYPE_ONESHOT)
12672                                 lun->delay_info.datamove_delay = 0;
12673                         return;
12674                 }
12675         }
12676 #endif
12677
12678         /*
12679          * This command has been aborted.  Set the port status, so we fail
12680          * the data move.
12681          */
12682         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12683                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12684                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12685                        io->io_hdr.nexus.targ_port,
12686                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12687                        io->io_hdr.nexus.targ_lun);
12688                 io->io_hdr.port_status = 31337;
12689                 /*
12690                  * Note that the backend, in this case, will get the
12691                  * callback in its context.  In other cases it may get
12692                  * called in the frontend's interrupt thread context.
12693                  */
12694                 io->scsiio.be_move_done(io);
12695                 return;
12696         }
12697
12698         /* Don't confuse frontend with zero length data move. */
12699         if (io->scsiio.kern_data_len == 0) {
12700                 io->scsiio.be_move_done(io);
12701                 return;
12702         }
12703
12704         /*
12705          * If we're in XFER mode and this I/O is from the other shelf
12706          * controller, we need to send the DMA to the other side to
12707          * actually transfer the data to/from the host.  In serialize only
12708          * mode the transfer happens below CTL and ctl_datamove() is only
12709          * called on the machine that originally received the I/O.
12710          */
12711         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12712          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12713                 union ctl_ha_msg msg;
12714                 uint32_t sg_entries_sent;
12715                 int do_sg_copy;
12716                 int i;
12717
12718                 memset(&msg, 0, sizeof(msg));
12719                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12720                 msg.hdr.original_sc = io->io_hdr.original_sc;
12721                 msg.hdr.serializing_sc = io;
12722                 msg.hdr.nexus = io->io_hdr.nexus;
12723                 msg.dt.flags = io->io_hdr.flags;
12724                 /*
12725                  * We convert everything into a S/G list here.  We can't
12726                  * pass by reference, only by value between controllers.
12727                  * So we can't pass a pointer to the S/G list, only as many
12728                  * S/G entries as we can fit in here.  If it's possible for
12729                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12730                  * then we need to break this up into multiple transfers.
12731                  */
12732                 if (io->scsiio.kern_sg_entries == 0) {
12733                         msg.dt.kern_sg_entries = 1;
12734                         /*
12735                          * If this is in cached memory, flush the cache
12736                          * before we send the DMA request to the other
12737                          * controller.  We want to do this in either the
12738                          * read or the write case.  The read case is
12739                          * straightforward.  In the write case, we want to
12740                          * make sure nothing is in the local cache that
12741                          * could overwrite the DMAed data.
12742                          */
12743                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12744                                 /*
12745                                  * XXX KDM use bus_dmamap_sync() here.
12746                                  */
12747                         }
12748
12749                         /*
12750                          * Convert to a physical address if this is a
12751                          * virtual address.
12752                          */
12753                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12754                                 msg.dt.sg_list[0].addr =
12755                                         io->scsiio.kern_data_ptr;
12756                         } else {
12757                                 /*
12758                                  * XXX KDM use busdma here!
12759                                  */
12760 #if 0
12761                                 msg.dt.sg_list[0].addr = (void *)
12762                                         vtophys(io->scsiio.kern_data_ptr);
12763 #endif
12764                         }
12765
12766                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12767                         do_sg_copy = 0;
12768                 } else {
12769                         struct ctl_sg_entry *sgl;
12770
12771                         do_sg_copy = 1;
12772                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12773                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12774                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12775                                 /*
12776                                  * XXX KDM use bus_dmamap_sync() here.
12777                                  */
12778                         }
12779                 }
12780
12781                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12782                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12783                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12784                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12785                 msg.dt.sg_sequence = 0;
12786
12787                 /*
12788                  * Loop until we've sent all of the S/G entries.  On the
12789                  * other end, we'll recompose these S/G entries into one
12790                  * contiguous list before passing it to the
12791                  */
12792                 for (sg_entries_sent = 0; sg_entries_sent <
12793                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12794                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12795                                 sizeof(msg.dt.sg_list[0])),
12796                                 msg.dt.kern_sg_entries - sg_entries_sent);
12797
12798                         if (do_sg_copy != 0) {
12799                                 struct ctl_sg_entry *sgl;
12800                                 int j;
12801
12802                                 sgl = (struct ctl_sg_entry *)
12803                                         io->scsiio.kern_data_ptr;
12804                                 /*
12805                                  * If this is in cached memory, flush the cache
12806                                  * before we send the DMA request to the other
12807                                  * controller.  We want to do this in either
12808                                  * the * read or the write case.  The read
12809                                  * case is straightforward.  In the write
12810                                  * case, we want to make sure nothing is
12811                                  * in the local cache that could overwrite
12812                                  * the DMAed data.
12813                                  */
12814
12815                                 for (i = sg_entries_sent, j = 0;
12816                                      i < msg.dt.cur_sg_entries; i++, j++) {
12817                                         if ((io->io_hdr.flags &
12818                                              CTL_FLAG_NO_DATASYNC) == 0) {
12819                                                 /*
12820                                                  * XXX KDM use bus_dmamap_sync()
12821                                                  */
12822                                         }
12823                                         if ((io->io_hdr.flags &
12824                                              CTL_FLAG_BUS_ADDR) == 0) {
12825                                                 /*
12826                                                  * XXX KDM use busdma.
12827                                                  */
12828 #if 0
12829                                                 msg.dt.sg_list[j].addr =(void *)
12830                                                        vtophys(sgl[i].addr);
12831 #endif
12832                                         } else {
12833                                                 msg.dt.sg_list[j].addr =
12834                                                         sgl[i].addr;
12835                                         }
12836                                         msg.dt.sg_list[j].len = sgl[i].len;
12837                                 }
12838                         }
12839
12840                         sg_entries_sent += msg.dt.cur_sg_entries;
12841                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12842                                 msg.dt.sg_last = 1;
12843                         else
12844                                 msg.dt.sg_last = 0;
12845
12846                         /*
12847                          * XXX KDM drop and reacquire the lock here?
12848                          */
12849                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12850                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12851                                 /*
12852                                  * XXX do something here.
12853                                  */
12854                         }
12855
12856                         msg.dt.sent_sg_entries = sg_entries_sent;
12857                 }
12858                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12859                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12860                         ctl_failover_io(io, /*have_lock*/ 0);
12861
12862         } else {
12863
12864                 /*
12865                  * Lookup the fe_datamove() function for this particular
12866                  * front end.
12867                  */
12868                 fe_datamove =
12869                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12870
12871                 fe_datamove(io);
12872         }
12873 }
12874
12875 static void
12876 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12877 {
12878         union ctl_ha_msg msg;
12879         int isc_status;
12880
12881         memset(&msg, 0, sizeof(msg));
12882
12883         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12884         msg.hdr.original_sc = io;
12885         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12886         msg.hdr.nexus = io->io_hdr.nexus;
12887         msg.hdr.status = io->io_hdr.status;
12888         msg.scsi.tag_num = io->scsiio.tag_num;
12889         msg.scsi.tag_type = io->scsiio.tag_type;
12890         msg.scsi.scsi_status = io->scsiio.scsi_status;
12891         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12892                sizeof(io->scsiio.sense_data));
12893         msg.scsi.sense_len = io->scsiio.sense_len;
12894         msg.scsi.sense_residual = io->scsiio.sense_residual;
12895         msg.scsi.fetd_status = io->io_hdr.port_status;
12896         msg.scsi.residual = io->scsiio.residual;
12897         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12898
12899         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12900                 ctl_failover_io(io, /*have_lock*/ have_lock);
12901                 return;
12902         }
12903
12904         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12905         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12906                 /* XXX do something if this fails */
12907         }
12908
12909 }
12910
12911 /*
12912  * The DMA to the remote side is done, now we need to tell the other side
12913  * we're done so it can continue with its data movement.
12914  */
12915 static void
12916 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12917 {
12918         union ctl_io *io;
12919
12920         io = rq->context;
12921
12922         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12923                 printf("%s: ISC DMA write failed with error %d", __func__,
12924                        rq->ret);
12925                 ctl_set_internal_failure(&io->scsiio,
12926                                          /*sks_valid*/ 1,
12927                                          /*retry_count*/ rq->ret);
12928         }
12929
12930         ctl_dt_req_free(rq);
12931
12932         /*
12933          * In this case, we had to malloc the memory locally.  Free it.
12934          */
12935         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12936                 int i;
12937                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12938                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12939         }
12940         /*
12941          * The data is in local and remote memory, so now we need to send
12942          * status (good or back) back to the other side.
12943          */
12944         ctl_send_datamove_done(io, /*have_lock*/ 0);
12945 }
12946
12947 /*
12948  * We've moved the data from the host/controller into local memory.  Now we
12949  * need to push it over to the remote controller's memory.
12950  */
12951 static int
12952 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12953 {
12954         int retval;
12955
12956         retval = 0;
12957
12958         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12959                                           ctl_datamove_remote_write_cb);
12960
12961         return (retval);
12962 }
12963
12964 static void
12965 ctl_datamove_remote_write(union ctl_io *io)
12966 {
12967         int retval;
12968         void (*fe_datamove)(union ctl_io *io);
12969
12970         /*
12971          * - Get the data from the host/HBA into local memory.
12972          * - DMA memory from the local controller to the remote controller.
12973          * - Send status back to the remote controller.
12974          */
12975
12976         retval = ctl_datamove_remote_sgl_setup(io);
12977         if (retval != 0)
12978                 return;
12979
12980         /* Switch the pointer over so the FETD knows what to do */
12981         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12982
12983         /*
12984          * Use a custom move done callback, since we need to send completion
12985          * back to the other controller, not to the backend on this side.
12986          */
12987         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12988
12989         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12990
12991         fe_datamove(io);
12992
12993         return;
12994
12995 }
12996
12997 static int
12998 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12999 {
13000 #if 0
13001         char str[256];
13002         char path_str[64];
13003         struct sbuf sb;
13004 #endif
13005
13006         /*
13007          * In this case, we had to malloc the memory locally.  Free it.
13008          */
13009         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13010                 int i;
13011                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13012                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13013         }
13014
13015 #if 0
13016         scsi_path_string(io, path_str, sizeof(path_str));
13017         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13018         sbuf_cat(&sb, path_str);
13019         scsi_command_string(&io->scsiio, NULL, &sb);
13020         sbuf_printf(&sb, "\n");
13021         sbuf_cat(&sb, path_str);
13022         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13023                     io->scsiio.tag_num, io->scsiio.tag_type);
13024         sbuf_cat(&sb, path_str);
13025         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13026                     io->io_hdr.flags, io->io_hdr.status);
13027         sbuf_finish(&sb);
13028         printk("%s", sbuf_data(&sb));
13029 #endif
13030
13031
13032         /*
13033          * The read is done, now we need to send status (good or bad) back
13034          * to the other side.
13035          */
13036         ctl_send_datamove_done(io, /*have_lock*/ 0);
13037
13038         return (0);
13039 }
13040
13041 static void
13042 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13043 {
13044         union ctl_io *io;
13045         void (*fe_datamove)(union ctl_io *io);
13046
13047         io = rq->context;
13048
13049         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13050                 printf("%s: ISC DMA read failed with error %d", __func__,
13051                        rq->ret);
13052                 ctl_set_internal_failure(&io->scsiio,
13053                                          /*sks_valid*/ 1,
13054                                          /*retry_count*/ rq->ret);
13055         }
13056
13057         ctl_dt_req_free(rq);
13058
13059         /* Switch the pointer over so the FETD knows what to do */
13060         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13061
13062         /*
13063          * Use a custom move done callback, since we need to send completion
13064          * back to the other controller, not to the backend on this side.
13065          */
13066         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13067
13068         /* XXX KDM add checks like the ones in ctl_datamove? */
13069
13070         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13071
13072         fe_datamove(io);
13073 }
13074
13075 static int
13076 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13077 {
13078         struct ctl_sg_entry *local_sglist, *remote_sglist;
13079         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13080         struct ctl_softc *softc;
13081         int retval;
13082         int i;
13083
13084         retval = 0;
13085         softc = control_softc;
13086
13087         local_sglist = io->io_hdr.local_sglist;
13088         local_dma_sglist = io->io_hdr.local_dma_sglist;
13089         remote_sglist = io->io_hdr.remote_sglist;
13090         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13091
13092         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13093                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13094                         local_sglist[i].len = remote_sglist[i].len;
13095
13096                         /*
13097                          * XXX Detect the situation where the RS-level I/O
13098                          * redirector on the other side has already read the
13099                          * data off of the AOR RS on this side, and
13100                          * transferred it to remote (mirror) memory on the
13101                          * other side.  Since we already have the data in
13102                          * memory here, we just need to use it.
13103                          *
13104                          * XXX KDM this can probably be removed once we
13105                          * get the cache device code in and take the
13106                          * current AOR implementation out.
13107                          */
13108 #ifdef NEEDTOPORT
13109                         if ((remote_sglist[i].addr >=
13110                              (void *)vtophys(softc->mirr->addr))
13111                          && (remote_sglist[i].addr <
13112                              ((void *)vtophys(softc->mirr->addr) +
13113                              CacheMirrorOffset))) {
13114                                 local_sglist[i].addr = remote_sglist[i].addr -
13115                                         CacheMirrorOffset;
13116                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13117                                      CTL_FLAG_DATA_IN)
13118                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13119                         } else {
13120                                 local_sglist[i].addr = remote_sglist[i].addr +
13121                                         CacheMirrorOffset;
13122                         }
13123 #endif
13124 #if 0
13125                         printf("%s: local %p, remote %p, len %d\n",
13126                                __func__, local_sglist[i].addr,
13127                                remote_sglist[i].addr, local_sglist[i].len);
13128 #endif
13129                 }
13130         } else {
13131                 uint32_t len_to_go;
13132
13133                 /*
13134                  * In this case, we don't have automatically allocated
13135                  * memory for this I/O on this controller.  This typically
13136                  * happens with internal CTL I/O -- e.g. inquiry, mode
13137                  * sense, etc.  Anything coming from RAIDCore will have
13138                  * a mirror area available.
13139                  */
13140                 len_to_go = io->scsiio.kern_data_len;
13141
13142                 /*
13143                  * Clear the no datasync flag, we have to use malloced
13144                  * buffers.
13145                  */
13146                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13147
13148                 /*
13149                  * The difficult thing here is that the size of the various
13150                  * S/G segments may be different than the size from the
13151                  * remote controller.  That'll make it harder when DMAing
13152                  * the data back to the other side.
13153                  */
13154                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13155                      sizeof(io->io_hdr.remote_sglist[0])) &&
13156                      (len_to_go > 0); i++) {
13157                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13158                         CTL_SIZE_8B(local_dma_sglist[i].len,
13159                                     local_sglist[i].len);
13160                         local_sglist[i].addr =
13161                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13162
13163                         local_dma_sglist[i].addr = local_sglist[i].addr;
13164
13165                         if (local_sglist[i].addr == NULL) {
13166                                 int j;
13167
13168                                 printf("malloc failed for %zd bytes!",
13169                                        local_dma_sglist[i].len);
13170                                 for (j = 0; j < i; j++) {
13171                                         free(local_sglist[j].addr, M_CTL);
13172                                 }
13173                                 ctl_set_internal_failure(&io->scsiio,
13174                                                          /*sks_valid*/ 1,
13175                                                          /*retry_count*/ 4857);
13176                                 retval = 1;
13177                                 goto bailout_error;
13178                                 
13179                         }
13180                         /* XXX KDM do we need a sync here? */
13181
13182                         len_to_go -= local_sglist[i].len;
13183                 }
13184                 /*
13185                  * Reset the number of S/G entries accordingly.  The
13186                  * original number of S/G entries is available in
13187                  * rem_sg_entries.
13188                  */
13189                 io->scsiio.kern_sg_entries = i;
13190
13191 #if 0
13192                 printf("%s: kern_sg_entries = %d\n", __func__,
13193                        io->scsiio.kern_sg_entries);
13194                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13195                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13196                                local_sglist[i].addr, local_sglist[i].len,
13197                                local_dma_sglist[i].len);
13198 #endif
13199         }
13200
13201
13202         return (retval);
13203
13204 bailout_error:
13205
13206         ctl_send_datamove_done(io, /*have_lock*/ 0);
13207
13208         return (retval);
13209 }
13210
13211 static int
13212 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13213                          ctl_ha_dt_cb callback)
13214 {
13215         struct ctl_ha_dt_req *rq;
13216         struct ctl_sg_entry *remote_sglist, *local_sglist;
13217         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13218         uint32_t local_used, remote_used, total_used;
13219         int retval;
13220         int i, j;
13221
13222         retval = 0;
13223
13224         rq = ctl_dt_req_alloc();
13225
13226         /*
13227          * If we failed to allocate the request, and if the DMA didn't fail
13228          * anyway, set busy status.  This is just a resource allocation
13229          * failure.
13230          */
13231         if ((rq == NULL)
13232          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13233                 ctl_set_busy(&io->scsiio);
13234
13235         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13236
13237                 if (rq != NULL)
13238                         ctl_dt_req_free(rq);
13239
13240                 /*
13241                  * The data move failed.  We need to return status back
13242                  * to the other controller.  No point in trying to DMA
13243                  * data to the remote controller.
13244                  */
13245
13246                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13247
13248                 retval = 1;
13249
13250                 goto bailout;
13251         }
13252
13253         local_sglist = io->io_hdr.local_sglist;
13254         local_dma_sglist = io->io_hdr.local_dma_sglist;
13255         remote_sglist = io->io_hdr.remote_sglist;
13256         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13257         local_used = 0;
13258         remote_used = 0;
13259         total_used = 0;
13260
13261         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13262                 rq->ret = CTL_HA_STATUS_SUCCESS;
13263                 rq->context = io;
13264                 callback(rq);
13265                 goto bailout;
13266         }
13267
13268         /*
13269          * Pull/push the data over the wire from/to the other controller.
13270          * This takes into account the possibility that the local and
13271          * remote sglists may not be identical in terms of the size of
13272          * the elements and the number of elements.
13273          *
13274          * One fundamental assumption here is that the length allocated for
13275          * both the local and remote sglists is identical.  Otherwise, we've
13276          * essentially got a coding error of some sort.
13277          */
13278         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13279                 int isc_ret;
13280                 uint32_t cur_len, dma_length;
13281                 uint8_t *tmp_ptr;
13282
13283                 rq->id = CTL_HA_DATA_CTL;
13284                 rq->command = command;
13285                 rq->context = io;
13286
13287                 /*
13288                  * Both pointers should be aligned.  But it is possible
13289                  * that the allocation length is not.  They should both
13290                  * also have enough slack left over at the end, though,
13291                  * to round up to the next 8 byte boundary.
13292                  */
13293                 cur_len = ctl_min(local_sglist[i].len - local_used,
13294                                   remote_sglist[j].len - remote_used);
13295
13296                 /*
13297                  * In this case, we have a size issue and need to decrease
13298                  * the size, except in the case where we actually have less
13299                  * than 8 bytes left.  In that case, we need to increase
13300                  * the DMA length to get the last bit.
13301                  */
13302                 if ((cur_len & 0x7) != 0) {
13303                         if (cur_len > 0x7) {
13304                                 cur_len = cur_len - (cur_len & 0x7);
13305                                 dma_length = cur_len;
13306                         } else {
13307                                 CTL_SIZE_8B(dma_length, cur_len);
13308                         }
13309
13310                 } else
13311                         dma_length = cur_len;
13312
13313                 /*
13314                  * If we had to allocate memory for this I/O, instead of using
13315                  * the non-cached mirror memory, we'll need to flush the cache
13316                  * before trying to DMA to the other controller.
13317                  *
13318                  * We could end up doing this multiple times for the same
13319                  * segment if we have a larger local segment than remote
13320                  * segment.  That shouldn't be an issue.
13321                  */
13322                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13323                         /*
13324                          * XXX KDM use bus_dmamap_sync() here.
13325                          */
13326                 }
13327
13328                 rq->size = dma_length;
13329
13330                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13331                 tmp_ptr += local_used;
13332
13333                 /* Use physical addresses when talking to ISC hardware */
13334                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13335                         /* XXX KDM use busdma */
13336 #if 0
13337                         rq->local = vtophys(tmp_ptr);
13338 #endif
13339                 } else
13340                         rq->local = tmp_ptr;
13341
13342                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13343                 tmp_ptr += remote_used;
13344                 rq->remote = tmp_ptr;
13345
13346                 rq->callback = NULL;
13347
13348                 local_used += cur_len;
13349                 if (local_used >= local_sglist[i].len) {
13350                         i++;
13351                         local_used = 0;
13352                 }
13353
13354                 remote_used += cur_len;
13355                 if (remote_used >= remote_sglist[j].len) {
13356                         j++;
13357                         remote_used = 0;
13358                 }
13359                 total_used += cur_len;
13360
13361                 if (total_used >= io->scsiio.kern_data_len)
13362                         rq->callback = callback;
13363
13364                 if ((rq->size & 0x7) != 0) {
13365                         printf("%s: warning: size %d is not on 8b boundary\n",
13366                                __func__, rq->size);
13367                 }
13368                 if (((uintptr_t)rq->local & 0x7) != 0) {
13369                         printf("%s: warning: local %p not on 8b boundary\n",
13370                                __func__, rq->local);
13371                 }
13372                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13373                         printf("%s: warning: remote %p not on 8b boundary\n",
13374                                __func__, rq->local);
13375                 }
13376 #if 0
13377                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13378                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13379                        rq->local, rq->remote, rq->size);
13380 #endif
13381
13382                 isc_ret = ctl_dt_single(rq);
13383                 if (isc_ret == CTL_HA_STATUS_WAIT)
13384                         continue;
13385
13386                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13387                         rq->ret = CTL_HA_STATUS_SUCCESS;
13388                 } else {
13389                         rq->ret = isc_ret;
13390                 }
13391                 callback(rq);
13392                 goto bailout;
13393         }
13394
13395 bailout:
13396         return (retval);
13397
13398 }
13399
13400 static void
13401 ctl_datamove_remote_read(union ctl_io *io)
13402 {
13403         int retval;
13404         int i;
13405
13406         /*
13407          * This will send an error to the other controller in the case of a
13408          * failure.
13409          */
13410         retval = ctl_datamove_remote_sgl_setup(io);
13411         if (retval != 0)
13412                 return;
13413
13414         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13415                                           ctl_datamove_remote_read_cb);
13416         if ((retval != 0)
13417          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13418                 /*
13419                  * Make sure we free memory if there was an error..  The
13420                  * ctl_datamove_remote_xfer() function will send the
13421                  * datamove done message, or call the callback with an
13422                  * error if there is a problem.
13423                  */
13424                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13425                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13426         }
13427
13428         return;
13429 }
13430
13431 /*
13432  * Process a datamove request from the other controller.  This is used for
13433  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13434  * first.  Once that is complete, the data gets DMAed into the remote
13435  * controller's memory.  For reads, we DMA from the remote controller's
13436  * memory into our memory first, and then move it out to the FETD.
13437  */
13438 static void
13439 ctl_datamove_remote(union ctl_io *io)
13440 {
13441         struct ctl_softc *softc;
13442
13443         softc = control_softc;
13444
13445         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13446
13447         /*
13448          * Note that we look for an aborted I/O here, but don't do some of
13449          * the other checks that ctl_datamove() normally does.
13450          * We don't need to run the datamove delay code, since that should
13451          * have been done if need be on the other controller.
13452          */
13453         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13454                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13455                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13456                        io->io_hdr.nexus.targ_port,
13457                        io->io_hdr.nexus.targ_target.id,
13458                        io->io_hdr.nexus.targ_lun);
13459                 io->io_hdr.port_status = 31338;
13460                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13461                 return;
13462         }
13463
13464         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13465                 ctl_datamove_remote_write(io);
13466         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13467                 ctl_datamove_remote_read(io);
13468         } else {
13469                 union ctl_ha_msg msg;
13470                 struct scsi_sense_data *sense;
13471                 uint8_t sks[3];
13472                 int retry_count;
13473
13474                 memset(&msg, 0, sizeof(msg));
13475
13476                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13477                 msg.hdr.status = CTL_SCSI_ERROR;
13478                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13479
13480                 retry_count = 4243;
13481
13482                 sense = &msg.scsi.sense_data;
13483                 sks[0] = SSD_SCS_VALID;
13484                 sks[1] = (retry_count >> 8) & 0xff;
13485                 sks[2] = retry_count & 0xff;
13486
13487                 /* "Internal target failure" */
13488                 scsi_set_sense_data(sense,
13489                                     /*sense_format*/ SSD_TYPE_NONE,
13490                                     /*current_error*/ 1,
13491                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13492                                     /*asc*/ 0x44,
13493                                     /*ascq*/ 0x00,
13494                                     /*type*/ SSD_ELEM_SKS,
13495                                     /*size*/ sizeof(sks),
13496                                     /*data*/ sks,
13497                                     SSD_ELEM_NONE);
13498
13499                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13500                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13501                         ctl_failover_io(io, /*have_lock*/ 1);
13502                         return;
13503                 }
13504
13505                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13506                     CTL_HA_STATUS_SUCCESS) {
13507                         /* XXX KDM what to do if this fails? */
13508                 }
13509                 return;
13510         }
13511         
13512 }
13513
13514 static int
13515 ctl_process_done(union ctl_io *io)
13516 {
13517         struct ctl_lun *lun;
13518         struct ctl_softc *ctl_softc;
13519         void (*fe_done)(union ctl_io *io);
13520         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13521
13522         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13523
13524         fe_done =
13525             control_softc->ctl_ports[targ_port]->fe_done;
13526
13527 #ifdef CTL_TIME_IO
13528         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13529                 char str[256];
13530                 char path_str[64];
13531                 struct sbuf sb;
13532
13533                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13534                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13535
13536                 sbuf_cat(&sb, path_str);
13537                 switch (io->io_hdr.io_type) {
13538                 case CTL_IO_SCSI:
13539                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13540                         sbuf_printf(&sb, "\n");
13541                         sbuf_cat(&sb, path_str);
13542                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13543                                     io->scsiio.tag_num, io->scsiio.tag_type);
13544                         break;
13545                 case CTL_IO_TASK:
13546                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13547                                     "Tag Type: %d\n", io->taskio.task_action,
13548                                     io->taskio.tag_num, io->taskio.tag_type);
13549                         break;
13550                 default:
13551                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13552                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13553                         break;
13554                 }
13555                 sbuf_cat(&sb, path_str);
13556                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13557                             (intmax_t)time_uptime - io->io_hdr.start_time);
13558                 sbuf_finish(&sb);
13559                 printf("%s", sbuf_data(&sb));
13560         }
13561 #endif /* CTL_TIME_IO */
13562
13563         switch (io->io_hdr.io_type) {
13564         case CTL_IO_SCSI:
13565                 break;
13566         case CTL_IO_TASK:
13567                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13568                         ctl_io_error_print(io, NULL);
13569                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13570                         ctl_free_io(io);
13571                 else
13572                         fe_done(io);
13573                 return (CTL_RETVAL_COMPLETE);
13574         default:
13575                 panic("ctl_process_done: invalid io type %d\n",
13576                       io->io_hdr.io_type);
13577                 break; /* NOTREACHED */
13578         }
13579
13580         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13581         if (lun == NULL) {
13582                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13583                                  io->io_hdr.nexus.targ_mapped_lun));
13584                 fe_done(io);
13585                 goto bailout;
13586         }
13587         ctl_softc = lun->ctl_softc;
13588
13589         mtx_lock(&lun->lun_lock);
13590
13591         /*
13592          * Check to see if we have any errors to inject here.  We only
13593          * inject errors for commands that don't already have errors set.
13594          */
13595         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13596          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13597                 ctl_inject_error(lun, io);
13598
13599         /*
13600          * XXX KDM how do we treat commands that aren't completed
13601          * successfully?
13602          *
13603          * XXX KDM should we also track I/O latency?
13604          */
13605         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13606             io->io_hdr.io_type == CTL_IO_SCSI) {
13607 #ifdef CTL_TIME_IO
13608                 struct bintime cur_bt;
13609 #endif
13610                 int type;
13611
13612                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13613                     CTL_FLAG_DATA_IN)
13614                         type = CTL_STATS_READ;
13615                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13616                     CTL_FLAG_DATA_OUT)
13617                         type = CTL_STATS_WRITE;
13618                 else
13619                         type = CTL_STATS_NO_IO;
13620
13621                 lun->stats.ports[targ_port].bytes[type] +=
13622                     io->scsiio.kern_total_len;
13623                 lun->stats.ports[targ_port].operations[type]++;
13624 #ifdef CTL_TIME_IO
13625                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13626                    &io->io_hdr.dma_bt);
13627                 lun->stats.ports[targ_port].num_dmas[type] +=
13628                     io->io_hdr.num_dmas;
13629                 getbintime(&cur_bt);
13630                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13631                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13632 #endif
13633         }
13634
13635         /*
13636          * Remove this from the OOA queue.
13637          */
13638         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13639
13640         /*
13641          * Run through the blocked queue on this LUN and see if anything
13642          * has become unblocked, now that this transaction is done.
13643          */
13644         ctl_check_blocked(lun);
13645
13646         /*
13647          * If the LUN has been invalidated, free it if there is nothing
13648          * left on its OOA queue.
13649          */
13650         if ((lun->flags & CTL_LUN_INVALID)
13651          && TAILQ_EMPTY(&lun->ooa_queue)) {
13652                 mtx_unlock(&lun->lun_lock);
13653                 mtx_lock(&ctl_softc->ctl_lock);
13654                 ctl_free_lun(lun);
13655                 mtx_unlock(&ctl_softc->ctl_lock);
13656         } else
13657                 mtx_unlock(&lun->lun_lock);
13658
13659         /*
13660          * If this command has been aborted, make sure we set the status
13661          * properly.  The FETD is responsible for freeing the I/O and doing
13662          * whatever it needs to do to clean up its state.
13663          */
13664         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13665                 ctl_set_task_aborted(&io->scsiio);
13666
13667         /*
13668          * If enabled, print command error status.
13669          * We don't print UAs unless debugging was enabled explicitly.
13670          */
13671         do {
13672                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13673                         break;
13674                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13675                         break;
13676                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13677                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13678                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13679                         int error_code, sense_key, asc, ascq;
13680
13681                         scsi_extract_sense_len(&io->scsiio.sense_data,
13682                             io->scsiio.sense_len, &error_code, &sense_key,
13683                             &asc, &ascq, /*show_errors*/ 0);
13684                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13685                                 break;
13686                 }
13687
13688                 ctl_io_error_print(io, NULL);
13689         } while (0);
13690
13691         /*
13692          * Tell the FETD or the other shelf controller we're done with this
13693          * command.  Note that only SCSI commands get to this point.  Task
13694          * management commands are completed above.
13695          *
13696          * We only send status to the other controller if we're in XFER
13697          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13698          * received the I/O (from CTL's perspective), and so the status is
13699          * generated there.
13700          * 
13701          * XXX KDM if we hold the lock here, we could cause a deadlock
13702          * if the frontend comes back in in this context to queue
13703          * something.
13704          */
13705         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13706          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13707                 union ctl_ha_msg msg;
13708
13709                 memset(&msg, 0, sizeof(msg));
13710                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13711                 msg.hdr.original_sc = io->io_hdr.original_sc;
13712                 msg.hdr.nexus = io->io_hdr.nexus;
13713                 msg.hdr.status = io->io_hdr.status;
13714                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13715                 msg.scsi.tag_num = io->scsiio.tag_num;
13716                 msg.scsi.tag_type = io->scsiio.tag_type;
13717                 msg.scsi.sense_len = io->scsiio.sense_len;
13718                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13719                 msg.scsi.residual = io->scsiio.residual;
13720                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13721                        sizeof(io->scsiio.sense_data));
13722                 /*
13723                  * We copy this whether or not this is an I/O-related
13724                  * command.  Otherwise, we'd have to go and check to see
13725                  * whether it's a read/write command, and it really isn't
13726                  * worth it.
13727                  */
13728                 memcpy(&msg.scsi.lbalen,
13729                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13730                        sizeof(msg.scsi.lbalen));
13731
13732                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13733                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13734                         /* XXX do something here */
13735                 }
13736
13737                 ctl_free_io(io);
13738         } else 
13739                 fe_done(io);
13740
13741 bailout:
13742
13743         return (CTL_RETVAL_COMPLETE);
13744 }
13745
13746 #ifdef CTL_WITH_CA
13747 /*
13748  * Front end should call this if it doesn't do autosense.  When the request
13749  * sense comes back in from the initiator, we'll dequeue this and send it.
13750  */
13751 int
13752 ctl_queue_sense(union ctl_io *io)
13753 {
13754         struct ctl_lun *lun;
13755         struct ctl_softc *ctl_softc;
13756         uint32_t initidx, targ_lun;
13757
13758         ctl_softc = control_softc;
13759
13760         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13761
13762         /*
13763          * LUN lookup will likely move to the ctl_work_thread() once we
13764          * have our new queueing infrastructure (that doesn't put things on
13765          * a per-LUN queue initially).  That is so that we can handle
13766          * things like an INQUIRY to a LUN that we don't have enabled.  We
13767          * can't deal with that right now.
13768          */
13769         mtx_lock(&ctl_softc->ctl_lock);
13770
13771         /*
13772          * If we don't have a LUN for this, just toss the sense
13773          * information.
13774          */
13775         targ_lun = io->io_hdr.nexus.targ_lun;
13776         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13777         if ((targ_lun < CTL_MAX_LUNS)
13778          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13779                 lun = ctl_softc->ctl_luns[targ_lun];
13780         else
13781                 goto bailout;
13782
13783         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13784
13785         mtx_lock(&lun->lun_lock);
13786         /*
13787          * Already have CA set for this LUN...toss the sense information.
13788          */
13789         if (ctl_is_set(lun->have_ca, initidx)) {
13790                 mtx_unlock(&lun->lun_lock);
13791                 goto bailout;
13792         }
13793
13794         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13795                ctl_min(sizeof(lun->pending_sense[initidx]),
13796                sizeof(io->scsiio.sense_data)));
13797         ctl_set_mask(lun->have_ca, initidx);
13798         mtx_unlock(&lun->lun_lock);
13799
13800 bailout:
13801         mtx_unlock(&ctl_softc->ctl_lock);
13802
13803         ctl_free_io(io);
13804
13805         return (CTL_RETVAL_COMPLETE);
13806 }
13807 #endif
13808
13809 /*
13810  * Primary command inlet from frontend ports.  All SCSI and task I/O
13811  * requests must go through this function.
13812  */
13813 int
13814 ctl_queue(union ctl_io *io)
13815 {
13816         struct ctl_softc *ctl_softc;
13817
13818         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13819
13820         ctl_softc = control_softc;
13821
13822 #ifdef CTL_TIME_IO
13823         io->io_hdr.start_time = time_uptime;
13824         getbintime(&io->io_hdr.start_bt);
13825 #endif /* CTL_TIME_IO */
13826
13827         /* Map FE-specific LUN ID into global one. */
13828         io->io_hdr.nexus.targ_mapped_lun =
13829             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13830
13831         switch (io->io_hdr.io_type) {
13832         case CTL_IO_SCSI:
13833         case CTL_IO_TASK:
13834                 if (ctl_debug & CTL_DEBUG_CDB)
13835                         ctl_io_print(io);
13836                 ctl_enqueue_incoming(io);
13837                 break;
13838         default:
13839                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13840                 return (EINVAL);
13841         }
13842
13843         return (CTL_RETVAL_COMPLETE);
13844 }
13845
13846 #ifdef CTL_IO_DELAY
13847 static void
13848 ctl_done_timer_wakeup(void *arg)
13849 {
13850         union ctl_io *io;
13851
13852         io = (union ctl_io *)arg;
13853         ctl_done(io);
13854 }
13855 #endif /* CTL_IO_DELAY */
13856
13857 void
13858 ctl_done(union ctl_io *io)
13859 {
13860         struct ctl_softc *ctl_softc;
13861
13862         ctl_softc = control_softc;
13863
13864         /*
13865          * Enable this to catch duplicate completion issues.
13866          */
13867 #if 0
13868         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13869                 printf("%s: type %d msg %d cdb %x iptl: "
13870                        "%d:%d:%d:%d tag 0x%04x "
13871                        "flag %#x status %x\n",
13872                         __func__,
13873                         io->io_hdr.io_type,
13874                         io->io_hdr.msg_type,
13875                         io->scsiio.cdb[0],
13876                         io->io_hdr.nexus.initid.id,
13877                         io->io_hdr.nexus.targ_port,
13878                         io->io_hdr.nexus.targ_target.id,
13879                         io->io_hdr.nexus.targ_lun,
13880                         (io->io_hdr.io_type ==
13881                         CTL_IO_TASK) ?
13882                         io->taskio.tag_num :
13883                         io->scsiio.tag_num,
13884                         io->io_hdr.flags,
13885                         io->io_hdr.status);
13886         } else
13887                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13888 #endif
13889
13890         /*
13891          * This is an internal copy of an I/O, and should not go through
13892          * the normal done processing logic.
13893          */
13894         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13895                 return;
13896
13897         /*
13898          * We need to send a msg to the serializing shelf to finish the IO
13899          * as well.  We don't send a finish message to the other shelf if
13900          * this is a task management command.  Task management commands
13901          * aren't serialized in the OOA queue, but rather just executed on
13902          * both shelf controllers for commands that originated on that
13903          * controller.
13904          */
13905         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13906          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13907                 union ctl_ha_msg msg_io;
13908
13909                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13910                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13911                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13912                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13913                 }
13914                 /* continue on to finish IO */
13915         }
13916 #ifdef CTL_IO_DELAY
13917         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13918                 struct ctl_lun *lun;
13919
13920                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13921
13922                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13923         } else {
13924                 struct ctl_lun *lun;
13925
13926                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13927
13928                 if ((lun != NULL)
13929                  && (lun->delay_info.done_delay > 0)) {
13930                         struct callout *callout;
13931
13932                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13933                         callout_init(callout, /*mpsafe*/ 1);
13934                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13935                         callout_reset(callout,
13936                                       lun->delay_info.done_delay * hz,
13937                                       ctl_done_timer_wakeup, io);
13938                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13939                                 lun->delay_info.done_delay = 0;
13940                         return;
13941                 }
13942         }
13943 #endif /* CTL_IO_DELAY */
13944
13945         ctl_enqueue_done(io);
13946 }
13947
13948 int
13949 ctl_isc(struct ctl_scsiio *ctsio)
13950 {
13951         struct ctl_lun *lun;
13952         int retval;
13953
13954         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13955
13956         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13957
13958         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13959
13960         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13961
13962         return (retval);
13963 }
13964
13965
13966 static void
13967 ctl_work_thread(void *arg)
13968 {
13969         struct ctl_thread *thr = (struct ctl_thread *)arg;
13970         struct ctl_softc *softc = thr->ctl_softc;
13971         union ctl_io *io;
13972         int retval;
13973
13974         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13975
13976         for (;;) {
13977                 retval = 0;
13978
13979                 /*
13980                  * We handle the queues in this order:
13981                  * - ISC
13982                  * - done queue (to free up resources, unblock other commands)
13983                  * - RtR queue
13984                  * - incoming queue
13985                  *
13986                  * If those queues are empty, we break out of the loop and
13987                  * go to sleep.
13988                  */
13989                 mtx_lock(&thr->queue_lock);
13990                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13991                 if (io != NULL) {
13992                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13993                         mtx_unlock(&thr->queue_lock);
13994                         ctl_handle_isc(io);
13995                         continue;
13996                 }
13997                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13998                 if (io != NULL) {
13999                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14000                         /* clear any blocked commands, call fe_done */
14001                         mtx_unlock(&thr->queue_lock);
14002                         retval = ctl_process_done(io);
14003                         continue;
14004                 }
14005                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14006                 if (io != NULL) {
14007                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14008                         mtx_unlock(&thr->queue_lock);
14009                         if (io->io_hdr.io_type == CTL_IO_TASK)
14010                                 ctl_run_task(io);
14011                         else
14012                                 ctl_scsiio_precheck(softc, &io->scsiio);
14013                         continue;
14014                 }
14015                 if (!ctl_pause_rtr) {
14016                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14017                         if (io != NULL) {
14018                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14019                                 mtx_unlock(&thr->queue_lock);
14020                                 retval = ctl_scsiio(&io->scsiio);
14021                                 if (retval != CTL_RETVAL_COMPLETE)
14022                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14023                                 continue;
14024                         }
14025                 }
14026
14027                 /* Sleep until we have something to do. */
14028                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14029         }
14030 }
14031
14032 static void
14033 ctl_lun_thread(void *arg)
14034 {
14035         struct ctl_softc *softc = (struct ctl_softc *)arg;
14036         struct ctl_be_lun *be_lun;
14037         int retval;
14038
14039         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14040
14041         for (;;) {
14042                 retval = 0;
14043                 mtx_lock(&softc->ctl_lock);
14044                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14045                 if (be_lun != NULL) {
14046                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14047                         mtx_unlock(&softc->ctl_lock);
14048                         ctl_create_lun(be_lun);
14049                         continue;
14050                 }
14051
14052                 /* Sleep until we have something to do. */
14053                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14054                     PDROP | PRIBIO, "-", 0);
14055         }
14056 }
14057
14058 static void
14059 ctl_enqueue_incoming(union ctl_io *io)
14060 {
14061         struct ctl_softc *softc = control_softc;
14062         struct ctl_thread *thr;
14063         u_int idx;
14064
14065         idx = (io->io_hdr.nexus.targ_port * 127 +
14066                io->io_hdr.nexus.initid.id) % worker_threads;
14067         thr = &softc->threads[idx];
14068         mtx_lock(&thr->queue_lock);
14069         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14070         mtx_unlock(&thr->queue_lock);
14071         wakeup(thr);
14072 }
14073
14074 static void
14075 ctl_enqueue_rtr(union ctl_io *io)
14076 {
14077         struct ctl_softc *softc = control_softc;
14078         struct ctl_thread *thr;
14079
14080         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14081         mtx_lock(&thr->queue_lock);
14082         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14083         mtx_unlock(&thr->queue_lock);
14084         wakeup(thr);
14085 }
14086
14087 static void
14088 ctl_enqueue_done(union ctl_io *io)
14089 {
14090         struct ctl_softc *softc = control_softc;
14091         struct ctl_thread *thr;
14092
14093         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14094         mtx_lock(&thr->queue_lock);
14095         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14096         mtx_unlock(&thr->queue_lock);
14097         wakeup(thr);
14098 }
14099
14100 static void
14101 ctl_enqueue_isc(union ctl_io *io)
14102 {
14103         struct ctl_softc *softc = control_softc;
14104         struct ctl_thread *thr;
14105
14106         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14107         mtx_lock(&thr->queue_lock);
14108         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14109         mtx_unlock(&thr->queue_lock);
14110         wakeup(thr);
14111 }
14112
14113 /* Initialization and failover */
14114
14115 void
14116 ctl_init_isc_msg(void)
14117 {
14118         printf("CTL: Still calling this thing\n");
14119 }
14120
14121 /*
14122  * Init component
14123  *      Initializes component into configuration defined by bootMode
14124  *      (see hasc-sv.c)
14125  *      returns hasc_Status:
14126  *              OK
14127  *              ERROR - fatal error
14128  */
14129 static ctl_ha_comp_status
14130 ctl_isc_init(struct ctl_ha_component *c)
14131 {
14132         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14133
14134         c->status = ret;
14135         return ret;
14136 }
14137
14138 /* Start component
14139  *      Starts component in state requested. If component starts successfully,
14140  *      it must set its own state to the requestrd state
14141  *      When requested state is HASC_STATE_HA, the component may refine it
14142  *      by adding _SLAVE or _MASTER flags.
14143  *      Currently allowed state transitions are:
14144  *      UNKNOWN->HA             - initial startup
14145  *      UNKNOWN->SINGLE - initial startup when no parter detected
14146  *      HA->SINGLE              - failover
14147  * returns ctl_ha_comp_status:
14148  *              OK      - component successfully started in requested state
14149  *              FAILED  - could not start the requested state, failover may
14150  *                        be possible
14151  *              ERROR   - fatal error detected, no future startup possible
14152  */
14153 static ctl_ha_comp_status
14154 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14155 {
14156         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14157
14158         printf("%s: go\n", __func__);
14159
14160         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14161         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14162                 ctl_is_single = 0;
14163                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14164                     != CTL_HA_STATUS_SUCCESS) {
14165                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14166                         ret = CTL_HA_COMP_STATUS_ERROR;
14167                 }
14168         } else if (CTL_HA_STATE_IS_HA(c->state)
14169                 && CTL_HA_STATE_IS_SINGLE(state)){
14170                 // HA->SINGLE transition
14171                 ctl_failover();
14172                 ctl_is_single = 1;
14173         } else {
14174                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14175                        c->state, state);
14176                 ret = CTL_HA_COMP_STATUS_ERROR;
14177         }
14178         if (CTL_HA_STATE_IS_SINGLE(state))
14179                 ctl_is_single = 1;
14180
14181         c->state = state;
14182         c->status = ret;
14183         return ret;
14184 }
14185
14186 /*
14187  * Quiesce component
14188  * The component must clear any error conditions (set status to OK) and
14189  * prepare itself to another Start call
14190  * returns ctl_ha_comp_status:
14191  *      OK
14192  *      ERROR
14193  */
14194 static ctl_ha_comp_status
14195 ctl_isc_quiesce(struct ctl_ha_component *c)
14196 {
14197         int ret = CTL_HA_COMP_STATUS_OK;
14198
14199         ctl_pause_rtr = 1;
14200         c->status = ret;
14201         return ret;
14202 }
14203
14204 struct ctl_ha_component ctl_ha_component_ctlisc =
14205 {
14206         .name = "CTL ISC",
14207         .state = CTL_HA_STATE_UNKNOWN,
14208         .init = ctl_isc_init,
14209         .start = ctl_isc_start,
14210         .quiesce = ctl_isc_quiesce
14211 };
14212
14213 /*
14214  *  vim: ts=8
14215  */