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