]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r288110: Add support for Control extension mode page.
[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  * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42
43 #define _CTL_C
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_da.h>
73 #include <cam/ctl/ctl_io.h>
74 #include <cam/ctl/ctl.h>
75 #include <cam/ctl/ctl_frontend.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Template mode pages.
89  */
90
91 /*
92  * Note that these are default values only.  The actual values will be
93  * filled in when the user does a mode sense.
94  */
95 const static struct copan_debugconf_subpage debugconf_page_default = {
96         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
97         DBGCNF_SUBPAGE_CODE,            /* subpage */
98         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
99          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
100         DBGCNF_VERSION,                 /* page_version */
101         {CTL_TIME_IO_DEFAULT_SECS>>8,
102          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
103 };
104
105 const static struct copan_debugconf_subpage debugconf_page_changeable = {
106         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
107         DBGCNF_SUBPAGE_CODE,            /* subpage */
108         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
109          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
110         0,                              /* page_version */
111         {0xff,0xff},                    /* ctl_time_io_secs */
112 };
113
114 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
115         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
118         /*read_retry_count*/0,
119         /*correction_span*/0,
120         /*head_offset_count*/0,
121         /*data_strobe_offset_cnt*/0,
122         /*byte8*/SMS_RWER_LBPERE,
123         /*write_retry_count*/0,
124         /*reserved2*/0,
125         /*recovery_time_limit*/{0, 0},
126 };
127
128 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
129         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
130         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
131         /*byte3*/0,
132         /*read_retry_count*/0,
133         /*correction_span*/0,
134         /*head_offset_count*/0,
135         /*data_strobe_offset_cnt*/0,
136         /*byte8*/0,
137         /*write_retry_count*/0,
138         /*reserved2*/0,
139         /*recovery_time_limit*/{0, 0},
140 };
141
142 const static struct scsi_format_page format_page_default = {
143         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
144         /*page_length*/sizeof(struct scsi_format_page) - 2,
145         /*tracks_per_zone*/ {0, 0},
146         /*alt_sectors_per_zone*/ {0, 0},
147         /*alt_tracks_per_zone*/ {0, 0},
148         /*alt_tracks_per_lun*/ {0, 0},
149         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
150                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
151         /*bytes_per_sector*/ {0, 0},
152         /*interleave*/ {0, 0},
153         /*track_skew*/ {0, 0},
154         /*cylinder_skew*/ {0, 0},
155         /*flags*/ SFP_HSEC,
156         /*reserved*/ {0, 0, 0}
157 };
158
159 const static struct scsi_format_page format_page_changeable = {
160         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
161         /*page_length*/sizeof(struct scsi_format_page) - 2,
162         /*tracks_per_zone*/ {0, 0},
163         /*alt_sectors_per_zone*/ {0, 0},
164         /*alt_tracks_per_zone*/ {0, 0},
165         /*alt_tracks_per_lun*/ {0, 0},
166         /*sectors_per_track*/ {0, 0},
167         /*bytes_per_sector*/ {0, 0},
168         /*interleave*/ {0, 0},
169         /*track_skew*/ {0, 0},
170         /*cylinder_skew*/ {0, 0},
171         /*flags*/ 0,
172         /*reserved*/ {0, 0, 0}
173 };
174
175 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
176         /*page_code*/SMS_RIGID_DISK_PAGE,
177         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
178         /*cylinders*/ {0, 0, 0},
179         /*heads*/ CTL_DEFAULT_HEADS,
180         /*start_write_precomp*/ {0, 0, 0},
181         /*start_reduced_current*/ {0, 0, 0},
182         /*step_rate*/ {0, 0},
183         /*landing_zone_cylinder*/ {0, 0, 0},
184         /*rpl*/ SRDP_RPL_DISABLED,
185         /*rotational_offset*/ 0,
186         /*reserved1*/ 0,
187         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
188                            CTL_DEFAULT_ROTATION_RATE & 0xff},
189         /*reserved2*/ {0, 0}
190 };
191
192 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
193         /*page_code*/SMS_RIGID_DISK_PAGE,
194         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
195         /*cylinders*/ {0, 0, 0},
196         /*heads*/ 0,
197         /*start_write_precomp*/ {0, 0, 0},
198         /*start_reduced_current*/ {0, 0, 0},
199         /*step_rate*/ {0, 0},
200         /*landing_zone_cylinder*/ {0, 0, 0},
201         /*rpl*/ 0,
202         /*rotational_offset*/ 0,
203         /*reserved1*/ 0,
204         /*rotation_rate*/ {0, 0},
205         /*reserved2*/ {0, 0}
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
265
266 const static struct scsi_control_ext_page control_ext_page_default = {
267         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268         /*subpage_code*/0x01,
269         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270         /*flags*/0,
271         /*prio*/0,
272         /*max_sense*/0
273 };
274
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277         /*subpage_code*/0x01,
278         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279         /*flags*/0,
280         /*prio*/0,
281         /*max_sense*/0
282 };
283
284 const static struct scsi_info_exceptions_page ie_page_default = {
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287         /*info_flags*/SIEP_FLAGS_DEXCPT,
288         /*mrie*/0,
289         /*interval_timer*/{0, 0, 0, 0},
290         /*report_count*/{0, 0, 0, 0}
291 };
292
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296         /*info_flags*/0,
297         /*mrie*/0,
298         /*interval_timer*/{0, 0, 0, 0},
299         /*report_count*/{0, 0, 0, 0}
300 };
301
302 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
303
304 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
305         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
306         /*subpage_code*/0x02,
307         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
308         /*flags*/0,
309         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
310         /*descr*/{}},
311         {{/*flags*/0,
312           /*resource*/0x01,
313           /*reserved*/{0, 0},
314           /*count*/{0, 0, 0, 0}},
315          {/*flags*/0,
316           /*resource*/0x02,
317           /*reserved*/{0, 0},
318           /*count*/{0, 0, 0, 0}},
319          {/*flags*/0,
320           /*resource*/0xf1,
321           /*reserved*/{0, 0},
322           /*count*/{0, 0, 0, 0}},
323          {/*flags*/0,
324           /*resource*/0xf2,
325           /*reserved*/{0, 0},
326           /*count*/{0, 0, 0, 0}}
327         }
328 };
329
330 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
331         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
332         /*subpage_code*/0x02,
333         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
334         /*flags*/0,
335         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
336         /*descr*/{}},
337         {{/*flags*/0,
338           /*resource*/0,
339           /*reserved*/{0, 0},
340           /*count*/{0, 0, 0, 0}},
341          {/*flags*/0,
342           /*resource*/0,
343           /*reserved*/{0, 0},
344           /*count*/{0, 0, 0, 0}},
345          {/*flags*/0,
346           /*resource*/0,
347           /*reserved*/{0, 0},
348           /*count*/{0, 0, 0, 0}},
349          {/*flags*/0,
350           /*resource*/0,
351           /*reserved*/{0, 0},
352           /*count*/{0, 0, 0, 0}}
353         }
354 };
355
356 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
357 static int worker_threads = -1;
358 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
359 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
360     &worker_threads, 1, "Number of worker threads");
361 static int ctl_debug = CTL_DEBUG_NONE;
362 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
363 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
364     &ctl_debug, 0, "Enabled debug flags");
365
366 /*
367  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
368  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
369  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
370  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
371  */
372 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
373
374 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
375                                   int param);
376 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
377 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
378 static int ctl_init(void);
379 void ctl_shutdown(void);
380 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
381 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
382 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
383 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
384                               struct ctl_ooa *ooa_hdr,
385                               struct ctl_ooa_entry *kern_entries);
386 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
387                      struct thread *td);
388 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
389                          struct ctl_be_lun *be_lun);
390 static int ctl_free_lun(struct ctl_lun *lun);
391 static void ctl_create_lun(struct ctl_be_lun *be_lun);
392 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
393
394 static int ctl_do_mode_select(union ctl_io *io);
395 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
396                            uint64_t res_key, uint64_t sa_res_key,
397                            uint8_t type, uint32_t residx,
398                            struct ctl_scsiio *ctsio,
399                            struct scsi_per_res_out *cdb,
400                            struct scsi_per_res_out_parms* param);
401 static void ctl_pro_preempt_other(struct ctl_lun *lun,
402                                   union ctl_ha_msg *msg);
403 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
404 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
405 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
406 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
407 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
408 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
409 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
410                                          int alloc_len);
411 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
412                                          int alloc_len);
413 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
414 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
415 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
416 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
417 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
418 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
419     bool seq);
420 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
421 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
422     union ctl_io *pending_io, union ctl_io *ooa_io);
423 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
424                                 union ctl_io *starting_io);
425 static int ctl_check_blocked(struct ctl_lun *lun);
426 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
427                                 const struct ctl_cmd_entry *entry,
428                                 struct ctl_scsiio *ctsio);
429 static void ctl_failover_lun(struct ctl_lun *lun);
430 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
431                                struct ctl_scsiio *ctsio);
432 static int ctl_scsiio(struct ctl_scsiio *ctsio);
433
434 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
435 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
436                             ctl_ua_type ua_type);
437 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
438                          ctl_ua_type ua_type);
439 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
440 static int ctl_abort_task(union ctl_io *io);
441 static int ctl_abort_task_set(union ctl_io *io);
442 static int ctl_query_task(union ctl_io *io, int task_set);
443 static int ctl_i_t_nexus_reset(union ctl_io *io);
444 static int ctl_query_async_event(union ctl_io *io);
445 static void ctl_run_task(union ctl_io *io);
446 #ifdef CTL_IO_DELAY
447 static void ctl_datamove_timer_wakeup(void *arg);
448 static void ctl_done_timer_wakeup(void *arg);
449 #endif /* CTL_IO_DELAY */
450
451 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
452 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
453 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
454 static void ctl_datamove_remote_write(union ctl_io *io);
455 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
456 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
457 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
458 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
459                                     ctl_ha_dt_cb callback);
460 static void ctl_datamove_remote_read(union ctl_io *io);
461 static void ctl_datamove_remote(union ctl_io *io);
462 static int ctl_process_done(union ctl_io *io);
463 static void ctl_lun_thread(void *arg);
464 static void ctl_thresh_thread(void *arg);
465 static void ctl_work_thread(void *arg);
466 static void ctl_enqueue_incoming(union ctl_io *io);
467 static void ctl_enqueue_rtr(union ctl_io *io);
468 static void ctl_enqueue_done(union ctl_io *io);
469 static void ctl_enqueue_isc(union ctl_io *io);
470 static const struct ctl_cmd_entry *
471     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
472 static const struct ctl_cmd_entry *
473     ctl_validate_command(struct ctl_scsiio *ctsio);
474 static int ctl_cmd_applicable(uint8_t lun_type,
475     const struct ctl_cmd_entry *entry);
476
477 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
478 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
479 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
480 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
481
482 /*
483  * Load the serialization table.  This isn't very pretty, but is probably
484  * the easiest way to do it.
485  */
486 #include "ctl_ser_table.c"
487
488 /*
489  * We only need to define open, close and ioctl routines for this driver.
490  */
491 static struct cdevsw ctl_cdevsw = {
492         .d_version =    D_VERSION,
493         .d_flags =      0,
494         .d_open =       ctl_open,
495         .d_close =      ctl_close,
496         .d_ioctl =      ctl_ioctl,
497         .d_name =       "ctl",
498 };
499
500
501 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
502
503 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
504
505 static moduledata_t ctl_moduledata = {
506         "ctl",
507         ctl_module_event_handler,
508         NULL
509 };
510
511 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
512 MODULE_VERSION(ctl, 1);
513
514 static struct ctl_frontend ha_frontend =
515 {
516         .name = "ha",
517 };
518
519 static void
520 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
521                             union ctl_ha_msg *msg_info)
522 {
523         struct ctl_scsiio *ctsio;
524
525         if (msg_info->hdr.original_sc == NULL) {
526                 printf("%s: original_sc == NULL!\n", __func__);
527                 /* XXX KDM now what? */
528                 return;
529         }
530
531         ctsio = &msg_info->hdr.original_sc->scsiio;
532         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
533         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
534         ctsio->io_hdr.status = msg_info->hdr.status;
535         ctsio->scsi_status = msg_info->scsi.scsi_status;
536         ctsio->sense_len = msg_info->scsi.sense_len;
537         ctsio->sense_residual = msg_info->scsi.sense_residual;
538         ctsio->residual = msg_info->scsi.residual;
539         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
540                msg_info->scsi.sense_len);
541         ctl_enqueue_isc((union ctl_io *)ctsio);
542 }
543
544 static void
545 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
546                                 union ctl_ha_msg *msg_info)
547 {
548         struct ctl_scsiio *ctsio;
549
550         if (msg_info->hdr.serializing_sc == NULL) {
551                 printf("%s: serializing_sc == NULL!\n", __func__);
552                 /* XXX KDM now what? */
553                 return;
554         }
555
556         ctsio = &msg_info->hdr.serializing_sc->scsiio;
557         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
558         ctl_enqueue_isc((union ctl_io *)ctsio);
559 }
560
561 void
562 ctl_isc_announce_lun(struct ctl_lun *lun)
563 {
564         struct ctl_softc *softc = lun->ctl_softc;
565         union ctl_ha_msg *msg;
566         struct ctl_ha_msg_lun_pr_key pr_key;
567         int i, k;
568
569         if (softc->ha_link != CTL_HA_LINK_ONLINE)
570                 return;
571         mtx_lock(&lun->lun_lock);
572         i = sizeof(msg->lun);
573         if (lun->lun_devid)
574                 i += lun->lun_devid->len;
575         i += sizeof(pr_key) * lun->pr_key_count;
576 alloc:
577         mtx_unlock(&lun->lun_lock);
578         msg = malloc(i, M_CTL, M_WAITOK);
579         mtx_lock(&lun->lun_lock);
580         k = sizeof(msg->lun);
581         if (lun->lun_devid)
582                 k += lun->lun_devid->len;
583         k += sizeof(pr_key) * lun->pr_key_count;
584         if (i < k) {
585                 free(msg, M_CTL);
586                 i = k;
587                 goto alloc;
588         }
589         bzero(&msg->lun, sizeof(msg->lun));
590         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
591         msg->hdr.nexus.targ_lun = lun->lun;
592         msg->hdr.nexus.targ_mapped_lun = lun->lun;
593         msg->lun.flags = lun->flags;
594         msg->lun.pr_generation = lun->PRGeneration;
595         msg->lun.pr_res_idx = lun->pr_res_idx;
596         msg->lun.pr_res_type = lun->res_type;
597         msg->lun.pr_key_count = lun->pr_key_count;
598         i = 0;
599         if (lun->lun_devid) {
600                 msg->lun.lun_devid_len = lun->lun_devid->len;
601                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
602                     msg->lun.lun_devid_len);
603                 i += msg->lun.lun_devid_len;
604         }
605         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
606                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
607                         continue;
608                 pr_key.pr_iid = k;
609                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
610                 i += sizeof(pr_key);
611         }
612         mtx_unlock(&lun->lun_lock);
613         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
614             M_WAITOK);
615         free(msg, M_CTL);
616 }
617
618 void
619 ctl_isc_announce_port(struct ctl_port *port)
620 {
621         struct ctl_softc *softc = control_softc;
622         union ctl_ha_msg *msg;
623         int i;
624
625         if (port->targ_port < softc->port_min ||
626             port->targ_port >= softc->port_max ||
627             softc->ha_link != CTL_HA_LINK_ONLINE)
628                 return;
629         i = sizeof(msg->port) + strlen(port->port_name) + 1;
630         if (port->lun_map)
631                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
632         if (port->port_devid)
633                 i += port->port_devid->len;
634         if (port->target_devid)
635                 i += port->target_devid->len;
636         if (port->init_devid)
637                 i += port->init_devid->len;
638         msg = malloc(i, M_CTL, M_WAITOK);
639         bzero(&msg->port, sizeof(msg->port));
640         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
641         msg->hdr.nexus.targ_port = port->targ_port;
642         msg->port.port_type = port->port_type;
643         msg->port.physical_port = port->physical_port;
644         msg->port.virtual_port = port->virtual_port;
645         msg->port.status = port->status;
646         i = 0;
647         msg->port.name_len = sprintf(&msg->port.data[i],
648             "%d:%s", softc->ha_id, port->port_name) + 1;
649         i += msg->port.name_len;
650         if (port->lun_map) {
651                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
652                 memcpy(&msg->port.data[i], port->lun_map,
653                     msg->port.lun_map_len);
654                 i += msg->port.lun_map_len;
655         }
656         if (port->port_devid) {
657                 msg->port.port_devid_len = port->port_devid->len;
658                 memcpy(&msg->port.data[i], port->port_devid->data,
659                     msg->port.port_devid_len);
660                 i += msg->port.port_devid_len;
661         }
662         if (port->target_devid) {
663                 msg->port.target_devid_len = port->target_devid->len;
664                 memcpy(&msg->port.data[i], port->target_devid->data,
665                     msg->port.target_devid_len);
666                 i += msg->port.target_devid_len;
667         }
668         if (port->init_devid) {
669                 msg->port.init_devid_len = port->init_devid->len;
670                 memcpy(&msg->port.data[i], port->init_devid->data,
671                     msg->port.init_devid_len);
672                 i += msg->port.init_devid_len;
673         }
674         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
675             M_WAITOK);
676         free(msg, M_CTL);
677 }
678
679 void
680 ctl_isc_announce_iid(struct ctl_port *port, int iid)
681 {
682         struct ctl_softc *softc = control_softc;
683         union ctl_ha_msg *msg;
684         int i, l;
685
686         if (port->targ_port < softc->port_min ||
687             port->targ_port >= softc->port_max ||
688             softc->ha_link != CTL_HA_LINK_ONLINE)
689                 return;
690         mtx_lock(&softc->ctl_lock);
691         i = sizeof(msg->iid);
692         l = 0;
693         if (port->wwpn_iid[iid].name)
694                 l = strlen(port->wwpn_iid[iid].name) + 1;
695         i += l;
696         msg = malloc(i, M_CTL, M_NOWAIT);
697         if (msg == NULL) {
698                 mtx_unlock(&softc->ctl_lock);
699                 return;
700         }
701         bzero(&msg->iid, sizeof(msg->iid));
702         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
703         msg->hdr.nexus.targ_port = port->targ_port;
704         msg->hdr.nexus.initid = iid;
705         msg->iid.in_use = port->wwpn_iid[iid].in_use;
706         msg->iid.name_len = l;
707         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
708         if (port->wwpn_iid[iid].name)
709                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
710         mtx_unlock(&softc->ctl_lock);
711         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
712         free(msg, M_CTL);
713 }
714
715 static void
716 ctl_isc_ha_link_up(struct ctl_softc *softc)
717 {
718         struct ctl_port *port;
719         struct ctl_lun *lun;
720         int i;
721
722         STAILQ_FOREACH(port, &softc->port_list, links) {
723                 ctl_isc_announce_port(port);
724                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
725                         if (port->wwpn_iid[i].in_use)
726                                 ctl_isc_announce_iid(port, i);
727                 }
728         }
729         STAILQ_FOREACH(lun, &softc->lun_list, links)
730                 ctl_isc_announce_lun(lun);
731 }
732
733 static void
734 ctl_isc_ha_link_down(struct ctl_softc *softc)
735 {
736         struct ctl_port *port;
737         struct ctl_lun *lun;
738         union ctl_io *io;
739         int i;
740
741         mtx_lock(&softc->ctl_lock);
742         STAILQ_FOREACH(lun, &softc->lun_list, links) {
743                 mtx_lock(&lun->lun_lock);
744                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
745                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
746                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
747                 }
748                 mtx_unlock(&lun->lun_lock);
749
750                 mtx_unlock(&softc->ctl_lock);
751                 io = ctl_alloc_io(softc->othersc_pool);
752                 mtx_lock(&softc->ctl_lock);
753                 ctl_zero_io(io);
754                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
755                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
756                 ctl_enqueue_isc(io);
757         }
758
759         STAILQ_FOREACH(port, &softc->port_list, links) {
760                 if (port->targ_port >= softc->port_min &&
761                     port->targ_port < softc->port_max)
762                         continue;
763                 port->status &= ~CTL_PORT_STATUS_ONLINE;
764                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
765                         port->wwpn_iid[i].in_use = 0;
766                         free(port->wwpn_iid[i].name, M_CTL);
767                         port->wwpn_iid[i].name = NULL;
768                 }
769         }
770         mtx_unlock(&softc->ctl_lock);
771 }
772
773 static void
774 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
775 {
776         struct ctl_lun *lun;
777         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
778
779         mtx_lock(&softc->ctl_lock);
780         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
781             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
782                 mtx_lock(&lun->lun_lock);
783                 mtx_unlock(&softc->ctl_lock);
784                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
785                     msg->ua.ua_set)
786                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
787                 if (msg->ua.ua_all) {
788                         if (msg->ua.ua_set)
789                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
790                         else
791                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
792                 } else {
793                         if (msg->ua.ua_set)
794                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
795                         else
796                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
797                 }
798                 mtx_unlock(&lun->lun_lock);
799         } else
800                 mtx_unlock(&softc->ctl_lock);
801 }
802
803 static void
804 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
805 {
806         struct ctl_lun *lun;
807         struct ctl_ha_msg_lun_pr_key pr_key;
808         int i, k;
809         ctl_lun_flags oflags;
810         uint32_t targ_lun;
811
812         targ_lun = msg->hdr.nexus.targ_mapped_lun;
813         mtx_lock(&softc->ctl_lock);
814         if ((targ_lun >= CTL_MAX_LUNS) ||
815             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
816                 mtx_unlock(&softc->ctl_lock);
817                 return;
818         }
819         mtx_lock(&lun->lun_lock);
820         mtx_unlock(&softc->ctl_lock);
821         if (lun->flags & CTL_LUN_DISABLED) {
822                 mtx_unlock(&lun->lun_lock);
823                 return;
824         }
825         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
826         if (msg->lun.lun_devid_len != i || (i > 0 &&
827             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
828                 mtx_unlock(&lun->lun_lock);
829                 printf("%s: Received conflicting HA LUN %d\n",
830                     __func__, msg->hdr.nexus.targ_lun);
831                 return;
832         } else {
833                 /* Record whether peer is primary. */
834                 oflags = lun->flags;
835                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
836                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
837                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
838                 else
839                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
840                 if (oflags != lun->flags)
841                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
842
843                 /* If peer is primary and we are not -- use data */
844                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
845                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
846                         lun->PRGeneration = msg->lun.pr_generation;
847                         lun->pr_res_idx = msg->lun.pr_res_idx;
848                         lun->res_type = msg->lun.pr_res_type;
849                         lun->pr_key_count = msg->lun.pr_key_count;
850                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
851                                 ctl_clr_prkey(lun, k);
852                         for (k = 0; k < msg->lun.pr_key_count; k++) {
853                                 memcpy(&pr_key, &msg->lun.data[i],
854                                     sizeof(pr_key));
855                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
856                                 ctl_set_prkey(lun, pr_key.pr_iid,
857                                     pr_key.pr_key);
858                                 i += sizeof(pr_key);
859                         }
860                 }
861
862                 mtx_unlock(&lun->lun_lock);
863                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
864                     __func__, msg->hdr.nexus.targ_lun,
865                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
866                     "primary" : "secondary"));
867
868                 /* If we are primary but peer doesn't know -- notify */
869                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
870                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
871                         ctl_isc_announce_lun(lun);
872         }
873 }
874
875 static void
876 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
877 {
878         struct ctl_port *port;
879         struct ctl_lun *lun;
880         int i, new;
881
882         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
883         if (port == NULL) {
884                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
885                     msg->hdr.nexus.targ_port));
886                 new = 1;
887                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
888                 port->frontend = &ha_frontend;
889                 port->targ_port = msg->hdr.nexus.targ_port;
890         } else if (port->frontend == &ha_frontend) {
891                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
892                     msg->hdr.nexus.targ_port));
893                 new = 0;
894         } else {
895                 printf("%s: Received conflicting HA port %d\n",
896                     __func__, msg->hdr.nexus.targ_port);
897                 return;
898         }
899         port->port_type = msg->port.port_type;
900         port->physical_port = msg->port.physical_port;
901         port->virtual_port = msg->port.virtual_port;
902         port->status = msg->port.status;
903         i = 0;
904         free(port->port_name, M_CTL);
905         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
906             M_CTL);
907         i += msg->port.name_len;
908         if (msg->port.lun_map_len != 0) {
909                 if (port->lun_map == NULL)
910                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
911                             M_CTL, M_WAITOK);
912                 memcpy(port->lun_map, &msg->port.data[i],
913                     sizeof(uint32_t) * CTL_MAX_LUNS);
914                 i += msg->port.lun_map_len;
915         } else {
916                 free(port->lun_map, M_CTL);
917                 port->lun_map = NULL;
918         }
919         if (msg->port.port_devid_len != 0) {
920                 if (port->port_devid == NULL ||
921                     port->port_devid->len != msg->port.port_devid_len) {
922                         free(port->port_devid, M_CTL);
923                         port->port_devid = malloc(sizeof(struct ctl_devid) +
924                             msg->port.port_devid_len, M_CTL, M_WAITOK);
925                 }
926                 memcpy(port->port_devid->data, &msg->port.data[i],
927                     msg->port.port_devid_len);
928                 port->port_devid->len = msg->port.port_devid_len;
929                 i += msg->port.port_devid_len;
930         } else {
931                 free(port->port_devid, M_CTL);
932                 port->port_devid = NULL;
933         }
934         if (msg->port.target_devid_len != 0) {
935                 if (port->target_devid == NULL ||
936                     port->target_devid->len != msg->port.target_devid_len) {
937                         free(port->target_devid, M_CTL);
938                         port->target_devid = malloc(sizeof(struct ctl_devid) +
939                             msg->port.target_devid_len, M_CTL, M_WAITOK);
940                 }
941                 memcpy(port->target_devid->data, &msg->port.data[i],
942                     msg->port.target_devid_len);
943                 port->target_devid->len = msg->port.target_devid_len;
944                 i += msg->port.target_devid_len;
945         } else {
946                 free(port->target_devid, M_CTL);
947                 port->target_devid = NULL;
948         }
949         if (msg->port.init_devid_len != 0) {
950                 if (port->init_devid == NULL ||
951                     port->init_devid->len != msg->port.init_devid_len) {
952                         free(port->init_devid, M_CTL);
953                         port->init_devid = malloc(sizeof(struct ctl_devid) +
954                             msg->port.init_devid_len, M_CTL, M_WAITOK);
955                 }
956                 memcpy(port->init_devid->data, &msg->port.data[i],
957                     msg->port.init_devid_len);
958                 port->init_devid->len = msg->port.init_devid_len;
959                 i += msg->port.init_devid_len;
960         } else {
961                 free(port->init_devid, M_CTL);
962                 port->init_devid = NULL;
963         }
964         if (new) {
965                 if (ctl_port_register(port) != 0) {
966                         printf("%s: ctl_port_register() failed with error\n",
967                             __func__);
968                 }
969         }
970         mtx_lock(&softc->ctl_lock);
971         STAILQ_FOREACH(lun, &softc->lun_list, links) {
972                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
973                         continue;
974                 mtx_lock(&lun->lun_lock);
975                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
976                 mtx_unlock(&lun->lun_lock);
977         }
978         mtx_unlock(&softc->ctl_lock);
979 }
980
981 static void
982 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
983 {
984         struct ctl_port *port;
985         int iid;
986
987         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
988         if (port == NULL) {
989                 printf("%s: Received IID for unknown port %d\n",
990                     __func__, msg->hdr.nexus.targ_port);
991                 return;
992         }
993         iid = msg->hdr.nexus.initid;
994         port->wwpn_iid[iid].in_use = msg->iid.in_use;
995         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
996         free(port->wwpn_iid[iid].name, M_CTL);
997         if (msg->iid.name_len) {
998                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
999                     msg->iid.name_len, M_CTL);
1000         } else
1001                 port->wwpn_iid[iid].name = NULL;
1002 }
1003
1004 /*
1005  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1006  * subsystem come in here.
1007  */
1008 static void
1009 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1010 {
1011         struct ctl_softc *softc;
1012         union ctl_io *io;
1013         struct ctl_prio *presio;
1014         ctl_ha_status isc_status;
1015
1016         softc = control_softc;
1017         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1018         if (event == CTL_HA_EVT_MSG_RECV) {
1019                 union ctl_ha_msg *msg, msgbuf;
1020
1021                 if (param > sizeof(msgbuf))
1022                         msg = malloc(param, M_CTL, M_WAITOK);
1023                 else
1024                         msg = &msgbuf;
1025                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1026                     M_WAITOK);
1027                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1028                         printf("%s: Error receiving message: %d\n",
1029                             __func__, isc_status);
1030                         if (msg != &msgbuf)
1031                                 free(msg, M_CTL);
1032                         return;
1033                 }
1034
1035                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1036                 switch (msg->hdr.msg_type) {
1037                 case CTL_MSG_SERIALIZE:
1038                         io = ctl_alloc_io(softc->othersc_pool);
1039                         ctl_zero_io(io);
1040                         // populate ctsio from msg
1041                         io->io_hdr.io_type = CTL_IO_SCSI;
1042                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1043                         io->io_hdr.original_sc = msg->hdr.original_sc;
1044                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1045                                             CTL_FLAG_IO_ACTIVE;
1046                         /*
1047                          * If we're in serialization-only mode, we don't
1048                          * want to go through full done processing.  Thus
1049                          * the COPY flag.
1050                          *
1051                          * XXX KDM add another flag that is more specific.
1052                          */
1053                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1054                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1055                         io->io_hdr.nexus = msg->hdr.nexus;
1056 #if 0
1057                         printf("port %u, iid %u, lun %u\n",
1058                                io->io_hdr.nexus.targ_port,
1059                                io->io_hdr.nexus.initid,
1060                                io->io_hdr.nexus.targ_lun);
1061 #endif
1062                         io->scsiio.tag_num = msg->scsi.tag_num;
1063                         io->scsiio.tag_type = msg->scsi.tag_type;
1064 #ifdef CTL_TIME_IO
1065                         io->io_hdr.start_time = time_uptime;
1066                         getbintime(&io->io_hdr.start_bt);
1067 #endif /* CTL_TIME_IO */
1068                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1069                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1070                                CTL_MAX_CDBLEN);
1071                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1072                                 const struct ctl_cmd_entry *entry;
1073
1074                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1075                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1076                                 io->io_hdr.flags |=
1077                                         entry->flags & CTL_FLAG_DATA_MASK;
1078                         }
1079                         ctl_enqueue_isc(io);
1080                         break;
1081
1082                 /* Performed on the Originating SC, XFER mode only */
1083                 case CTL_MSG_DATAMOVE: {
1084                         struct ctl_sg_entry *sgl;
1085                         int i, j;
1086
1087                         io = msg->hdr.original_sc;
1088                         if (io == NULL) {
1089                                 printf("%s: original_sc == NULL!\n", __func__);
1090                                 /* XXX KDM do something here */
1091                                 break;
1092                         }
1093                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1094                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1095                         /*
1096                          * Keep track of this, we need to send it back over
1097                          * when the datamove is complete.
1098                          */
1099                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1100                         if (msg->hdr.status == CTL_SUCCESS)
1101                                 io->io_hdr.status = msg->hdr.status;
1102
1103                         if (msg->dt.sg_sequence == 0) {
1104                                 i = msg->dt.kern_sg_entries +
1105                                     msg->dt.kern_data_len /
1106                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1107                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1108                                     M_WAITOK | M_ZERO);
1109                                 io->io_hdr.remote_sglist = sgl;
1110                                 io->io_hdr.local_sglist =
1111                                     &sgl[msg->dt.kern_sg_entries];
1112
1113                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1114
1115                                 io->scsiio.kern_sg_entries =
1116                                         msg->dt.kern_sg_entries;
1117                                 io->scsiio.rem_sg_entries =
1118                                         msg->dt.kern_sg_entries;
1119                                 io->scsiio.kern_data_len =
1120                                         msg->dt.kern_data_len;
1121                                 io->scsiio.kern_total_len =
1122                                         msg->dt.kern_total_len;
1123                                 io->scsiio.kern_data_resid =
1124                                         msg->dt.kern_data_resid;
1125                                 io->scsiio.kern_rel_offset =
1126                                         msg->dt.kern_rel_offset;
1127                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1128                                 io->io_hdr.flags |= msg->dt.flags &
1129                                     CTL_FLAG_BUS_ADDR;
1130                         } else
1131                                 sgl = (struct ctl_sg_entry *)
1132                                         io->scsiio.kern_data_ptr;
1133
1134                         for (i = msg->dt.sent_sg_entries, j = 0;
1135                              i < (msg->dt.sent_sg_entries +
1136                              msg->dt.cur_sg_entries); i++, j++) {
1137                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1138                                 sgl[i].len = msg->dt.sg_list[j].len;
1139
1140 #if 0
1141                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1142                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1143 #endif
1144                         }
1145
1146                         /*
1147                          * If this is the last piece of the I/O, we've got
1148                          * the full S/G list.  Queue processing in the thread.
1149                          * Otherwise wait for the next piece.
1150                          */
1151                         if (msg->dt.sg_last != 0)
1152                                 ctl_enqueue_isc(io);
1153                         break;
1154                 }
1155                 /* Performed on the Serializing (primary) SC, XFER mode only */
1156                 case CTL_MSG_DATAMOVE_DONE: {
1157                         if (msg->hdr.serializing_sc == NULL) {
1158                                 printf("%s: serializing_sc == NULL!\n",
1159                                        __func__);
1160                                 /* XXX KDM now what? */
1161                                 break;
1162                         }
1163                         /*
1164                          * We grab the sense information here in case
1165                          * there was a failure, so we can return status
1166                          * back to the initiator.
1167                          */
1168                         io = msg->hdr.serializing_sc;
1169                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1170                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1171                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1172                         io->io_hdr.port_status = msg->scsi.fetd_status;
1173                         io->scsiio.residual = msg->scsi.residual;
1174                         if (msg->hdr.status != CTL_STATUS_NONE) {
1175                                 io->io_hdr.status = msg->hdr.status;
1176                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1177                                 io->scsiio.sense_len = msg->scsi.sense_len;
1178                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1179                                 memcpy(&io->scsiio.sense_data,
1180                                     &msg->scsi.sense_data,
1181                                     msg->scsi.sense_len);
1182                                 if (msg->hdr.status == CTL_SUCCESS)
1183                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1184                         }
1185                         ctl_enqueue_isc(io);
1186                         break;
1187                 }
1188
1189                 /* Preformed on Originating SC, SER_ONLY mode */
1190                 case CTL_MSG_R2R:
1191                         io = msg->hdr.original_sc;
1192                         if (io == NULL) {
1193                                 printf("%s: original_sc == NULL!\n",
1194                                     __func__);
1195                                 break;
1196                         }
1197                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1198                         io->io_hdr.msg_type = CTL_MSG_R2R;
1199                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1200                         ctl_enqueue_isc(io);
1201                         break;
1202
1203                 /*
1204                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1205                  * mode.
1206                  * Performed on the Originating (i.e. secondary) SC in XFER
1207                  * mode
1208                  */
1209                 case CTL_MSG_FINISH_IO:
1210                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1211                                 ctl_isc_handler_finish_xfer(softc, msg);
1212                         else
1213                                 ctl_isc_handler_finish_ser_only(softc, msg);
1214                         break;
1215
1216                 /* Preformed on Originating SC */
1217                 case CTL_MSG_BAD_JUJU:
1218                         io = msg->hdr.original_sc;
1219                         if (io == NULL) {
1220                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1221                                        __func__);
1222                                 break;
1223                         }
1224                         ctl_copy_sense_data(msg, io);
1225                         /*
1226                          * IO should have already been cleaned up on other
1227                          * SC so clear this flag so we won't send a message
1228                          * back to finish the IO there.
1229                          */
1230                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1231                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1232
1233                         /* io = msg->hdr.serializing_sc; */
1234                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1235                         ctl_enqueue_isc(io);
1236                         break;
1237
1238                 /* Handle resets sent from the other side */
1239                 case CTL_MSG_MANAGE_TASKS: {
1240                         struct ctl_taskio *taskio;
1241                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1242                             softc->othersc_pool);
1243                         ctl_zero_io((union ctl_io *)taskio);
1244                         taskio->io_hdr.io_type = CTL_IO_TASK;
1245                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1246                         taskio->io_hdr.nexus = msg->hdr.nexus;
1247                         taskio->task_action = msg->task.task_action;
1248                         taskio->tag_num = msg->task.tag_num;
1249                         taskio->tag_type = msg->task.tag_type;
1250 #ifdef CTL_TIME_IO
1251                         taskio->io_hdr.start_time = time_uptime;
1252                         getbintime(&taskio->io_hdr.start_bt);
1253 #endif /* CTL_TIME_IO */
1254                         ctl_run_task((union ctl_io *)taskio);
1255                         break;
1256                 }
1257                 /* Persistent Reserve action which needs attention */
1258                 case CTL_MSG_PERS_ACTION:
1259                         presio = (struct ctl_prio *)ctl_alloc_io(
1260                             softc->othersc_pool);
1261                         ctl_zero_io((union ctl_io *)presio);
1262                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1263                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1264                         presio->io_hdr.nexus = msg->hdr.nexus;
1265                         presio->pr_msg = msg->pr;
1266                         ctl_enqueue_isc((union ctl_io *)presio);
1267                         break;
1268                 case CTL_MSG_UA:
1269                         ctl_isc_ua(softc, msg, param);
1270                         break;
1271                 case CTL_MSG_PORT_SYNC:
1272                         ctl_isc_port_sync(softc, msg, param);
1273                         break;
1274                 case CTL_MSG_LUN_SYNC:
1275                         ctl_isc_lun_sync(softc, msg, param);
1276                         break;
1277                 case CTL_MSG_IID_SYNC:
1278                         ctl_isc_iid_sync(softc, msg, param);
1279                         break;
1280                 default:
1281                         printf("Received HA message of unknown type %d\n",
1282                             msg->hdr.msg_type);
1283                         break;
1284                 }
1285                 if (msg != &msgbuf)
1286                         free(msg, M_CTL);
1287         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1288                 printf("CTL: HA link status changed from %d to %d\n",
1289                     softc->ha_link, param);
1290                 if (param == softc->ha_link)
1291                         return;
1292                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1293                         softc->ha_link = param;
1294                         ctl_isc_ha_link_down(softc);
1295                 } else {
1296                         softc->ha_link = param;
1297                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1298                                 ctl_isc_ha_link_up(softc);
1299                 }
1300                 return;
1301         } else {
1302                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1303                 return;
1304         }
1305 }
1306
1307 static void
1308 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1309 {
1310
1311         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1312             src->scsi.sense_len);
1313         dest->scsiio.scsi_status = src->scsi.scsi_status;
1314         dest->scsiio.sense_len = src->scsi.sense_len;
1315         dest->io_hdr.status = src->hdr.status;
1316 }
1317
1318 static void
1319 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1320 {
1321
1322         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1323             src->scsiio.sense_len);
1324         dest->scsi.scsi_status = src->scsiio.scsi_status;
1325         dest->scsi.sense_len = src->scsiio.sense_len;
1326         dest->hdr.status = src->io_hdr.status;
1327 }
1328
1329 void
1330 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1331 {
1332         struct ctl_softc *softc = lun->ctl_softc;
1333         ctl_ua_type *pu;
1334
1335         if (initidx < softc->init_min || initidx >= softc->init_max)
1336                 return;
1337         mtx_assert(&lun->lun_lock, MA_OWNED);
1338         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1339         if (pu == NULL)
1340                 return;
1341         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1342 }
1343
1344 void
1345 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1346 {
1347         int i;
1348
1349         mtx_assert(&lun->lun_lock, MA_OWNED);
1350         if (lun->pending_ua[port] == NULL)
1351                 return;
1352         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1353                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1354                         continue;
1355                 lun->pending_ua[port][i] |= ua;
1356         }
1357 }
1358
1359 void
1360 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1361 {
1362         struct ctl_softc *softc = lun->ctl_softc;
1363         int i;
1364
1365         mtx_assert(&lun->lun_lock, MA_OWNED);
1366         for (i = softc->port_min; i < softc->port_max; i++)
1367                 ctl_est_ua_port(lun, i, except, ua);
1368 }
1369
1370 void
1371 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1372 {
1373         struct ctl_softc *softc = lun->ctl_softc;
1374         ctl_ua_type *pu;
1375
1376         if (initidx < softc->init_min || initidx >= softc->init_max)
1377                 return;
1378         mtx_assert(&lun->lun_lock, MA_OWNED);
1379         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1380         if (pu == NULL)
1381                 return;
1382         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1383 }
1384
1385 void
1386 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1387 {
1388         struct ctl_softc *softc = lun->ctl_softc;
1389         int i, j;
1390
1391         mtx_assert(&lun->lun_lock, MA_OWNED);
1392         for (i = softc->port_min; i < softc->port_max; i++) {
1393                 if (lun->pending_ua[i] == NULL)
1394                         continue;
1395                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1396                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1397                                 continue;
1398                         lun->pending_ua[i][j] &= ~ua;
1399                 }
1400         }
1401 }
1402
1403 void
1404 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1405     ctl_ua_type ua_type)
1406 {
1407         struct ctl_lun *lun;
1408
1409         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1410         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1411                 mtx_lock(&lun->lun_lock);
1412                 ctl_clr_ua(lun, initidx, ua_type);
1413                 mtx_unlock(&lun->lun_lock);
1414         }
1415 }
1416
1417 static int
1418 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1419 {
1420         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1421         struct ctl_lun *lun;
1422         struct ctl_lun_req ireq;
1423         int error, value;
1424
1425         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1426         error = sysctl_handle_int(oidp, &value, 0, req);
1427         if ((error != 0) || (req->newptr == NULL))
1428                 return (error);
1429
1430         mtx_lock(&softc->ctl_lock);
1431         if (value == 0)
1432                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1433         else
1434                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1435         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1436                 mtx_unlock(&softc->ctl_lock);
1437                 bzero(&ireq, sizeof(ireq));
1438                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1439                 ireq.reqdata.modify.lun_id = lun->lun;
1440                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1441                     curthread);
1442                 if (ireq.status != CTL_LUN_OK) {
1443                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1444                             __func__, ireq.status, ireq.error_str);
1445                 }
1446                 mtx_lock(&softc->ctl_lock);
1447         }
1448         mtx_unlock(&softc->ctl_lock);
1449         return (0);
1450 }
1451
1452 static int
1453 ctl_init(void)
1454 {
1455         struct ctl_softc *softc;
1456         void *other_pool;
1457         int i, error, retval;
1458
1459         retval = 0;
1460         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1461                                M_WAITOK | M_ZERO);
1462         softc = control_softc;
1463
1464         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1465                               "cam/ctl");
1466
1467         softc->dev->si_drv1 = softc;
1468
1469         sysctl_ctx_init(&softc->sysctl_ctx);
1470         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1471                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1472                 CTLFLAG_RD, 0, "CAM Target Layer");
1473
1474         if (softc->sysctl_tree == NULL) {
1475                 printf("%s: unable to allocate sysctl tree\n", __func__);
1476                 destroy_dev(softc->dev);
1477                 free(control_softc, M_DEVBUF);
1478                 control_softc = NULL;
1479                 return (ENOMEM);
1480         }
1481
1482         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1483         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1484             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1485         softc->open_count = 0;
1486
1487         /*
1488          * Default to actually sending a SYNCHRONIZE CACHE command down to
1489          * the drive.
1490          */
1491         softc->flags = CTL_FLAG_REAL_SYNC;
1492
1493         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1494             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1495             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1496
1497         /*
1498          * In Copan's HA scheme, the "master" and "slave" roles are
1499          * figured out through the slot the controller is in.  Although it
1500          * is an active/active system, someone has to be in charge.
1501          */
1502         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1503             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1504             "HA head ID (0 - no HA)");
1505         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1506                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1507                 softc->is_single = 1;
1508                 softc->port_cnt = CTL_MAX_PORTS;
1509                 softc->port_min = 0;
1510         } else {
1511                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1512                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1513         }
1514         softc->port_max = softc->port_min + softc->port_cnt;
1515         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1516         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1517
1518         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1519             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1520             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1521
1522         STAILQ_INIT(&softc->lun_list);
1523         STAILQ_INIT(&softc->pending_lun_queue);
1524         STAILQ_INIT(&softc->fe_list);
1525         STAILQ_INIT(&softc->port_list);
1526         STAILQ_INIT(&softc->be_list);
1527         ctl_tpc_init(softc);
1528
1529         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1530                             &other_pool) != 0)
1531         {
1532                 printf("ctl: can't allocate %d entry other SC pool, "
1533                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1534                 return (ENOMEM);
1535         }
1536         softc->othersc_pool = other_pool;
1537
1538         if (worker_threads <= 0)
1539                 worker_threads = max(1, mp_ncpus / 4);
1540         if (worker_threads > CTL_MAX_THREADS)
1541                 worker_threads = CTL_MAX_THREADS;
1542
1543         for (i = 0; i < worker_threads; i++) {
1544                 struct ctl_thread *thr = &softc->threads[i];
1545
1546                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1547                 thr->ctl_softc = softc;
1548                 STAILQ_INIT(&thr->incoming_queue);
1549                 STAILQ_INIT(&thr->rtr_queue);
1550                 STAILQ_INIT(&thr->done_queue);
1551                 STAILQ_INIT(&thr->isc_queue);
1552
1553                 error = kproc_kthread_add(ctl_work_thread, thr,
1554                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1555                 if (error != 0) {
1556                         printf("error creating CTL work thread!\n");
1557                         ctl_pool_free(other_pool);
1558                         return (error);
1559                 }
1560         }
1561         error = kproc_kthread_add(ctl_lun_thread, softc,
1562             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1563         if (error != 0) {
1564                 printf("error creating CTL lun thread!\n");
1565                 ctl_pool_free(other_pool);
1566                 return (error);
1567         }
1568         error = kproc_kthread_add(ctl_thresh_thread, softc,
1569             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1570         if (error != 0) {
1571                 printf("error creating CTL threshold thread!\n");
1572                 ctl_pool_free(other_pool);
1573                 return (error);
1574         }
1575
1576         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1577             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1578             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1579
1580         if (softc->is_single == 0) {
1581                 ctl_frontend_register(&ha_frontend);
1582                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1583                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1584                         softc->is_single = 1;
1585                 } else
1586                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1587                     != CTL_HA_STATUS_SUCCESS) {
1588                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1589                         softc->is_single = 1;
1590                 }
1591         }
1592         return (0);
1593 }
1594
1595 void
1596 ctl_shutdown(void)
1597 {
1598         struct ctl_softc *softc;
1599         struct ctl_lun *lun, *next_lun;
1600
1601         softc = (struct ctl_softc *)control_softc;
1602
1603         if (softc->is_single == 0) {
1604                 ctl_ha_msg_shutdown(softc);
1605                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1606                     != CTL_HA_STATUS_SUCCESS)
1607                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1608                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1609                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1610                 ctl_frontend_deregister(&ha_frontend);
1611         }
1612
1613         mtx_lock(&softc->ctl_lock);
1614
1615         /*
1616          * Free up each LUN.
1617          */
1618         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1619                 next_lun = STAILQ_NEXT(lun, links);
1620                 ctl_free_lun(lun);
1621         }
1622
1623         mtx_unlock(&softc->ctl_lock);
1624
1625 #if 0
1626         ctl_shutdown_thread(softc->work_thread);
1627         mtx_destroy(&softc->queue_lock);
1628 #endif
1629
1630         ctl_tpc_shutdown(softc);
1631         uma_zdestroy(softc->io_zone);
1632         mtx_destroy(&softc->ctl_lock);
1633
1634         destroy_dev(softc->dev);
1635
1636         sysctl_ctx_free(&softc->sysctl_ctx);
1637
1638         free(control_softc, M_DEVBUF);
1639         control_softc = NULL;
1640 }
1641
1642 static int
1643 ctl_module_event_handler(module_t mod, int what, void *arg)
1644 {
1645
1646         switch (what) {
1647         case MOD_LOAD:
1648                 return (ctl_init());
1649         case MOD_UNLOAD:
1650                 return (EBUSY);
1651         default:
1652                 return (EOPNOTSUPP);
1653         }
1654 }
1655
1656 /*
1657  * XXX KDM should we do some access checks here?  Bump a reference count to
1658  * prevent a CTL module from being unloaded while someone has it open?
1659  */
1660 static int
1661 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1662 {
1663         return (0);
1664 }
1665
1666 static int
1667 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1668 {
1669         return (0);
1670 }
1671
1672 /*
1673  * Remove an initiator by port number and initiator ID.
1674  * Returns 0 for success, -1 for failure.
1675  */
1676 int
1677 ctl_remove_initiator(struct ctl_port *port, int iid)
1678 {
1679         struct ctl_softc *softc = control_softc;
1680
1681         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1682
1683         if (iid > CTL_MAX_INIT_PER_PORT) {
1684                 printf("%s: initiator ID %u > maximun %u!\n",
1685                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1686                 return (-1);
1687         }
1688
1689         mtx_lock(&softc->ctl_lock);
1690         port->wwpn_iid[iid].in_use--;
1691         port->wwpn_iid[iid].last_use = time_uptime;
1692         mtx_unlock(&softc->ctl_lock);
1693         ctl_isc_announce_iid(port, iid);
1694
1695         return (0);
1696 }
1697
1698 /*
1699  * Add an initiator to the initiator map.
1700  * Returns iid for success, < 0 for failure.
1701  */
1702 int
1703 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1704 {
1705         struct ctl_softc *softc = control_softc;
1706         time_t best_time;
1707         int i, best;
1708
1709         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1710
1711         if (iid >= CTL_MAX_INIT_PER_PORT) {
1712                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1713                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1714                 free(name, M_CTL);
1715                 return (-1);
1716         }
1717
1718         mtx_lock(&softc->ctl_lock);
1719
1720         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1721                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1722                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1723                                 iid = i;
1724                                 break;
1725                         }
1726                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1727                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1728                                 iid = i;
1729                                 break;
1730                         }
1731                 }
1732         }
1733
1734         if (iid < 0) {
1735                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1736                         if (port->wwpn_iid[i].in_use == 0 &&
1737                             port->wwpn_iid[i].wwpn == 0 &&
1738                             port->wwpn_iid[i].name == NULL) {
1739                                 iid = i;
1740                                 break;
1741                         }
1742                 }
1743         }
1744
1745         if (iid < 0) {
1746                 best = -1;
1747                 best_time = INT32_MAX;
1748                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1749                         if (port->wwpn_iid[i].in_use == 0) {
1750                                 if (port->wwpn_iid[i].last_use < best_time) {
1751                                         best = i;
1752                                         best_time = port->wwpn_iid[i].last_use;
1753                                 }
1754                         }
1755                 }
1756                 iid = best;
1757         }
1758
1759         if (iid < 0) {
1760                 mtx_unlock(&softc->ctl_lock);
1761                 free(name, M_CTL);
1762                 return (-2);
1763         }
1764
1765         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1766                 /*
1767                  * This is not an error yet.
1768                  */
1769                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1770 #if 0
1771                         printf("%s: port %d iid %u WWPN %#jx arrived"
1772                             " again\n", __func__, port->targ_port,
1773                             iid, (uintmax_t)wwpn);
1774 #endif
1775                         goto take;
1776                 }
1777                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1778                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1779 #if 0
1780                         printf("%s: port %d iid %u name '%s' arrived"
1781                             " again\n", __func__, port->targ_port,
1782                             iid, name);
1783 #endif
1784                         goto take;
1785                 }
1786
1787                 /*
1788                  * This is an error, but what do we do about it?  The
1789                  * driver is telling us we have a new WWPN for this
1790                  * initiator ID, so we pretty much need to use it.
1791                  */
1792                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1793                     " but WWPN %#jx '%s' is still at that address\n",
1794                     __func__, port->targ_port, iid, wwpn, name,
1795                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1796                     port->wwpn_iid[iid].name);
1797
1798                 /*
1799                  * XXX KDM clear have_ca and ua_pending on each LUN for
1800                  * this initiator.
1801                  */
1802         }
1803 take:
1804         free(port->wwpn_iid[iid].name, M_CTL);
1805         port->wwpn_iid[iid].name = name;
1806         port->wwpn_iid[iid].wwpn = wwpn;
1807         port->wwpn_iid[iid].in_use++;
1808         mtx_unlock(&softc->ctl_lock);
1809         ctl_isc_announce_iid(port, iid);
1810
1811         return (iid);
1812 }
1813
1814 static int
1815 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1816 {
1817         int len;
1818
1819         switch (port->port_type) {
1820         case CTL_PORT_FC:
1821         {
1822                 struct scsi_transportid_fcp *id =
1823                     (struct scsi_transportid_fcp *)buf;
1824                 if (port->wwpn_iid[iid].wwpn == 0)
1825                         return (0);
1826                 memset(id, 0, sizeof(*id));
1827                 id->format_protocol = SCSI_PROTO_FC;
1828                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1829                 return (sizeof(*id));
1830         }
1831         case CTL_PORT_ISCSI:
1832         {
1833                 struct scsi_transportid_iscsi_port *id =
1834                     (struct scsi_transportid_iscsi_port *)buf;
1835                 if (port->wwpn_iid[iid].name == NULL)
1836                         return (0);
1837                 memset(id, 0, 256);
1838                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1839                     SCSI_PROTO_ISCSI;
1840                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1841                 len = roundup2(min(len, 252), 4);
1842                 scsi_ulto2b(len, id->additional_length);
1843                 return (sizeof(*id) + len);
1844         }
1845         case CTL_PORT_SAS:
1846         {
1847                 struct scsi_transportid_sas *id =
1848                     (struct scsi_transportid_sas *)buf;
1849                 if (port->wwpn_iid[iid].wwpn == 0)
1850                         return (0);
1851                 memset(id, 0, sizeof(*id));
1852                 id->format_protocol = SCSI_PROTO_SAS;
1853                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1854                 return (sizeof(*id));
1855         }
1856         default:
1857         {
1858                 struct scsi_transportid_spi *id =
1859                     (struct scsi_transportid_spi *)buf;
1860                 memset(id, 0, sizeof(*id));
1861                 id->format_protocol = SCSI_PROTO_SPI;
1862                 scsi_ulto2b(iid, id->scsi_addr);
1863                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1864                 return (sizeof(*id));
1865         }
1866         }
1867 }
1868
1869 /*
1870  * Serialize a command that went down the "wrong" side, and so was sent to
1871  * this controller for execution.  The logic is a little different than the
1872  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1873  * sent back to the other side, but in the success case, we execute the
1874  * command on this side (XFER mode) or tell the other side to execute it
1875  * (SER_ONLY mode).
1876  */
1877 static int
1878 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1879 {
1880         struct ctl_softc *softc;
1881         union ctl_ha_msg msg_info;
1882         struct ctl_lun *lun;
1883         const struct ctl_cmd_entry *entry;
1884         int retval = 0;
1885         uint32_t targ_lun;
1886
1887         softc = control_softc;
1888
1889         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1890         mtx_lock(&softc->ctl_lock);
1891         if ((targ_lun < CTL_MAX_LUNS) &&
1892             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
1893                 mtx_lock(&lun->lun_lock);
1894                 mtx_unlock(&softc->ctl_lock);
1895                 /*
1896                  * If the LUN is invalid, pretend that it doesn't exist.
1897                  * It will go away as soon as all pending I/O has been
1898                  * completed.
1899                  */
1900                 if (lun->flags & CTL_LUN_DISABLED) {
1901                         mtx_unlock(&lun->lun_lock);
1902                         lun = NULL;
1903                 }
1904         } else {
1905                 mtx_unlock(&softc->ctl_lock);
1906                 lun = NULL;
1907         }
1908         if (lun == NULL) {
1909                 /*
1910                  * The other node would not send this request to us unless
1911                  * received announce that we are primary node for this LUN.
1912                  * If this LUN does not exist now, it is probably result of
1913                  * a race, so respond to initiator in the most opaque way.
1914                  */
1915                 ctl_set_busy(ctsio);
1916                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1917                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1918                 msg_info.hdr.serializing_sc = NULL;
1919                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1920                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1921                     sizeof(msg_info.scsi), M_WAITOK);
1922                 return(1);
1923         }
1924
1925         entry = ctl_get_cmd_entry(ctsio, NULL);
1926         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
1927                 mtx_unlock(&lun->lun_lock);
1928                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1929                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1930                 msg_info.hdr.serializing_sc = NULL;
1931                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1932                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1933                     sizeof(msg_info.scsi), M_WAITOK);
1934                 return(1);
1935         }
1936
1937         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
1938         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
1939
1940         /*
1941          * Every I/O goes into the OOA queue for a
1942          * particular LUN, and stays there until completion.
1943          */
1944 #ifdef CTL_TIME_IO
1945         if (TAILQ_EMPTY(&lun->ooa_queue))
1946                 lun->idle_time += getsbinuptime() - lun->last_busy;
1947 #endif
1948         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1949
1950         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1951                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1952                  ooa_links))) {
1953         case CTL_ACTION_BLOCK:
1954                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1955                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1956                                   blocked_links);
1957                 mtx_unlock(&lun->lun_lock);
1958                 break;
1959         case CTL_ACTION_PASS:
1960         case CTL_ACTION_SKIP:
1961                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1962                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1963                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1964                         mtx_unlock(&lun->lun_lock);
1965                 } else {
1966                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
1967                         mtx_unlock(&lun->lun_lock);
1968
1969                         /* send msg back to other side */
1970                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1971                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1972                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1973                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1974                             sizeof(msg_info.hdr), M_WAITOK);
1975                 }
1976                 break;
1977         case CTL_ACTION_OVERLAP:
1978                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1979                 mtx_unlock(&lun->lun_lock);
1980                 retval = 1;
1981
1982                 ctl_set_overlapped_cmd(ctsio);
1983                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1984                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1985                 msg_info.hdr.serializing_sc = NULL;
1986                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1987                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1988                     sizeof(msg_info.scsi), M_WAITOK);
1989                 break;
1990         case CTL_ACTION_OVERLAP_TAG:
1991                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1992                 mtx_unlock(&lun->lun_lock);
1993                 retval = 1;
1994                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
1995                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1996                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1997                 msg_info.hdr.serializing_sc = NULL;
1998                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1999                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2000                     sizeof(msg_info.scsi), M_WAITOK);
2001                 break;
2002         case CTL_ACTION_ERROR:
2003         default:
2004                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2005                 mtx_unlock(&lun->lun_lock);
2006                 retval = 1;
2007
2008                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2009                                          /*retry_count*/ 0);
2010                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2011                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2012                 msg_info.hdr.serializing_sc = NULL;
2013                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2014                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2015                     sizeof(msg_info.scsi), M_WAITOK);
2016                 break;
2017         }
2018         return (retval);
2019 }
2020
2021 /*
2022  * Returns 0 for success, errno for failure.
2023  */
2024 static int
2025 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2026                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2027 {
2028         union ctl_io *io;
2029         int retval;
2030
2031         retval = 0;
2032
2033         mtx_lock(&lun->lun_lock);
2034         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2035              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2036              ooa_links)) {
2037                 struct ctl_ooa_entry *entry;
2038
2039                 /*
2040                  * If we've got more than we can fit, just count the
2041                  * remaining entries.
2042                  */
2043                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2044                         continue;
2045
2046                 entry = &kern_entries[*cur_fill_num];
2047
2048                 entry->tag_num = io->scsiio.tag_num;
2049                 entry->lun_num = lun->lun;
2050 #ifdef CTL_TIME_IO
2051                 entry->start_bt = io->io_hdr.start_bt;
2052 #endif
2053                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2054                 entry->cdb_len = io->scsiio.cdb_len;
2055                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2056                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2057
2058                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2059                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2060
2061                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2062                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2063
2064                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2065                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2066
2067                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2068                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2069         }
2070         mtx_unlock(&lun->lun_lock);
2071
2072         return (retval);
2073 }
2074
2075 static void *
2076 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2077                  size_t error_str_len)
2078 {
2079         void *kptr;
2080
2081         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2082
2083         if (copyin(user_addr, kptr, len) != 0) {
2084                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2085                          "from user address %p to kernel address %p", len,
2086                          user_addr, kptr);
2087                 free(kptr, M_CTL);
2088                 return (NULL);
2089         }
2090
2091         return (kptr);
2092 }
2093
2094 static void
2095 ctl_free_args(int num_args, struct ctl_be_arg *args)
2096 {
2097         int i;
2098
2099         if (args == NULL)
2100                 return;
2101
2102         for (i = 0; i < num_args; i++) {
2103                 free(args[i].kname, M_CTL);
2104                 free(args[i].kvalue, M_CTL);
2105         }
2106
2107         free(args, M_CTL);
2108 }
2109
2110 static struct ctl_be_arg *
2111 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2112                 char *error_str, size_t error_str_len)
2113 {
2114         struct ctl_be_arg *args;
2115         int i;
2116
2117         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2118                                 error_str, error_str_len);
2119
2120         if (args == NULL)
2121                 goto bailout;
2122
2123         for (i = 0; i < num_args; i++) {
2124                 args[i].kname = NULL;
2125                 args[i].kvalue = NULL;
2126         }
2127
2128         for (i = 0; i < num_args; i++) {
2129                 uint8_t *tmpptr;
2130
2131                 args[i].kname = ctl_copyin_alloc(args[i].name,
2132                         args[i].namelen, error_str, error_str_len);
2133                 if (args[i].kname == NULL)
2134                         goto bailout;
2135
2136                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2137                         snprintf(error_str, error_str_len, "Argument %d "
2138                                  "name is not NUL-terminated", i);
2139                         goto bailout;
2140                 }
2141
2142                 if (args[i].flags & CTL_BEARG_RD) {
2143                         tmpptr = ctl_copyin_alloc(args[i].value,
2144                                 args[i].vallen, error_str, error_str_len);
2145                         if (tmpptr == NULL)
2146                                 goto bailout;
2147                         if ((args[i].flags & CTL_BEARG_ASCII)
2148                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2149                                 snprintf(error_str, error_str_len, "Argument "
2150                                     "%d value is not NUL-terminated", i);
2151                                 goto bailout;
2152                         }
2153                         args[i].kvalue = tmpptr;
2154                 } else {
2155                         args[i].kvalue = malloc(args[i].vallen,
2156                             M_CTL, M_WAITOK | M_ZERO);
2157                 }
2158         }
2159
2160         return (args);
2161 bailout:
2162
2163         ctl_free_args(num_args, args);
2164
2165         return (NULL);
2166 }
2167
2168 static void
2169 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2170 {
2171         int i;
2172
2173         for (i = 0; i < num_args; i++) {
2174                 if (args[i].flags & CTL_BEARG_WR)
2175                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2176         }
2177 }
2178
2179 /*
2180  * Escape characters that are illegal or not recommended in XML.
2181  */
2182 int
2183 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2184 {
2185         char *end = str + size;
2186         int retval;
2187
2188         retval = 0;
2189
2190         for (; *str && str < end; str++) {
2191                 switch (*str) {
2192                 case '&':
2193                         retval = sbuf_printf(sb, "&amp;");
2194                         break;
2195                 case '>':
2196                         retval = sbuf_printf(sb, "&gt;");
2197                         break;
2198                 case '<':
2199                         retval = sbuf_printf(sb, "&lt;");
2200                         break;
2201                 default:
2202                         retval = sbuf_putc(sb, *str);
2203                         break;
2204                 }
2205
2206                 if (retval != 0)
2207                         break;
2208
2209         }
2210
2211         return (retval);
2212 }
2213
2214 static void
2215 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2216 {
2217         struct scsi_vpd_id_descriptor *desc;
2218         int i;
2219
2220         if (id == NULL || id->len < 4)
2221                 return;
2222         desc = (struct scsi_vpd_id_descriptor *)id->data;
2223         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2224         case SVPD_ID_TYPE_T10:
2225                 sbuf_printf(sb, "t10.");
2226                 break;
2227         case SVPD_ID_TYPE_EUI64:
2228                 sbuf_printf(sb, "eui.");
2229                 break;
2230         case SVPD_ID_TYPE_NAA:
2231                 sbuf_printf(sb, "naa.");
2232                 break;
2233         case SVPD_ID_TYPE_SCSI_NAME:
2234                 break;
2235         }
2236         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2237         case SVPD_ID_CODESET_BINARY:
2238                 for (i = 0; i < desc->length; i++)
2239                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2240                 break;
2241         case SVPD_ID_CODESET_ASCII:
2242                 sbuf_printf(sb, "%.*s", (int)desc->length,
2243                     (char *)desc->identifier);
2244                 break;
2245         case SVPD_ID_CODESET_UTF8:
2246                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2247                 break;
2248         }
2249 }
2250
2251 static int
2252 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2253           struct thread *td)
2254 {
2255         struct ctl_softc *softc;
2256         struct ctl_lun *lun;
2257         int retval;
2258
2259         softc = control_softc;
2260
2261         retval = 0;
2262
2263         switch (cmd) {
2264         case CTL_IO:
2265                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2266                 break;
2267         case CTL_ENABLE_PORT:
2268         case CTL_DISABLE_PORT:
2269         case CTL_SET_PORT_WWNS: {
2270                 struct ctl_port *port;
2271                 struct ctl_port_entry *entry;
2272
2273                 entry = (struct ctl_port_entry *)addr;
2274                 
2275                 mtx_lock(&softc->ctl_lock);
2276                 STAILQ_FOREACH(port, &softc->port_list, links) {
2277                         int action, done;
2278
2279                         if (port->targ_port < softc->port_min ||
2280                             port->targ_port >= softc->port_max)
2281                                 continue;
2282
2283                         action = 0;
2284                         done = 0;
2285                         if ((entry->port_type == CTL_PORT_NONE)
2286                          && (entry->targ_port == port->targ_port)) {
2287                                 /*
2288                                  * If the user only wants to enable or
2289                                  * disable or set WWNs on a specific port,
2290                                  * do the operation and we're done.
2291                                  */
2292                                 action = 1;
2293                                 done = 1;
2294                         } else if (entry->port_type & port->port_type) {
2295                                 /*
2296                                  * Compare the user's type mask with the
2297                                  * particular frontend type to see if we
2298                                  * have a match.
2299                                  */
2300                                 action = 1;
2301                                 done = 0;
2302
2303                                 /*
2304                                  * Make sure the user isn't trying to set
2305                                  * WWNs on multiple ports at the same time.
2306                                  */
2307                                 if (cmd == CTL_SET_PORT_WWNS) {
2308                                         printf("%s: Can't set WWNs on "
2309                                                "multiple ports\n", __func__);
2310                                         retval = EINVAL;
2311                                         break;
2312                                 }
2313                         }
2314                         if (action == 0)
2315                                 continue;
2316
2317                         /*
2318                          * XXX KDM we have to drop the lock here, because
2319                          * the online/offline operations can potentially
2320                          * block.  We need to reference count the frontends
2321                          * so they can't go away,
2322                          */
2323                         if (cmd == CTL_ENABLE_PORT) {
2324                                 mtx_unlock(&softc->ctl_lock);
2325                                 ctl_port_online(port);
2326                                 mtx_lock(&softc->ctl_lock);
2327                         } else if (cmd == CTL_DISABLE_PORT) {
2328                                 mtx_unlock(&softc->ctl_lock);
2329                                 ctl_port_offline(port);
2330                                 mtx_lock(&softc->ctl_lock);
2331                         } else if (cmd == CTL_SET_PORT_WWNS) {
2332                                 ctl_port_set_wwns(port,
2333                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2334                                     1 : 0, entry->wwnn,
2335                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2336                                     1 : 0, entry->wwpn);
2337                         }
2338                         if (done != 0)
2339                                 break;
2340                 }
2341                 mtx_unlock(&softc->ctl_lock);
2342                 break;
2343         }
2344         case CTL_GET_PORT_LIST: {
2345                 struct ctl_port *port;
2346                 struct ctl_port_list *list;
2347                 int i;
2348
2349                 list = (struct ctl_port_list *)addr;
2350
2351                 if (list->alloc_len != (list->alloc_num *
2352                     sizeof(struct ctl_port_entry))) {
2353                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2354                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2355                                "%zu\n", __func__, list->alloc_len,
2356                                list->alloc_num, sizeof(struct ctl_port_entry));
2357                         retval = EINVAL;
2358                         break;
2359                 }
2360                 list->fill_len = 0;
2361                 list->fill_num = 0;
2362                 list->dropped_num = 0;
2363                 i = 0;
2364                 mtx_lock(&softc->ctl_lock);
2365                 STAILQ_FOREACH(port, &softc->port_list, links) {
2366                         struct ctl_port_entry entry, *list_entry;
2367
2368                         if (list->fill_num >= list->alloc_num) {
2369                                 list->dropped_num++;
2370                                 continue;
2371                         }
2372
2373                         entry.port_type = port->port_type;
2374                         strlcpy(entry.port_name, port->port_name,
2375                                 sizeof(entry.port_name));
2376                         entry.targ_port = port->targ_port;
2377                         entry.physical_port = port->physical_port;
2378                         entry.virtual_port = port->virtual_port;
2379                         entry.wwnn = port->wwnn;
2380                         entry.wwpn = port->wwpn;
2381                         if (port->status & CTL_PORT_STATUS_ONLINE)
2382                                 entry.online = 1;
2383                         else
2384                                 entry.online = 0;
2385
2386                         list_entry = &list->entries[i];
2387
2388                         retval = copyout(&entry, list_entry, sizeof(entry));
2389                         if (retval != 0) {
2390                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2391                                        "returned %d\n", __func__, retval);
2392                                 break;
2393                         }
2394                         i++;
2395                         list->fill_num++;
2396                         list->fill_len += sizeof(entry);
2397                 }
2398                 mtx_unlock(&softc->ctl_lock);
2399
2400                 /*
2401                  * If this is non-zero, we had a copyout fault, so there's
2402                  * probably no point in attempting to set the status inside
2403                  * the structure.
2404                  */
2405                 if (retval != 0)
2406                         break;
2407
2408                 if (list->dropped_num > 0)
2409                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2410                 else
2411                         list->status = CTL_PORT_LIST_OK;
2412                 break;
2413         }
2414         case CTL_DUMP_OOA: {
2415                 union ctl_io *io;
2416                 char printbuf[128];
2417                 struct sbuf sb;
2418
2419                 mtx_lock(&softc->ctl_lock);
2420                 printf("Dumping OOA queues:\n");
2421                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2422                         mtx_lock(&lun->lun_lock);
2423                         for (io = (union ctl_io *)TAILQ_FIRST(
2424                              &lun->ooa_queue); io != NULL;
2425                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2426                              ooa_links)) {
2427                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2428                                          SBUF_FIXEDLEN);
2429                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2430                                             (intmax_t)lun->lun,
2431                                             io->scsiio.tag_num,
2432                                             (io->io_hdr.flags &
2433                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2434                                             (io->io_hdr.flags &
2435                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2436                                             (io->io_hdr.flags &
2437                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2438                                             (io->io_hdr.flags &
2439                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2440                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2441                                 sbuf_finish(&sb);
2442                                 printf("%s\n", sbuf_data(&sb));
2443                         }
2444                         mtx_unlock(&lun->lun_lock);
2445                 }
2446                 printf("OOA queues dump done\n");
2447                 mtx_unlock(&softc->ctl_lock);
2448                 break;
2449         }
2450         case CTL_GET_OOA: {
2451                 struct ctl_ooa *ooa_hdr;
2452                 struct ctl_ooa_entry *entries;
2453                 uint32_t cur_fill_num;
2454
2455                 ooa_hdr = (struct ctl_ooa *)addr;
2456
2457                 if ((ooa_hdr->alloc_len == 0)
2458                  || (ooa_hdr->alloc_num == 0)) {
2459                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2460                                "must be non-zero\n", __func__,
2461                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2462                         retval = EINVAL;
2463                         break;
2464                 }
2465
2466                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2467                     sizeof(struct ctl_ooa_entry))) {
2468                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2469                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2470                                __func__, ooa_hdr->alloc_len,
2471                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2472                         retval = EINVAL;
2473                         break;
2474                 }
2475
2476                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2477                 if (entries == NULL) {
2478                         printf("%s: could not allocate %d bytes for OOA "
2479                                "dump\n", __func__, ooa_hdr->alloc_len);
2480                         retval = ENOMEM;
2481                         break;
2482                 }
2483
2484                 mtx_lock(&softc->ctl_lock);
2485                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2486                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2487                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2488                         mtx_unlock(&softc->ctl_lock);
2489                         free(entries, M_CTL);
2490                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2491                                __func__, (uintmax_t)ooa_hdr->lun_num);
2492                         retval = EINVAL;
2493                         break;
2494                 }
2495
2496                 cur_fill_num = 0;
2497
2498                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2499                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2500                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2501                                         ooa_hdr, entries);
2502                                 if (retval != 0)
2503                                         break;
2504                         }
2505                         if (retval != 0) {
2506                                 mtx_unlock(&softc->ctl_lock);
2507                                 free(entries, M_CTL);
2508                                 break;
2509                         }
2510                 } else {
2511                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2512
2513                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2514                                                     entries);
2515                 }
2516                 mtx_unlock(&softc->ctl_lock);
2517
2518                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2519                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2520                         sizeof(struct ctl_ooa_entry);
2521                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2522                 if (retval != 0) {
2523                         printf("%s: error copying out %d bytes for OOA dump\n", 
2524                                __func__, ooa_hdr->fill_len);
2525                 }
2526
2527                 getbintime(&ooa_hdr->cur_bt);
2528
2529                 if (cur_fill_num > ooa_hdr->alloc_num) {
2530                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2531                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2532                 } else {
2533                         ooa_hdr->dropped_num = 0;
2534                         ooa_hdr->status = CTL_OOA_OK;
2535                 }
2536
2537                 free(entries, M_CTL);
2538                 break;
2539         }
2540         case CTL_CHECK_OOA: {
2541                 union ctl_io *io;
2542                 struct ctl_ooa_info *ooa_info;
2543
2544
2545                 ooa_info = (struct ctl_ooa_info *)addr;
2546
2547                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2548                         ooa_info->status = CTL_OOA_INVALID_LUN;
2549                         break;
2550                 }
2551                 mtx_lock(&softc->ctl_lock);
2552                 lun = softc->ctl_luns[ooa_info->lun_id];
2553                 if (lun == NULL) {
2554                         mtx_unlock(&softc->ctl_lock);
2555                         ooa_info->status = CTL_OOA_INVALID_LUN;
2556                         break;
2557                 }
2558                 mtx_lock(&lun->lun_lock);
2559                 mtx_unlock(&softc->ctl_lock);
2560                 ooa_info->num_entries = 0;
2561                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2562                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2563                      &io->io_hdr, ooa_links)) {
2564                         ooa_info->num_entries++;
2565                 }
2566                 mtx_unlock(&lun->lun_lock);
2567
2568                 ooa_info->status = CTL_OOA_SUCCESS;
2569
2570                 break;
2571         }
2572         case CTL_DELAY_IO: {
2573                 struct ctl_io_delay_info *delay_info;
2574
2575                 delay_info = (struct ctl_io_delay_info *)addr;
2576
2577 #ifdef CTL_IO_DELAY
2578                 mtx_lock(&softc->ctl_lock);
2579
2580                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2581                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2582                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2583                 } else {
2584                         lun = softc->ctl_luns[delay_info->lun_id];
2585                         mtx_lock(&lun->lun_lock);
2586
2587                         delay_info->status = CTL_DELAY_STATUS_OK;
2588
2589                         switch (delay_info->delay_type) {
2590                         case CTL_DELAY_TYPE_CONT:
2591                                 break;
2592                         case CTL_DELAY_TYPE_ONESHOT:
2593                                 break;
2594                         default:
2595                                 delay_info->status =
2596                                         CTL_DELAY_STATUS_INVALID_TYPE;
2597                                 break;
2598                         }
2599
2600                         switch (delay_info->delay_loc) {
2601                         case CTL_DELAY_LOC_DATAMOVE:
2602                                 lun->delay_info.datamove_type =
2603                                         delay_info->delay_type;
2604                                 lun->delay_info.datamove_delay =
2605                                         delay_info->delay_secs;
2606                                 break;
2607                         case CTL_DELAY_LOC_DONE:
2608                                 lun->delay_info.done_type =
2609                                         delay_info->delay_type;
2610                                 lun->delay_info.done_delay =
2611                                         delay_info->delay_secs;
2612                                 break;
2613                         default:
2614                                 delay_info->status =
2615                                         CTL_DELAY_STATUS_INVALID_LOC;
2616                                 break;
2617                         }
2618                         mtx_unlock(&lun->lun_lock);
2619                 }
2620
2621                 mtx_unlock(&softc->ctl_lock);
2622 #else
2623                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2624 #endif /* CTL_IO_DELAY */
2625                 break;
2626         }
2627         case CTL_REALSYNC_SET: {
2628                 int *syncstate;
2629
2630                 syncstate = (int *)addr;
2631
2632                 mtx_lock(&softc->ctl_lock);
2633                 switch (*syncstate) {
2634                 case 0:
2635                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2636                         break;
2637                 case 1:
2638                         softc->flags |= CTL_FLAG_REAL_SYNC;
2639                         break;
2640                 default:
2641                         retval = EINVAL;
2642                         break;
2643                 }
2644                 mtx_unlock(&softc->ctl_lock);
2645                 break;
2646         }
2647         case CTL_REALSYNC_GET: {
2648                 int *syncstate;
2649
2650                 syncstate = (int*)addr;
2651
2652                 mtx_lock(&softc->ctl_lock);
2653                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2654                         *syncstate = 1;
2655                 else
2656                         *syncstate = 0;
2657                 mtx_unlock(&softc->ctl_lock);
2658
2659                 break;
2660         }
2661         case CTL_SETSYNC:
2662         case CTL_GETSYNC: {
2663                 struct ctl_sync_info *sync_info;
2664
2665                 sync_info = (struct ctl_sync_info *)addr;
2666
2667                 mtx_lock(&softc->ctl_lock);
2668                 lun = softc->ctl_luns[sync_info->lun_id];
2669                 if (lun == NULL) {
2670                         mtx_unlock(&softc->ctl_lock);
2671                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2672                         break;
2673                 }
2674                 /*
2675                  * Get or set the sync interval.  We're not bounds checking
2676                  * in the set case, hopefully the user won't do something
2677                  * silly.
2678                  */
2679                 mtx_lock(&lun->lun_lock);
2680                 mtx_unlock(&softc->ctl_lock);
2681                 if (cmd == CTL_GETSYNC)
2682                         sync_info->sync_interval = lun->sync_interval;
2683                 else
2684                         lun->sync_interval = sync_info->sync_interval;
2685                 mtx_unlock(&lun->lun_lock);
2686
2687                 sync_info->status = CTL_GS_SYNC_OK;
2688
2689                 break;
2690         }
2691         case CTL_GETSTATS: {
2692                 struct ctl_stats *stats;
2693                 int i;
2694
2695                 stats = (struct ctl_stats *)addr;
2696
2697                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2698                      stats->alloc_len) {
2699                         stats->status = CTL_SS_NEED_MORE_SPACE;
2700                         stats->num_luns = softc->num_luns;
2701                         break;
2702                 }
2703                 /*
2704                  * XXX KDM no locking here.  If the LUN list changes,
2705                  * things can blow up.
2706                  */
2707                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2708                      i++, lun = STAILQ_NEXT(lun, links)) {
2709                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2710                                          sizeof(lun->stats));
2711                         if (retval != 0)
2712                                 break;
2713                 }
2714                 stats->num_luns = softc->num_luns;
2715                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2716                                  softc->num_luns;
2717                 stats->status = CTL_SS_OK;
2718 #ifdef CTL_TIME_IO
2719                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2720 #else
2721                 stats->flags = CTL_STATS_FLAG_NONE;
2722 #endif
2723                 getnanouptime(&stats->timestamp);
2724                 break;
2725         }
2726         case CTL_ERROR_INJECT: {
2727                 struct ctl_error_desc *err_desc, *new_err_desc;
2728
2729                 err_desc = (struct ctl_error_desc *)addr;
2730
2731                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2732                                       M_WAITOK | M_ZERO);
2733                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2734
2735                 mtx_lock(&softc->ctl_lock);
2736                 lun = softc->ctl_luns[err_desc->lun_id];
2737                 if (lun == NULL) {
2738                         mtx_unlock(&softc->ctl_lock);
2739                         free(new_err_desc, M_CTL);
2740                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2741                                __func__, (uintmax_t)err_desc->lun_id);
2742                         retval = EINVAL;
2743                         break;
2744                 }
2745                 mtx_lock(&lun->lun_lock);
2746                 mtx_unlock(&softc->ctl_lock);
2747
2748                 /*
2749                  * We could do some checking here to verify the validity
2750                  * of the request, but given the complexity of error
2751                  * injection requests, the checking logic would be fairly
2752                  * complex.
2753                  *
2754                  * For now, if the request is invalid, it just won't get
2755                  * executed and might get deleted.
2756                  */
2757                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2758
2759                 /*
2760                  * XXX KDM check to make sure the serial number is unique,
2761                  * in case we somehow manage to wrap.  That shouldn't
2762                  * happen for a very long time, but it's the right thing to
2763                  * do.
2764                  */
2765                 new_err_desc->serial = lun->error_serial;
2766                 err_desc->serial = lun->error_serial;
2767                 lun->error_serial++;
2768
2769                 mtx_unlock(&lun->lun_lock);
2770                 break;
2771         }
2772         case CTL_ERROR_INJECT_DELETE: {
2773                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2774                 int delete_done;
2775
2776                 delete_desc = (struct ctl_error_desc *)addr;
2777                 delete_done = 0;
2778
2779                 mtx_lock(&softc->ctl_lock);
2780                 lun = softc->ctl_luns[delete_desc->lun_id];
2781                 if (lun == NULL) {
2782                         mtx_unlock(&softc->ctl_lock);
2783                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2784                                __func__, (uintmax_t)delete_desc->lun_id);
2785                         retval = EINVAL;
2786                         break;
2787                 }
2788                 mtx_lock(&lun->lun_lock);
2789                 mtx_unlock(&softc->ctl_lock);
2790                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2791                         if (desc->serial != delete_desc->serial)
2792                                 continue;
2793
2794                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2795                                       links);
2796                         free(desc, M_CTL);
2797                         delete_done = 1;
2798                 }
2799                 mtx_unlock(&lun->lun_lock);
2800                 if (delete_done == 0) {
2801                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2802                                "error serial %ju on LUN %u\n", __func__, 
2803                                delete_desc->serial, delete_desc->lun_id);
2804                         retval = EINVAL;
2805                         break;
2806                 }
2807                 break;
2808         }
2809         case CTL_DUMP_STRUCTS: {
2810                 int i, j, k;
2811                 struct ctl_port *port;
2812                 struct ctl_frontend *fe;
2813
2814                 mtx_lock(&softc->ctl_lock);
2815                 printf("CTL Persistent Reservation information start:\n");
2816                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2817                         lun = softc->ctl_luns[i];
2818
2819                         if ((lun == NULL)
2820                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2821                                 continue;
2822
2823                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2824                                 if (lun->pr_keys[j] == NULL)
2825                                         continue;
2826                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2827                                         if (lun->pr_keys[j][k] == 0)
2828                                                 continue;
2829                                         printf("  LUN %d port %d iid %d key "
2830                                                "%#jx\n", i, j, k,
2831                                                (uintmax_t)lun->pr_keys[j][k]);
2832                                 }
2833                         }
2834                 }
2835                 printf("CTL Persistent Reservation information end\n");
2836                 printf("CTL Ports:\n");
2837                 STAILQ_FOREACH(port, &softc->port_list, links) {
2838                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2839                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2840                                port->frontend->name, port->port_type,
2841                                port->physical_port, port->virtual_port,
2842                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2843                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2844                                 if (port->wwpn_iid[j].in_use == 0 &&
2845                                     port->wwpn_iid[j].wwpn == 0 &&
2846                                     port->wwpn_iid[j].name == NULL)
2847                                         continue;
2848
2849                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2850                                     j, port->wwpn_iid[j].in_use,
2851                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2852                                     port->wwpn_iid[j].name);
2853                         }
2854                 }
2855                 printf("CTL Port information end\n");
2856                 mtx_unlock(&softc->ctl_lock);
2857                 /*
2858                  * XXX KDM calling this without a lock.  We'd likely want
2859                  * to drop the lock before calling the frontend's dump
2860                  * routine anyway.
2861                  */
2862                 printf("CTL Frontends:\n");
2863                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2864                         printf("  Frontend '%s'\n", fe->name);
2865                         if (fe->fe_dump != NULL)
2866                                 fe->fe_dump();
2867                 }
2868                 printf("CTL Frontend information end\n");
2869                 break;
2870         }
2871         case CTL_LUN_REQ: {
2872                 struct ctl_lun_req *lun_req;
2873                 struct ctl_backend_driver *backend;
2874
2875                 lun_req = (struct ctl_lun_req *)addr;
2876
2877                 backend = ctl_backend_find(lun_req->backend);
2878                 if (backend == NULL) {
2879                         lun_req->status = CTL_LUN_ERROR;
2880                         snprintf(lun_req->error_str,
2881                                  sizeof(lun_req->error_str),
2882                                  "Backend \"%s\" not found.",
2883                                  lun_req->backend);
2884                         break;
2885                 }
2886                 if (lun_req->num_be_args > 0) {
2887                         lun_req->kern_be_args = ctl_copyin_args(
2888                                 lun_req->num_be_args,
2889                                 lun_req->be_args,
2890                                 lun_req->error_str,
2891                                 sizeof(lun_req->error_str));
2892                         if (lun_req->kern_be_args == NULL) {
2893                                 lun_req->status = CTL_LUN_ERROR;
2894                                 break;
2895                         }
2896                 }
2897
2898                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2899
2900                 if (lun_req->num_be_args > 0) {
2901                         ctl_copyout_args(lun_req->num_be_args,
2902                                       lun_req->kern_be_args);
2903                         ctl_free_args(lun_req->num_be_args,
2904                                       lun_req->kern_be_args);
2905                 }
2906                 break;
2907         }
2908         case CTL_LUN_LIST: {
2909                 struct sbuf *sb;
2910                 struct ctl_lun_list *list;
2911                 struct ctl_option *opt;
2912
2913                 list = (struct ctl_lun_list *)addr;
2914
2915                 /*
2916                  * Allocate a fixed length sbuf here, based on the length
2917                  * of the user's buffer.  We could allocate an auto-extending
2918                  * buffer, and then tell the user how much larger our
2919                  * amount of data is than his buffer, but that presents
2920                  * some problems:
2921                  *
2922                  * 1.  The sbuf(9) routines use a blocking malloc, and so
2923                  *     we can't hold a lock while calling them with an
2924                  *     auto-extending buffer.
2925                  *
2926                  * 2.  There is not currently a LUN reference counting
2927                  *     mechanism, outside of outstanding transactions on
2928                  *     the LUN's OOA queue.  So a LUN could go away on us
2929                  *     while we're getting the LUN number, backend-specific
2930                  *     information, etc.  Thus, given the way things
2931                  *     currently work, we need to hold the CTL lock while
2932                  *     grabbing LUN information.
2933                  *
2934                  * So, from the user's standpoint, the best thing to do is
2935                  * allocate what he thinks is a reasonable buffer length,
2936                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2937                  * double the buffer length and try again.  (And repeat
2938                  * that until he succeeds.)
2939                  */
2940                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2941                 if (sb == NULL) {
2942                         list->status = CTL_LUN_LIST_ERROR;
2943                         snprintf(list->error_str, sizeof(list->error_str),
2944                                  "Unable to allocate %d bytes for LUN list",
2945                                  list->alloc_len);
2946                         break;
2947                 }
2948
2949                 sbuf_printf(sb, "<ctllunlist>\n");
2950
2951                 mtx_lock(&softc->ctl_lock);
2952                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2953                         mtx_lock(&lun->lun_lock);
2954                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2955                                              (uintmax_t)lun->lun);
2956
2957                         /*
2958                          * Bail out as soon as we see that we've overfilled
2959                          * the buffer.
2960                          */
2961                         if (retval != 0)
2962                                 break;
2963
2964                         retval = sbuf_printf(sb, "\t<backend_type>%s"
2965                                              "</backend_type>\n",
2966                                              (lun->backend == NULL) ?  "none" :
2967                                              lun->backend->name);
2968
2969                         if (retval != 0)
2970                                 break;
2971
2972                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2973                                              lun->be_lun->lun_type);
2974
2975                         if (retval != 0)
2976                                 break;
2977
2978                         if (lun->backend == NULL) {
2979                                 retval = sbuf_printf(sb, "</lun>\n");
2980                                 if (retval != 0)
2981                                         break;
2982                                 continue;
2983                         }
2984
2985                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2986                                              (lun->be_lun->maxlba > 0) ?
2987                                              lun->be_lun->maxlba + 1 : 0);
2988
2989                         if (retval != 0)
2990                                 break;
2991
2992                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2993                                              lun->be_lun->blocksize);
2994
2995                         if (retval != 0)
2996                                 break;
2997
2998                         retval = sbuf_printf(sb, "\t<serial_number>");
2999
3000                         if (retval != 0)
3001                                 break;
3002
3003                         retval = ctl_sbuf_printf_esc(sb,
3004                             lun->be_lun->serial_num,
3005                             sizeof(lun->be_lun->serial_num));
3006
3007                         if (retval != 0)
3008                                 break;
3009
3010                         retval = sbuf_printf(sb, "</serial_number>\n");
3011                 
3012                         if (retval != 0)
3013                                 break;
3014
3015                         retval = sbuf_printf(sb, "\t<device_id>");
3016
3017                         if (retval != 0)
3018                                 break;
3019
3020                         retval = ctl_sbuf_printf_esc(sb,
3021                             lun->be_lun->device_id,
3022                             sizeof(lun->be_lun->device_id));
3023
3024                         if (retval != 0)
3025                                 break;
3026
3027                         retval = sbuf_printf(sb, "</device_id>\n");
3028
3029                         if (retval != 0)
3030                                 break;
3031
3032                         if (lun->backend->lun_info != NULL) {
3033                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3034                                 if (retval != 0)
3035                                         break;
3036                         }
3037                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3038                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3039                                     opt->name, opt->value, opt->name);
3040                                 if (retval != 0)
3041                                         break;
3042                         }
3043
3044                         retval = sbuf_printf(sb, "</lun>\n");
3045
3046                         if (retval != 0)
3047                                 break;
3048                         mtx_unlock(&lun->lun_lock);
3049                 }
3050                 if (lun != NULL)
3051                         mtx_unlock(&lun->lun_lock);
3052                 mtx_unlock(&softc->ctl_lock);
3053
3054                 if ((retval != 0)
3055                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3056                         retval = 0;
3057                         sbuf_delete(sb);
3058                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3059                         snprintf(list->error_str, sizeof(list->error_str),
3060                                  "Out of space, %d bytes is too small",
3061                                  list->alloc_len);
3062                         break;
3063                 }
3064
3065                 sbuf_finish(sb);
3066
3067                 retval = copyout(sbuf_data(sb), list->lun_xml,
3068                                  sbuf_len(sb) + 1);
3069
3070                 list->fill_len = sbuf_len(sb) + 1;
3071                 list->status = CTL_LUN_LIST_OK;
3072                 sbuf_delete(sb);
3073                 break;
3074         }
3075         case CTL_ISCSI: {
3076                 struct ctl_iscsi *ci;
3077                 struct ctl_frontend *fe;
3078
3079                 ci = (struct ctl_iscsi *)addr;
3080
3081                 fe = ctl_frontend_find("iscsi");
3082                 if (fe == NULL) {
3083                         ci->status = CTL_ISCSI_ERROR;
3084                         snprintf(ci->error_str, sizeof(ci->error_str),
3085                             "Frontend \"iscsi\" not found.");
3086                         break;
3087                 }
3088
3089                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3090                 break;
3091         }
3092         case CTL_PORT_REQ: {
3093                 struct ctl_req *req;
3094                 struct ctl_frontend *fe;
3095
3096                 req = (struct ctl_req *)addr;
3097
3098                 fe = ctl_frontend_find(req->driver);
3099                 if (fe == NULL) {
3100                         req->status = CTL_LUN_ERROR;
3101                         snprintf(req->error_str, sizeof(req->error_str),
3102                             "Frontend \"%s\" not found.", req->driver);
3103                         break;
3104                 }
3105                 if (req->num_args > 0) {
3106                         req->kern_args = ctl_copyin_args(req->num_args,
3107                             req->args, req->error_str, sizeof(req->error_str));
3108                         if (req->kern_args == NULL) {
3109                                 req->status = CTL_LUN_ERROR;
3110                                 break;
3111                         }
3112                 }
3113
3114                 if (fe->ioctl)
3115                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3116                 else
3117                         retval = ENODEV;
3118
3119                 if (req->num_args > 0) {
3120                         ctl_copyout_args(req->num_args, req->kern_args);
3121                         ctl_free_args(req->num_args, req->kern_args);
3122                 }
3123                 break;
3124         }
3125         case CTL_PORT_LIST: {
3126                 struct sbuf *sb;
3127                 struct ctl_port *port;
3128                 struct ctl_lun_list *list;
3129                 struct ctl_option *opt;
3130                 int j;
3131                 uint32_t plun;
3132
3133                 list = (struct ctl_lun_list *)addr;
3134
3135                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3136                 if (sb == NULL) {
3137                         list->status = CTL_LUN_LIST_ERROR;
3138                         snprintf(list->error_str, sizeof(list->error_str),
3139                                  "Unable to allocate %d bytes for LUN list",
3140                                  list->alloc_len);
3141                         break;
3142                 }
3143
3144                 sbuf_printf(sb, "<ctlportlist>\n");
3145
3146                 mtx_lock(&softc->ctl_lock);
3147                 STAILQ_FOREACH(port, &softc->port_list, links) {
3148                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3149                                              (uintmax_t)port->targ_port);
3150
3151                         /*
3152                          * Bail out as soon as we see that we've overfilled
3153                          * the buffer.
3154                          */
3155                         if (retval != 0)
3156                                 break;
3157
3158                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3159                             "</frontend_type>\n", port->frontend->name);
3160                         if (retval != 0)
3161                                 break;
3162
3163                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3164                                              port->port_type);
3165                         if (retval != 0)
3166                                 break;
3167
3168                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3169                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3170                         if (retval != 0)
3171                                 break;
3172
3173                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3174                             port->port_name);
3175                         if (retval != 0)
3176                                 break;
3177
3178                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3179                             port->physical_port);
3180                         if (retval != 0)
3181                                 break;
3182
3183                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3184                             port->virtual_port);
3185                         if (retval != 0)
3186                                 break;
3187
3188                         if (port->target_devid != NULL) {
3189                                 sbuf_printf(sb, "\t<target>");
3190                                 ctl_id_sbuf(port->target_devid, sb);
3191                                 sbuf_printf(sb, "</target>\n");
3192                         }
3193
3194                         if (port->port_devid != NULL) {
3195                                 sbuf_printf(sb, "\t<port>");
3196                                 ctl_id_sbuf(port->port_devid, sb);
3197                                 sbuf_printf(sb, "</port>\n");
3198                         }
3199
3200                         if (port->port_info != NULL) {
3201                                 retval = port->port_info(port->onoff_arg, sb);
3202                                 if (retval != 0)
3203                                         break;
3204                         }
3205                         STAILQ_FOREACH(opt, &port->options, links) {
3206                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3207                                     opt->name, opt->value, opt->name);
3208                                 if (retval != 0)
3209                                         break;
3210                         }
3211
3212                         if (port->lun_map != NULL) {
3213                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3214                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3215                                         plun = ctl_lun_map_from_port(port, j);
3216                                         if (plun >= CTL_MAX_LUNS)
3217                                                 continue;
3218                                         sbuf_printf(sb,
3219                                             "\t<lun id=\"%u\">%u</lun>\n",
3220                                             j, plun);
3221                                 }
3222                         }
3223
3224                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3225                                 if (port->wwpn_iid[j].in_use == 0 ||
3226                                     (port->wwpn_iid[j].wwpn == 0 &&
3227                                      port->wwpn_iid[j].name == NULL))
3228                                         continue;
3229
3230                                 if (port->wwpn_iid[j].name != NULL)
3231                                         retval = sbuf_printf(sb,
3232                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3233                                             j, port->wwpn_iid[j].name);
3234                                 else
3235                                         retval = sbuf_printf(sb,
3236                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3237                                             j, port->wwpn_iid[j].wwpn);
3238                                 if (retval != 0)
3239                                         break;
3240                         }
3241                         if (retval != 0)
3242                                 break;
3243
3244                         retval = sbuf_printf(sb, "</targ_port>\n");
3245                         if (retval != 0)
3246                                 break;
3247                 }
3248                 mtx_unlock(&softc->ctl_lock);
3249
3250                 if ((retval != 0)
3251                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3252                         retval = 0;
3253                         sbuf_delete(sb);
3254                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3255                         snprintf(list->error_str, sizeof(list->error_str),
3256                                  "Out of space, %d bytes is too small",
3257                                  list->alloc_len);
3258                         break;
3259                 }
3260
3261                 sbuf_finish(sb);
3262
3263                 retval = copyout(sbuf_data(sb), list->lun_xml,
3264                                  sbuf_len(sb) + 1);
3265
3266                 list->fill_len = sbuf_len(sb) + 1;
3267                 list->status = CTL_LUN_LIST_OK;
3268                 sbuf_delete(sb);
3269                 break;
3270         }
3271         case CTL_LUN_MAP: {
3272                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3273                 struct ctl_port *port;
3274
3275                 mtx_lock(&softc->ctl_lock);
3276                 if (lm->port < softc->port_min ||
3277                     lm->port >= softc->port_max ||
3278                     (port = softc->ctl_ports[lm->port]) == NULL) {
3279                         mtx_unlock(&softc->ctl_lock);
3280                         return (ENXIO);
3281                 }
3282                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3283                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3284                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3285                                     CTL_MAX_LUNS)
3286                                         continue;
3287                                 mtx_lock(&lun->lun_lock);
3288                                 ctl_est_ua_port(lun, lm->port, -1,
3289                                     CTL_UA_LUN_CHANGE);
3290                                 mtx_unlock(&lun->lun_lock);
3291                         }
3292                 }
3293                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3294                 if (lm->plun < CTL_MAX_LUNS) {
3295                         if (lm->lun == UINT32_MAX)
3296                                 retval = ctl_lun_map_unset(port, lm->plun);
3297                         else if (lm->lun < CTL_MAX_LUNS &&
3298                             softc->ctl_luns[lm->lun] != NULL)
3299                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3300                         else
3301                                 return (ENXIO);
3302                 } else if (lm->plun == UINT32_MAX) {
3303                         if (lm->lun == UINT32_MAX)
3304                                 retval = ctl_lun_map_deinit(port);
3305                         else
3306                                 retval = ctl_lun_map_init(port);
3307                 } else
3308                         return (ENXIO);
3309                 if (port->status & CTL_PORT_STATUS_ONLINE)
3310                         ctl_isc_announce_port(port);
3311                 break;
3312         }
3313         default: {
3314                 /* XXX KDM should we fix this? */
3315 #if 0
3316                 struct ctl_backend_driver *backend;
3317                 unsigned int type;
3318                 int found;
3319
3320                 found = 0;
3321
3322                 /*
3323                  * We encode the backend type as the ioctl type for backend
3324                  * ioctls.  So parse it out here, and then search for a
3325                  * backend of this type.
3326                  */
3327                 type = _IOC_TYPE(cmd);
3328
3329                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3330                         if (backend->type == type) {
3331                                 found = 1;
3332                                 break;
3333                         }
3334                 }
3335                 if (found == 0) {
3336                         printf("ctl: unknown ioctl command %#lx or backend "
3337                                "%d\n", cmd, type);
3338                         retval = EINVAL;
3339                         break;
3340                 }
3341                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3342 #endif
3343                 retval = ENOTTY;
3344                 break;
3345         }
3346         }
3347         return (retval);
3348 }
3349
3350 uint32_t
3351 ctl_get_initindex(struct ctl_nexus *nexus)
3352 {
3353         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3354 }
3355
3356 int
3357 ctl_lun_map_init(struct ctl_port *port)
3358 {
3359         struct ctl_softc *softc = control_softc;
3360         struct ctl_lun *lun;
3361         uint32_t i;
3362
3363         if (port->lun_map == NULL)
3364                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3365                     M_CTL, M_NOWAIT);
3366         if (port->lun_map == NULL)
3367                 return (ENOMEM);
3368         for (i = 0; i < CTL_MAX_LUNS; i++)
3369                 port->lun_map[i] = UINT32_MAX;
3370         if (port->status & CTL_PORT_STATUS_ONLINE) {
3371                 if (port->lun_disable != NULL) {
3372                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3373                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3374                 }
3375                 ctl_isc_announce_port(port);
3376         }
3377         return (0);
3378 }
3379
3380 int
3381 ctl_lun_map_deinit(struct ctl_port *port)
3382 {
3383         struct ctl_softc *softc = control_softc;
3384         struct ctl_lun *lun;
3385
3386         if (port->lun_map == NULL)
3387                 return (0);
3388         free(port->lun_map, M_CTL);
3389         port->lun_map = NULL;
3390         if (port->status & CTL_PORT_STATUS_ONLINE) {
3391                 if (port->lun_enable != NULL) {
3392                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3393                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3394                 }
3395                 ctl_isc_announce_port(port);
3396         }
3397         return (0);
3398 }
3399
3400 int
3401 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3402 {
3403         int status;
3404         uint32_t old;
3405
3406         if (port->lun_map == NULL) {
3407                 status = ctl_lun_map_init(port);
3408                 if (status != 0)
3409                         return (status);
3410         }
3411         old = port->lun_map[plun];
3412         port->lun_map[plun] = glun;
3413         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3414                 if (port->lun_enable != NULL)
3415                         port->lun_enable(port->targ_lun_arg, plun);
3416                 ctl_isc_announce_port(port);
3417         }
3418         return (0);
3419 }
3420
3421 int
3422 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3423 {
3424         uint32_t old;
3425
3426         if (port->lun_map == NULL)
3427                 return (0);
3428         old = port->lun_map[plun];
3429         port->lun_map[plun] = UINT32_MAX;
3430         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3431                 if (port->lun_disable != NULL)
3432                         port->lun_disable(port->targ_lun_arg, plun);
3433                 ctl_isc_announce_port(port);
3434         }
3435         return (0);
3436 }
3437
3438 uint32_t
3439 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3440 {
3441
3442         if (port == NULL)
3443                 return (UINT32_MAX);
3444         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3445                 return (lun_id);
3446         return (port->lun_map[lun_id]);
3447 }
3448
3449 uint32_t
3450 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3451 {
3452         uint32_t i;
3453
3454         if (port == NULL)
3455                 return (UINT32_MAX);
3456         if (port->lun_map == NULL)
3457                 return (lun_id);
3458         for (i = 0; i < CTL_MAX_LUNS; i++) {
3459                 if (port->lun_map[i] == lun_id)
3460                         return (i);
3461         }
3462         return (UINT32_MAX);
3463 }
3464
3465 static struct ctl_port *
3466 ctl_io_port(struct ctl_io_hdr *io_hdr)
3467 {
3468
3469         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3470 }
3471
3472 int
3473 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3474 {
3475         int i;
3476
3477         for (i = first; i < last; i++) {
3478                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3479                         return (i);
3480         }
3481         return (-1);
3482 }
3483
3484 int
3485 ctl_set_mask(uint32_t *mask, uint32_t bit)
3486 {
3487         uint32_t chunk, piece;
3488
3489         chunk = bit >> 5;
3490         piece = bit % (sizeof(uint32_t) * 8);
3491
3492         if ((mask[chunk] & (1 << piece)) != 0)
3493                 return (-1);
3494         else
3495                 mask[chunk] |= (1 << piece);
3496
3497         return (0);
3498 }
3499
3500 int
3501 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3502 {
3503         uint32_t chunk, piece;
3504
3505         chunk = bit >> 5;
3506         piece = bit % (sizeof(uint32_t) * 8);
3507
3508         if ((mask[chunk] & (1 << piece)) == 0)
3509                 return (-1);
3510         else
3511                 mask[chunk] &= ~(1 << piece);
3512
3513         return (0);
3514 }
3515
3516 int
3517 ctl_is_set(uint32_t *mask, uint32_t bit)
3518 {
3519         uint32_t chunk, piece;
3520
3521         chunk = bit >> 5;
3522         piece = bit % (sizeof(uint32_t) * 8);
3523
3524         if ((mask[chunk] & (1 << piece)) == 0)
3525                 return (0);
3526         else
3527                 return (1);
3528 }
3529
3530 static uint64_t
3531 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3532 {
3533         uint64_t *t;
3534
3535         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3536         if (t == NULL)
3537                 return (0);
3538         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3539 }
3540
3541 static void
3542 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3543 {
3544         uint64_t *t;
3545
3546         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3547         if (t == NULL)
3548                 return;
3549         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3550 }
3551
3552 static void
3553 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3554 {
3555         uint64_t *p;
3556         u_int i;
3557
3558         i = residx/CTL_MAX_INIT_PER_PORT;
3559         if (lun->pr_keys[i] != NULL)
3560                 return;
3561         mtx_unlock(&lun->lun_lock);
3562         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3563             M_WAITOK | M_ZERO);
3564         mtx_lock(&lun->lun_lock);
3565         if (lun->pr_keys[i] == NULL)
3566                 lun->pr_keys[i] = p;
3567         else
3568                 free(p, M_CTL);
3569 }
3570
3571 static void
3572 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3573 {
3574         uint64_t *t;
3575
3576         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3577         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3578         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3579 }
3580
3581 /*
3582  * ctl_softc, pool_name, total_ctl_io are passed in.
3583  * npool is passed out.
3584  */
3585 int
3586 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3587                 uint32_t total_ctl_io, void **npool)
3588 {
3589 #ifdef IO_POOLS
3590         struct ctl_io_pool *pool;
3591
3592         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3593                                             M_NOWAIT | M_ZERO);
3594         if (pool == NULL)
3595                 return (ENOMEM);
3596
3597         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3598         pool->ctl_softc = ctl_softc;
3599         pool->zone = uma_zsecond_create(pool->name, NULL,
3600             NULL, NULL, NULL, ctl_softc->io_zone);
3601         /* uma_prealloc(pool->zone, total_ctl_io); */
3602
3603         *npool = pool;
3604 #else
3605         *npool = ctl_softc->io_zone;
3606 #endif
3607         return (0);
3608 }
3609
3610 void
3611 ctl_pool_free(struct ctl_io_pool *pool)
3612 {
3613
3614         if (pool == NULL)
3615                 return;
3616
3617 #ifdef IO_POOLS
3618         uma_zdestroy(pool->zone);
3619         free(pool, M_CTL);
3620 #endif
3621 }
3622
3623 union ctl_io *
3624 ctl_alloc_io(void *pool_ref)
3625 {
3626         union ctl_io *io;
3627 #ifdef IO_POOLS
3628         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3629
3630         io = uma_zalloc(pool->zone, M_WAITOK);
3631 #else
3632         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3633 #endif
3634         if (io != NULL)
3635                 io->io_hdr.pool = pool_ref;
3636         return (io);
3637 }
3638
3639 union ctl_io *
3640 ctl_alloc_io_nowait(void *pool_ref)
3641 {
3642         union ctl_io *io;
3643 #ifdef IO_POOLS
3644         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3645
3646         io = uma_zalloc(pool->zone, M_NOWAIT);
3647 #else
3648         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3649 #endif
3650         if (io != NULL)
3651                 io->io_hdr.pool = pool_ref;
3652         return (io);
3653 }
3654
3655 void
3656 ctl_free_io(union ctl_io *io)
3657 {
3658 #ifdef IO_POOLS
3659         struct ctl_io_pool *pool;
3660 #endif
3661
3662         if (io == NULL)
3663                 return;
3664
3665 #ifdef IO_POOLS
3666         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3667         uma_zfree(pool->zone, io);
3668 #else
3669         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3670 #endif
3671 }
3672
3673 void
3674 ctl_zero_io(union ctl_io *io)
3675 {
3676         void *pool_ref;
3677
3678         if (io == NULL)
3679                 return;
3680
3681         /*
3682          * May need to preserve linked list pointers at some point too.
3683          */
3684         pool_ref = io->io_hdr.pool;
3685         memset(io, 0, sizeof(*io));
3686         io->io_hdr.pool = pool_ref;
3687 }
3688
3689 /*
3690  * This routine is currently used for internal copies of ctl_ios that need
3691  * to persist for some reason after we've already returned status to the
3692  * FETD.  (Thus the flag set.)
3693  *
3694  * XXX XXX
3695  * Note that this makes a blind copy of all fields in the ctl_io, except
3696  * for the pool reference.  This includes any memory that has been
3697  * allocated!  That memory will no longer be valid after done has been
3698  * called, so this would be VERY DANGEROUS for command that actually does
3699  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3700  * start and stop commands, which don't transfer any data, so this is not a
3701  * problem.  If it is used for anything else, the caller would also need to
3702  * allocate data buffer space and this routine would need to be modified to
3703  * copy the data buffer(s) as well.
3704  */
3705 void
3706 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3707 {
3708         void *pool_ref;
3709
3710         if ((src == NULL)
3711          || (dest == NULL))
3712                 return;
3713
3714         /*
3715          * May need to preserve linked list pointers at some point too.
3716          */
3717         pool_ref = dest->io_hdr.pool;
3718
3719         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3720
3721         dest->io_hdr.pool = pool_ref;
3722         /*
3723          * We need to know that this is an internal copy, and doesn't need
3724          * to get passed back to the FETD that allocated it.
3725          */
3726         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3727 }
3728
3729 int
3730 ctl_expand_number(const char *buf, uint64_t *num)
3731 {
3732         char *endptr;
3733         uint64_t number;
3734         unsigned shift;
3735
3736         number = strtoq(buf, &endptr, 0);
3737
3738         switch (tolower((unsigned char)*endptr)) {
3739         case 'e':
3740                 shift = 60;
3741                 break;
3742         case 'p':
3743                 shift = 50;
3744                 break;
3745         case 't':
3746                 shift = 40;
3747                 break;
3748         case 'g':
3749                 shift = 30;
3750                 break;
3751         case 'm':
3752                 shift = 20;
3753                 break;
3754         case 'k':
3755                 shift = 10;
3756                 break;
3757         case 'b':
3758         case '\0': /* No unit. */
3759                 *num = number;
3760                 return (0);
3761         default:
3762                 /* Unrecognized unit. */
3763                 return (-1);
3764         }
3765
3766         if ((number << shift) >> shift != number) {
3767                 /* Overflow */
3768                 return (-1);
3769         }
3770         *num = number << shift;
3771         return (0);
3772 }
3773
3774
3775 /*
3776  * This routine could be used in the future to load default and/or saved
3777  * mode page parameters for a particuar lun.
3778  */
3779 static int
3780 ctl_init_page_index(struct ctl_lun *lun)
3781 {
3782         int i;
3783         struct ctl_page_index *page_index;
3784         const char *value;
3785         uint64_t ival;
3786
3787         memcpy(&lun->mode_pages.index, page_index_template,
3788                sizeof(page_index_template));
3789
3790         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3791
3792                 page_index = &lun->mode_pages.index[i];
3793                 /*
3794                  * If this is a disk-only mode page, there's no point in
3795                  * setting it up.  For some pages, we have to have some
3796                  * basic information about the disk in order to calculate the
3797                  * mode page data.
3798                  */
3799                 if ((lun->be_lun->lun_type != T_DIRECT)
3800                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3801                         continue;
3802
3803                 switch (page_index->page_code & SMPH_PC_MASK) {
3804                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3805                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3806                                 panic("subpage is incorrect!");
3807                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3808                                &rw_er_page_default,
3809                                sizeof(rw_er_page_default));
3810                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3811                                &rw_er_page_changeable,
3812                                sizeof(rw_er_page_changeable));
3813                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3814                                &rw_er_page_default,
3815                                sizeof(rw_er_page_default));
3816                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3817                                &rw_er_page_default,
3818                                sizeof(rw_er_page_default));
3819                         page_index->page_data =
3820                                 (uint8_t *)lun->mode_pages.rw_er_page;
3821                         break;
3822                 }
3823                 case SMS_FORMAT_DEVICE_PAGE: {
3824                         struct scsi_format_page *format_page;
3825
3826                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3827                                 panic("subpage is incorrect!");
3828
3829                         /*
3830                          * Sectors per track are set above.  Bytes per
3831                          * sector need to be set here on a per-LUN basis.
3832                          */
3833                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3834                                &format_page_default,
3835                                sizeof(format_page_default));
3836                         memcpy(&lun->mode_pages.format_page[
3837                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3838                                sizeof(format_page_changeable));
3839                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3840                                &format_page_default,
3841                                sizeof(format_page_default));
3842                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3843                                &format_page_default,
3844                                sizeof(format_page_default));
3845
3846                         format_page = &lun->mode_pages.format_page[
3847                                 CTL_PAGE_CURRENT];
3848                         scsi_ulto2b(lun->be_lun->blocksize,
3849                                     format_page->bytes_per_sector);
3850
3851                         format_page = &lun->mode_pages.format_page[
3852                                 CTL_PAGE_DEFAULT];
3853                         scsi_ulto2b(lun->be_lun->blocksize,
3854                                     format_page->bytes_per_sector);
3855
3856                         format_page = &lun->mode_pages.format_page[
3857                                 CTL_PAGE_SAVED];
3858                         scsi_ulto2b(lun->be_lun->blocksize,
3859                                     format_page->bytes_per_sector);
3860
3861                         page_index->page_data =
3862                                 (uint8_t *)lun->mode_pages.format_page;
3863                         break;
3864                 }
3865                 case SMS_RIGID_DISK_PAGE: {
3866                         struct scsi_rigid_disk_page *rigid_disk_page;
3867                         uint32_t sectors_per_cylinder;
3868                         uint64_t cylinders;
3869 #ifndef __XSCALE__
3870                         int shift;
3871 #endif /* !__XSCALE__ */
3872
3873                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3874                                 panic("invalid subpage value %d",
3875                                       page_index->subpage);
3876
3877                         /*
3878                          * Rotation rate and sectors per track are set
3879                          * above.  We calculate the cylinders here based on
3880                          * capacity.  Due to the number of heads and
3881                          * sectors per track we're using, smaller arrays
3882                          * may turn out to have 0 cylinders.  Linux and
3883                          * FreeBSD don't pay attention to these mode pages
3884                          * to figure out capacity, but Solaris does.  It
3885                          * seems to deal with 0 cylinders just fine, and
3886                          * works out a fake geometry based on the capacity.
3887                          */
3888                         memcpy(&lun->mode_pages.rigid_disk_page[
3889                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3890                                sizeof(rigid_disk_page_default));
3891                         memcpy(&lun->mode_pages.rigid_disk_page[
3892                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3893                                sizeof(rigid_disk_page_changeable));
3894
3895                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3896                                 CTL_DEFAULT_HEADS;
3897
3898                         /*
3899                          * The divide method here will be more accurate,
3900                          * probably, but results in floating point being
3901                          * used in the kernel on i386 (__udivdi3()).  On the
3902                          * XScale, though, __udivdi3() is implemented in
3903                          * software.
3904                          *
3905                          * The shift method for cylinder calculation is
3906                          * accurate if sectors_per_cylinder is a power of
3907                          * 2.  Otherwise it might be slightly off -- you
3908                          * might have a bit of a truncation problem.
3909                          */
3910 #ifdef  __XSCALE__
3911                         cylinders = (lun->be_lun->maxlba + 1) /
3912                                 sectors_per_cylinder;
3913 #else
3914                         for (shift = 31; shift > 0; shift--) {
3915                                 if (sectors_per_cylinder & (1 << shift))
3916                                         break;
3917                         }
3918                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
3919 #endif
3920
3921                         /*
3922                          * We've basically got 3 bytes, or 24 bits for the
3923                          * cylinder size in the mode page.  If we're over,
3924                          * just round down to 2^24.
3925                          */
3926                         if (cylinders > 0xffffff)
3927                                 cylinders = 0xffffff;
3928
3929                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3930                                 CTL_PAGE_DEFAULT];
3931                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3932
3933                         if ((value = ctl_get_opt(&lun->be_lun->options,
3934                             "rpm")) != NULL) {
3935                                 scsi_ulto2b(strtol(value, NULL, 0),
3936                                      rigid_disk_page->rotation_rate);
3937                         }
3938
3939                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3940                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3941                                sizeof(rigid_disk_page_default));
3942                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3943                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3944                                sizeof(rigid_disk_page_default));
3945
3946                         page_index->page_data =
3947                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
3948                         break;
3949                 }
3950                 case SMS_CACHING_PAGE: {
3951                         struct scsi_caching_page *caching_page;
3952
3953                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3954                                 panic("invalid subpage value %d",
3955                                       page_index->subpage);
3956                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3957                                &caching_page_default,
3958                                sizeof(caching_page_default));
3959                         memcpy(&lun->mode_pages.caching_page[
3960                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3961                                sizeof(caching_page_changeable));
3962                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3963                                &caching_page_default,
3964                                sizeof(caching_page_default));
3965                         caching_page = &lun->mode_pages.caching_page[
3966                             CTL_PAGE_SAVED];
3967                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
3968                         if (value != NULL && strcmp(value, "off") == 0)
3969                                 caching_page->flags1 &= ~SCP_WCE;
3970                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
3971                         if (value != NULL && strcmp(value, "off") == 0)
3972                                 caching_page->flags1 |= SCP_RCD;
3973                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3974                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3975                                sizeof(caching_page_default));
3976                         page_index->page_data =
3977                                 (uint8_t *)lun->mode_pages.caching_page;
3978                         break;
3979                 }
3980                 case SMS_CONTROL_MODE_PAGE: {
3981                         switch (page_index->subpage) {
3982                         case SMS_SUBPAGE_PAGE_0: {
3983                                 struct scsi_control_page *control_page;
3984
3985                                 memcpy(&lun->mode_pages.control_page[
3986                                     CTL_PAGE_DEFAULT],
3987                                        &control_page_default,
3988                                        sizeof(control_page_default));
3989                                 memcpy(&lun->mode_pages.control_page[
3990                                     CTL_PAGE_CHANGEABLE],
3991                                        &control_page_changeable,
3992                                        sizeof(control_page_changeable));
3993                                 memcpy(&lun->mode_pages.control_page[
3994                                     CTL_PAGE_SAVED],
3995                                        &control_page_default,
3996                                        sizeof(control_page_default));
3997                                 control_page = &lun->mode_pages.control_page[
3998                                     CTL_PAGE_SAVED];
3999                                 value = ctl_get_opt(&lun->be_lun->options,
4000                                     "reordering");
4001                                 if (value != NULL &&
4002                                     strcmp(value, "unrestricted") == 0) {
4003                                         control_page->queue_flags &=
4004                                             ~SCP_QUEUE_ALG_MASK;
4005                                         control_page->queue_flags |=
4006                                             SCP_QUEUE_ALG_UNRESTRICTED;
4007                                 }
4008                                 memcpy(&lun->mode_pages.control_page[
4009                                     CTL_PAGE_CURRENT],
4010                                        &lun->mode_pages.control_page[
4011                                     CTL_PAGE_SAVED],
4012                                        sizeof(control_page_default));
4013                                 page_index->page_data =
4014                                     (uint8_t *)lun->mode_pages.control_page;
4015                                 break;
4016                         }
4017                         case 0x01:
4018                                 memcpy(&lun->mode_pages.control_ext_page[
4019                                     CTL_PAGE_DEFAULT],
4020                                        &control_ext_page_default,
4021                                        sizeof(control_ext_page_default));
4022                                 memcpy(&lun->mode_pages.control_ext_page[
4023                                     CTL_PAGE_CHANGEABLE],
4024                                        &control_ext_page_changeable,
4025                                        sizeof(control_ext_page_changeable));
4026                                 memcpy(&lun->mode_pages.control_ext_page[
4027                                     CTL_PAGE_SAVED],
4028                                        &control_ext_page_default,
4029                                        sizeof(control_ext_page_default));
4030                                 memcpy(&lun->mode_pages.control_ext_page[
4031                                     CTL_PAGE_CURRENT],
4032                                        &lun->mode_pages.control_ext_page[
4033                                     CTL_PAGE_SAVED],
4034                                        sizeof(control_ext_page_default));
4035                                 page_index->page_data =
4036                                     (uint8_t *)lun->mode_pages.control_ext_page;
4037                                 break;
4038                         }
4039                         break;
4040                 }
4041                 case SMS_INFO_EXCEPTIONS_PAGE: {
4042                         switch (page_index->subpage) {
4043                         case SMS_SUBPAGE_PAGE_0:
4044                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4045                                        &ie_page_default,
4046                                        sizeof(ie_page_default));
4047                                 memcpy(&lun->mode_pages.ie_page[
4048                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4049                                        sizeof(ie_page_changeable));
4050                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4051                                        &ie_page_default,
4052                                        sizeof(ie_page_default));
4053                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4054                                        &ie_page_default,
4055                                        sizeof(ie_page_default));
4056                                 page_index->page_data =
4057                                         (uint8_t *)lun->mode_pages.ie_page;
4058                                 break;
4059                         case 0x02: {
4060                                 struct ctl_logical_block_provisioning_page *page;
4061
4062                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4063                                        &lbp_page_default,
4064                                        sizeof(lbp_page_default));
4065                                 memcpy(&lun->mode_pages.lbp_page[
4066                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4067                                        sizeof(lbp_page_changeable));
4068                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4069                                        &lbp_page_default,
4070                                        sizeof(lbp_page_default));
4071                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4072                                 value = ctl_get_opt(&lun->be_lun->options,
4073                                     "avail-threshold");
4074                                 if (value != NULL &&
4075                                     ctl_expand_number(value, &ival) == 0) {
4076                                         page->descr[0].flags |= SLBPPD_ENABLED |
4077                                             SLBPPD_ARMING_DEC;
4078                                         if (lun->be_lun->blocksize)
4079                                                 ival /= lun->be_lun->blocksize;
4080                                         else
4081                                                 ival /= 512;
4082                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4083                                             page->descr[0].count);
4084                                 }
4085                                 value = ctl_get_opt(&lun->be_lun->options,
4086                                     "used-threshold");
4087                                 if (value != NULL &&
4088                                     ctl_expand_number(value, &ival) == 0) {
4089                                         page->descr[1].flags |= SLBPPD_ENABLED |
4090                                             SLBPPD_ARMING_INC;
4091                                         if (lun->be_lun->blocksize)
4092                                                 ival /= lun->be_lun->blocksize;
4093                                         else
4094                                                 ival /= 512;
4095                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4096                                             page->descr[1].count);
4097                                 }
4098                                 value = ctl_get_opt(&lun->be_lun->options,
4099                                     "pool-avail-threshold");
4100                                 if (value != NULL &&
4101                                     ctl_expand_number(value, &ival) == 0) {
4102                                         page->descr[2].flags |= SLBPPD_ENABLED |
4103                                             SLBPPD_ARMING_DEC;
4104                                         if (lun->be_lun->blocksize)
4105                                                 ival /= lun->be_lun->blocksize;
4106                                         else
4107                                                 ival /= 512;
4108                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4109                                             page->descr[2].count);
4110                                 }
4111                                 value = ctl_get_opt(&lun->be_lun->options,
4112                                     "pool-used-threshold");
4113                                 if (value != NULL &&
4114                                     ctl_expand_number(value, &ival) == 0) {
4115                                         page->descr[3].flags |= SLBPPD_ENABLED |
4116                                             SLBPPD_ARMING_INC;
4117                                         if (lun->be_lun->blocksize)
4118                                                 ival /= lun->be_lun->blocksize;
4119                                         else
4120                                                 ival /= 512;
4121                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4122                                             page->descr[3].count);
4123                                 }
4124                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4125                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4126                                        sizeof(lbp_page_default));
4127                                 page_index->page_data =
4128                                         (uint8_t *)lun->mode_pages.lbp_page;
4129                         }}
4130                         break;
4131                 }
4132                 case SMS_VENDOR_SPECIFIC_PAGE:{
4133                         switch (page_index->subpage) {
4134                         case DBGCNF_SUBPAGE_CODE: {
4135                                 struct copan_debugconf_subpage *current_page,
4136                                                                *saved_page;
4137
4138                                 memcpy(&lun->mode_pages.debugconf_subpage[
4139                                        CTL_PAGE_CURRENT],
4140                                        &debugconf_page_default,
4141                                        sizeof(debugconf_page_default));
4142                                 memcpy(&lun->mode_pages.debugconf_subpage[
4143                                        CTL_PAGE_CHANGEABLE],
4144                                        &debugconf_page_changeable,
4145                                        sizeof(debugconf_page_changeable));
4146                                 memcpy(&lun->mode_pages.debugconf_subpage[
4147                                        CTL_PAGE_DEFAULT],
4148                                        &debugconf_page_default,
4149                                        sizeof(debugconf_page_default));
4150                                 memcpy(&lun->mode_pages.debugconf_subpage[
4151                                        CTL_PAGE_SAVED],
4152                                        &debugconf_page_default,
4153                                        sizeof(debugconf_page_default));
4154                                 page_index->page_data =
4155                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4156
4157                                 current_page = (struct copan_debugconf_subpage *)
4158                                         (page_index->page_data +
4159                                          (page_index->page_len *
4160                                           CTL_PAGE_CURRENT));
4161                                 saved_page = (struct copan_debugconf_subpage *)
4162                                         (page_index->page_data +
4163                                          (page_index->page_len *
4164                                           CTL_PAGE_SAVED));
4165                                 break;
4166                         }
4167                         default:
4168                                 panic("invalid subpage value %d",
4169                                       page_index->subpage);
4170                                 break;
4171                         }
4172                         break;
4173                 }
4174                 default:
4175                         panic("invalid page value %d",
4176                               page_index->page_code & SMPH_PC_MASK);
4177                         break;
4178         }
4179         }
4180
4181         return (CTL_RETVAL_COMPLETE);
4182 }
4183
4184 static int
4185 ctl_init_log_page_index(struct ctl_lun *lun)
4186 {
4187         struct ctl_page_index *page_index;
4188         int i, j, k, prev;
4189
4190         memcpy(&lun->log_pages.index, log_page_index_template,
4191                sizeof(log_page_index_template));
4192
4193         prev = -1;
4194         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4195
4196                 page_index = &lun->log_pages.index[i];
4197                 /*
4198                  * If this is a disk-only mode page, there's no point in
4199                  * setting it up.  For some pages, we have to have some
4200                  * basic information about the disk in order to calculate the
4201                  * mode page data.
4202                  */
4203                 if ((lun->be_lun->lun_type != T_DIRECT)
4204                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4205                         continue;
4206
4207                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4208                      lun->backend->lun_attr == NULL)
4209                         continue;
4210
4211                 if (page_index->page_code != prev) {
4212                         lun->log_pages.pages_page[j] = page_index->page_code;
4213                         prev = page_index->page_code;
4214                         j++;
4215                 }
4216                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4217                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4218                 k++;
4219         }
4220         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4221         lun->log_pages.index[0].page_len = j;
4222         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4223         lun->log_pages.index[1].page_len = k * 2;
4224         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4225         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4226         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4227         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4228
4229         return (CTL_RETVAL_COMPLETE);
4230 }
4231
4232 static int
4233 hex2bin(const char *str, uint8_t *buf, int buf_size)
4234 {
4235         int i;
4236         u_char c;
4237
4238         memset(buf, 0, buf_size);
4239         while (isspace(str[0]))
4240                 str++;
4241         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4242                 str += 2;
4243         buf_size *= 2;
4244         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4245                 c = str[i];
4246                 if (isdigit(c))
4247                         c -= '0';
4248                 else if (isalpha(c))
4249                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4250                 else
4251                         break;
4252                 if (c >= 16)
4253                         break;
4254                 if ((i & 1) == 0)
4255                         buf[i / 2] |= (c << 4);
4256                 else
4257                         buf[i / 2] |= c;
4258         }
4259         return ((i + 1) / 2);
4260 }
4261
4262 /*
4263  * LUN allocation.
4264  *
4265  * Requirements:
4266  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4267  *   wants us to allocate the LUN and he can block.
4268  * - ctl_softc is always set
4269  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4270  *
4271  * Returns 0 for success, non-zero (errno) for failure.
4272  */
4273 static int
4274 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4275               struct ctl_be_lun *const be_lun)
4276 {
4277         struct ctl_lun *nlun, *lun;
4278         struct scsi_vpd_id_descriptor *desc;
4279         struct scsi_vpd_id_t10 *t10id;
4280         const char *eui, *naa, *scsiname, *vendor;
4281         int lun_number, i, lun_malloced;
4282         int devidlen, idlen1, idlen2 = 0, len;
4283
4284         if (be_lun == NULL)
4285                 return (EINVAL);
4286
4287         /*
4288          * We currently only support Direct Access or Processor LUN types.
4289          */
4290         switch (be_lun->lun_type) {
4291         case T_DIRECT:
4292                 break;
4293         case T_PROCESSOR:
4294                 break;
4295         case T_SEQUENTIAL:
4296         case T_CHANGER:
4297         default:
4298                 be_lun->lun_config_status(be_lun->be_lun,
4299                                           CTL_LUN_CONFIG_FAILURE);
4300                 break;
4301         }
4302         if (ctl_lun == NULL) {
4303                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4304                 lun_malloced = 1;
4305         } else {
4306                 lun_malloced = 0;
4307                 lun = ctl_lun;
4308         }
4309
4310         memset(lun, 0, sizeof(*lun));
4311         if (lun_malloced)
4312                 lun->flags = CTL_LUN_MALLOCED;
4313
4314         /* Generate LUN ID. */
4315         devidlen = max(CTL_DEVID_MIN_LEN,
4316             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4317         idlen1 = sizeof(*t10id) + devidlen;
4318         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4319         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4320         if (scsiname != NULL) {
4321                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4322                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4323         }
4324         eui = ctl_get_opt(&be_lun->options, "eui");
4325         if (eui != NULL) {
4326                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4327         }
4328         naa = ctl_get_opt(&be_lun->options, "naa");
4329         if (naa != NULL) {
4330                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4331         }
4332         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4333             M_CTL, M_WAITOK | M_ZERO);
4334         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4335         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4336         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4337         desc->length = idlen1;
4338         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4339         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4340         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4341                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4342         } else {
4343                 strncpy(t10id->vendor, vendor,
4344                     min(sizeof(t10id->vendor), strlen(vendor)));
4345         }
4346         strncpy((char *)t10id->vendor_spec_id,
4347             (char *)be_lun->device_id, devidlen);
4348         if (scsiname != NULL) {
4349                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4350                     desc->length);
4351                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4352                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4353                     SVPD_ID_TYPE_SCSI_NAME;
4354                 desc->length = idlen2;
4355                 strlcpy(desc->identifier, scsiname, idlen2);
4356         }
4357         if (eui != NULL) {
4358                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4359                     desc->length);
4360                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4361                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4362                     SVPD_ID_TYPE_EUI64;
4363                 desc->length = hex2bin(eui, desc->identifier, 16);
4364                 desc->length = desc->length > 12 ? 16 :
4365                     (desc->length > 8 ? 12 : 8);
4366                 len -= 16 - desc->length;
4367         }
4368         if (naa != NULL) {
4369                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4370                     desc->length);
4371                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4372                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4373                     SVPD_ID_TYPE_NAA;
4374                 desc->length = hex2bin(naa, desc->identifier, 16);
4375                 desc->length = desc->length > 8 ? 16 : 8;
4376                 len -= 16 - desc->length;
4377         }
4378         lun->lun_devid->len = len;
4379
4380         mtx_lock(&ctl_softc->ctl_lock);
4381         /*
4382          * See if the caller requested a particular LUN number.  If so, see
4383          * if it is available.  Otherwise, allocate the first available LUN.
4384          */
4385         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4386                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4387                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4388                         mtx_unlock(&ctl_softc->ctl_lock);
4389                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4390                                 printf("ctl: requested LUN ID %d is higher "
4391                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4392                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4393                         } else {
4394                                 /*
4395                                  * XXX KDM return an error, or just assign
4396                                  * another LUN ID in this case??
4397                                  */
4398                                 printf("ctl: requested LUN ID %d is already "
4399                                        "in use\n", be_lun->req_lun_id);
4400                         }
4401                         if (lun->flags & CTL_LUN_MALLOCED)
4402                                 free(lun, M_CTL);
4403                         be_lun->lun_config_status(be_lun->be_lun,
4404                                                   CTL_LUN_CONFIG_FAILURE);
4405                         return (ENOSPC);
4406                 }
4407                 lun_number = be_lun->req_lun_id;
4408         } else {
4409                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4410                 if (lun_number == -1) {
4411                         mtx_unlock(&ctl_softc->ctl_lock);
4412                         printf("ctl: can't allocate LUN, out of LUNs\n");
4413                         if (lun->flags & CTL_LUN_MALLOCED)
4414                                 free(lun, M_CTL);
4415                         be_lun->lun_config_status(be_lun->be_lun,
4416                                                   CTL_LUN_CONFIG_FAILURE);
4417                         return (ENOSPC);
4418                 }
4419         }
4420         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4421
4422         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4423         lun->lun = lun_number;
4424         lun->be_lun = be_lun;
4425         /*
4426          * The processor LUN is always enabled.  Disk LUNs come on line
4427          * disabled, and must be enabled by the backend.
4428          */
4429         lun->flags |= CTL_LUN_DISABLED;
4430         lun->backend = be_lun->be;
4431         be_lun->ctl_lun = lun;
4432         be_lun->lun_id = lun_number;
4433         atomic_add_int(&be_lun->be->num_luns, 1);
4434         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4435                 lun->flags |= CTL_LUN_OFFLINE;
4436
4437         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4438                 lun->flags |= CTL_LUN_STOPPED;
4439
4440         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4441                 lun->flags |= CTL_LUN_INOPERABLE;
4442
4443         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4444                 lun->flags |= CTL_LUN_PRIMARY_SC;
4445
4446         lun->ctl_softc = ctl_softc;
4447 #ifdef CTL_TIME_IO
4448         lun->last_busy = getsbinuptime();
4449 #endif
4450         TAILQ_INIT(&lun->ooa_queue);
4451         TAILQ_INIT(&lun->blocked_queue);
4452         STAILQ_INIT(&lun->error_list);
4453         ctl_tpc_lun_init(lun);
4454
4455         /*
4456          * Initialize the mode and log page index.
4457          */
4458         ctl_init_page_index(lun);
4459         ctl_init_log_page_index(lun);
4460
4461         /*
4462          * Now, before we insert this lun on the lun list, set the lun
4463          * inventory changed UA for all other luns.
4464          */
4465         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4466                 mtx_lock(&nlun->lun_lock);
4467                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4468                 mtx_unlock(&nlun->lun_lock);
4469         }
4470
4471         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4472
4473         ctl_softc->ctl_luns[lun_number] = lun;
4474
4475         ctl_softc->num_luns++;
4476
4477         /* Setup statistics gathering */
4478         lun->stats.device_type = be_lun->lun_type;
4479         lun->stats.lun_number = lun_number;
4480         if (lun->stats.device_type == T_DIRECT)
4481                 lun->stats.blocksize = be_lun->blocksize;
4482         else
4483                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4484         for (i = 0;i < CTL_MAX_PORTS;i++)
4485                 lun->stats.ports[i].targ_port = i;
4486
4487         mtx_unlock(&ctl_softc->ctl_lock);
4488
4489         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4490         return (0);
4491 }
4492
4493 /*
4494  * Delete a LUN.
4495  * Assumptions:
4496  * - LUN has already been marked invalid and any pending I/O has been taken
4497  *   care of.
4498  */
4499 static int
4500 ctl_free_lun(struct ctl_lun *lun)
4501 {
4502         struct ctl_softc *softc;
4503         struct ctl_lun *nlun;
4504         int i;
4505
4506         softc = lun->ctl_softc;
4507
4508         mtx_assert(&softc->ctl_lock, MA_OWNED);
4509
4510         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4511
4512         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4513
4514         softc->ctl_luns[lun->lun] = NULL;
4515
4516         if (!TAILQ_EMPTY(&lun->ooa_queue))
4517                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4518
4519         softc->num_luns--;
4520
4521         /*
4522          * Tell the backend to free resources, if this LUN has a backend.
4523          */
4524         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4525         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4526
4527         ctl_tpc_lun_shutdown(lun);
4528         mtx_destroy(&lun->lun_lock);
4529         free(lun->lun_devid, M_CTL);
4530         for (i = 0; i < CTL_MAX_PORTS; i++)
4531                 free(lun->pending_ua[i], M_CTL);
4532         for (i = 0; i < CTL_MAX_PORTS; i++)
4533                 free(lun->pr_keys[i], M_CTL);
4534         free(lun->write_buffer, M_CTL);
4535         if (lun->flags & CTL_LUN_MALLOCED)
4536                 free(lun, M_CTL);
4537
4538         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4539                 mtx_lock(&nlun->lun_lock);
4540                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4541                 mtx_unlock(&nlun->lun_lock);
4542         }
4543
4544         return (0);
4545 }
4546
4547 static void
4548 ctl_create_lun(struct ctl_be_lun *be_lun)
4549 {
4550         struct ctl_softc *softc;
4551
4552         softc = control_softc;
4553
4554         /*
4555          * ctl_alloc_lun() should handle all potential failure cases.
4556          */
4557         ctl_alloc_lun(softc, NULL, be_lun);
4558 }
4559
4560 int
4561 ctl_add_lun(struct ctl_be_lun *be_lun)
4562 {
4563         struct ctl_softc *softc = control_softc;
4564
4565         mtx_lock(&softc->ctl_lock);
4566         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4567         mtx_unlock(&softc->ctl_lock);
4568         wakeup(&softc->pending_lun_queue);
4569
4570         return (0);
4571 }
4572
4573 int
4574 ctl_enable_lun(struct ctl_be_lun *be_lun)
4575 {
4576         struct ctl_softc *softc;
4577         struct ctl_port *port, *nport;
4578         struct ctl_lun *lun;
4579         int retval;
4580
4581         lun = (struct ctl_lun *)be_lun->ctl_lun;
4582         softc = lun->ctl_softc;
4583
4584         mtx_lock(&softc->ctl_lock);
4585         mtx_lock(&lun->lun_lock);
4586         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4587                 /*
4588                  * eh?  Why did we get called if the LUN is already
4589                  * enabled?
4590                  */
4591                 mtx_unlock(&lun->lun_lock);
4592                 mtx_unlock(&softc->ctl_lock);
4593                 return (0);
4594         }
4595         lun->flags &= ~CTL_LUN_DISABLED;
4596         mtx_unlock(&lun->lun_lock);
4597
4598         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4599                 nport = STAILQ_NEXT(port, links);
4600                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4601                     port->lun_map != NULL || port->lun_enable == NULL)
4602                         continue;
4603
4604                 /*
4605                  * Drop the lock while we call the FETD's enable routine.
4606                  * This can lead to a callback into CTL (at least in the
4607                  * case of the internal initiator frontend.
4608                  */
4609                 mtx_unlock(&softc->ctl_lock);
4610                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4611                 mtx_lock(&softc->ctl_lock);
4612                 if (retval != 0) {
4613                         printf("%s: FETD %s port %d returned error "
4614                                "%d for lun_enable on lun %jd\n",
4615                                __func__, port->port_name, port->targ_port,
4616                                retval, (intmax_t)lun->lun);
4617                 }
4618         }
4619
4620         mtx_unlock(&softc->ctl_lock);
4621         ctl_isc_announce_lun(lun);
4622
4623         return (0);
4624 }
4625
4626 int
4627 ctl_disable_lun(struct ctl_be_lun *be_lun)
4628 {
4629         struct ctl_softc *softc;
4630         struct ctl_port *port;
4631         struct ctl_lun *lun;
4632         int retval;
4633
4634         lun = (struct ctl_lun *)be_lun->ctl_lun;
4635         softc = lun->ctl_softc;
4636
4637         mtx_lock(&softc->ctl_lock);
4638         mtx_lock(&lun->lun_lock);
4639         if (lun->flags & CTL_LUN_DISABLED) {
4640                 mtx_unlock(&lun->lun_lock);
4641                 mtx_unlock(&softc->ctl_lock);
4642                 return (0);
4643         }
4644         lun->flags |= CTL_LUN_DISABLED;
4645         mtx_unlock(&lun->lun_lock);
4646
4647         STAILQ_FOREACH(port, &softc->port_list, links) {
4648                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4649                     port->lun_map != NULL || port->lun_disable == NULL)
4650                         continue;
4651
4652                 /*
4653                  * Drop the lock before we call the frontend's disable
4654                  * routine, to avoid lock order reversals.
4655                  *
4656                  * XXX KDM what happens if the frontend list changes while
4657                  * we're traversing it?  It's unlikely, but should be handled.
4658                  */
4659                 mtx_unlock(&softc->ctl_lock);
4660                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4661                 mtx_lock(&softc->ctl_lock);
4662                 if (retval != 0) {
4663                         printf("%s: FETD %s port %d returned error "
4664                                "%d for lun_disable on lun %jd\n",
4665                                __func__, port->port_name, port->targ_port,
4666                                retval, (intmax_t)lun->lun);
4667                 }
4668         }
4669
4670         mtx_unlock(&softc->ctl_lock);
4671         ctl_isc_announce_lun(lun);
4672
4673         return (0);
4674 }
4675
4676 int
4677 ctl_start_lun(struct ctl_be_lun *be_lun)
4678 {
4679         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4680
4681         mtx_lock(&lun->lun_lock);
4682         lun->flags &= ~CTL_LUN_STOPPED;
4683         mtx_unlock(&lun->lun_lock);
4684         return (0);
4685 }
4686
4687 int
4688 ctl_stop_lun(struct ctl_be_lun *be_lun)
4689 {
4690         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4691
4692         mtx_lock(&lun->lun_lock);
4693         lun->flags |= CTL_LUN_STOPPED;
4694         mtx_unlock(&lun->lun_lock);
4695         return (0);
4696 }
4697
4698 int
4699 ctl_lun_offline(struct ctl_be_lun *be_lun)
4700 {
4701         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4702
4703         mtx_lock(&lun->lun_lock);
4704         lun->flags |= CTL_LUN_OFFLINE;
4705         mtx_unlock(&lun->lun_lock);
4706         return (0);
4707 }
4708
4709 int
4710 ctl_lun_online(struct ctl_be_lun *be_lun)
4711 {
4712         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4713
4714         mtx_lock(&lun->lun_lock);
4715         lun->flags &= ~CTL_LUN_OFFLINE;
4716         mtx_unlock(&lun->lun_lock);
4717         return (0);
4718 }
4719
4720 int
4721 ctl_lun_primary(struct ctl_be_lun *be_lun)
4722 {
4723         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4724
4725         mtx_lock(&lun->lun_lock);
4726         lun->flags |= CTL_LUN_PRIMARY_SC;
4727         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4728         mtx_unlock(&lun->lun_lock);
4729         ctl_isc_announce_lun(lun);
4730         return (0);
4731 }
4732
4733 int
4734 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4735 {
4736         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4737
4738         mtx_lock(&lun->lun_lock);
4739         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4740         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4741         mtx_unlock(&lun->lun_lock);
4742         ctl_isc_announce_lun(lun);
4743         return (0);
4744 }
4745
4746 int
4747 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4748 {
4749         struct ctl_softc *softc;
4750         struct ctl_lun *lun;
4751
4752         lun = (struct ctl_lun *)be_lun->ctl_lun;
4753         softc = lun->ctl_softc;
4754
4755         mtx_lock(&lun->lun_lock);
4756
4757         /*
4758          * The LUN needs to be disabled before it can be marked invalid.
4759          */
4760         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4761                 mtx_unlock(&lun->lun_lock);
4762                 return (-1);
4763         }
4764         /*
4765          * Mark the LUN invalid.
4766          */
4767         lun->flags |= CTL_LUN_INVALID;
4768
4769         /*
4770          * If there is nothing in the OOA queue, go ahead and free the LUN.
4771          * If we have something in the OOA queue, we'll free it when the
4772          * last I/O completes.
4773          */
4774         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4775                 mtx_unlock(&lun->lun_lock);
4776                 mtx_lock(&softc->ctl_lock);
4777                 ctl_free_lun(lun);
4778                 mtx_unlock(&softc->ctl_lock);
4779         } else
4780                 mtx_unlock(&lun->lun_lock);
4781
4782         return (0);
4783 }
4784
4785 int
4786 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4787 {
4788         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4789
4790         mtx_lock(&lun->lun_lock);
4791         lun->flags |= CTL_LUN_INOPERABLE;
4792         mtx_unlock(&lun->lun_lock);
4793         return (0);
4794 }
4795
4796 int
4797 ctl_lun_operable(struct ctl_be_lun *be_lun)
4798 {
4799         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4800
4801         mtx_lock(&lun->lun_lock);
4802         lun->flags &= ~CTL_LUN_INOPERABLE;
4803         mtx_unlock(&lun->lun_lock);
4804         return (0);
4805 }
4806
4807 void
4808 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4809 {
4810         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4811         union ctl_ha_msg msg;
4812
4813         mtx_lock(&lun->lun_lock);
4814         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4815         mtx_unlock(&lun->lun_lock);
4816         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4817                 /* Send msg to other side. */
4818                 bzero(&msg.ua, sizeof(msg.ua));
4819                 msg.hdr.msg_type = CTL_MSG_UA;
4820                 msg.hdr.nexus.initid = -1;
4821                 msg.hdr.nexus.targ_port = -1;
4822                 msg.hdr.nexus.targ_lun = lun->lun;
4823                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4824                 msg.ua.ua_all = 1;
4825                 msg.ua.ua_set = 1;
4826                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4827                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4828                     M_WAITOK);
4829         }
4830 }
4831
4832 /*
4833  * Backend "memory move is complete" callback for requests that never
4834  * make it down to say RAIDCore's configuration code.
4835  */
4836 int
4837 ctl_config_move_done(union ctl_io *io)
4838 {
4839         int retval;
4840
4841         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4842         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4843             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4844
4845         if ((io->io_hdr.port_status != 0) &&
4846             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4847              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4848                 /*
4849                  * For hardware error sense keys, the sense key
4850                  * specific value is defined to be a retry count,
4851                  * but we use it to pass back an internal FETD
4852                  * error code.  XXX KDM  Hopefully the FETD is only
4853                  * using 16 bits for an error code, since that's
4854                  * all the space we have in the sks field.
4855                  */
4856                 ctl_set_internal_failure(&io->scsiio,
4857                                          /*sks_valid*/ 1,
4858                                          /*retry_count*/
4859                                          io->io_hdr.port_status);
4860         }
4861
4862         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4863                 ctl_data_print(io);
4864         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4865             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4866              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4867             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4868                 /*
4869                  * XXX KDM just assuming a single pointer here, and not a
4870                  * S/G list.  If we start using S/G lists for config data,
4871                  * we'll need to know how to clean them up here as well.
4872                  */
4873                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4874                         free(io->scsiio.kern_data_ptr, M_CTL);
4875                 ctl_done(io);
4876                 retval = CTL_RETVAL_COMPLETE;
4877         } else {
4878                 /*
4879                  * XXX KDM now we need to continue data movement.  Some
4880                  * options:
4881                  * - call ctl_scsiio() again?  We don't do this for data
4882                  *   writes, because for those at least we know ahead of
4883                  *   time where the write will go and how long it is.  For
4884                  *   config writes, though, that information is largely
4885                  *   contained within the write itself, thus we need to
4886                  *   parse out the data again.
4887                  *
4888                  * - Call some other function once the data is in?
4889                  */
4890
4891                 /*
4892                  * XXX KDM call ctl_scsiio() again for now, and check flag
4893                  * bits to see whether we're allocated or not.
4894                  */
4895                 retval = ctl_scsiio(&io->scsiio);
4896         }
4897         return (retval);
4898 }
4899
4900 /*
4901  * This gets called by a backend driver when it is done with a
4902  * data_submit method.
4903  */
4904 void
4905 ctl_data_submit_done(union ctl_io *io)
4906 {
4907         /*
4908          * If the IO_CONT flag is set, we need to call the supplied
4909          * function to continue processing the I/O, instead of completing
4910          * the I/O just yet.
4911          *
4912          * If there is an error, though, we don't want to keep processing.
4913          * Instead, just send status back to the initiator.
4914          */
4915         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4916             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4917             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4918              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4919                 io->scsiio.io_cont(io);
4920                 return;
4921         }
4922         ctl_done(io);
4923 }
4924
4925 /*
4926  * This gets called by a backend driver when it is done with a
4927  * configuration write.
4928  */
4929 void
4930 ctl_config_write_done(union ctl_io *io)
4931 {
4932         uint8_t *buf;
4933
4934         /*
4935          * If the IO_CONT flag is set, we need to call the supplied
4936          * function to continue processing the I/O, instead of completing
4937          * the I/O just yet.
4938          *
4939          * If there is an error, though, we don't want to keep processing.
4940          * Instead, just send status back to the initiator.
4941          */
4942         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4943             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4944             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4945              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4946                 io->scsiio.io_cont(io);
4947                 return;
4948         }
4949         /*
4950          * Since a configuration write can be done for commands that actually
4951          * have data allocated, like write buffer, and commands that have
4952          * no data, like start/stop unit, we need to check here.
4953          */
4954         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4955                 buf = io->scsiio.kern_data_ptr;
4956         else
4957                 buf = NULL;
4958         ctl_done(io);
4959         if (buf)
4960                 free(buf, M_CTL);
4961 }
4962
4963 void
4964 ctl_config_read_done(union ctl_io *io)
4965 {
4966         uint8_t *buf;
4967
4968         /*
4969          * If there is some error -- we are done, skip data transfer.
4970          */
4971         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4972             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4973              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4974                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4975                         buf = io->scsiio.kern_data_ptr;
4976                 else
4977                         buf = NULL;
4978                 ctl_done(io);
4979                 if (buf)
4980                         free(buf, M_CTL);
4981                 return;
4982         }
4983
4984         /*
4985          * If the IO_CONT flag is set, we need to call the supplied
4986          * function to continue processing the I/O, instead of completing
4987          * the I/O just yet.
4988          */
4989         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4990                 io->scsiio.io_cont(io);
4991                 return;
4992         }
4993
4994         ctl_datamove(io);
4995 }
4996
4997 /*
4998  * SCSI release command.
4999  */
5000 int
5001 ctl_scsi_release(struct ctl_scsiio *ctsio)
5002 {
5003         int length, longid, thirdparty_id, resv_id;
5004         struct ctl_lun *lun;
5005         uint32_t residx;
5006
5007         length = 0;
5008         resv_id = 0;
5009
5010         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5011
5012         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5013         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5014
5015         switch (ctsio->cdb[0]) {
5016         case RELEASE_10: {
5017                 struct scsi_release_10 *cdb;
5018
5019                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5020
5021                 if (cdb->byte2 & SR10_LONGID)
5022                         longid = 1;
5023                 else
5024                         thirdparty_id = cdb->thirdparty_id;
5025
5026                 resv_id = cdb->resv_id;
5027                 length = scsi_2btoul(cdb->length);
5028                 break;
5029         }
5030         }
5031
5032
5033         /*
5034          * XXX KDM right now, we only support LUN reservation.  We don't
5035          * support 3rd party reservations, or extent reservations, which
5036          * might actually need the parameter list.  If we've gotten this
5037          * far, we've got a LUN reservation.  Anything else got kicked out
5038          * above.  So, according to SPC, ignore the length.
5039          */
5040         length = 0;
5041
5042         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5043          && (length > 0)) {
5044                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5045                 ctsio->kern_data_len = length;
5046                 ctsio->kern_total_len = length;
5047                 ctsio->kern_data_resid = 0;
5048                 ctsio->kern_rel_offset = 0;
5049                 ctsio->kern_sg_entries = 0;
5050                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5051                 ctsio->be_move_done = ctl_config_move_done;
5052                 ctl_datamove((union ctl_io *)ctsio);
5053
5054                 return (CTL_RETVAL_COMPLETE);
5055         }
5056
5057         if (length > 0)
5058                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5059
5060         mtx_lock(&lun->lun_lock);
5061
5062         /*
5063          * According to SPC, it is not an error for an intiator to attempt
5064          * to release a reservation on a LUN that isn't reserved, or that
5065          * is reserved by another initiator.  The reservation can only be
5066          * released, though, by the initiator who made it or by one of
5067          * several reset type events.
5068          */
5069         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5070                         lun->flags &= ~CTL_LUN_RESERVED;
5071
5072         mtx_unlock(&lun->lun_lock);
5073
5074         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5075                 free(ctsio->kern_data_ptr, M_CTL);
5076                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5077         }
5078
5079         ctl_set_success(ctsio);
5080         ctl_done((union ctl_io *)ctsio);
5081         return (CTL_RETVAL_COMPLETE);
5082 }
5083
5084 int
5085 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5086 {
5087         int extent, thirdparty, longid;
5088         int resv_id, length;
5089         uint64_t thirdparty_id;
5090         struct ctl_lun *lun;
5091         uint32_t residx;
5092
5093         extent = 0;
5094         thirdparty = 0;
5095         longid = 0;
5096         resv_id = 0;
5097         length = 0;
5098         thirdparty_id = 0;
5099
5100         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5101
5102         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5103         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5104
5105         switch (ctsio->cdb[0]) {
5106         case RESERVE_10: {
5107                 struct scsi_reserve_10 *cdb;
5108
5109                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5110
5111                 if (cdb->byte2 & SR10_LONGID)
5112                         longid = 1;
5113                 else
5114                         thirdparty_id = cdb->thirdparty_id;
5115
5116                 resv_id = cdb->resv_id;
5117                 length = scsi_2btoul(cdb->length);
5118                 break;
5119         }
5120         }
5121
5122         /*
5123          * XXX KDM right now, we only support LUN reservation.  We don't
5124          * support 3rd party reservations, or extent reservations, which
5125          * might actually need the parameter list.  If we've gotten this
5126          * far, we've got a LUN reservation.  Anything else got kicked out
5127          * above.  So, according to SPC, ignore the length.
5128          */
5129         length = 0;
5130
5131         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5132          && (length > 0)) {
5133                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5134                 ctsio->kern_data_len = length;
5135                 ctsio->kern_total_len = length;
5136                 ctsio->kern_data_resid = 0;
5137                 ctsio->kern_rel_offset = 0;
5138                 ctsio->kern_sg_entries = 0;
5139                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5140                 ctsio->be_move_done = ctl_config_move_done;
5141                 ctl_datamove((union ctl_io *)ctsio);
5142
5143                 return (CTL_RETVAL_COMPLETE);
5144         }
5145
5146         if (length > 0)
5147                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5148
5149         mtx_lock(&lun->lun_lock);
5150         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5151                 ctl_set_reservation_conflict(ctsio);
5152                 goto bailout;
5153         }
5154
5155         lun->flags |= CTL_LUN_RESERVED;
5156         lun->res_idx = residx;
5157
5158         ctl_set_success(ctsio);
5159
5160 bailout:
5161         mtx_unlock(&lun->lun_lock);
5162
5163         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5164                 free(ctsio->kern_data_ptr, M_CTL);
5165                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5166         }
5167
5168         ctl_done((union ctl_io *)ctsio);
5169         return (CTL_RETVAL_COMPLETE);
5170 }
5171
5172 int
5173 ctl_start_stop(struct ctl_scsiio *ctsio)
5174 {
5175         struct scsi_start_stop_unit *cdb;
5176         struct ctl_lun *lun;
5177         int retval;
5178
5179         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5180
5181         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5182         retval = 0;
5183
5184         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5185
5186         /*
5187          * XXX KDM
5188          * We don't support the immediate bit on a stop unit.  In order to
5189          * do that, we would need to code up a way to know that a stop is
5190          * pending, and hold off any new commands until it completes, one
5191          * way or another.  Then we could accept or reject those commands
5192          * depending on its status.  We would almost need to do the reverse
5193          * of what we do below for an immediate start -- return the copy of
5194          * the ctl_io to the FETD with status to send to the host (and to
5195          * free the copy!) and then free the original I/O once the stop
5196          * actually completes.  That way, the OOA queue mechanism can work
5197          * to block commands that shouldn't proceed.  Another alternative
5198          * would be to put the copy in the queue in place of the original,
5199          * and return the original back to the caller.  That could be
5200          * slightly safer..
5201          */
5202         if ((cdb->byte2 & SSS_IMMED)
5203          && ((cdb->how & SSS_START) == 0)) {
5204                 ctl_set_invalid_field(ctsio,
5205                                       /*sks_valid*/ 1,
5206                                       /*command*/ 1,
5207                                       /*field*/ 1,
5208                                       /*bit_valid*/ 1,
5209                                       /*bit*/ 0);
5210                 ctl_done((union ctl_io *)ctsio);
5211                 return (CTL_RETVAL_COMPLETE);
5212         }
5213
5214         if ((lun->flags & CTL_LUN_PR_RESERVED)
5215          && ((cdb->how & SSS_START)==0)) {
5216                 uint32_t residx;
5217
5218                 residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5219                 if (ctl_get_prkey(lun, residx) == 0
5220                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5221
5222                         ctl_set_reservation_conflict(ctsio);
5223                         ctl_done((union ctl_io *)ctsio);
5224                         return (CTL_RETVAL_COMPLETE);
5225                 }
5226         }
5227
5228         /*
5229          * If there is no backend on this device, we can't start or stop
5230          * it.  In theory we shouldn't get any start/stop commands in the
5231          * first place at this level if the LUN doesn't have a backend.
5232          * That should get stopped by the command decode code.
5233          */
5234         if (lun->backend == NULL) {
5235                 ctl_set_invalid_opcode(ctsio);
5236                 ctl_done((union ctl_io *)ctsio);
5237                 return (CTL_RETVAL_COMPLETE);
5238         }
5239
5240         /*
5241          * XXX KDM Copan-specific offline behavior.
5242          * Figure out a reasonable way to port this?
5243          */
5244 #ifdef NEEDTOPORT
5245         mtx_lock(&lun->lun_lock);
5246
5247         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5248          && (lun->flags & CTL_LUN_OFFLINE)) {
5249                 /*
5250                  * If the LUN is offline, and the on/offline bit isn't set,
5251                  * reject the start or stop.  Otherwise, let it through.
5252                  */
5253                 mtx_unlock(&lun->lun_lock);
5254                 ctl_set_lun_not_ready(ctsio);
5255                 ctl_done((union ctl_io *)ctsio);
5256         } else {
5257                 mtx_unlock(&lun->lun_lock);
5258 #endif /* NEEDTOPORT */
5259                 /*
5260                  * This could be a start or a stop when we're online,
5261                  * or a stop/offline or start/online.  A start or stop when
5262                  * we're offline is covered in the case above.
5263                  */
5264                 /*
5265                  * In the non-immediate case, we send the request to
5266                  * the backend and return status to the user when
5267                  * it is done.
5268                  *
5269                  * In the immediate case, we allocate a new ctl_io
5270                  * to hold a copy of the request, and send that to
5271                  * the backend.  We then set good status on the
5272                  * user's request and return it immediately.
5273                  */
5274                 if (cdb->byte2 & SSS_IMMED) {
5275                         union ctl_io *new_io;
5276
5277                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5278                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5279                         retval = lun->backend->config_write(new_io);
5280                         ctl_set_success(ctsio);
5281                         ctl_done((union ctl_io *)ctsio);
5282                 } else {
5283                         retval = lun->backend->config_write(
5284                                 (union ctl_io *)ctsio);
5285                 }
5286 #ifdef NEEDTOPORT
5287         }
5288 #endif
5289         return (retval);
5290 }
5291
5292 /*
5293  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5294  * we don't really do anything with the LBA and length fields if the user
5295  * passes them in.  Instead we'll just flush out the cache for the entire
5296  * LUN.
5297  */
5298 int
5299 ctl_sync_cache(struct ctl_scsiio *ctsio)
5300 {
5301         struct ctl_lun *lun;
5302         struct ctl_softc *softc;
5303         struct ctl_lba_len_flags *lbalen;
5304         uint64_t starting_lba;
5305         uint32_t block_count;
5306         int retval;
5307         uint8_t byte2;
5308
5309         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5310
5311         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5312         softc = lun->ctl_softc;
5313         retval = 0;
5314
5315         switch (ctsio->cdb[0]) {
5316         case SYNCHRONIZE_CACHE: {
5317                 struct scsi_sync_cache *cdb;
5318                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5319
5320                 starting_lba = scsi_4btoul(cdb->begin_lba);
5321                 block_count = scsi_2btoul(cdb->lb_count);
5322                 byte2 = cdb->byte2;
5323                 break;
5324         }
5325         case SYNCHRONIZE_CACHE_16: {
5326                 struct scsi_sync_cache_16 *cdb;
5327                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5328
5329                 starting_lba = scsi_8btou64(cdb->begin_lba);
5330                 block_count = scsi_4btoul(cdb->lb_count);
5331                 byte2 = cdb->byte2;
5332                 break;
5333         }
5334         default:
5335                 ctl_set_invalid_opcode(ctsio);
5336                 ctl_done((union ctl_io *)ctsio);
5337                 goto bailout;
5338                 break; /* NOTREACHED */
5339         }
5340
5341         /*
5342          * We check the LBA and length, but don't do anything with them.
5343          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5344          * get flushed.  This check will just help satisfy anyone who wants
5345          * to see an error for an out of range LBA.
5346          */
5347         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5348                 ctl_set_lba_out_of_range(ctsio);
5349                 ctl_done((union ctl_io *)ctsio);
5350                 goto bailout;
5351         }
5352
5353         /*
5354          * If this LUN has no backend, we can't flush the cache anyway.
5355          */
5356         if (lun->backend == NULL) {
5357                 ctl_set_invalid_opcode(ctsio);
5358                 ctl_done((union ctl_io *)ctsio);
5359                 goto bailout;
5360         }
5361
5362         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5363         lbalen->lba = starting_lba;
5364         lbalen->len = block_count;
5365         lbalen->flags = byte2;
5366
5367         /*
5368          * Check to see whether we're configured to send the SYNCHRONIZE
5369          * CACHE command directly to the back end.
5370          */
5371         mtx_lock(&lun->lun_lock);
5372         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5373          && (++(lun->sync_count) >= lun->sync_interval)) {
5374                 lun->sync_count = 0;
5375                 mtx_unlock(&lun->lun_lock);
5376                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5377         } else {
5378                 mtx_unlock(&lun->lun_lock);
5379                 ctl_set_success(ctsio);
5380                 ctl_done((union ctl_io *)ctsio);
5381         }
5382
5383 bailout:
5384
5385         return (retval);
5386 }
5387
5388 int
5389 ctl_format(struct ctl_scsiio *ctsio)
5390 {
5391         struct scsi_format *cdb;
5392         struct ctl_lun *lun;
5393         int length, defect_list_len;
5394
5395         CTL_DEBUG_PRINT(("ctl_format\n"));
5396
5397         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5398
5399         cdb = (struct scsi_format *)ctsio->cdb;
5400
5401         length = 0;
5402         if (cdb->byte2 & SF_FMTDATA) {
5403                 if (cdb->byte2 & SF_LONGLIST)
5404                         length = sizeof(struct scsi_format_header_long);
5405                 else
5406                         length = sizeof(struct scsi_format_header_short);
5407         }
5408
5409         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5410          && (length > 0)) {
5411                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5412                 ctsio->kern_data_len = length;
5413                 ctsio->kern_total_len = length;
5414                 ctsio->kern_data_resid = 0;
5415                 ctsio->kern_rel_offset = 0;
5416                 ctsio->kern_sg_entries = 0;
5417                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5418                 ctsio->be_move_done = ctl_config_move_done;
5419                 ctl_datamove((union ctl_io *)ctsio);
5420
5421                 return (CTL_RETVAL_COMPLETE);
5422         }
5423
5424         defect_list_len = 0;
5425
5426         if (cdb->byte2 & SF_FMTDATA) {
5427                 if (cdb->byte2 & SF_LONGLIST) {
5428                         struct scsi_format_header_long *header;
5429
5430                         header = (struct scsi_format_header_long *)
5431                                 ctsio->kern_data_ptr;
5432
5433                         defect_list_len = scsi_4btoul(header->defect_list_len);
5434                         if (defect_list_len != 0) {
5435                                 ctl_set_invalid_field(ctsio,
5436                                                       /*sks_valid*/ 1,
5437                                                       /*command*/ 0,
5438                                                       /*field*/ 2,
5439                                                       /*bit_valid*/ 0,
5440                                                       /*bit*/ 0);
5441                                 goto bailout;
5442                         }
5443                 } else {
5444                         struct scsi_format_header_short *header;
5445
5446                         header = (struct scsi_format_header_short *)
5447                                 ctsio->kern_data_ptr;
5448
5449                         defect_list_len = scsi_2btoul(header->defect_list_len);
5450                         if (defect_list_len != 0) {
5451                                 ctl_set_invalid_field(ctsio,
5452                                                       /*sks_valid*/ 1,
5453                                                       /*command*/ 0,
5454                                                       /*field*/ 2,
5455                                                       /*bit_valid*/ 0,
5456                                                       /*bit*/ 0);
5457                                 goto bailout;
5458                         }
5459                 }
5460         }
5461
5462         /*
5463          * The format command will clear out the "Medium format corrupted"
5464          * status if set by the configuration code.  That status is really
5465          * just a way to notify the host that we have lost the media, and
5466          * get them to issue a command that will basically make them think
5467          * they're blowing away the media.
5468          */
5469         mtx_lock(&lun->lun_lock);
5470         lun->flags &= ~CTL_LUN_INOPERABLE;
5471         mtx_unlock(&lun->lun_lock);
5472
5473         ctl_set_success(ctsio);
5474 bailout:
5475
5476         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5477                 free(ctsio->kern_data_ptr, M_CTL);
5478                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5479         }
5480
5481         ctl_done((union ctl_io *)ctsio);
5482         return (CTL_RETVAL_COMPLETE);
5483 }
5484
5485 int
5486 ctl_read_buffer(struct ctl_scsiio *ctsio)
5487 {
5488         struct scsi_read_buffer *cdb;
5489         struct ctl_lun *lun;
5490         int buffer_offset, len;
5491         static uint8_t descr[4];
5492         static uint8_t echo_descr[4] = { 0 };
5493
5494         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5495
5496         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5497         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5498
5499         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5500             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5501             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5502                 ctl_set_invalid_field(ctsio,
5503                                       /*sks_valid*/ 1,
5504                                       /*command*/ 1,
5505                                       /*field*/ 1,
5506                                       /*bit_valid*/ 1,
5507                                       /*bit*/ 4);
5508                 ctl_done((union ctl_io *)ctsio);
5509                 return (CTL_RETVAL_COMPLETE);
5510         }
5511
5512         len = scsi_3btoul(cdb->length);
5513         buffer_offset = scsi_3btoul(cdb->offset);
5514
5515         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5516                 ctl_set_invalid_field(ctsio,
5517                                       /*sks_valid*/ 1,
5518                                       /*command*/ 1,
5519                                       /*field*/ 6,
5520                                       /*bit_valid*/ 0,
5521                                       /*bit*/ 0);
5522                 ctl_done((union ctl_io *)ctsio);
5523                 return (CTL_RETVAL_COMPLETE);
5524         }
5525
5526         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5527                 descr[0] = 0;
5528                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5529                 ctsio->kern_data_ptr = descr;
5530                 len = min(len, sizeof(descr));
5531         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5532                 ctsio->kern_data_ptr = echo_descr;
5533                 len = min(len, sizeof(echo_descr));
5534         } else {
5535                 if (lun->write_buffer == NULL) {
5536                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5537                             M_CTL, M_WAITOK);
5538                 }
5539                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5540         }
5541         ctsio->kern_data_len = len;
5542         ctsio->kern_total_len = len;
5543         ctsio->kern_data_resid = 0;
5544         ctsio->kern_rel_offset = 0;
5545         ctsio->kern_sg_entries = 0;
5546         ctl_set_success(ctsio);
5547         ctsio->be_move_done = ctl_config_move_done;
5548         ctl_datamove((union ctl_io *)ctsio);
5549         return (CTL_RETVAL_COMPLETE);
5550 }
5551
5552 int
5553 ctl_write_buffer(struct ctl_scsiio *ctsio)
5554 {
5555         struct scsi_write_buffer *cdb;
5556         struct ctl_lun *lun;
5557         int buffer_offset, len;
5558
5559         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5560
5561         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5562         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5563
5564         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5565                 ctl_set_invalid_field(ctsio,
5566                                       /*sks_valid*/ 1,
5567                                       /*command*/ 1,
5568                                       /*field*/ 1,
5569                                       /*bit_valid*/ 1,
5570                                       /*bit*/ 4);
5571                 ctl_done((union ctl_io *)ctsio);
5572                 return (CTL_RETVAL_COMPLETE);
5573         }
5574
5575         len = scsi_3btoul(cdb->length);
5576         buffer_offset = scsi_3btoul(cdb->offset);
5577
5578         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5579                 ctl_set_invalid_field(ctsio,
5580                                       /*sks_valid*/ 1,
5581                                       /*command*/ 1,
5582                                       /*field*/ 6,
5583                                       /*bit_valid*/ 0,
5584                                       /*bit*/ 0);
5585                 ctl_done((union ctl_io *)ctsio);
5586                 return (CTL_RETVAL_COMPLETE);
5587         }
5588
5589         /*
5590          * If we've got a kernel request that hasn't been malloced yet,
5591          * malloc it and tell the caller the data buffer is here.
5592          */
5593         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5594                 if (lun->write_buffer == NULL) {
5595                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5596                             M_CTL, M_WAITOK);
5597                 }
5598                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5599                 ctsio->kern_data_len = len;
5600                 ctsio->kern_total_len = len;
5601                 ctsio->kern_data_resid = 0;
5602                 ctsio->kern_rel_offset = 0;
5603                 ctsio->kern_sg_entries = 0;
5604                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5605                 ctsio->be_move_done = ctl_config_move_done;
5606                 ctl_datamove((union ctl_io *)ctsio);
5607
5608                 return (CTL_RETVAL_COMPLETE);
5609         }
5610
5611         ctl_set_success(ctsio);
5612         ctl_done((union ctl_io *)ctsio);
5613         return (CTL_RETVAL_COMPLETE);
5614 }
5615
5616 int
5617 ctl_write_same(struct ctl_scsiio *ctsio)
5618 {
5619         struct ctl_lun *lun;
5620         struct ctl_lba_len_flags *lbalen;
5621         uint64_t lba;
5622         uint32_t num_blocks;
5623         int len, retval;
5624         uint8_t byte2;
5625
5626         retval = CTL_RETVAL_COMPLETE;
5627
5628         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5629
5630         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5631
5632         switch (ctsio->cdb[0]) {
5633         case WRITE_SAME_10: {
5634                 struct scsi_write_same_10 *cdb;
5635
5636                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5637
5638                 lba = scsi_4btoul(cdb->addr);
5639                 num_blocks = scsi_2btoul(cdb->length);
5640                 byte2 = cdb->byte2;
5641                 break;
5642         }
5643         case WRITE_SAME_16: {
5644                 struct scsi_write_same_16 *cdb;
5645
5646                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5647
5648                 lba = scsi_8btou64(cdb->addr);
5649                 num_blocks = scsi_4btoul(cdb->length);
5650                 byte2 = cdb->byte2;
5651                 break;
5652         }
5653         default:
5654                 /*
5655                  * We got a command we don't support.  This shouldn't
5656                  * happen, commands should be filtered out above us.
5657                  */
5658                 ctl_set_invalid_opcode(ctsio);
5659                 ctl_done((union ctl_io *)ctsio);
5660
5661                 return (CTL_RETVAL_COMPLETE);
5662                 break; /* NOTREACHED */
5663         }
5664
5665         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5666         if ((byte2 & SWS_UNMAP) == 0 &&
5667             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5668                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5669                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5670                 ctl_done((union ctl_io *)ctsio);
5671                 return (CTL_RETVAL_COMPLETE);
5672         }
5673
5674         /*
5675          * The first check is to make sure we're in bounds, the second
5676          * check is to catch wrap-around problems.  If the lba + num blocks
5677          * is less than the lba, then we've wrapped around and the block
5678          * range is invalid anyway.
5679          */
5680         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5681          || ((lba + num_blocks) < lba)) {
5682                 ctl_set_lba_out_of_range(ctsio);
5683                 ctl_done((union ctl_io *)ctsio);
5684                 return (CTL_RETVAL_COMPLETE);
5685         }
5686
5687         /* Zero number of blocks means "to the last logical block" */
5688         if (num_blocks == 0) {
5689                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5690                         ctl_set_invalid_field(ctsio,
5691                                               /*sks_valid*/ 0,
5692                                               /*command*/ 1,
5693                                               /*field*/ 0,
5694                                               /*bit_valid*/ 0,
5695                                               /*bit*/ 0);
5696                         ctl_done((union ctl_io *)ctsio);
5697                         return (CTL_RETVAL_COMPLETE);
5698                 }
5699                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5700         }
5701
5702         len = lun->be_lun->blocksize;
5703
5704         /*
5705          * If we've got a kernel request that hasn't been malloced yet,
5706          * malloc it and tell the caller the data buffer is here.
5707          */
5708         if ((byte2 & SWS_NDOB) == 0 &&
5709             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5710                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5711                 ctsio->kern_data_len = len;
5712                 ctsio->kern_total_len = len;
5713                 ctsio->kern_data_resid = 0;
5714                 ctsio->kern_rel_offset = 0;
5715                 ctsio->kern_sg_entries = 0;
5716                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5717                 ctsio->be_move_done = ctl_config_move_done;
5718                 ctl_datamove((union ctl_io *)ctsio);
5719
5720                 return (CTL_RETVAL_COMPLETE);
5721         }
5722
5723         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5724         lbalen->lba = lba;
5725         lbalen->len = num_blocks;
5726         lbalen->flags = byte2;
5727         retval = lun->backend->config_write((union ctl_io *)ctsio);
5728
5729         return (retval);
5730 }
5731
5732 int
5733 ctl_unmap(struct ctl_scsiio *ctsio)
5734 {
5735         struct ctl_lun *lun;
5736         struct scsi_unmap *cdb;
5737         struct ctl_ptr_len_flags *ptrlen;
5738         struct scsi_unmap_header *hdr;
5739         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5740         uint64_t lba;
5741         uint32_t num_blocks;
5742         int len, retval;
5743         uint8_t byte2;
5744
5745         retval = CTL_RETVAL_COMPLETE;
5746
5747         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5748
5749         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5750         cdb = (struct scsi_unmap *)ctsio->cdb;
5751
5752         len = scsi_2btoul(cdb->length);
5753         byte2 = cdb->byte2;
5754
5755         /*
5756          * If we've got a kernel request that hasn't been malloced yet,
5757          * malloc it and tell the caller the data buffer is here.
5758          */
5759         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5760                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5761                 ctsio->kern_data_len = len;
5762                 ctsio->kern_total_len = len;
5763                 ctsio->kern_data_resid = 0;
5764                 ctsio->kern_rel_offset = 0;
5765                 ctsio->kern_sg_entries = 0;
5766                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5767                 ctsio->be_move_done = ctl_config_move_done;
5768                 ctl_datamove((union ctl_io *)ctsio);
5769
5770                 return (CTL_RETVAL_COMPLETE);
5771         }
5772
5773         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5774         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5775         if (len < sizeof (*hdr) ||
5776             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5777             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5778             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5779                 ctl_set_invalid_field(ctsio,
5780                                       /*sks_valid*/ 0,
5781                                       /*command*/ 0,
5782                                       /*field*/ 0,
5783                                       /*bit_valid*/ 0,
5784                                       /*bit*/ 0);
5785                 goto done;
5786         }
5787         len = scsi_2btoul(hdr->desc_length);
5788         buf = (struct scsi_unmap_desc *)(hdr + 1);
5789         end = buf + len / sizeof(*buf);
5790
5791         endnz = buf;
5792         for (range = buf; range < end; range++) {
5793                 lba = scsi_8btou64(range->lba);
5794                 num_blocks = scsi_4btoul(range->length);
5795                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5796                  || ((lba + num_blocks) < lba)) {
5797                         ctl_set_lba_out_of_range(ctsio);
5798                         ctl_done((union ctl_io *)ctsio);
5799                         return (CTL_RETVAL_COMPLETE);
5800                 }
5801                 if (num_blocks != 0)
5802                         endnz = range + 1;
5803         }
5804
5805         /*
5806          * Block backend can not handle zero last range.
5807          * Filter it out and return if there is nothing left.
5808          */
5809         len = (uint8_t *)endnz - (uint8_t *)buf;
5810         if (len == 0) {
5811                 ctl_set_success(ctsio);
5812                 goto done;
5813         }
5814
5815         mtx_lock(&lun->lun_lock);
5816         ptrlen = (struct ctl_ptr_len_flags *)
5817             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5818         ptrlen->ptr = (void *)buf;
5819         ptrlen->len = len;
5820         ptrlen->flags = byte2;
5821         ctl_check_blocked(lun);
5822         mtx_unlock(&lun->lun_lock);
5823
5824         retval = lun->backend->config_write((union ctl_io *)ctsio);
5825         return (retval);
5826
5827 done:
5828         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5829                 free(ctsio->kern_data_ptr, M_CTL);
5830                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5831         }
5832         ctl_done((union ctl_io *)ctsio);
5833         return (CTL_RETVAL_COMPLETE);
5834 }
5835
5836 /*
5837  * Note that this function currently doesn't actually do anything inside
5838  * CTL to enforce things if the DQue bit is turned on.
5839  *
5840  * Also note that this function can't be used in the default case, because
5841  * the DQue bit isn't set in the changeable mask for the control mode page
5842  * anyway.  This is just here as an example for how to implement a page
5843  * handler, and a placeholder in case we want to allow the user to turn
5844  * tagged queueing on and off.
5845  *
5846  * The D_SENSE bit handling is functional, however, and will turn
5847  * descriptor sense on and off for a given LUN.
5848  */
5849 int
5850 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5851                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5852 {
5853         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5854         struct ctl_lun *lun;
5855         int set_ua;
5856         uint32_t initidx;
5857
5858         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5859         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5860         set_ua = 0;
5861
5862         user_cp = (struct scsi_control_page *)page_ptr;
5863         current_cp = (struct scsi_control_page *)
5864                 (page_index->page_data + (page_index->page_len *
5865                 CTL_PAGE_CURRENT));
5866         saved_cp = (struct scsi_control_page *)
5867                 (page_index->page_data + (page_index->page_len *
5868                 CTL_PAGE_SAVED));
5869
5870         mtx_lock(&lun->lun_lock);
5871         if (((current_cp->rlec & SCP_DSENSE) == 0)
5872          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5873                 /*
5874                  * Descriptor sense is currently turned off and the user
5875                  * wants to turn it on.
5876                  */
5877                 current_cp->rlec |= SCP_DSENSE;
5878                 saved_cp->rlec |= SCP_DSENSE;
5879                 lun->flags |= CTL_LUN_SENSE_DESC;
5880                 set_ua = 1;
5881         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5882                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5883                 /*
5884                  * Descriptor sense is currently turned on, and the user
5885                  * wants to turn it off.
5886                  */
5887                 current_cp->rlec &= ~SCP_DSENSE;
5888                 saved_cp->rlec &= ~SCP_DSENSE;
5889                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5890                 set_ua = 1;
5891         }
5892         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5893             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5894                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5895                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5896                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5897                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5898                 set_ua = 1;
5899         }
5900         if ((current_cp->eca_and_aen & SCP_SWP) !=
5901             (user_cp->eca_and_aen & SCP_SWP)) {
5902                 current_cp->eca_and_aen &= ~SCP_SWP;
5903                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5904                 saved_cp->eca_and_aen &= ~SCP_SWP;
5905                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5906                 set_ua = 1;
5907         }
5908         if (set_ua != 0)
5909                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5910         mtx_unlock(&lun->lun_lock);
5911
5912         return (0);
5913 }
5914
5915 int
5916 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5917                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5918 {
5919         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5920         struct ctl_lun *lun;
5921         int set_ua;
5922         uint32_t initidx;
5923
5924         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5925         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5926         set_ua = 0;
5927
5928         user_cp = (struct scsi_caching_page *)page_ptr;
5929         current_cp = (struct scsi_caching_page *)
5930                 (page_index->page_data + (page_index->page_len *
5931                 CTL_PAGE_CURRENT));
5932         saved_cp = (struct scsi_caching_page *)
5933                 (page_index->page_data + (page_index->page_len *
5934                 CTL_PAGE_SAVED));
5935
5936         mtx_lock(&lun->lun_lock);
5937         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5938             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5939                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5940                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5941                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5942                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5943                 set_ua = 1;
5944         }
5945         if (set_ua != 0)
5946                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5947         mtx_unlock(&lun->lun_lock);
5948
5949         return (0);
5950 }
5951
5952 int
5953 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5954                                 struct ctl_page_index *page_index,
5955                                 uint8_t *page_ptr)
5956 {
5957         uint8_t *c;
5958         int i;
5959
5960         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5961         ctl_time_io_secs =
5962                 (c[0] << 8) |
5963                 (c[1] << 0) |
5964                 0;
5965         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5966         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5967         printf("page data:");
5968         for (i=0; i<8; i++)
5969                 printf(" %.2x",page_ptr[i]);
5970         printf("\n");
5971         return (0);
5972 }
5973
5974 int
5975 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5976                                struct ctl_page_index *page_index,
5977                                int pc)
5978 {
5979         struct copan_debugconf_subpage *page;
5980
5981         page = (struct copan_debugconf_subpage *)page_index->page_data +
5982                 (page_index->page_len * pc);
5983
5984         switch (pc) {
5985         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5986         case SMS_PAGE_CTRL_DEFAULT >> 6:
5987         case SMS_PAGE_CTRL_SAVED >> 6:
5988                 /*
5989                  * We don't update the changable or default bits for this page.
5990                  */
5991                 break;
5992         case SMS_PAGE_CTRL_CURRENT >> 6:
5993                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5994                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5995                 break;
5996         default:
5997 #ifdef NEEDTOPORT
5998                 EPRINT(0, "Invalid PC %d!!", pc);
5999 #endif /* NEEDTOPORT */
6000                 break;
6001         }
6002         return (0);
6003 }
6004
6005
6006 static int
6007 ctl_do_mode_select(union ctl_io *io)
6008 {
6009         struct scsi_mode_page_header *page_header;
6010         struct ctl_page_index *page_index;
6011         struct ctl_scsiio *ctsio;
6012         int control_dev, page_len;
6013         int page_len_offset, page_len_size;
6014         union ctl_modepage_info *modepage_info;
6015         struct ctl_lun *lun;
6016         int *len_left, *len_used;
6017         int retval, i;
6018
6019         ctsio = &io->scsiio;
6020         page_index = NULL;
6021         page_len = 0;
6022         retval = CTL_RETVAL_COMPLETE;
6023
6024         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6025
6026         if (lun->be_lun->lun_type != T_DIRECT)
6027                 control_dev = 1;
6028         else
6029                 control_dev = 0;
6030
6031         modepage_info = (union ctl_modepage_info *)
6032                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6033         len_left = &modepage_info->header.len_left;
6034         len_used = &modepage_info->header.len_used;
6035
6036 do_next_page:
6037
6038         page_header = (struct scsi_mode_page_header *)
6039                 (ctsio->kern_data_ptr + *len_used);
6040
6041         if (*len_left == 0) {
6042                 free(ctsio->kern_data_ptr, M_CTL);
6043                 ctl_set_success(ctsio);
6044                 ctl_done((union ctl_io *)ctsio);
6045                 return (CTL_RETVAL_COMPLETE);
6046         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6047
6048                 free(ctsio->kern_data_ptr, M_CTL);
6049                 ctl_set_param_len_error(ctsio);
6050                 ctl_done((union ctl_io *)ctsio);
6051                 return (CTL_RETVAL_COMPLETE);
6052
6053         } else if ((page_header->page_code & SMPH_SPF)
6054                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6055
6056                 free(ctsio->kern_data_ptr, M_CTL);
6057                 ctl_set_param_len_error(ctsio);
6058                 ctl_done((union ctl_io *)ctsio);
6059                 return (CTL_RETVAL_COMPLETE);
6060         }
6061
6062
6063         /*
6064          * XXX KDM should we do something with the block descriptor?
6065          */
6066         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6067
6068                 if ((control_dev != 0)
6069                  && (lun->mode_pages.index[i].page_flags &
6070                      CTL_PAGE_FLAG_DISK_ONLY))
6071                         continue;
6072
6073                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6074                     (page_header->page_code & SMPH_PC_MASK))
6075                         continue;
6076
6077                 /*
6078                  * If neither page has a subpage code, then we've got a
6079                  * match.
6080                  */
6081                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6082                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6083                         page_index = &lun->mode_pages.index[i];
6084                         page_len = page_header->page_length;
6085                         break;
6086                 }
6087
6088                 /*
6089                  * If both pages have subpages, then the subpage numbers
6090                  * have to match.
6091                  */
6092                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6093                   && (page_header->page_code & SMPH_SPF)) {
6094                         struct scsi_mode_page_header_sp *sph;
6095
6096                         sph = (struct scsi_mode_page_header_sp *)page_header;
6097
6098                         if (lun->mode_pages.index[i].subpage ==
6099                             sph->subpage) {
6100                                 page_index = &lun->mode_pages.index[i];
6101                                 page_len = scsi_2btoul(sph->page_length);
6102                                 break;
6103                         }
6104                 }
6105         }
6106
6107         /*
6108          * If we couldn't find the page, or if we don't have a mode select
6109          * handler for it, send back an error to the user.
6110          */
6111         if ((page_index == NULL)
6112          || (page_index->select_handler == NULL)) {
6113                 ctl_set_invalid_field(ctsio,
6114                                       /*sks_valid*/ 1,
6115                                       /*command*/ 0,
6116                                       /*field*/ *len_used,
6117                                       /*bit_valid*/ 0,
6118                                       /*bit*/ 0);
6119                 free(ctsio->kern_data_ptr, M_CTL);
6120                 ctl_done((union ctl_io *)ctsio);
6121                 return (CTL_RETVAL_COMPLETE);
6122         }
6123
6124         if (page_index->page_code & SMPH_SPF) {
6125                 page_len_offset = 2;
6126                 page_len_size = 2;
6127         } else {
6128                 page_len_size = 1;
6129                 page_len_offset = 1;
6130         }
6131
6132         /*
6133          * If the length the initiator gives us isn't the one we specify in
6134          * the mode page header, or if they didn't specify enough data in
6135          * the CDB to avoid truncating this page, kick out the request.
6136          */
6137         if ((page_len != (page_index->page_len - page_len_offset -
6138                           page_len_size))
6139          || (*len_left < page_index->page_len)) {
6140
6141
6142                 ctl_set_invalid_field(ctsio,
6143                                       /*sks_valid*/ 1,
6144                                       /*command*/ 0,
6145                                       /*field*/ *len_used + page_len_offset,
6146                                       /*bit_valid*/ 0,
6147                                       /*bit*/ 0);
6148                 free(ctsio->kern_data_ptr, M_CTL);
6149                 ctl_done((union ctl_io *)ctsio);
6150                 return (CTL_RETVAL_COMPLETE);
6151         }
6152
6153         /*
6154          * Run through the mode page, checking to make sure that the bits
6155          * the user changed are actually legal for him to change.
6156          */
6157         for (i = 0; i < page_index->page_len; i++) {
6158                 uint8_t *user_byte, *change_mask, *current_byte;
6159                 int bad_bit;
6160                 int j;
6161
6162                 user_byte = (uint8_t *)page_header + i;
6163                 change_mask = page_index->page_data +
6164                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6165                 current_byte = page_index->page_data +
6166                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6167
6168                 /*
6169                  * Check to see whether the user set any bits in this byte
6170                  * that he is not allowed to set.
6171                  */
6172                 if ((*user_byte & ~(*change_mask)) ==
6173                     (*current_byte & ~(*change_mask)))
6174                         continue;
6175
6176                 /*
6177                  * Go through bit by bit to determine which one is illegal.
6178                  */
6179                 bad_bit = 0;
6180                 for (j = 7; j >= 0; j--) {
6181                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6182                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6183                                 bad_bit = i;
6184                                 break;
6185                         }
6186                 }
6187                 ctl_set_invalid_field(ctsio,
6188                                       /*sks_valid*/ 1,
6189                                       /*command*/ 0,
6190                                       /*field*/ *len_used + i,
6191                                       /*bit_valid*/ 1,
6192                                       /*bit*/ bad_bit);
6193                 free(ctsio->kern_data_ptr, M_CTL);
6194                 ctl_done((union ctl_io *)ctsio);
6195                 return (CTL_RETVAL_COMPLETE);
6196         }
6197
6198         /*
6199          * Decrement these before we call the page handler, since we may
6200          * end up getting called back one way or another before the handler
6201          * returns to this context.
6202          */
6203         *len_left -= page_index->page_len;
6204         *len_used += page_index->page_len;
6205
6206         retval = page_index->select_handler(ctsio, page_index,
6207                                             (uint8_t *)page_header);
6208
6209         /*
6210          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6211          * wait until this queued command completes to finish processing
6212          * the mode page.  If it returns anything other than
6213          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6214          * already set the sense information, freed the data pointer, and
6215          * completed the io for us.
6216          */
6217         if (retval != CTL_RETVAL_COMPLETE)
6218                 goto bailout_no_done;
6219
6220         /*
6221          * If the initiator sent us more than one page, parse the next one.
6222          */
6223         if (*len_left > 0)
6224                 goto do_next_page;
6225
6226         ctl_set_success(ctsio);
6227         free(ctsio->kern_data_ptr, M_CTL);
6228         ctl_done((union ctl_io *)ctsio);
6229
6230 bailout_no_done:
6231
6232         return (CTL_RETVAL_COMPLETE);
6233
6234 }
6235
6236 int
6237 ctl_mode_select(struct ctl_scsiio *ctsio)
6238 {
6239         int param_len, pf, sp;
6240         int header_size, bd_len;
6241         int len_left, len_used;
6242         struct ctl_page_index *page_index;
6243         struct ctl_lun *lun;
6244         int control_dev, page_len;
6245         union ctl_modepage_info *modepage_info;
6246         int retval;
6247
6248         pf = 0;
6249         sp = 0;
6250         page_len = 0;
6251         len_used = 0;
6252         len_left = 0;
6253         retval = 0;
6254         bd_len = 0;
6255         page_index = NULL;
6256
6257         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6258
6259         if (lun->be_lun->lun_type != T_DIRECT)
6260                 control_dev = 1;
6261         else
6262                 control_dev = 0;
6263
6264         switch (ctsio->cdb[0]) {
6265         case MODE_SELECT_6: {
6266                 struct scsi_mode_select_6 *cdb;
6267
6268                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6269
6270                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6271                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6272
6273                 param_len = cdb->length;
6274                 header_size = sizeof(struct scsi_mode_header_6);
6275                 break;
6276         }
6277         case MODE_SELECT_10: {
6278                 struct scsi_mode_select_10 *cdb;
6279
6280                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6281
6282                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6283                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6284
6285                 param_len = scsi_2btoul(cdb->length);
6286                 header_size = sizeof(struct scsi_mode_header_10);
6287                 break;
6288         }
6289         default:
6290                 ctl_set_invalid_opcode(ctsio);
6291                 ctl_done((union ctl_io *)ctsio);
6292                 return (CTL_RETVAL_COMPLETE);
6293                 break; /* NOTREACHED */
6294         }
6295
6296         /*
6297          * From SPC-3:
6298          * "A parameter list length of zero indicates that the Data-Out Buffer
6299          * shall be empty. This condition shall not be considered as an error."
6300          */
6301         if (param_len == 0) {
6302                 ctl_set_success(ctsio);
6303                 ctl_done((union ctl_io *)ctsio);
6304                 return (CTL_RETVAL_COMPLETE);
6305         }
6306
6307         /*
6308          * Since we'll hit this the first time through, prior to
6309          * allocation, we don't need to free a data buffer here.
6310          */
6311         if (param_len < header_size) {
6312                 ctl_set_param_len_error(ctsio);
6313                 ctl_done((union ctl_io *)ctsio);
6314                 return (CTL_RETVAL_COMPLETE);
6315         }
6316
6317         /*
6318          * Allocate the data buffer and grab the user's data.  In theory,
6319          * we shouldn't have to sanity check the parameter list length here
6320          * because the maximum size is 64K.  We should be able to malloc
6321          * that much without too many problems.
6322          */
6323         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6324                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6325                 ctsio->kern_data_len = param_len;
6326                 ctsio->kern_total_len = param_len;
6327                 ctsio->kern_data_resid = 0;
6328                 ctsio->kern_rel_offset = 0;
6329                 ctsio->kern_sg_entries = 0;
6330                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6331                 ctsio->be_move_done = ctl_config_move_done;
6332                 ctl_datamove((union ctl_io *)ctsio);
6333
6334                 return (CTL_RETVAL_COMPLETE);
6335         }
6336
6337         switch (ctsio->cdb[0]) {
6338         case MODE_SELECT_6: {
6339                 struct scsi_mode_header_6 *mh6;
6340
6341                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6342                 bd_len = mh6->blk_desc_len;
6343                 break;
6344         }
6345         case MODE_SELECT_10: {
6346                 struct scsi_mode_header_10 *mh10;
6347
6348                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6349                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6350                 break;
6351         }
6352         default:
6353                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6354                 break;
6355         }
6356
6357         if (param_len < (header_size + bd_len)) {
6358                 free(ctsio->kern_data_ptr, M_CTL);
6359                 ctl_set_param_len_error(ctsio);
6360                 ctl_done((union ctl_io *)ctsio);
6361                 return (CTL_RETVAL_COMPLETE);
6362         }
6363
6364         /*
6365          * Set the IO_CONT flag, so that if this I/O gets passed to
6366          * ctl_config_write_done(), it'll get passed back to
6367          * ctl_do_mode_select() for further processing, or completion if
6368          * we're all done.
6369          */
6370         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6371         ctsio->io_cont = ctl_do_mode_select;
6372
6373         modepage_info = (union ctl_modepage_info *)
6374                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6375
6376         memset(modepage_info, 0, sizeof(*modepage_info));
6377
6378         len_left = param_len - header_size - bd_len;
6379         len_used = header_size + bd_len;
6380
6381         modepage_info->header.len_left = len_left;
6382         modepage_info->header.len_used = len_used;
6383
6384         return (ctl_do_mode_select((union ctl_io *)ctsio));
6385 }
6386
6387 int
6388 ctl_mode_sense(struct ctl_scsiio *ctsio)
6389 {
6390         struct ctl_lun *lun;
6391         int pc, page_code, dbd, llba, subpage;
6392         int alloc_len, page_len, header_len, total_len;
6393         struct scsi_mode_block_descr *block_desc;
6394         struct ctl_page_index *page_index;
6395         int control_dev;
6396
6397         dbd = 0;
6398         llba = 0;
6399         block_desc = NULL;
6400         page_index = NULL;
6401
6402         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6403
6404         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6405
6406         if (lun->be_lun->lun_type != T_DIRECT)
6407                 control_dev = 1;
6408         else
6409                 control_dev = 0;
6410
6411         switch (ctsio->cdb[0]) {
6412         case MODE_SENSE_6: {
6413                 struct scsi_mode_sense_6 *cdb;
6414
6415                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6416
6417                 header_len = sizeof(struct scsi_mode_hdr_6);
6418                 if (cdb->byte2 & SMS_DBD)
6419                         dbd = 1;
6420                 else
6421                         header_len += sizeof(struct scsi_mode_block_descr);
6422
6423                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6424                 page_code = cdb->page & SMS_PAGE_CODE;
6425                 subpage = cdb->subpage;
6426                 alloc_len = cdb->length;
6427                 break;
6428         }
6429         case MODE_SENSE_10: {
6430                 struct scsi_mode_sense_10 *cdb;
6431
6432                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6433
6434                 header_len = sizeof(struct scsi_mode_hdr_10);
6435
6436                 if (cdb->byte2 & SMS_DBD)
6437                         dbd = 1;
6438                 else
6439                         header_len += sizeof(struct scsi_mode_block_descr);
6440                 if (cdb->byte2 & SMS10_LLBAA)
6441                         llba = 1;
6442                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6443                 page_code = cdb->page & SMS_PAGE_CODE;
6444                 subpage = cdb->subpage;
6445                 alloc_len = scsi_2btoul(cdb->length);
6446                 break;
6447         }
6448         default:
6449                 ctl_set_invalid_opcode(ctsio);
6450                 ctl_done((union ctl_io *)ctsio);
6451                 return (CTL_RETVAL_COMPLETE);
6452                 break; /* NOTREACHED */
6453         }
6454
6455         /*
6456          * We have to make a first pass through to calculate the size of
6457          * the pages that match the user's query.  Then we allocate enough
6458          * memory to hold it, and actually copy the data into the buffer.
6459          */
6460         switch (page_code) {
6461         case SMS_ALL_PAGES_PAGE: {
6462                 int i;
6463
6464                 page_len = 0;
6465
6466                 /*
6467                  * At the moment, values other than 0 and 0xff here are
6468                  * reserved according to SPC-3.
6469                  */
6470                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6471                  && (subpage != SMS_SUBPAGE_ALL)) {
6472                         ctl_set_invalid_field(ctsio,
6473                                               /*sks_valid*/ 1,
6474                                               /*command*/ 1,
6475                                               /*field*/ 3,
6476                                               /*bit_valid*/ 0,
6477                                               /*bit*/ 0);
6478                         ctl_done((union ctl_io *)ctsio);
6479                         return (CTL_RETVAL_COMPLETE);
6480                 }
6481
6482                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6483                         if ((control_dev != 0)
6484                          && (lun->mode_pages.index[i].page_flags &
6485                              CTL_PAGE_FLAG_DISK_ONLY))
6486                                 continue;
6487
6488                         /*
6489                          * We don't use this subpage if the user didn't
6490                          * request all subpages.
6491                          */
6492                         if ((lun->mode_pages.index[i].subpage != 0)
6493                          && (subpage == SMS_SUBPAGE_PAGE_0))
6494                                 continue;
6495
6496 #if 0
6497                         printf("found page %#x len %d\n",
6498                                lun->mode_pages.index[i].page_code &
6499                                SMPH_PC_MASK,
6500                                lun->mode_pages.index[i].page_len);
6501 #endif
6502                         page_len += lun->mode_pages.index[i].page_len;
6503                 }
6504                 break;
6505         }
6506         default: {
6507                 int i;
6508
6509                 page_len = 0;
6510
6511                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6512                         /* Look for the right page code */
6513                         if ((lun->mode_pages.index[i].page_code &
6514                              SMPH_PC_MASK) != page_code)
6515                                 continue;
6516
6517                         /* Look for the right subpage or the subpage wildcard*/
6518                         if ((lun->mode_pages.index[i].subpage != subpage)
6519                          && (subpage != SMS_SUBPAGE_ALL))
6520                                 continue;
6521
6522                         /* Make sure the page is supported for this dev type */
6523                         if ((control_dev != 0)
6524                          && (lun->mode_pages.index[i].page_flags &
6525                              CTL_PAGE_FLAG_DISK_ONLY))
6526                                 continue;
6527
6528 #if 0
6529                         printf("found page %#x len %d\n",
6530                                lun->mode_pages.index[i].page_code &
6531                                SMPH_PC_MASK,
6532                                lun->mode_pages.index[i].page_len);
6533 #endif
6534
6535                         page_len += lun->mode_pages.index[i].page_len;
6536                 }
6537
6538                 if (page_len == 0) {
6539                         ctl_set_invalid_field(ctsio,
6540                                               /*sks_valid*/ 1,
6541                                               /*command*/ 1,
6542                                               /*field*/ 2,
6543                                               /*bit_valid*/ 1,
6544                                               /*bit*/ 5);
6545                         ctl_done((union ctl_io *)ctsio);
6546                         return (CTL_RETVAL_COMPLETE);
6547                 }
6548                 break;
6549         }
6550         }
6551
6552         total_len = header_len + page_len;
6553 #if 0
6554         printf("header_len = %d, page_len = %d, total_len = %d\n",
6555                header_len, page_len, total_len);
6556 #endif
6557
6558         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6559         ctsio->kern_sg_entries = 0;
6560         ctsio->kern_data_resid = 0;
6561         ctsio->kern_rel_offset = 0;
6562         if (total_len < alloc_len) {
6563                 ctsio->residual = alloc_len - total_len;
6564                 ctsio->kern_data_len = total_len;
6565                 ctsio->kern_total_len = total_len;
6566         } else {
6567                 ctsio->residual = 0;
6568                 ctsio->kern_data_len = alloc_len;
6569                 ctsio->kern_total_len = alloc_len;
6570         }
6571
6572         switch (ctsio->cdb[0]) {
6573         case MODE_SENSE_6: {
6574                 struct scsi_mode_hdr_6 *header;
6575
6576                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6577
6578                 header->datalen = MIN(total_len - 1, 254);
6579                 if (control_dev == 0) {
6580                         header->dev_specific = 0x10; /* DPOFUA */
6581                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6582                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6583                             .eca_and_aen & SCP_SWP) != 0)
6584                                     header->dev_specific |= 0x80; /* WP */
6585                 }
6586                 if (dbd)
6587                         header->block_descr_len = 0;
6588                 else
6589                         header->block_descr_len =
6590                                 sizeof(struct scsi_mode_block_descr);
6591                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6592                 break;
6593         }
6594         case MODE_SENSE_10: {
6595                 struct scsi_mode_hdr_10 *header;
6596                 int datalen;
6597
6598                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6599
6600                 datalen = MIN(total_len - 2, 65533);
6601                 scsi_ulto2b(datalen, header->datalen);
6602                 if (control_dev == 0) {
6603                         header->dev_specific = 0x10; /* DPOFUA */
6604                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6605                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6606                             .eca_and_aen & SCP_SWP) != 0)
6607                                     header->dev_specific |= 0x80; /* WP */
6608                 }
6609                 if (dbd)
6610                         scsi_ulto2b(0, header->block_descr_len);
6611                 else
6612                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6613                                     header->block_descr_len);
6614                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6615                 break;
6616         }
6617         default:
6618                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6619                 break; /* NOTREACHED */
6620         }
6621
6622         /*
6623          * If we've got a disk, use its blocksize in the block
6624          * descriptor.  Otherwise, just set it to 0.
6625          */
6626         if (dbd == 0) {
6627                 if (control_dev == 0)
6628                         scsi_ulto3b(lun->be_lun->blocksize,
6629                                     block_desc->block_len);
6630                 else
6631                         scsi_ulto3b(0, block_desc->block_len);
6632         }
6633
6634         switch (page_code) {
6635         case SMS_ALL_PAGES_PAGE: {
6636                 int i, data_used;
6637
6638                 data_used = header_len;
6639                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6640                         struct ctl_page_index *page_index;
6641
6642                         page_index = &lun->mode_pages.index[i];
6643
6644                         if ((control_dev != 0)
6645                          && (page_index->page_flags &
6646                             CTL_PAGE_FLAG_DISK_ONLY))
6647                                 continue;
6648
6649                         /*
6650                          * We don't use this subpage if the user didn't
6651                          * request all subpages.  We already checked (above)
6652                          * to make sure the user only specified a subpage
6653                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6654                          */
6655                         if ((page_index->subpage != 0)
6656                          && (subpage == SMS_SUBPAGE_PAGE_0))
6657                                 continue;
6658
6659                         /*
6660                          * Call the handler, if it exists, to update the
6661                          * page to the latest values.
6662                          */
6663                         if (page_index->sense_handler != NULL)
6664                                 page_index->sense_handler(ctsio, page_index,pc);
6665
6666                         memcpy(ctsio->kern_data_ptr + data_used,
6667                                page_index->page_data +
6668                                (page_index->page_len * pc),
6669                                page_index->page_len);
6670                         data_used += page_index->page_len;
6671                 }
6672                 break;
6673         }
6674         default: {
6675                 int i, data_used;
6676
6677                 data_used = header_len;
6678
6679                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6680                         struct ctl_page_index *page_index;
6681
6682                         page_index = &lun->mode_pages.index[i];
6683
6684                         /* Look for the right page code */
6685                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6686                                 continue;
6687
6688                         /* Look for the right subpage or the subpage wildcard*/
6689                         if ((page_index->subpage != subpage)
6690                          && (subpage != SMS_SUBPAGE_ALL))
6691                                 continue;
6692
6693                         /* Make sure the page is supported for this dev type */
6694                         if ((control_dev != 0)
6695                          && (page_index->page_flags &
6696                              CTL_PAGE_FLAG_DISK_ONLY))
6697                                 continue;
6698
6699                         /*
6700                          * Call the handler, if it exists, to update the
6701                          * page to the latest values.
6702                          */
6703                         if (page_index->sense_handler != NULL)
6704                                 page_index->sense_handler(ctsio, page_index,pc);
6705
6706                         memcpy(ctsio->kern_data_ptr + data_used,
6707                                page_index->page_data +
6708                                (page_index->page_len * pc),
6709                                page_index->page_len);
6710                         data_used += page_index->page_len;
6711                 }
6712                 break;
6713         }
6714         }
6715
6716         ctl_set_success(ctsio);
6717         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6718         ctsio->be_move_done = ctl_config_move_done;
6719         ctl_datamove((union ctl_io *)ctsio);
6720         return (CTL_RETVAL_COMPLETE);
6721 }
6722
6723 int
6724 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6725                                struct ctl_page_index *page_index,
6726                                int pc)
6727 {
6728         struct ctl_lun *lun;
6729         struct scsi_log_param_header *phdr;
6730         uint8_t *data;
6731         uint64_t val;
6732
6733         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6734         data = page_index->page_data;
6735
6736         if (lun->backend->lun_attr != NULL &&
6737             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6738              != UINT64_MAX) {
6739                 phdr = (struct scsi_log_param_header *)data;
6740                 scsi_ulto2b(0x0001, phdr->param_code);
6741                 phdr->param_control = SLP_LBIN | SLP_LP;
6742                 phdr->param_len = 8;
6743                 data = (uint8_t *)(phdr + 1);
6744                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6745                 data[4] = 0x02; /* per-pool */
6746                 data += phdr->param_len;
6747         }
6748
6749         if (lun->backend->lun_attr != NULL &&
6750             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6751              != UINT64_MAX) {
6752                 phdr = (struct scsi_log_param_header *)data;
6753                 scsi_ulto2b(0x0002, phdr->param_code);
6754                 phdr->param_control = SLP_LBIN | SLP_LP;
6755                 phdr->param_len = 8;
6756                 data = (uint8_t *)(phdr + 1);
6757                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6758                 data[4] = 0x01; /* per-LUN */
6759                 data += phdr->param_len;
6760         }
6761
6762         if (lun->backend->lun_attr != NULL &&
6763             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6764              != UINT64_MAX) {
6765                 phdr = (struct scsi_log_param_header *)data;
6766                 scsi_ulto2b(0x00f1, phdr->param_code);
6767                 phdr->param_control = SLP_LBIN | SLP_LP;
6768                 phdr->param_len = 8;
6769                 data = (uint8_t *)(phdr + 1);
6770                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6771                 data[4] = 0x02; /* per-pool */
6772                 data += phdr->param_len;
6773         }
6774
6775         if (lun->backend->lun_attr != NULL &&
6776             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6777              != UINT64_MAX) {
6778                 phdr = (struct scsi_log_param_header *)data;
6779                 scsi_ulto2b(0x00f2, phdr->param_code);
6780                 phdr->param_control = SLP_LBIN | SLP_LP;
6781                 phdr->param_len = 8;
6782                 data = (uint8_t *)(phdr + 1);
6783                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6784                 data[4] = 0x02; /* per-pool */
6785                 data += phdr->param_len;
6786         }
6787
6788         page_index->page_len = data - page_index->page_data;
6789         return (0);
6790 }
6791
6792 int
6793 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6794                                struct ctl_page_index *page_index,
6795                                int pc)
6796 {
6797         struct ctl_lun *lun;
6798         struct stat_page *data;
6799         uint64_t rn, wn, rb, wb;
6800         struct bintime rt, wt;
6801         int i;
6802
6803         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6804         data = (struct stat_page *)page_index->page_data;
6805
6806         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6807         data->sap.hdr.param_control = SLP_LBIN;
6808         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6809             sizeof(struct scsi_log_param_header);
6810         rn = wn = rb = wb = 0;
6811         bintime_clear(&rt);
6812         bintime_clear(&wt);
6813         for (i = 0; i < CTL_MAX_PORTS; i++) {
6814                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6815                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6816                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6817                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6818                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6819                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6820         }
6821         scsi_u64to8b(rn, data->sap.read_num);
6822         scsi_u64to8b(wn, data->sap.write_num);
6823         if (lun->stats.blocksize > 0) {
6824                 scsi_u64to8b(wb / lun->stats.blocksize,
6825                     data->sap.recvieved_lba);
6826                 scsi_u64to8b(rb / lun->stats.blocksize,
6827                     data->sap.transmitted_lba);
6828         }
6829         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6830             data->sap.read_int);
6831         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6832             data->sap.write_int);
6833         scsi_u64to8b(0, data->sap.weighted_num);
6834         scsi_u64to8b(0, data->sap.weighted_int);
6835         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6836         data->it.hdr.param_control = SLP_LBIN;
6837         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6838             sizeof(struct scsi_log_param_header);
6839 #ifdef CTL_TIME_IO
6840         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6841 #endif
6842         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6843         data->it.hdr.param_control = SLP_LBIN;
6844         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6845             sizeof(struct scsi_log_param_header);
6846         scsi_ulto4b(3, data->ti.exponent);
6847         scsi_ulto4b(1, data->ti.integer);
6848
6849         page_index->page_len = sizeof(*data);
6850         return (0);
6851 }
6852
6853 int
6854 ctl_log_sense(struct ctl_scsiio *ctsio)
6855 {
6856         struct ctl_lun *lun;
6857         int i, pc, page_code, subpage;
6858         int alloc_len, total_len;
6859         struct ctl_page_index *page_index;
6860         struct scsi_log_sense *cdb;
6861         struct scsi_log_header *header;
6862
6863         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6864
6865         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6866         cdb = (struct scsi_log_sense *)ctsio->cdb;
6867         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6868         page_code = cdb->page & SLS_PAGE_CODE;
6869         subpage = cdb->subpage;
6870         alloc_len = scsi_2btoul(cdb->length);
6871
6872         page_index = NULL;
6873         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6874                 page_index = &lun->log_pages.index[i];
6875
6876                 /* Look for the right page code */
6877                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6878                         continue;
6879
6880                 /* Look for the right subpage or the subpage wildcard*/
6881                 if (page_index->subpage != subpage)
6882                         continue;
6883
6884                 break;
6885         }
6886         if (i >= CTL_NUM_LOG_PAGES) {
6887                 ctl_set_invalid_field(ctsio,
6888                                       /*sks_valid*/ 1,
6889                                       /*command*/ 1,
6890                                       /*field*/ 2,
6891                                       /*bit_valid*/ 0,
6892                                       /*bit*/ 0);
6893                 ctl_done((union ctl_io *)ctsio);
6894                 return (CTL_RETVAL_COMPLETE);
6895         }
6896
6897         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6898
6899         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6900         ctsio->kern_sg_entries = 0;
6901         ctsio->kern_data_resid = 0;
6902         ctsio->kern_rel_offset = 0;
6903         if (total_len < alloc_len) {
6904                 ctsio->residual = alloc_len - total_len;
6905                 ctsio->kern_data_len = total_len;
6906                 ctsio->kern_total_len = total_len;
6907         } else {
6908                 ctsio->residual = 0;
6909                 ctsio->kern_data_len = alloc_len;
6910                 ctsio->kern_total_len = alloc_len;
6911         }
6912
6913         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6914         header->page = page_index->page_code;
6915         if (page_index->subpage) {
6916                 header->page |= SL_SPF;
6917                 header->subpage = page_index->subpage;
6918         }
6919         scsi_ulto2b(page_index->page_len, header->datalen);
6920
6921         /*
6922          * Call the handler, if it exists, to update the
6923          * page to the latest values.
6924          */
6925         if (page_index->sense_handler != NULL)
6926                 page_index->sense_handler(ctsio, page_index, pc);
6927
6928         memcpy(header + 1, page_index->page_data, page_index->page_len);
6929
6930         ctl_set_success(ctsio);
6931         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6932         ctsio->be_move_done = ctl_config_move_done;
6933         ctl_datamove((union ctl_io *)ctsio);
6934         return (CTL_RETVAL_COMPLETE);
6935 }
6936
6937 int
6938 ctl_read_capacity(struct ctl_scsiio *ctsio)
6939 {
6940         struct scsi_read_capacity *cdb;
6941         struct scsi_read_capacity_data *data;
6942         struct ctl_lun *lun;
6943         uint32_t lba;
6944
6945         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6946
6947         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6948
6949         lba = scsi_4btoul(cdb->addr);
6950         if (((cdb->pmi & SRC_PMI) == 0)
6951          && (lba != 0)) {
6952                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6953                                       /*sks_valid*/ 1,
6954                                       /*command*/ 1,
6955                                       /*field*/ 2,
6956                                       /*bit_valid*/ 0,
6957                                       /*bit*/ 0);
6958                 ctl_done((union ctl_io *)ctsio);
6959                 return (CTL_RETVAL_COMPLETE);
6960         }
6961
6962         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6963
6964         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6965         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6966         ctsio->residual = 0;
6967         ctsio->kern_data_len = sizeof(*data);
6968         ctsio->kern_total_len = sizeof(*data);
6969         ctsio->kern_data_resid = 0;
6970         ctsio->kern_rel_offset = 0;
6971         ctsio->kern_sg_entries = 0;
6972
6973         /*
6974          * If the maximum LBA is greater than 0xfffffffe, the user must
6975          * issue a SERVICE ACTION IN (16) command, with the read capacity
6976          * serivce action set.
6977          */
6978         if (lun->be_lun->maxlba > 0xfffffffe)
6979                 scsi_ulto4b(0xffffffff, data->addr);
6980         else
6981                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6982
6983         /*
6984          * XXX KDM this may not be 512 bytes...
6985          */
6986         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6987
6988         ctl_set_success(ctsio);
6989         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6990         ctsio->be_move_done = ctl_config_move_done;
6991         ctl_datamove((union ctl_io *)ctsio);
6992         return (CTL_RETVAL_COMPLETE);
6993 }
6994
6995 int
6996 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6997 {
6998         struct scsi_read_capacity_16 *cdb;
6999         struct scsi_read_capacity_data_long *data;
7000         struct ctl_lun *lun;
7001         uint64_t lba;
7002         uint32_t alloc_len;
7003
7004         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7005
7006         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7007
7008         alloc_len = scsi_4btoul(cdb->alloc_len);
7009         lba = scsi_8btou64(cdb->addr);
7010
7011         if ((cdb->reladr & SRC16_PMI)
7012          && (lba != 0)) {
7013                 ctl_set_invalid_field(/*ctsio*/ 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         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7024
7025         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7026         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7027
7028         if (sizeof(*data) < alloc_len) {
7029                 ctsio->residual = alloc_len - sizeof(*data);
7030                 ctsio->kern_data_len = sizeof(*data);
7031                 ctsio->kern_total_len = sizeof(*data);
7032         } else {
7033                 ctsio->residual = 0;
7034                 ctsio->kern_data_len = alloc_len;
7035                 ctsio->kern_total_len = alloc_len;
7036         }
7037         ctsio->kern_data_resid = 0;
7038         ctsio->kern_rel_offset = 0;
7039         ctsio->kern_sg_entries = 0;
7040
7041         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7042         /* XXX KDM this may not be 512 bytes... */
7043         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7044         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7045         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7046         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7047                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7048
7049         ctl_set_success(ctsio);
7050         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7051         ctsio->be_move_done = ctl_config_move_done;
7052         ctl_datamove((union ctl_io *)ctsio);
7053         return (CTL_RETVAL_COMPLETE);
7054 }
7055
7056 int
7057 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7058 {
7059         struct scsi_get_lba_status *cdb;
7060         struct scsi_get_lba_status_data *data;
7061         struct ctl_lun *lun;
7062         struct ctl_lba_len_flags *lbalen;
7063         uint64_t lba;
7064         uint32_t alloc_len, total_len;
7065         int retval;
7066
7067         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7068
7069         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7070         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7071         lba = scsi_8btou64(cdb->addr);
7072         alloc_len = scsi_4btoul(cdb->alloc_len);
7073
7074         if (lba > lun->be_lun->maxlba) {
7075                 ctl_set_lba_out_of_range(ctsio);
7076                 ctl_done((union ctl_io *)ctsio);
7077                 return (CTL_RETVAL_COMPLETE);
7078         }
7079
7080         total_len = sizeof(*data) + sizeof(data->descr[0]);
7081         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7082         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7083
7084         if (total_len < alloc_len) {
7085                 ctsio->residual = alloc_len - total_len;
7086                 ctsio->kern_data_len = total_len;
7087                 ctsio->kern_total_len = total_len;
7088         } else {
7089                 ctsio->residual = 0;
7090                 ctsio->kern_data_len = alloc_len;
7091                 ctsio->kern_total_len = alloc_len;
7092         }
7093         ctsio->kern_data_resid = 0;
7094         ctsio->kern_rel_offset = 0;
7095         ctsio->kern_sg_entries = 0;
7096
7097         /* Fill dummy data in case backend can't tell anything. */
7098         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7099         scsi_u64to8b(lba, data->descr[0].addr);
7100         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7101             data->descr[0].length);
7102         data->descr[0].status = 0; /* Mapped or unknown. */
7103
7104         ctl_set_success(ctsio);
7105         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7106         ctsio->be_move_done = ctl_config_move_done;
7107
7108         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7109         lbalen->lba = lba;
7110         lbalen->len = total_len;
7111         lbalen->flags = 0;
7112         retval = lun->backend->config_read((union ctl_io *)ctsio);
7113         return (CTL_RETVAL_COMPLETE);
7114 }
7115
7116 int
7117 ctl_read_defect(struct ctl_scsiio *ctsio)
7118 {
7119         struct scsi_read_defect_data_10 *ccb10;
7120         struct scsi_read_defect_data_12 *ccb12;
7121         struct scsi_read_defect_data_hdr_10 *data10;
7122         struct scsi_read_defect_data_hdr_12 *data12;
7123         uint32_t alloc_len, data_len;
7124         uint8_t format;
7125
7126         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7127
7128         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7129                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7130                 format = ccb10->format;
7131                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7132                 data_len = sizeof(*data10);
7133         } else {
7134                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7135                 format = ccb12->format;
7136                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7137                 data_len = sizeof(*data12);
7138         }
7139         if (alloc_len == 0) {
7140                 ctl_set_success(ctsio);
7141                 ctl_done((union ctl_io *)ctsio);
7142                 return (CTL_RETVAL_COMPLETE);
7143         }
7144
7145         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7146         if (data_len < alloc_len) {
7147                 ctsio->residual = alloc_len - data_len;
7148                 ctsio->kern_data_len = data_len;
7149                 ctsio->kern_total_len = data_len;
7150         } else {
7151                 ctsio->residual = 0;
7152                 ctsio->kern_data_len = alloc_len;
7153                 ctsio->kern_total_len = alloc_len;
7154         }
7155         ctsio->kern_data_resid = 0;
7156         ctsio->kern_rel_offset = 0;
7157         ctsio->kern_sg_entries = 0;
7158
7159         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7160                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7161                     ctsio->kern_data_ptr;
7162                 data10->format = format;
7163                 scsi_ulto2b(0, data10->length);
7164         } else {
7165                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7166                     ctsio->kern_data_ptr;
7167                 data12->format = format;
7168                 scsi_ulto2b(0, data12->generation);
7169                 scsi_ulto4b(0, data12->length);
7170         }
7171
7172         ctl_set_success(ctsio);
7173         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7174         ctsio->be_move_done = ctl_config_move_done;
7175         ctl_datamove((union ctl_io *)ctsio);
7176         return (CTL_RETVAL_COMPLETE);
7177 }
7178
7179 int
7180 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7181 {
7182         struct scsi_maintenance_in *cdb;
7183         int retval;
7184         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7185         int num_target_port_groups, num_target_ports;
7186         struct ctl_lun *lun;
7187         struct ctl_softc *softc;
7188         struct ctl_port *port;
7189         struct scsi_target_group_data *rtg_ptr;
7190         struct scsi_target_group_data_extended *rtg_ext_ptr;
7191         struct scsi_target_port_group_descriptor *tpg_desc;
7192
7193         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7194
7195         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7196         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7197         softc = lun->ctl_softc;
7198
7199         retval = CTL_RETVAL_COMPLETE;
7200
7201         switch (cdb->byte2 & STG_PDF_MASK) {
7202         case STG_PDF_LENGTH:
7203                 ext = 0;
7204                 break;
7205         case STG_PDF_EXTENDED:
7206                 ext = 1;
7207                 break;
7208         default:
7209                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7210                                       /*sks_valid*/ 1,
7211                                       /*command*/ 1,
7212                                       /*field*/ 2,
7213                                       /*bit_valid*/ 1,
7214                                       /*bit*/ 5);
7215                 ctl_done((union ctl_io *)ctsio);
7216                 return(retval);
7217         }
7218
7219         if (softc->is_single)
7220                 num_target_port_groups = 1;
7221         else
7222                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7223         num_target_ports = 0;
7224         mtx_lock(&softc->ctl_lock);
7225         STAILQ_FOREACH(port, &softc->port_list, links) {
7226                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7227                         continue;
7228                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7229                         continue;
7230                 num_target_ports++;
7231         }
7232         mtx_unlock(&softc->ctl_lock);
7233
7234         if (ext)
7235                 total_len = sizeof(struct scsi_target_group_data_extended);
7236         else
7237                 total_len = sizeof(struct scsi_target_group_data);
7238         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7239                 num_target_port_groups +
7240             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7241
7242         alloc_len = scsi_4btoul(cdb->length);
7243
7244         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7245
7246         ctsio->kern_sg_entries = 0;
7247
7248         if (total_len < alloc_len) {
7249                 ctsio->residual = alloc_len - total_len;
7250                 ctsio->kern_data_len = total_len;
7251                 ctsio->kern_total_len = total_len;
7252         } else {
7253                 ctsio->residual = 0;
7254                 ctsio->kern_data_len = alloc_len;
7255                 ctsio->kern_total_len = alloc_len;
7256         }
7257         ctsio->kern_data_resid = 0;
7258         ctsio->kern_rel_offset = 0;
7259
7260         if (ext) {
7261                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7262                     ctsio->kern_data_ptr;
7263                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7264                 rtg_ext_ptr->format_type = 0x10;
7265                 rtg_ext_ptr->implicit_transition_time = 0;
7266                 tpg_desc = &rtg_ext_ptr->groups[0];
7267         } else {
7268                 rtg_ptr = (struct scsi_target_group_data *)
7269                     ctsio->kern_data_ptr;
7270                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7271                 tpg_desc = &rtg_ptr->groups[0];
7272         }
7273
7274         mtx_lock(&softc->ctl_lock);
7275         pg = softc->port_min / softc->port_cnt;
7276         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7277                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7278         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7279                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7280         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7281                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7282         else
7283                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7284         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7285                 os = gs;
7286                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7287         } else
7288                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7289         for (g = 0; g < num_target_port_groups; g++) {
7290                 tpg_desc->pref_state = (g == pg) ? gs : os;
7291                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7292                     TPG_U_SUP | TPG_T_SUP;
7293                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7294                 tpg_desc->status = TPG_IMPLICIT;
7295                 pc = 0;
7296                 STAILQ_FOREACH(port, &softc->port_list, links) {
7297                         if (port->targ_port < g * softc->port_cnt ||
7298                             port->targ_port >= (g + 1) * softc->port_cnt)
7299                                 continue;
7300                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7301                                 continue;
7302                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7303                                 continue;
7304                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7305                             relative_target_port_identifier);
7306                         pc++;
7307                 }
7308                 tpg_desc->target_port_count = pc;
7309                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7310                     &tpg_desc->descriptors[pc];
7311         }
7312         mtx_unlock(&softc->ctl_lock);
7313
7314         ctl_set_success(ctsio);
7315         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7316         ctsio->be_move_done = ctl_config_move_done;
7317         ctl_datamove((union ctl_io *)ctsio);
7318         return(retval);
7319 }
7320
7321 int
7322 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7323 {
7324         struct ctl_lun *lun;
7325         struct scsi_report_supported_opcodes *cdb;
7326         const struct ctl_cmd_entry *entry, *sentry;
7327         struct scsi_report_supported_opcodes_all *all;
7328         struct scsi_report_supported_opcodes_descr *descr;
7329         struct scsi_report_supported_opcodes_one *one;
7330         int retval;
7331         int alloc_len, total_len;
7332         int opcode, service_action, i, j, num;
7333
7334         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7335
7336         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7337         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7338
7339         retval = CTL_RETVAL_COMPLETE;
7340
7341         opcode = cdb->requested_opcode;
7342         service_action = scsi_2btoul(cdb->requested_service_action);
7343         switch (cdb->options & RSO_OPTIONS_MASK) {
7344         case RSO_OPTIONS_ALL:
7345                 num = 0;
7346                 for (i = 0; i < 256; i++) {
7347                         entry = &ctl_cmd_table[i];
7348                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7349                                 for (j = 0; j < 32; j++) {
7350                                         sentry = &((const struct ctl_cmd_entry *)
7351                                             entry->execute)[j];
7352                                         if (ctl_cmd_applicable(
7353                                             lun->be_lun->lun_type, sentry))
7354                                                 num++;
7355                                 }
7356                         } else {
7357                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7358                                     entry))
7359                                         num++;
7360                         }
7361                 }
7362                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7363                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7364                 break;
7365         case RSO_OPTIONS_OC:
7366                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7367                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7368                                               /*sks_valid*/ 1,
7369                                               /*command*/ 1,
7370                                               /*field*/ 2,
7371                                               /*bit_valid*/ 1,
7372                                               /*bit*/ 2);
7373                         ctl_done((union ctl_io *)ctsio);
7374                         return (CTL_RETVAL_COMPLETE);
7375                 }
7376                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7377                 break;
7378         case RSO_OPTIONS_OC_SA:
7379                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7380                     service_action >= 32) {
7381                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7382                                               /*sks_valid*/ 1,
7383                                               /*command*/ 1,
7384                                               /*field*/ 2,
7385                                               /*bit_valid*/ 1,
7386                                               /*bit*/ 2);
7387                         ctl_done((union ctl_io *)ctsio);
7388                         return (CTL_RETVAL_COMPLETE);
7389                 }
7390                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7391                 break;
7392         default:
7393                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7394                                       /*sks_valid*/ 1,
7395                                       /*command*/ 1,
7396                                       /*field*/ 2,
7397                                       /*bit_valid*/ 1,
7398                                       /*bit*/ 2);
7399                 ctl_done((union ctl_io *)ctsio);
7400                 return (CTL_RETVAL_COMPLETE);
7401         }
7402
7403         alloc_len = scsi_4btoul(cdb->length);
7404
7405         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7406
7407         ctsio->kern_sg_entries = 0;
7408
7409         if (total_len < alloc_len) {
7410                 ctsio->residual = alloc_len - total_len;
7411                 ctsio->kern_data_len = total_len;
7412                 ctsio->kern_total_len = total_len;
7413         } else {
7414                 ctsio->residual = 0;
7415                 ctsio->kern_data_len = alloc_len;
7416                 ctsio->kern_total_len = alloc_len;
7417         }
7418         ctsio->kern_data_resid = 0;
7419         ctsio->kern_rel_offset = 0;
7420
7421         switch (cdb->options & RSO_OPTIONS_MASK) {
7422         case RSO_OPTIONS_ALL:
7423                 all = (struct scsi_report_supported_opcodes_all *)
7424                     ctsio->kern_data_ptr;
7425                 num = 0;
7426                 for (i = 0; i < 256; i++) {
7427                         entry = &ctl_cmd_table[i];
7428                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7429                                 for (j = 0; j < 32; j++) {
7430                                         sentry = &((const struct ctl_cmd_entry *)
7431                                             entry->execute)[j];
7432                                         if (!ctl_cmd_applicable(
7433                                             lun->be_lun->lun_type, sentry))
7434                                                 continue;
7435                                         descr = &all->descr[num++];
7436                                         descr->opcode = i;
7437                                         scsi_ulto2b(j, descr->service_action);
7438                                         descr->flags = RSO_SERVACTV;
7439                                         scsi_ulto2b(sentry->length,
7440                                             descr->cdb_length);
7441                                 }
7442                         } else {
7443                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7444                                     entry))
7445                                         continue;
7446                                 descr = &all->descr[num++];
7447                                 descr->opcode = i;
7448                                 scsi_ulto2b(0, descr->service_action);
7449                                 descr->flags = 0;
7450                                 scsi_ulto2b(entry->length, descr->cdb_length);
7451                         }
7452                 }
7453                 scsi_ulto4b(
7454                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7455                     all->length);
7456                 break;
7457         case RSO_OPTIONS_OC:
7458                 one = (struct scsi_report_supported_opcodes_one *)
7459                     ctsio->kern_data_ptr;
7460                 entry = &ctl_cmd_table[opcode];
7461                 goto fill_one;
7462         case RSO_OPTIONS_OC_SA:
7463                 one = (struct scsi_report_supported_opcodes_one *)
7464                     ctsio->kern_data_ptr;
7465                 entry = &ctl_cmd_table[opcode];
7466                 entry = &((const struct ctl_cmd_entry *)
7467                     entry->execute)[service_action];
7468 fill_one:
7469                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7470                         one->support = 3;
7471                         scsi_ulto2b(entry->length, one->cdb_length);
7472                         one->cdb_usage[0] = opcode;
7473                         memcpy(&one->cdb_usage[1], entry->usage,
7474                             entry->length - 1);
7475                 } else
7476                         one->support = 1;
7477                 break;
7478         }
7479
7480         ctl_set_success(ctsio);
7481         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7482         ctsio->be_move_done = ctl_config_move_done;
7483         ctl_datamove((union ctl_io *)ctsio);
7484         return(retval);
7485 }
7486
7487 int
7488 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7489 {
7490         struct scsi_report_supported_tmf *cdb;
7491         struct scsi_report_supported_tmf_data *data;
7492         int retval;
7493         int alloc_len, total_len;
7494
7495         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7496
7497         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7498
7499         retval = CTL_RETVAL_COMPLETE;
7500
7501         total_len = sizeof(struct scsi_report_supported_tmf_data);
7502         alloc_len = scsi_4btoul(cdb->length);
7503
7504         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7505
7506         ctsio->kern_sg_entries = 0;
7507
7508         if (total_len < alloc_len) {
7509                 ctsio->residual = alloc_len - total_len;
7510                 ctsio->kern_data_len = total_len;
7511                 ctsio->kern_total_len = total_len;
7512         } else {
7513                 ctsio->residual = 0;
7514                 ctsio->kern_data_len = alloc_len;
7515                 ctsio->kern_total_len = alloc_len;
7516         }
7517         ctsio->kern_data_resid = 0;
7518         ctsio->kern_rel_offset = 0;
7519
7520         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7521         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7522             RST_TRS;
7523         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7524
7525         ctl_set_success(ctsio);
7526         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7527         ctsio->be_move_done = ctl_config_move_done;
7528         ctl_datamove((union ctl_io *)ctsio);
7529         return (retval);
7530 }
7531
7532 int
7533 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7534 {
7535         struct scsi_report_timestamp *cdb;
7536         struct scsi_report_timestamp_data *data;
7537         struct timeval tv;
7538         int64_t timestamp;
7539         int retval;
7540         int alloc_len, total_len;
7541
7542         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7543
7544         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7545
7546         retval = CTL_RETVAL_COMPLETE;
7547
7548         total_len = sizeof(struct scsi_report_timestamp_data);
7549         alloc_len = scsi_4btoul(cdb->length);
7550
7551         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7552
7553         ctsio->kern_sg_entries = 0;
7554
7555         if (total_len < alloc_len) {
7556                 ctsio->residual = alloc_len - total_len;
7557                 ctsio->kern_data_len = total_len;
7558                 ctsio->kern_total_len = total_len;
7559         } else {
7560                 ctsio->residual = 0;
7561                 ctsio->kern_data_len = alloc_len;
7562                 ctsio->kern_total_len = alloc_len;
7563         }
7564         ctsio->kern_data_resid = 0;
7565         ctsio->kern_rel_offset = 0;
7566
7567         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7568         scsi_ulto2b(sizeof(*data) - 2, data->length);
7569         data->origin = RTS_ORIG_OUTSIDE;
7570         getmicrotime(&tv);
7571         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7572         scsi_ulto4b(timestamp >> 16, data->timestamp);
7573         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7574
7575         ctl_set_success(ctsio);
7576         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7577         ctsio->be_move_done = ctl_config_move_done;
7578         ctl_datamove((union ctl_io *)ctsio);
7579         return (retval);
7580 }
7581
7582 int
7583 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7584 {
7585         struct scsi_per_res_in *cdb;
7586         int alloc_len, total_len = 0;
7587         /* struct scsi_per_res_in_rsrv in_data; */
7588         struct ctl_lun *lun;
7589         struct ctl_softc *softc;
7590         uint64_t key;
7591
7592         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7593
7594         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7595
7596         alloc_len = scsi_2btoul(cdb->length);
7597
7598         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7599         softc = lun->ctl_softc;
7600
7601 retry:
7602         mtx_lock(&lun->lun_lock);
7603         switch (cdb->action) {
7604         case SPRI_RK: /* read keys */
7605                 total_len = sizeof(struct scsi_per_res_in_keys) +
7606                         lun->pr_key_count *
7607                         sizeof(struct scsi_per_res_key);
7608                 break;
7609         case SPRI_RR: /* read reservation */
7610                 if (lun->flags & CTL_LUN_PR_RESERVED)
7611                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7612                 else
7613                         total_len = sizeof(struct scsi_per_res_in_header);
7614                 break;
7615         case SPRI_RC: /* report capabilities */
7616                 total_len = sizeof(struct scsi_per_res_cap);
7617                 break;
7618         case SPRI_RS: /* read full status */
7619                 total_len = sizeof(struct scsi_per_res_in_header) +
7620                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7621                     lun->pr_key_count;
7622                 break;
7623         default:
7624                 panic("Invalid PR type %x", cdb->action);
7625         }
7626         mtx_unlock(&lun->lun_lock);
7627
7628         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7629
7630         if (total_len < alloc_len) {
7631                 ctsio->residual = alloc_len - total_len;
7632                 ctsio->kern_data_len = total_len;
7633                 ctsio->kern_total_len = total_len;
7634         } else {
7635                 ctsio->residual = 0;
7636                 ctsio->kern_data_len = alloc_len;
7637                 ctsio->kern_total_len = alloc_len;
7638         }
7639
7640         ctsio->kern_data_resid = 0;
7641         ctsio->kern_rel_offset = 0;
7642         ctsio->kern_sg_entries = 0;
7643
7644         mtx_lock(&lun->lun_lock);
7645         switch (cdb->action) {
7646         case SPRI_RK: { // read keys
7647         struct scsi_per_res_in_keys *res_keys;
7648                 int i, key_count;
7649
7650                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7651
7652                 /*
7653                  * We had to drop the lock to allocate our buffer, which
7654                  * leaves time for someone to come in with another
7655                  * persistent reservation.  (That is unlikely, though,
7656                  * since this should be the only persistent reservation
7657                  * command active right now.)
7658                  */
7659                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7660                     (lun->pr_key_count *
7661                      sizeof(struct scsi_per_res_key)))){
7662                         mtx_unlock(&lun->lun_lock);
7663                         free(ctsio->kern_data_ptr, M_CTL);
7664                         printf("%s: reservation length changed, retrying\n",
7665                                __func__);
7666                         goto retry;
7667                 }
7668
7669                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7670
7671                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7672                              lun->pr_key_count, res_keys->header.length);
7673
7674                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7675                         if ((key = ctl_get_prkey(lun, i)) == 0)
7676                                 continue;
7677
7678                         /*
7679                          * We used lun->pr_key_count to calculate the
7680                          * size to allocate.  If it turns out the number of
7681                          * initiators with the registered flag set is
7682                          * larger than that (i.e. they haven't been kept in
7683                          * sync), we've got a problem.
7684                          */
7685                         if (key_count >= lun->pr_key_count) {
7686 #ifdef NEEDTOPORT
7687                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7688                                             CTL_PR_ERROR,
7689                                             csevent_LogType_Fault,
7690                                             csevent_AlertLevel_Yellow,
7691                                             csevent_FRU_ShelfController,
7692                                             csevent_FRU_Firmware,
7693                                         csevent_FRU_Unknown,
7694                                             "registered keys %d >= key "
7695                                             "count %d", key_count,
7696                                             lun->pr_key_count);
7697 #endif
7698                                 key_count++;
7699                                 continue;
7700                         }
7701                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7702                         key_count++;
7703                 }
7704                 break;
7705         }
7706         case SPRI_RR: { // read reservation
7707                 struct scsi_per_res_in_rsrv *res;
7708                 int tmp_len, header_only;
7709
7710                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7711
7712                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7713
7714                 if (lun->flags & CTL_LUN_PR_RESERVED)
7715                 {
7716                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7717                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7718                                     res->header.length);
7719                         header_only = 0;
7720                 } else {
7721                         tmp_len = sizeof(struct scsi_per_res_in_header);
7722                         scsi_ulto4b(0, res->header.length);
7723                         header_only = 1;
7724                 }
7725
7726                 /*
7727                  * We had to drop the lock to allocate our buffer, which
7728                  * leaves time for someone to come in with another
7729                  * persistent reservation.  (That is unlikely, though,
7730                  * since this should be the only persistent reservation
7731                  * command active right now.)
7732                  */
7733                 if (tmp_len != total_len) {
7734                         mtx_unlock(&lun->lun_lock);
7735                         free(ctsio->kern_data_ptr, M_CTL);
7736                         printf("%s: reservation status changed, retrying\n",
7737                                __func__);
7738                         goto retry;
7739                 }
7740
7741                 /*
7742                  * No reservation held, so we're done.
7743                  */
7744                 if (header_only != 0)
7745                         break;
7746
7747                 /*
7748                  * If the registration is an All Registrants type, the key
7749                  * is 0, since it doesn't really matter.
7750                  */
7751                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7752                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7753                             res->data.reservation);
7754                 }
7755                 res->data.scopetype = lun->res_type;
7756                 break;
7757         }
7758         case SPRI_RC:     //report capabilities
7759         {
7760                 struct scsi_per_res_cap *res_cap;
7761                 uint16_t type_mask;
7762
7763                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7764                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7765                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7766                 type_mask = SPRI_TM_WR_EX_AR |
7767                             SPRI_TM_EX_AC_RO |
7768                             SPRI_TM_WR_EX_RO |
7769                             SPRI_TM_EX_AC |
7770                             SPRI_TM_WR_EX |
7771                             SPRI_TM_EX_AC_AR;
7772                 scsi_ulto2b(type_mask, res_cap->type_mask);
7773                 break;
7774         }
7775         case SPRI_RS: { // read full status
7776                 struct scsi_per_res_in_full *res_status;
7777                 struct scsi_per_res_in_full_desc *res_desc;
7778                 struct ctl_port *port;
7779                 int i, len;
7780
7781                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7782
7783                 /*
7784                  * We had to drop the lock to allocate our buffer, which
7785                  * leaves time for someone to come in with another
7786                  * persistent reservation.  (That is unlikely, though,
7787                  * since this should be the only persistent reservation
7788                  * command active right now.)
7789                  */
7790                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7791                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7792                      lun->pr_key_count)){
7793                         mtx_unlock(&lun->lun_lock);
7794                         free(ctsio->kern_data_ptr, M_CTL);
7795                         printf("%s: reservation length changed, retrying\n",
7796                                __func__);
7797                         goto retry;
7798                 }
7799
7800                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7801
7802                 res_desc = &res_status->desc[0];
7803                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7804                         if ((key = ctl_get_prkey(lun, i)) == 0)
7805                                 continue;
7806
7807                         scsi_u64to8b(key, res_desc->res_key.key);
7808                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7809                             (lun->pr_res_idx == i ||
7810                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7811                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7812                                 res_desc->scopetype = lun->res_type;
7813                         }
7814                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7815                             res_desc->rel_trgt_port_id);
7816                         len = 0;
7817                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7818                         if (port != NULL)
7819                                 len = ctl_create_iid(port,
7820                                     i % CTL_MAX_INIT_PER_PORT,
7821                                     res_desc->transport_id);
7822                         scsi_ulto4b(len, res_desc->additional_length);
7823                         res_desc = (struct scsi_per_res_in_full_desc *)
7824                             &res_desc->transport_id[len];
7825                 }
7826                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7827                     res_status->header.length);
7828                 break;
7829         }
7830         default:
7831                 /*
7832                  * This is a bug, because we just checked for this above,
7833                  * and should have returned an error.
7834                  */
7835                 panic("Invalid PR type %x", cdb->action);
7836                 break; /* NOTREACHED */
7837         }
7838         mtx_unlock(&lun->lun_lock);
7839
7840         ctl_set_success(ctsio);
7841         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7842         ctsio->be_move_done = ctl_config_move_done;
7843         ctl_datamove((union ctl_io *)ctsio);
7844         return (CTL_RETVAL_COMPLETE);
7845 }
7846
7847 /*
7848  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7849  * it should return.
7850  */
7851 static int
7852 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7853                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7854                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7855                 struct scsi_per_res_out_parms* param)
7856 {
7857         union ctl_ha_msg persis_io;
7858         int i;
7859
7860         mtx_lock(&lun->lun_lock);
7861         if (sa_res_key == 0) {
7862                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7863                         /* validate scope and type */
7864                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7865                              SPR_LU_SCOPE) {
7866                                 mtx_unlock(&lun->lun_lock);
7867                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7868                                                       /*sks_valid*/ 1,
7869                                                       /*command*/ 1,
7870                                                       /*field*/ 2,
7871                                                       /*bit_valid*/ 1,
7872                                                       /*bit*/ 4);
7873                                 ctl_done((union ctl_io *)ctsio);
7874                                 return (1);
7875                         }
7876
7877                         if (type>8 || type==2 || type==4 || type==0) {
7878                                 mtx_unlock(&lun->lun_lock);
7879                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7880                                                       /*sks_valid*/ 1,
7881                                                       /*command*/ 1,
7882                                                       /*field*/ 2,
7883                                                       /*bit_valid*/ 1,
7884                                                       /*bit*/ 0);
7885                                 ctl_done((union ctl_io *)ctsio);
7886                                 return (1);
7887                         }
7888
7889                         /*
7890                          * Unregister everybody else and build UA for
7891                          * them
7892                          */
7893                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7894                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7895                                         continue;
7896
7897                                 ctl_clr_prkey(lun, i);
7898                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7899                         }
7900                         lun->pr_key_count = 1;
7901                         lun->res_type = type;
7902                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7903                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7904                                 lun->pr_res_idx = residx;
7905                         lun->PRGeneration++;
7906                         mtx_unlock(&lun->lun_lock);
7907
7908                         /* send msg to other side */
7909                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7910                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7911                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7912                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7913                         persis_io.pr.pr_info.res_type = type;
7914                         memcpy(persis_io.pr.pr_info.sa_res_key,
7915                                param->serv_act_res_key,
7916                                sizeof(param->serv_act_res_key));
7917                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7918                             sizeof(persis_io.pr), M_WAITOK);
7919                 } else {
7920                         /* not all registrants */
7921                         mtx_unlock(&lun->lun_lock);
7922                         free(ctsio->kern_data_ptr, M_CTL);
7923                         ctl_set_invalid_field(ctsio,
7924                                               /*sks_valid*/ 1,
7925                                               /*command*/ 0,
7926                                               /*field*/ 8,
7927                                               /*bit_valid*/ 0,
7928                                               /*bit*/ 0);
7929                         ctl_done((union ctl_io *)ctsio);
7930                         return (1);
7931                 }
7932         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7933                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7934                 int found = 0;
7935
7936                 if (res_key == sa_res_key) {
7937                         /* special case */
7938                         /*
7939                          * The spec implies this is not good but doesn't
7940                          * say what to do. There are two choices either
7941                          * generate a res conflict or check condition
7942                          * with illegal field in parameter data. Since
7943                          * that is what is done when the sa_res_key is
7944                          * zero I'll take that approach since this has
7945                          * to do with the sa_res_key.
7946                          */
7947                         mtx_unlock(&lun->lun_lock);
7948                         free(ctsio->kern_data_ptr, M_CTL);
7949                         ctl_set_invalid_field(ctsio,
7950                                               /*sks_valid*/ 1,
7951                                               /*command*/ 0,
7952                                               /*field*/ 8,
7953                                               /*bit_valid*/ 0,
7954                                               /*bit*/ 0);
7955                         ctl_done((union ctl_io *)ctsio);
7956                         return (1);
7957                 }
7958
7959                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7960                         if (ctl_get_prkey(lun, i) != sa_res_key)
7961                                 continue;
7962
7963                         found = 1;
7964                         ctl_clr_prkey(lun, i);
7965                         lun->pr_key_count--;
7966                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7967                 }
7968                 if (!found) {
7969                         mtx_unlock(&lun->lun_lock);
7970                         free(ctsio->kern_data_ptr, M_CTL);
7971                         ctl_set_reservation_conflict(ctsio);
7972                         ctl_done((union ctl_io *)ctsio);
7973                         return (CTL_RETVAL_COMPLETE);
7974                 }
7975                 lun->PRGeneration++;
7976                 mtx_unlock(&lun->lun_lock);
7977
7978                 /* send msg to other side */
7979                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7980                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7981                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7982                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7983                 persis_io.pr.pr_info.res_type = type;
7984                 memcpy(persis_io.pr.pr_info.sa_res_key,
7985                        param->serv_act_res_key,
7986                        sizeof(param->serv_act_res_key));
7987                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7988                     sizeof(persis_io.pr), M_WAITOK);
7989         } else {
7990                 /* Reserved but not all registrants */
7991                 /* sa_res_key is res holder */
7992                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7993                         /* validate scope and type */
7994                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7995                              SPR_LU_SCOPE) {
7996                                 mtx_unlock(&lun->lun_lock);
7997                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7998                                                       /*sks_valid*/ 1,
7999                                                       /*command*/ 1,
8000                                                       /*field*/ 2,
8001                                                       /*bit_valid*/ 1,
8002                                                       /*bit*/ 4);
8003                                 ctl_done((union ctl_io *)ctsio);
8004                                 return (1);
8005                         }
8006
8007                         if (type>8 || type==2 || type==4 || type==0) {
8008                                 mtx_unlock(&lun->lun_lock);
8009                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8010                                                       /*sks_valid*/ 1,
8011                                                       /*command*/ 1,
8012                                                       /*field*/ 2,
8013                                                       /*bit_valid*/ 1,
8014                                                       /*bit*/ 0);
8015                                 ctl_done((union ctl_io *)ctsio);
8016                                 return (1);
8017                         }
8018
8019                         /*
8020                          * Do the following:
8021                          * if sa_res_key != res_key remove all
8022                          * registrants w/sa_res_key and generate UA
8023                          * for these registrants(Registrations
8024                          * Preempted) if it wasn't an exclusive
8025                          * reservation generate UA(Reservations
8026                          * Preempted) for all other registered nexuses
8027                          * if the type has changed. Establish the new
8028                          * reservation and holder. If res_key and
8029                          * sa_res_key are the same do the above
8030                          * except don't unregister the res holder.
8031                          */
8032
8033                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8034                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8035                                         continue;
8036
8037                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8038                                         ctl_clr_prkey(lun, i);
8039                                         lun->pr_key_count--;
8040                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8041                                 } else if (type != lun->res_type
8042                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8043                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8044                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8045                                 }
8046                         }
8047                         lun->res_type = type;
8048                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8049                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8050                                 lun->pr_res_idx = residx;
8051                         else
8052                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8053                         lun->PRGeneration++;
8054                         mtx_unlock(&lun->lun_lock);
8055
8056                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8057                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8058                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8059                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8060                         persis_io.pr.pr_info.res_type = type;
8061                         memcpy(persis_io.pr.pr_info.sa_res_key,
8062                                param->serv_act_res_key,
8063                                sizeof(param->serv_act_res_key));
8064                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8065                             sizeof(persis_io.pr), M_WAITOK);
8066                 } else {
8067                         /*
8068                          * sa_res_key is not the res holder just
8069                          * remove registrants
8070                          */
8071                         int found=0;
8072
8073                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8074                                 if (sa_res_key != ctl_get_prkey(lun, i))
8075                                         continue;
8076
8077                                 found = 1;
8078                                 ctl_clr_prkey(lun, i);
8079                                 lun->pr_key_count--;
8080                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8081                         }
8082
8083                         if (!found) {
8084                                 mtx_unlock(&lun->lun_lock);
8085                                 free(ctsio->kern_data_ptr, M_CTL);
8086                                 ctl_set_reservation_conflict(ctsio);
8087                                 ctl_done((union ctl_io *)ctsio);
8088                                 return (1);
8089                         }
8090                         lun->PRGeneration++;
8091                         mtx_unlock(&lun->lun_lock);
8092
8093                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8094                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8095                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8096                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8097                         persis_io.pr.pr_info.res_type = type;
8098                         memcpy(persis_io.pr.pr_info.sa_res_key,
8099                                param->serv_act_res_key,
8100                                sizeof(param->serv_act_res_key));
8101                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8102                             sizeof(persis_io.pr), M_WAITOK);
8103                 }
8104         }
8105         return (0);
8106 }
8107
8108 static void
8109 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8110 {
8111         uint64_t sa_res_key;
8112         int i;
8113
8114         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8115
8116         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8117          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8118          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8119                 if (sa_res_key == 0) {
8120                         /*
8121                          * Unregister everybody else and build UA for
8122                          * them
8123                          */
8124                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8125                                 if (i == msg->pr.pr_info.residx ||
8126                                     ctl_get_prkey(lun, i) == 0)
8127                                         continue;
8128
8129                                 ctl_clr_prkey(lun, i);
8130                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8131                         }
8132
8133                         lun->pr_key_count = 1;
8134                         lun->res_type = msg->pr.pr_info.res_type;
8135                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8136                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8137                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8138                 } else {
8139                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8140                                 if (sa_res_key == ctl_get_prkey(lun, i))
8141                                         continue;
8142
8143                                 ctl_clr_prkey(lun, i);
8144                                 lun->pr_key_count--;
8145                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8146                         }
8147                 }
8148         } else {
8149                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8150                         if (i == msg->pr.pr_info.residx ||
8151                             ctl_get_prkey(lun, i) == 0)
8152                                 continue;
8153
8154                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8155                                 ctl_clr_prkey(lun, i);
8156                                 lun->pr_key_count--;
8157                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8158                         } else if (msg->pr.pr_info.res_type != lun->res_type
8159                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8160                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8161                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8162                         }
8163                 }
8164                 lun->res_type = msg->pr.pr_info.res_type;
8165                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8166                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8167                         lun->pr_res_idx = msg->pr.pr_info.residx;
8168                 else
8169                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8170         }
8171         lun->PRGeneration++;
8172
8173 }
8174
8175
8176 int
8177 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8178 {
8179         int retval;
8180         u_int32_t param_len;
8181         struct scsi_per_res_out *cdb;
8182         struct ctl_lun *lun;
8183         struct scsi_per_res_out_parms* param;
8184         struct ctl_softc *softc;
8185         uint32_t residx;
8186         uint64_t res_key, sa_res_key, key;
8187         uint8_t type;
8188         union ctl_ha_msg persis_io;
8189         int    i;
8190
8191         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8192
8193         retval = CTL_RETVAL_COMPLETE;
8194
8195         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8196         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8197         softc = lun->ctl_softc;
8198
8199         /*
8200          * We only support whole-LUN scope.  The scope & type are ignored for
8201          * register, register and ignore existing key and clear.
8202          * We sometimes ignore scope and type on preempts too!!
8203          * Verify reservation type here as well.
8204          */
8205         type = cdb->scope_type & SPR_TYPE_MASK;
8206         if ((cdb->action == SPRO_RESERVE)
8207          || (cdb->action == SPRO_RELEASE)) {
8208                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8209                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8210                                               /*sks_valid*/ 1,
8211                                               /*command*/ 1,
8212                                               /*field*/ 2,
8213                                               /*bit_valid*/ 1,
8214                                               /*bit*/ 4);
8215                         ctl_done((union ctl_io *)ctsio);
8216                         return (CTL_RETVAL_COMPLETE);
8217                 }
8218
8219                 if (type>8 || type==2 || type==4 || type==0) {
8220                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8221                                               /*sks_valid*/ 1,
8222                                               /*command*/ 1,
8223                                               /*field*/ 2,
8224                                               /*bit_valid*/ 1,
8225                                               /*bit*/ 0);
8226                         ctl_done((union ctl_io *)ctsio);
8227                         return (CTL_RETVAL_COMPLETE);
8228                 }
8229         }
8230
8231         param_len = scsi_4btoul(cdb->length);
8232
8233         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8234                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8235                 ctsio->kern_data_len = param_len;
8236                 ctsio->kern_total_len = param_len;
8237                 ctsio->kern_data_resid = 0;
8238                 ctsio->kern_rel_offset = 0;
8239                 ctsio->kern_sg_entries = 0;
8240                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8241                 ctsio->be_move_done = ctl_config_move_done;
8242                 ctl_datamove((union ctl_io *)ctsio);
8243
8244                 return (CTL_RETVAL_COMPLETE);
8245         }
8246
8247         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8248
8249         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8250         res_key = scsi_8btou64(param->res_key.key);
8251         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8252
8253         /*
8254          * Validate the reservation key here except for SPRO_REG_IGNO
8255          * This must be done for all other service actions
8256          */
8257         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8258                 mtx_lock(&lun->lun_lock);
8259                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8260                         if (res_key != key) {
8261                                 /*
8262                                  * The current key passed in doesn't match
8263                                  * the one the initiator previously
8264                                  * registered.
8265                                  */
8266                                 mtx_unlock(&lun->lun_lock);
8267                                 free(ctsio->kern_data_ptr, M_CTL);
8268                                 ctl_set_reservation_conflict(ctsio);
8269                                 ctl_done((union ctl_io *)ctsio);
8270                                 return (CTL_RETVAL_COMPLETE);
8271                         }
8272                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8273                         /*
8274                          * We are not registered
8275                          */
8276                         mtx_unlock(&lun->lun_lock);
8277                         free(ctsio->kern_data_ptr, M_CTL);
8278                         ctl_set_reservation_conflict(ctsio);
8279                         ctl_done((union ctl_io *)ctsio);
8280                         return (CTL_RETVAL_COMPLETE);
8281                 } else if (res_key != 0) {
8282                         /*
8283                          * We are not registered and trying to register but
8284                          * the register key isn't zero.
8285                          */
8286                         mtx_unlock(&lun->lun_lock);
8287                         free(ctsio->kern_data_ptr, M_CTL);
8288                         ctl_set_reservation_conflict(ctsio);
8289                         ctl_done((union ctl_io *)ctsio);
8290                         return (CTL_RETVAL_COMPLETE);
8291                 }
8292                 mtx_unlock(&lun->lun_lock);
8293         }
8294
8295         switch (cdb->action & SPRO_ACTION_MASK) {
8296         case SPRO_REGISTER:
8297         case SPRO_REG_IGNO: {
8298
8299 #if 0
8300                 printf("Registration received\n");
8301 #endif
8302
8303                 /*
8304                  * We don't support any of these options, as we report in
8305                  * the read capabilities request (see
8306                  * ctl_persistent_reserve_in(), above).
8307                  */
8308                 if ((param->flags & SPR_SPEC_I_PT)
8309                  || (param->flags & SPR_ALL_TG_PT)
8310                  || (param->flags & SPR_APTPL)) {
8311                         int bit_ptr;
8312
8313                         if (param->flags & SPR_APTPL)
8314                                 bit_ptr = 0;
8315                         else if (param->flags & SPR_ALL_TG_PT)
8316                                 bit_ptr = 2;
8317                         else /* SPR_SPEC_I_PT */
8318                                 bit_ptr = 3;
8319
8320                         free(ctsio->kern_data_ptr, M_CTL);
8321                         ctl_set_invalid_field(ctsio,
8322                                               /*sks_valid*/ 1,
8323                                               /*command*/ 0,
8324                                               /*field*/ 20,
8325                                               /*bit_valid*/ 1,
8326                                               /*bit*/ bit_ptr);
8327                         ctl_done((union ctl_io *)ctsio);
8328                         return (CTL_RETVAL_COMPLETE);
8329                 }
8330
8331                 mtx_lock(&lun->lun_lock);
8332
8333                 /*
8334                  * The initiator wants to clear the
8335                  * key/unregister.
8336                  */
8337                 if (sa_res_key == 0) {
8338                         if ((res_key == 0
8339                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8340                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8341                           && ctl_get_prkey(lun, residx) == 0)) {
8342                                 mtx_unlock(&lun->lun_lock);
8343                                 goto done;
8344                         }
8345
8346                         ctl_clr_prkey(lun, residx);
8347                         lun->pr_key_count--;
8348
8349                         if (residx == lun->pr_res_idx) {
8350                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8351                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8352
8353                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8354                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8355                                  && lun->pr_key_count) {
8356                                         /*
8357                                          * If the reservation is a registrants
8358                                          * only type we need to generate a UA
8359                                          * for other registered inits.  The
8360                                          * sense code should be RESERVATIONS
8361                                          * RELEASED
8362                                          */
8363
8364                                         for (i = softc->init_min; i < softc->init_max; i++){
8365                                                 if (ctl_get_prkey(lun, i) == 0)
8366                                                         continue;
8367                                                 ctl_est_ua(lun, i,
8368                                                     CTL_UA_RES_RELEASE);
8369                                         }
8370                                 }
8371                                 lun->res_type = 0;
8372                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8373                                 if (lun->pr_key_count==0) {
8374                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8375                                         lun->res_type = 0;
8376                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8377                                 }
8378                         }
8379                         lun->PRGeneration++;
8380                         mtx_unlock(&lun->lun_lock);
8381
8382                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8383                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8384                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8385                         persis_io.pr.pr_info.residx = residx;
8386                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8387                             sizeof(persis_io.pr), M_WAITOK);
8388                 } else /* sa_res_key != 0 */ {
8389
8390                         /*
8391                          * If we aren't registered currently then increment
8392                          * the key count and set the registered flag.
8393                          */
8394                         ctl_alloc_prkey(lun, residx);
8395                         if (ctl_get_prkey(lun, residx) == 0)
8396                                 lun->pr_key_count++;
8397                         ctl_set_prkey(lun, residx, sa_res_key);
8398                         lun->PRGeneration++;
8399                         mtx_unlock(&lun->lun_lock);
8400
8401                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8402                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8403                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8404                         persis_io.pr.pr_info.residx = residx;
8405                         memcpy(persis_io.pr.pr_info.sa_res_key,
8406                                param->serv_act_res_key,
8407                                sizeof(param->serv_act_res_key));
8408                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8409                             sizeof(persis_io.pr), M_WAITOK);
8410                 }
8411
8412                 break;
8413         }
8414         case SPRO_RESERVE:
8415 #if 0
8416                 printf("Reserve executed type %d\n", type);
8417 #endif
8418                 mtx_lock(&lun->lun_lock);
8419                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8420                         /*
8421                          * if this isn't the reservation holder and it's
8422                          * not a "all registrants" type or if the type is
8423                          * different then we have a conflict
8424                          */
8425                         if ((lun->pr_res_idx != residx
8426                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8427                          || lun->res_type != type) {
8428                                 mtx_unlock(&lun->lun_lock);
8429                                 free(ctsio->kern_data_ptr, M_CTL);
8430                                 ctl_set_reservation_conflict(ctsio);
8431                                 ctl_done((union ctl_io *)ctsio);
8432                                 return (CTL_RETVAL_COMPLETE);
8433                         }
8434                         mtx_unlock(&lun->lun_lock);
8435                 } else /* create a reservation */ {
8436                         /*
8437                          * If it's not an "all registrants" type record
8438                          * reservation holder
8439                          */
8440                         if (type != SPR_TYPE_WR_EX_AR
8441                          && type != SPR_TYPE_EX_AC_AR)
8442                                 lun->pr_res_idx = residx; /* Res holder */
8443                         else
8444                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8445
8446                         lun->flags |= CTL_LUN_PR_RESERVED;
8447                         lun->res_type = type;
8448
8449                         mtx_unlock(&lun->lun_lock);
8450
8451                         /* send msg to other side */
8452                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8453                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8454                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8455                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8456                         persis_io.pr.pr_info.res_type = type;
8457                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8458                             sizeof(persis_io.pr), M_WAITOK);
8459                 }
8460                 break;
8461
8462         case SPRO_RELEASE:
8463                 mtx_lock(&lun->lun_lock);
8464                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8465                         /* No reservation exists return good status */
8466                         mtx_unlock(&lun->lun_lock);
8467                         goto done;
8468                 }
8469                 /*
8470                  * Is this nexus a reservation holder?
8471                  */
8472                 if (lun->pr_res_idx != residx
8473                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8474                         /*
8475                          * not a res holder return good status but
8476                          * do nothing
8477                          */
8478                         mtx_unlock(&lun->lun_lock);
8479                         goto done;
8480                 }
8481
8482                 if (lun->res_type != type) {
8483                         mtx_unlock(&lun->lun_lock);
8484                         free(ctsio->kern_data_ptr, M_CTL);
8485                         ctl_set_illegal_pr_release(ctsio);
8486                         ctl_done((union ctl_io *)ctsio);
8487                         return (CTL_RETVAL_COMPLETE);
8488                 }
8489
8490                 /* okay to release */
8491                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8492                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8493                 lun->res_type = 0;
8494
8495                 /*
8496                  * if this isn't an exclusive access
8497                  * res generate UA for all other
8498                  * registrants.
8499                  */
8500                 if (type != SPR_TYPE_EX_AC
8501                  && type != SPR_TYPE_WR_EX) {
8502                         for (i = softc->init_min; i < softc->init_max; i++) {
8503                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8504                                         continue;
8505                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8506                         }
8507                 }
8508                 mtx_unlock(&lun->lun_lock);
8509
8510                 /* Send msg to other side */
8511                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8512                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8513                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8514                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8515                      sizeof(persis_io.pr), M_WAITOK);
8516                 break;
8517
8518         case SPRO_CLEAR:
8519                 /* send msg to other side */
8520
8521                 mtx_lock(&lun->lun_lock);
8522                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8523                 lun->res_type = 0;
8524                 lun->pr_key_count = 0;
8525                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8526
8527                 ctl_clr_prkey(lun, residx);
8528                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8529                         if (ctl_get_prkey(lun, i) != 0) {
8530                                 ctl_clr_prkey(lun, i);
8531                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8532                         }
8533                 lun->PRGeneration++;
8534                 mtx_unlock(&lun->lun_lock);
8535
8536                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8537                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8538                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8539                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8540                      sizeof(persis_io.pr), M_WAITOK);
8541                 break;
8542
8543         case SPRO_PREEMPT:
8544         case SPRO_PRE_ABO: {
8545                 int nretval;
8546
8547                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8548                                           residx, ctsio, cdb, param);
8549                 if (nretval != 0)
8550                         return (CTL_RETVAL_COMPLETE);
8551                 break;
8552         }
8553         default:
8554                 panic("Invalid PR type %x", cdb->action);
8555         }
8556
8557 done:
8558         free(ctsio->kern_data_ptr, M_CTL);
8559         ctl_set_success(ctsio);
8560         ctl_done((union ctl_io *)ctsio);
8561
8562         return (retval);
8563 }
8564
8565 /*
8566  * This routine is for handling a message from the other SC pertaining to
8567  * persistent reserve out. All the error checking will have been done
8568  * so only perorming the action need be done here to keep the two
8569  * in sync.
8570  */
8571 static void
8572 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8573 {
8574         struct ctl_lun *lun;
8575         struct ctl_softc *softc;
8576         int i;
8577         uint32_t residx, targ_lun;
8578
8579         softc = control_softc;
8580         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8581         mtx_lock(&softc->ctl_lock);
8582         if ((targ_lun >= CTL_MAX_LUNS) ||
8583             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8584                 mtx_unlock(&softc->ctl_lock);
8585                 return;
8586         }
8587         mtx_lock(&lun->lun_lock);
8588         mtx_unlock(&softc->ctl_lock);
8589         if (lun->flags & CTL_LUN_DISABLED) {
8590                 mtx_unlock(&lun->lun_lock);
8591                 return;
8592         }
8593         residx = ctl_get_initindex(&msg->hdr.nexus);
8594         switch(msg->pr.pr_info.action) {
8595         case CTL_PR_REG_KEY:
8596                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8597                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8598                         lun->pr_key_count++;
8599                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8600                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8601                 lun->PRGeneration++;
8602                 break;
8603
8604         case CTL_PR_UNREG_KEY:
8605                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8606                 lun->pr_key_count--;
8607
8608                 /* XXX Need to see if the reservation has been released */
8609                 /* if so do we need to generate UA? */
8610                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8611                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8612                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8613
8614                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8615                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8616                          && lun->pr_key_count) {
8617                                 /*
8618                                  * If the reservation is a registrants
8619                                  * only type we need to generate a UA
8620                                  * for other registered inits.  The
8621                                  * sense code should be RESERVATIONS
8622                                  * RELEASED
8623                                  */
8624
8625                                 for (i = softc->init_min; i < softc->init_max; i++) {
8626                                         if (ctl_get_prkey(lun, i) == 0)
8627                                                 continue;
8628
8629                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8630                                 }
8631                         }
8632                         lun->res_type = 0;
8633                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8634                         if (lun->pr_key_count==0) {
8635                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8636                                 lun->res_type = 0;
8637                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8638                         }
8639                 }
8640                 lun->PRGeneration++;
8641                 break;
8642
8643         case CTL_PR_RESERVE:
8644                 lun->flags |= CTL_LUN_PR_RESERVED;
8645                 lun->res_type = msg->pr.pr_info.res_type;
8646                 lun->pr_res_idx = msg->pr.pr_info.residx;
8647
8648                 break;
8649
8650         case CTL_PR_RELEASE:
8651                 /*
8652                  * if this isn't an exclusive access res generate UA for all
8653                  * other registrants.
8654                  */
8655                 if (lun->res_type != SPR_TYPE_EX_AC
8656                  && lun->res_type != SPR_TYPE_WR_EX) {
8657                         for (i = softc->init_min; i < softc->init_max; i++)
8658                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8659                                         continue;
8660                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8661                 }
8662
8663                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8664                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8665                 lun->res_type = 0;
8666                 break;
8667
8668         case CTL_PR_PREEMPT:
8669                 ctl_pro_preempt_other(lun, msg);
8670                 break;
8671         case CTL_PR_CLEAR:
8672                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8673                 lun->res_type = 0;
8674                 lun->pr_key_count = 0;
8675                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8676
8677                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8678                         if (ctl_get_prkey(lun, i) == 0)
8679                                 continue;
8680                         ctl_clr_prkey(lun, i);
8681                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8682                 }
8683                 lun->PRGeneration++;
8684                 break;
8685         }
8686
8687         mtx_unlock(&lun->lun_lock);
8688 }
8689
8690 int
8691 ctl_read_write(struct ctl_scsiio *ctsio)
8692 {
8693         struct ctl_lun *lun;
8694         struct ctl_lba_len_flags *lbalen;
8695         uint64_t lba;
8696         uint32_t num_blocks;
8697         int flags, retval;
8698         int isread;
8699
8700         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8701
8702         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8703
8704         flags = 0;
8705         retval = CTL_RETVAL_COMPLETE;
8706
8707         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8708               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8709         switch (ctsio->cdb[0]) {
8710         case READ_6:
8711         case WRITE_6: {
8712                 struct scsi_rw_6 *cdb;
8713
8714                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8715
8716                 lba = scsi_3btoul(cdb->addr);
8717                 /* only 5 bits are valid in the most significant address byte */
8718                 lba &= 0x1fffff;
8719                 num_blocks = cdb->length;
8720                 /*
8721                  * This is correct according to SBC-2.
8722                  */
8723                 if (num_blocks == 0)
8724                         num_blocks = 256;
8725                 break;
8726         }
8727         case READ_10:
8728         case WRITE_10: {
8729                 struct scsi_rw_10 *cdb;
8730
8731                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8732                 if (cdb->byte2 & SRW10_FUA)
8733                         flags |= CTL_LLF_FUA;
8734                 if (cdb->byte2 & SRW10_DPO)
8735                         flags |= CTL_LLF_DPO;
8736                 lba = scsi_4btoul(cdb->addr);
8737                 num_blocks = scsi_2btoul(cdb->length);
8738                 break;
8739         }
8740         case WRITE_VERIFY_10: {
8741                 struct scsi_write_verify_10 *cdb;
8742
8743                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8744                 flags |= CTL_LLF_FUA;
8745                 if (cdb->byte2 & SWV_DPO)
8746                         flags |= CTL_LLF_DPO;
8747                 lba = scsi_4btoul(cdb->addr);
8748                 num_blocks = scsi_2btoul(cdb->length);
8749                 break;
8750         }
8751         case READ_12:
8752         case WRITE_12: {
8753                 struct scsi_rw_12 *cdb;
8754
8755                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8756                 if (cdb->byte2 & SRW12_FUA)
8757                         flags |= CTL_LLF_FUA;
8758                 if (cdb->byte2 & SRW12_DPO)
8759                         flags |= CTL_LLF_DPO;
8760                 lba = scsi_4btoul(cdb->addr);
8761                 num_blocks = scsi_4btoul(cdb->length);
8762                 break;
8763         }
8764         case WRITE_VERIFY_12: {
8765                 struct scsi_write_verify_12 *cdb;
8766
8767                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8768                 flags |= CTL_LLF_FUA;
8769                 if (cdb->byte2 & SWV_DPO)
8770                         flags |= CTL_LLF_DPO;
8771                 lba = scsi_4btoul(cdb->addr);
8772                 num_blocks = scsi_4btoul(cdb->length);
8773                 break;
8774         }
8775         case READ_16:
8776         case WRITE_16: {
8777                 struct scsi_rw_16 *cdb;
8778
8779                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8780                 if (cdb->byte2 & SRW12_FUA)
8781                         flags |= CTL_LLF_FUA;
8782                 if (cdb->byte2 & SRW12_DPO)
8783                         flags |= CTL_LLF_DPO;
8784                 lba = scsi_8btou64(cdb->addr);
8785                 num_blocks = scsi_4btoul(cdb->length);
8786                 break;
8787         }
8788         case WRITE_ATOMIC_16: {
8789                 struct scsi_rw_16 *cdb;
8790
8791                 if (lun->be_lun->atomicblock == 0) {
8792                         ctl_set_invalid_opcode(ctsio);
8793                         ctl_done((union ctl_io *)ctsio);
8794                         return (CTL_RETVAL_COMPLETE);
8795                 }
8796
8797                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8798                 if (cdb->byte2 & SRW12_FUA)
8799                         flags |= CTL_LLF_FUA;
8800                 if (cdb->byte2 & SRW12_DPO)
8801                         flags |= CTL_LLF_DPO;
8802                 lba = scsi_8btou64(cdb->addr);
8803                 num_blocks = scsi_4btoul(cdb->length);
8804                 if (num_blocks > lun->be_lun->atomicblock) {
8805                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8806                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8807                             /*bit*/ 0);
8808                         ctl_done((union ctl_io *)ctsio);
8809                         return (CTL_RETVAL_COMPLETE);
8810                 }
8811                 break;
8812         }
8813         case WRITE_VERIFY_16: {
8814                 struct scsi_write_verify_16 *cdb;
8815
8816                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8817                 flags |= CTL_LLF_FUA;
8818                 if (cdb->byte2 & SWV_DPO)
8819                         flags |= CTL_LLF_DPO;
8820                 lba = scsi_8btou64(cdb->addr);
8821                 num_blocks = scsi_4btoul(cdb->length);
8822                 break;
8823         }
8824         default:
8825                 /*
8826                  * We got a command we don't support.  This shouldn't
8827                  * happen, commands should be filtered out above us.
8828                  */
8829                 ctl_set_invalid_opcode(ctsio);
8830                 ctl_done((union ctl_io *)ctsio);
8831
8832                 return (CTL_RETVAL_COMPLETE);
8833                 break; /* NOTREACHED */
8834         }
8835
8836         /*
8837          * The first check is to make sure we're in bounds, the second
8838          * check is to catch wrap-around problems.  If the lba + num blocks
8839          * is less than the lba, then we've wrapped around and the block
8840          * range is invalid anyway.
8841          */
8842         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8843          || ((lba + num_blocks) < lba)) {
8844                 ctl_set_lba_out_of_range(ctsio);
8845                 ctl_done((union ctl_io *)ctsio);
8846                 return (CTL_RETVAL_COMPLETE);
8847         }
8848
8849         /*
8850          * According to SBC-3, a transfer length of 0 is not an error.
8851          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8852          * translates to 256 blocks for those commands.
8853          */
8854         if (num_blocks == 0) {
8855                 ctl_set_success(ctsio);
8856                 ctl_done((union ctl_io *)ctsio);
8857                 return (CTL_RETVAL_COMPLETE);
8858         }
8859
8860         /* Set FUA and/or DPO if caches are disabled. */
8861         if (isread) {
8862                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8863                     SCP_RCD) != 0)
8864                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8865         } else {
8866                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8867                     SCP_WCE) == 0)
8868                         flags |= CTL_LLF_FUA;
8869         }
8870
8871         lbalen = (struct ctl_lba_len_flags *)
8872             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8873         lbalen->lba = lba;
8874         lbalen->len = num_blocks;
8875         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8876
8877         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8878         ctsio->kern_rel_offset = 0;
8879
8880         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8881
8882         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8883
8884         return (retval);
8885 }
8886
8887 static int
8888 ctl_cnw_cont(union ctl_io *io)
8889 {
8890         struct ctl_scsiio *ctsio;
8891         struct ctl_lun *lun;
8892         struct ctl_lba_len_flags *lbalen;
8893         int retval;
8894
8895         ctsio = &io->scsiio;
8896         ctsio->io_hdr.status = CTL_STATUS_NONE;
8897         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8898         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8899         lbalen = (struct ctl_lba_len_flags *)
8900             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8901         lbalen->flags &= ~CTL_LLF_COMPARE;
8902         lbalen->flags |= CTL_LLF_WRITE;
8903
8904         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8905         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8906         return (retval);
8907 }
8908
8909 int
8910 ctl_cnw(struct ctl_scsiio *ctsio)
8911 {
8912         struct ctl_lun *lun;
8913         struct ctl_lba_len_flags *lbalen;
8914         uint64_t lba;
8915         uint32_t num_blocks;
8916         int flags, retval;
8917
8918         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8919
8920         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8921
8922         flags = 0;
8923         retval = CTL_RETVAL_COMPLETE;
8924
8925         switch (ctsio->cdb[0]) {
8926         case COMPARE_AND_WRITE: {
8927                 struct scsi_compare_and_write *cdb;
8928
8929                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8930                 if (cdb->byte2 & SRW10_FUA)
8931                         flags |= CTL_LLF_FUA;
8932                 if (cdb->byte2 & SRW10_DPO)
8933                         flags |= CTL_LLF_DPO;
8934                 lba = scsi_8btou64(cdb->addr);
8935                 num_blocks = cdb->length;
8936                 break;
8937         }
8938         default:
8939                 /*
8940                  * We got a command we don't support.  This shouldn't
8941                  * happen, commands should be filtered out above us.
8942                  */
8943                 ctl_set_invalid_opcode(ctsio);
8944                 ctl_done((union ctl_io *)ctsio);
8945
8946                 return (CTL_RETVAL_COMPLETE);
8947                 break; /* NOTREACHED */
8948         }
8949
8950         /*
8951          * The first check is to make sure we're in bounds, the second
8952          * check is to catch wrap-around problems.  If the lba + num blocks
8953          * is less than the lba, then we've wrapped around and the block
8954          * range is invalid anyway.
8955          */
8956         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8957          || ((lba + num_blocks) < lba)) {
8958                 ctl_set_lba_out_of_range(ctsio);
8959                 ctl_done((union ctl_io *)ctsio);
8960                 return (CTL_RETVAL_COMPLETE);
8961         }
8962
8963         /*
8964          * According to SBC-3, a transfer length of 0 is not an error.
8965          */
8966         if (num_blocks == 0) {
8967                 ctl_set_success(ctsio);
8968                 ctl_done((union ctl_io *)ctsio);
8969                 return (CTL_RETVAL_COMPLETE);
8970         }
8971
8972         /* Set FUA if write cache is disabled. */
8973         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8974             SCP_WCE) == 0)
8975                 flags |= CTL_LLF_FUA;
8976
8977         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8978         ctsio->kern_rel_offset = 0;
8979
8980         /*
8981          * Set the IO_CONT flag, so that if this I/O gets passed to
8982          * ctl_data_submit_done(), it'll get passed back to
8983          * ctl_ctl_cnw_cont() for further processing.
8984          */
8985         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8986         ctsio->io_cont = ctl_cnw_cont;
8987
8988         lbalen = (struct ctl_lba_len_flags *)
8989             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8990         lbalen->lba = lba;
8991         lbalen->len = num_blocks;
8992         lbalen->flags = CTL_LLF_COMPARE | flags;
8993
8994         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8995         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8996         return (retval);
8997 }
8998
8999 int
9000 ctl_verify(struct ctl_scsiio *ctsio)
9001 {
9002         struct ctl_lun *lun;
9003         struct ctl_lba_len_flags *lbalen;
9004         uint64_t lba;
9005         uint32_t num_blocks;
9006         int bytchk, flags;
9007         int retval;
9008
9009         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9010
9011         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9012
9013         bytchk = 0;
9014         flags = CTL_LLF_FUA;
9015         retval = CTL_RETVAL_COMPLETE;
9016
9017         switch (ctsio->cdb[0]) {
9018         case VERIFY_10: {
9019                 struct scsi_verify_10 *cdb;
9020
9021                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9022                 if (cdb->byte2 & SVFY_BYTCHK)
9023                         bytchk = 1;
9024                 if (cdb->byte2 & SVFY_DPO)
9025                         flags |= CTL_LLF_DPO;
9026                 lba = scsi_4btoul(cdb->addr);
9027                 num_blocks = scsi_2btoul(cdb->length);
9028                 break;
9029         }
9030         case VERIFY_12: {
9031                 struct scsi_verify_12 *cdb;
9032
9033                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9034                 if (cdb->byte2 & SVFY_BYTCHK)
9035                         bytchk = 1;
9036                 if (cdb->byte2 & SVFY_DPO)
9037                         flags |= CTL_LLF_DPO;
9038                 lba = scsi_4btoul(cdb->addr);
9039                 num_blocks = scsi_4btoul(cdb->length);
9040                 break;
9041         }
9042         case VERIFY_16: {
9043                 struct scsi_rw_16 *cdb;
9044
9045                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9046                 if (cdb->byte2 & SVFY_BYTCHK)
9047                         bytchk = 1;
9048                 if (cdb->byte2 & SVFY_DPO)
9049                         flags |= CTL_LLF_DPO;
9050                 lba = scsi_8btou64(cdb->addr);
9051                 num_blocks = scsi_4btoul(cdb->length);
9052                 break;
9053         }
9054         default:
9055                 /*
9056                  * We got a command we don't support.  This shouldn't
9057                  * happen, commands should be filtered out above us.
9058                  */
9059                 ctl_set_invalid_opcode(ctsio);
9060                 ctl_done((union ctl_io *)ctsio);
9061                 return (CTL_RETVAL_COMPLETE);
9062         }
9063
9064         /*
9065          * The first check is to make sure we're in bounds, the second
9066          * check is to catch wrap-around problems.  If the lba + num blocks
9067          * is less than the lba, then we've wrapped around and the block
9068          * range is invalid anyway.
9069          */
9070         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9071          || ((lba + num_blocks) < lba)) {
9072                 ctl_set_lba_out_of_range(ctsio);
9073                 ctl_done((union ctl_io *)ctsio);
9074                 return (CTL_RETVAL_COMPLETE);
9075         }
9076
9077         /*
9078          * According to SBC-3, a transfer length of 0 is not an error.
9079          */
9080         if (num_blocks == 0) {
9081                 ctl_set_success(ctsio);
9082                 ctl_done((union ctl_io *)ctsio);
9083                 return (CTL_RETVAL_COMPLETE);
9084         }
9085
9086         lbalen = (struct ctl_lba_len_flags *)
9087             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9088         lbalen->lba = lba;
9089         lbalen->len = num_blocks;
9090         if (bytchk) {
9091                 lbalen->flags = CTL_LLF_COMPARE | flags;
9092                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9093         } else {
9094                 lbalen->flags = CTL_LLF_VERIFY | flags;
9095                 ctsio->kern_total_len = 0;
9096         }
9097         ctsio->kern_rel_offset = 0;
9098
9099         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9100         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9101         return (retval);
9102 }
9103
9104 int
9105 ctl_report_luns(struct ctl_scsiio *ctsio)
9106 {
9107         struct ctl_softc *softc = control_softc;
9108         struct scsi_report_luns *cdb;
9109         struct scsi_report_luns_data *lun_data;
9110         struct ctl_lun *lun, *request_lun;
9111         struct ctl_port *port;
9112         int num_luns, retval;
9113         uint32_t alloc_len, lun_datalen;
9114         int num_filled, well_known;
9115         uint32_t initidx, targ_lun_id, lun_id;
9116
9117         retval = CTL_RETVAL_COMPLETE;
9118         well_known = 0;
9119
9120         cdb = (struct scsi_report_luns *)ctsio->cdb;
9121         port = ctl_io_port(&ctsio->io_hdr);
9122
9123         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9124
9125         mtx_lock(&softc->ctl_lock);
9126         num_luns = 0;
9127         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9128                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9129                         num_luns++;
9130         }
9131         mtx_unlock(&softc->ctl_lock);
9132
9133         switch (cdb->select_report) {
9134         case RPL_REPORT_DEFAULT:
9135         case RPL_REPORT_ALL:
9136                 break;
9137         case RPL_REPORT_WELLKNOWN:
9138                 well_known = 1;
9139                 num_luns = 0;
9140                 break;
9141         default:
9142                 ctl_set_invalid_field(ctsio,
9143                                       /*sks_valid*/ 1,
9144                                       /*command*/ 1,
9145                                       /*field*/ 2,
9146                                       /*bit_valid*/ 0,
9147                                       /*bit*/ 0);
9148                 ctl_done((union ctl_io *)ctsio);
9149                 return (retval);
9150                 break; /* NOTREACHED */
9151         }
9152
9153         alloc_len = scsi_4btoul(cdb->length);
9154         /*
9155          * The initiator has to allocate at least 16 bytes for this request,
9156          * so he can at least get the header and the first LUN.  Otherwise
9157          * we reject the request (per SPC-3 rev 14, section 6.21).
9158          */
9159         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9160             sizeof(struct scsi_report_luns_lundata))) {
9161                 ctl_set_invalid_field(ctsio,
9162                                       /*sks_valid*/ 1,
9163                                       /*command*/ 1,
9164                                       /*field*/ 6,
9165                                       /*bit_valid*/ 0,
9166                                       /*bit*/ 0);
9167                 ctl_done((union ctl_io *)ctsio);
9168                 return (retval);
9169         }
9170
9171         request_lun = (struct ctl_lun *)
9172                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9173
9174         lun_datalen = sizeof(*lun_data) +
9175                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9176
9177         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9178         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9179         ctsio->kern_sg_entries = 0;
9180
9181         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9182
9183         mtx_lock(&softc->ctl_lock);
9184         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9185                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9186                 if (lun_id >= CTL_MAX_LUNS)
9187                         continue;
9188                 lun = softc->ctl_luns[lun_id];
9189                 if (lun == NULL)
9190                         continue;
9191
9192                 if (targ_lun_id <= 0xff) {
9193                         /*
9194                          * Peripheral addressing method, bus number 0.
9195                          */
9196                         lun_data->luns[num_filled].lundata[0] =
9197                                 RPL_LUNDATA_ATYP_PERIPH;
9198                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9199                         num_filled++;
9200                 } else if (targ_lun_id <= 0x3fff) {
9201                         /*
9202                          * Flat addressing method.
9203                          */
9204                         lun_data->luns[num_filled].lundata[0] =
9205                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9206                         lun_data->luns[num_filled].lundata[1] =
9207                                 (targ_lun_id & 0xff);
9208                         num_filled++;
9209                 } else if (targ_lun_id <= 0xffffff) {
9210                         /*
9211                          * Extended flat addressing method.
9212                          */
9213                         lun_data->luns[num_filled].lundata[0] =
9214                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9215                         scsi_ulto3b(targ_lun_id,
9216                             &lun_data->luns[num_filled].lundata[1]);
9217                         num_filled++;
9218                 } else {
9219                         printf("ctl_report_luns: bogus LUN number %jd, "
9220                                "skipping\n", (intmax_t)targ_lun_id);
9221                 }
9222                 /*
9223                  * According to SPC-3, rev 14 section 6.21:
9224                  *
9225                  * "The execution of a REPORT LUNS command to any valid and
9226                  * installed logical unit shall clear the REPORTED LUNS DATA
9227                  * HAS CHANGED unit attention condition for all logical
9228                  * units of that target with respect to the requesting
9229                  * initiator. A valid and installed logical unit is one
9230                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9231                  * INQUIRY data (see 6.4.2)."
9232                  *
9233                  * If request_lun is NULL, the LUN this report luns command
9234                  * was issued to is either disabled or doesn't exist. In that
9235                  * case, we shouldn't clear any pending lun change unit
9236                  * attention.
9237                  */
9238                 if (request_lun != NULL) {
9239                         mtx_lock(&lun->lun_lock);
9240                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9241                         mtx_unlock(&lun->lun_lock);
9242                 }
9243         }
9244         mtx_unlock(&softc->ctl_lock);
9245
9246         /*
9247          * It's quite possible that we've returned fewer LUNs than we allocated
9248          * space for.  Trim it.
9249          */
9250         lun_datalen = sizeof(*lun_data) +
9251                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9252
9253         if (lun_datalen < alloc_len) {
9254                 ctsio->residual = alloc_len - lun_datalen;
9255                 ctsio->kern_data_len = lun_datalen;
9256                 ctsio->kern_total_len = lun_datalen;
9257         } else {
9258                 ctsio->residual = 0;
9259                 ctsio->kern_data_len = alloc_len;
9260                 ctsio->kern_total_len = alloc_len;
9261         }
9262         ctsio->kern_data_resid = 0;
9263         ctsio->kern_rel_offset = 0;
9264         ctsio->kern_sg_entries = 0;
9265
9266         /*
9267          * We set this to the actual data length, regardless of how much
9268          * space we actually have to return results.  If the user looks at
9269          * this value, he'll know whether or not he allocated enough space
9270          * and reissue the command if necessary.  We don't support well
9271          * known logical units, so if the user asks for that, return none.
9272          */
9273         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9274
9275         /*
9276          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9277          * this request.
9278          */
9279         ctl_set_success(ctsio);
9280         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9281         ctsio->be_move_done = ctl_config_move_done;
9282         ctl_datamove((union ctl_io *)ctsio);
9283         return (retval);
9284 }
9285
9286 int
9287 ctl_request_sense(struct ctl_scsiio *ctsio)
9288 {
9289         struct scsi_request_sense *cdb;
9290         struct scsi_sense_data *sense_ptr;
9291         struct ctl_softc *ctl_softc;
9292         struct ctl_lun *lun;
9293         uint32_t initidx;
9294         int have_error;
9295         scsi_sense_data_type sense_format;
9296         ctl_ua_type ua_type;
9297
9298         cdb = (struct scsi_request_sense *)ctsio->cdb;
9299
9300         ctl_softc = control_softc;
9301         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9302
9303         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9304
9305         /*
9306          * Determine which sense format the user wants.
9307          */
9308         if (cdb->byte2 & SRS_DESC)
9309                 sense_format = SSD_TYPE_DESC;
9310         else
9311                 sense_format = SSD_TYPE_FIXED;
9312
9313         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9314         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9315         ctsio->kern_sg_entries = 0;
9316
9317         /*
9318          * struct scsi_sense_data, which is currently set to 256 bytes, is
9319          * larger than the largest allowed value for the length field in the
9320          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9321          */
9322         ctsio->residual = 0;
9323         ctsio->kern_data_len = cdb->length;
9324         ctsio->kern_total_len = cdb->length;
9325
9326         ctsio->kern_data_resid = 0;
9327         ctsio->kern_rel_offset = 0;
9328         ctsio->kern_sg_entries = 0;
9329
9330         /*
9331          * If we don't have a LUN, we don't have any pending sense.
9332          */
9333         if (lun == NULL)
9334                 goto no_sense;
9335
9336         have_error = 0;
9337         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9338         /*
9339          * Check for pending sense, and then for pending unit attentions.
9340          * Pending sense gets returned first, then pending unit attentions.
9341          */
9342         mtx_lock(&lun->lun_lock);
9343 #ifdef CTL_WITH_CA
9344         if (ctl_is_set(lun->have_ca, initidx)) {
9345                 scsi_sense_data_type stored_format;
9346
9347                 /*
9348                  * Check to see which sense format was used for the stored
9349                  * sense data.
9350                  */
9351                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9352
9353                 /*
9354                  * If the user requested a different sense format than the
9355                  * one we stored, then we need to convert it to the other
9356                  * format.  If we're going from descriptor to fixed format
9357                  * sense data, we may lose things in translation, depending
9358                  * on what options were used.
9359                  *
9360                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9361                  * for some reason we'll just copy it out as-is.
9362                  */
9363                 if ((stored_format == SSD_TYPE_FIXED)
9364                  && (sense_format == SSD_TYPE_DESC))
9365                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9366                             &lun->pending_sense[initidx],
9367                             (struct scsi_sense_data_desc *)sense_ptr);
9368                 else if ((stored_format == SSD_TYPE_DESC)
9369                       && (sense_format == SSD_TYPE_FIXED))
9370                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9371                             &lun->pending_sense[initidx],
9372                             (struct scsi_sense_data_fixed *)sense_ptr);
9373                 else
9374                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9375                                MIN(sizeof(*sense_ptr),
9376                                sizeof(lun->pending_sense[initidx])));
9377
9378                 ctl_clear_mask(lun->have_ca, initidx);
9379                 have_error = 1;
9380         } else
9381 #endif
9382         {
9383                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9384                 if (ua_type != CTL_UA_NONE)
9385                         have_error = 1;
9386                 if (ua_type == CTL_UA_LUN_CHANGE) {
9387                         mtx_unlock(&lun->lun_lock);
9388                         mtx_lock(&ctl_softc->ctl_lock);
9389                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9390                         mtx_unlock(&ctl_softc->ctl_lock);
9391                         mtx_lock(&lun->lun_lock);
9392                 }
9393
9394         }
9395         mtx_unlock(&lun->lun_lock);
9396
9397         /*
9398          * We already have a pending error, return it.
9399          */
9400         if (have_error != 0) {
9401                 /*
9402                  * We report the SCSI status as OK, since the status of the
9403                  * request sense command itself is OK.
9404                  * We report 0 for the sense length, because we aren't doing
9405                  * autosense in this case.  We're reporting sense as
9406                  * parameter data.
9407                  */
9408                 ctl_set_success(ctsio);
9409                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9410                 ctsio->be_move_done = ctl_config_move_done;
9411                 ctl_datamove((union ctl_io *)ctsio);
9412                 return (CTL_RETVAL_COMPLETE);
9413         }
9414
9415 no_sense:
9416
9417         /*
9418          * No sense information to report, so we report that everything is
9419          * okay.
9420          */
9421         ctl_set_sense_data(sense_ptr,
9422                            lun,
9423                            sense_format,
9424                            /*current_error*/ 1,
9425                            /*sense_key*/ SSD_KEY_NO_SENSE,
9426                            /*asc*/ 0x00,
9427                            /*ascq*/ 0x00,
9428                            SSD_ELEM_NONE);
9429
9430         /*
9431          * We report 0 for the sense length, because we aren't doing
9432          * autosense in this case.  We're reporting sense as parameter data.
9433          */
9434         ctl_set_success(ctsio);
9435         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9436         ctsio->be_move_done = ctl_config_move_done;
9437         ctl_datamove((union ctl_io *)ctsio);
9438         return (CTL_RETVAL_COMPLETE);
9439 }
9440
9441 int
9442 ctl_tur(struct ctl_scsiio *ctsio)
9443 {
9444
9445         CTL_DEBUG_PRINT(("ctl_tur\n"));
9446
9447         ctl_set_success(ctsio);
9448         ctl_done((union ctl_io *)ctsio);
9449
9450         return (CTL_RETVAL_COMPLETE);
9451 }
9452
9453 /*
9454  * SCSI VPD page 0x00, the Supported VPD Pages page.
9455  */
9456 static int
9457 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9458 {
9459         struct scsi_vpd_supported_pages *pages;
9460         int sup_page_size;
9461         struct ctl_lun *lun;
9462         int p;
9463
9464         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9465
9466         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9467             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9468         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9469         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9470         ctsio->kern_sg_entries = 0;
9471
9472         if (sup_page_size < alloc_len) {
9473                 ctsio->residual = alloc_len - sup_page_size;
9474                 ctsio->kern_data_len = sup_page_size;
9475                 ctsio->kern_total_len = sup_page_size;
9476         } else {
9477                 ctsio->residual = 0;
9478                 ctsio->kern_data_len = alloc_len;
9479                 ctsio->kern_total_len = alloc_len;
9480         }
9481         ctsio->kern_data_resid = 0;
9482         ctsio->kern_rel_offset = 0;
9483         ctsio->kern_sg_entries = 0;
9484
9485         /*
9486          * The control device is always connected.  The disk device, on the
9487          * other hand, may not be online all the time.  Need to change this
9488          * to figure out whether the disk device is actually online or not.
9489          */
9490         if (lun != NULL)
9491                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9492                                 lun->be_lun->lun_type;
9493         else
9494                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9495
9496         p = 0;
9497         /* Supported VPD pages */
9498         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9499         /* Serial Number */
9500         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9501         /* Device Identification */
9502         pages->page_list[p++] = SVPD_DEVICE_ID;
9503         /* Extended INQUIRY Data */
9504         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9505         /* Mode Page Policy */
9506         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9507         /* SCSI Ports */
9508         pages->page_list[p++] = SVPD_SCSI_PORTS;
9509         /* Third-party Copy */
9510         pages->page_list[p++] = SVPD_SCSI_TPC;
9511         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9512                 /* Block limits */
9513                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9514                 /* Block Device Characteristics */
9515                 pages->page_list[p++] = SVPD_BDC;
9516                 /* Logical Block Provisioning */
9517                 pages->page_list[p++] = SVPD_LBP;
9518         }
9519         pages->length = p;
9520
9521         ctl_set_success(ctsio);
9522         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9523         ctsio->be_move_done = ctl_config_move_done;
9524         ctl_datamove((union ctl_io *)ctsio);
9525         return (CTL_RETVAL_COMPLETE);
9526 }
9527
9528 /*
9529  * SCSI VPD page 0x80, the Unit Serial Number page.
9530  */
9531 static int
9532 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9533 {
9534         struct scsi_vpd_unit_serial_number *sn_ptr;
9535         struct ctl_lun *lun;
9536         int data_len;
9537
9538         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9539
9540         data_len = 4 + CTL_SN_LEN;
9541         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9542         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9543         if (data_len < alloc_len) {
9544                 ctsio->residual = alloc_len - data_len;
9545                 ctsio->kern_data_len = data_len;
9546                 ctsio->kern_total_len = data_len;
9547         } else {
9548                 ctsio->residual = 0;
9549                 ctsio->kern_data_len = alloc_len;
9550                 ctsio->kern_total_len = alloc_len;
9551         }
9552         ctsio->kern_data_resid = 0;
9553         ctsio->kern_rel_offset = 0;
9554         ctsio->kern_sg_entries = 0;
9555
9556         /*
9557          * The control device is always connected.  The disk device, on the
9558          * other hand, may not be online all the time.  Need to change this
9559          * to figure out whether the disk device is actually online or not.
9560          */
9561         if (lun != NULL)
9562                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9563                                   lun->be_lun->lun_type;
9564         else
9565                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9566
9567         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9568         sn_ptr->length = CTL_SN_LEN;
9569         /*
9570          * If we don't have a LUN, we just leave the serial number as
9571          * all spaces.
9572          */
9573         if (lun != NULL) {
9574                 strncpy((char *)sn_ptr->serial_num,
9575                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9576         } else
9577                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9578
9579         ctl_set_success(ctsio);
9580         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9581         ctsio->be_move_done = ctl_config_move_done;
9582         ctl_datamove((union ctl_io *)ctsio);
9583         return (CTL_RETVAL_COMPLETE);
9584 }
9585
9586
9587 /*
9588  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9589  */
9590 static int
9591 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9592 {
9593         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9594         struct ctl_lun *lun;
9595         int data_len;
9596
9597         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9598
9599         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9600         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9601         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9602         ctsio->kern_sg_entries = 0;
9603
9604         if (data_len < alloc_len) {
9605                 ctsio->residual = alloc_len - data_len;
9606                 ctsio->kern_data_len = data_len;
9607                 ctsio->kern_total_len = data_len;
9608         } else {
9609                 ctsio->residual = 0;
9610                 ctsio->kern_data_len = alloc_len;
9611                 ctsio->kern_total_len = alloc_len;
9612         }
9613         ctsio->kern_data_resid = 0;
9614         ctsio->kern_rel_offset = 0;
9615         ctsio->kern_sg_entries = 0;
9616
9617         /*
9618          * The control device is always connected.  The disk device, on the
9619          * other hand, may not be online all the time.
9620          */
9621         if (lun != NULL)
9622                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9623                                      lun->be_lun->lun_type;
9624         else
9625                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9626         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9627         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9628         /*
9629          * We support head of queue, ordered and simple tags.
9630          */
9631         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9632         /*
9633          * Volatile cache supported.
9634          */
9635         eid_ptr->flags3 = SVPD_EID_V_SUP;
9636
9637         /*
9638          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9639          * attention for a particular IT nexus on all LUNs once we report
9640          * it to that nexus once.  This bit is required as of SPC-4.
9641          */
9642         eid_ptr->flags4 = SVPD_EID_LUICLT;
9643
9644         /*
9645          * XXX KDM in order to correctly answer this, we would need
9646          * information from the SIM to determine how much sense data it
9647          * can send.  So this would really be a path inquiry field, most
9648          * likely.  This can be set to a maximum of 252 according to SPC-4,
9649          * but the hardware may or may not be able to support that much.
9650          * 0 just means that the maximum sense data length is not reported.
9651          */
9652         eid_ptr->max_sense_length = 0;
9653
9654         ctl_set_success(ctsio);
9655         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9656         ctsio->be_move_done = ctl_config_move_done;
9657         ctl_datamove((union ctl_io *)ctsio);
9658         return (CTL_RETVAL_COMPLETE);
9659 }
9660
9661 static int
9662 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9663 {
9664         struct scsi_vpd_mode_page_policy *mpp_ptr;
9665         struct ctl_lun *lun;
9666         int data_len;
9667
9668         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9669
9670         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9671             sizeof(struct scsi_vpd_mode_page_policy_descr);
9672
9673         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9674         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9675         ctsio->kern_sg_entries = 0;
9676
9677         if (data_len < alloc_len) {
9678                 ctsio->residual = alloc_len - data_len;
9679                 ctsio->kern_data_len = data_len;
9680                 ctsio->kern_total_len = data_len;
9681         } else {
9682                 ctsio->residual = 0;
9683                 ctsio->kern_data_len = alloc_len;
9684                 ctsio->kern_total_len = alloc_len;
9685         }
9686         ctsio->kern_data_resid = 0;
9687         ctsio->kern_rel_offset = 0;
9688         ctsio->kern_sg_entries = 0;
9689
9690         /*
9691          * The control device is always connected.  The disk device, on the
9692          * other hand, may not be online all the time.
9693          */
9694         if (lun != NULL)
9695                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9696                                      lun->be_lun->lun_type;
9697         else
9698                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9699         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9700         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9701         mpp_ptr->descr[0].page_code = 0x3f;
9702         mpp_ptr->descr[0].subpage_code = 0xff;
9703         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9704
9705         ctl_set_success(ctsio);
9706         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9707         ctsio->be_move_done = ctl_config_move_done;
9708         ctl_datamove((union ctl_io *)ctsio);
9709         return (CTL_RETVAL_COMPLETE);
9710 }
9711
9712 /*
9713  * SCSI VPD page 0x83, the Device Identification page.
9714  */
9715 static int
9716 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9717 {
9718         struct scsi_vpd_device_id *devid_ptr;
9719         struct scsi_vpd_id_descriptor *desc;
9720         struct ctl_softc *softc;
9721         struct ctl_lun *lun;
9722         struct ctl_port *port;
9723         int data_len;
9724         uint8_t proto;
9725
9726         softc = control_softc;
9727
9728         port = ctl_io_port(&ctsio->io_hdr);
9729         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9730
9731         data_len = sizeof(struct scsi_vpd_device_id) +
9732             sizeof(struct scsi_vpd_id_descriptor) +
9733                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9734             sizeof(struct scsi_vpd_id_descriptor) +
9735                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9736         if (lun && lun->lun_devid)
9737                 data_len += lun->lun_devid->len;
9738         if (port && port->port_devid)
9739                 data_len += port->port_devid->len;
9740         if (port && port->target_devid)
9741                 data_len += port->target_devid->len;
9742
9743         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9744         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9745         ctsio->kern_sg_entries = 0;
9746
9747         if (data_len < alloc_len) {
9748                 ctsio->residual = alloc_len - data_len;
9749                 ctsio->kern_data_len = data_len;
9750                 ctsio->kern_total_len = data_len;
9751         } else {
9752                 ctsio->residual = 0;
9753                 ctsio->kern_data_len = alloc_len;
9754                 ctsio->kern_total_len = alloc_len;
9755         }
9756         ctsio->kern_data_resid = 0;
9757         ctsio->kern_rel_offset = 0;
9758         ctsio->kern_sg_entries = 0;
9759
9760         /*
9761          * The control device is always connected.  The disk device, on the
9762          * other hand, may not be online all the time.
9763          */
9764         if (lun != NULL)
9765                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9766                                      lun->be_lun->lun_type;
9767         else
9768                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9769         devid_ptr->page_code = SVPD_DEVICE_ID;
9770         scsi_ulto2b(data_len - 4, devid_ptr->length);
9771
9772         if (port && port->port_type == CTL_PORT_FC)
9773                 proto = SCSI_PROTO_FC << 4;
9774         else if (port && port->port_type == CTL_PORT_ISCSI)
9775                 proto = SCSI_PROTO_ISCSI << 4;
9776         else
9777                 proto = SCSI_PROTO_SPI << 4;
9778         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9779
9780         /*
9781          * We're using a LUN association here.  i.e., this device ID is a
9782          * per-LUN identifier.
9783          */
9784         if (lun && lun->lun_devid) {
9785                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9786                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9787                     lun->lun_devid->len);
9788         }
9789
9790         /*
9791          * This is for the WWPN which is a port association.
9792          */
9793         if (port && port->port_devid) {
9794                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9795                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9796                     port->port_devid->len);
9797         }
9798
9799         /*
9800          * This is for the Relative Target Port(type 4h) identifier
9801          */
9802         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9803         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9804             SVPD_ID_TYPE_RELTARG;
9805         desc->length = 4;
9806         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9807         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9808             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9809
9810         /*
9811          * This is for the Target Port Group(type 5h) identifier
9812          */
9813         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9814         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9815             SVPD_ID_TYPE_TPORTGRP;
9816         desc->length = 4;
9817         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9818             &desc->identifier[2]);
9819         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9820             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9821
9822         /*
9823          * This is for the Target identifier
9824          */
9825         if (port && port->target_devid) {
9826                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9827         }
9828
9829         ctl_set_success(ctsio);
9830         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9831         ctsio->be_move_done = ctl_config_move_done;
9832         ctl_datamove((union ctl_io *)ctsio);
9833         return (CTL_RETVAL_COMPLETE);
9834 }
9835
9836 static int
9837 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9838 {
9839         struct ctl_softc *softc = control_softc;
9840         struct scsi_vpd_scsi_ports *sp;
9841         struct scsi_vpd_port_designation *pd;
9842         struct scsi_vpd_port_designation_cont *pdc;
9843         struct ctl_lun *lun;
9844         struct ctl_port *port;
9845         int data_len, num_target_ports, iid_len, id_len;
9846
9847         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9848
9849         num_target_ports = 0;
9850         iid_len = 0;
9851         id_len = 0;
9852         mtx_lock(&softc->ctl_lock);
9853         STAILQ_FOREACH(port, &softc->port_list, links) {
9854                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9855                         continue;
9856                 if (lun != NULL &&
9857                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9858                         continue;
9859                 num_target_ports++;
9860                 if (port->init_devid)
9861                         iid_len += port->init_devid->len;
9862                 if (port->port_devid)
9863                         id_len += port->port_devid->len;
9864         }
9865         mtx_unlock(&softc->ctl_lock);
9866
9867         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9868             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9869              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9870         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9871         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9872         ctsio->kern_sg_entries = 0;
9873
9874         if (data_len < alloc_len) {
9875                 ctsio->residual = alloc_len - data_len;
9876                 ctsio->kern_data_len = data_len;
9877                 ctsio->kern_total_len = data_len;
9878         } else {
9879                 ctsio->residual = 0;
9880                 ctsio->kern_data_len = alloc_len;
9881                 ctsio->kern_total_len = alloc_len;
9882         }
9883         ctsio->kern_data_resid = 0;
9884         ctsio->kern_rel_offset = 0;
9885         ctsio->kern_sg_entries = 0;
9886
9887         /*
9888          * The control device is always connected.  The disk device, on the
9889          * other hand, may not be online all the time.  Need to change this
9890          * to figure out whether the disk device is actually online or not.
9891          */
9892         if (lun != NULL)
9893                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9894                                   lun->be_lun->lun_type;
9895         else
9896                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9897
9898         sp->page_code = SVPD_SCSI_PORTS;
9899         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9900             sp->page_length);
9901         pd = &sp->design[0];
9902
9903         mtx_lock(&softc->ctl_lock);
9904         STAILQ_FOREACH(port, &softc->port_list, links) {
9905                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9906                         continue;
9907                 if (lun != NULL &&
9908                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9909                         continue;
9910                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9911                 if (port->init_devid) {
9912                         iid_len = port->init_devid->len;
9913                         memcpy(pd->initiator_transportid,
9914                             port->init_devid->data, port->init_devid->len);
9915                 } else
9916                         iid_len = 0;
9917                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9918                 pdc = (struct scsi_vpd_port_designation_cont *)
9919                     (&pd->initiator_transportid[iid_len]);
9920                 if (port->port_devid) {
9921                         id_len = port->port_devid->len;
9922                         memcpy(pdc->target_port_descriptors,
9923                             port->port_devid->data, port->port_devid->len);
9924                 } else
9925                         id_len = 0;
9926                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9927                 pd = (struct scsi_vpd_port_designation *)
9928                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9929         }
9930         mtx_unlock(&softc->ctl_lock);
9931
9932         ctl_set_success(ctsio);
9933         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9934         ctsio->be_move_done = ctl_config_move_done;
9935         ctl_datamove((union ctl_io *)ctsio);
9936         return (CTL_RETVAL_COMPLETE);
9937 }
9938
9939 static int
9940 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9941 {
9942         struct scsi_vpd_block_limits *bl_ptr;
9943         struct ctl_lun *lun;
9944         int bs;
9945
9946         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9947
9948         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9949         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9950         ctsio->kern_sg_entries = 0;
9951
9952         if (sizeof(*bl_ptr) < alloc_len) {
9953                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9954                 ctsio->kern_data_len = sizeof(*bl_ptr);
9955                 ctsio->kern_total_len = sizeof(*bl_ptr);
9956         } else {
9957                 ctsio->residual = 0;
9958                 ctsio->kern_data_len = alloc_len;
9959                 ctsio->kern_total_len = alloc_len;
9960         }
9961         ctsio->kern_data_resid = 0;
9962         ctsio->kern_rel_offset = 0;
9963         ctsio->kern_sg_entries = 0;
9964
9965         /*
9966          * The control device is always connected.  The disk device, on the
9967          * other hand, may not be online all the time.  Need to change this
9968          * to figure out whether the disk device is actually online or not.
9969          */
9970         if (lun != NULL)
9971                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9972                                   lun->be_lun->lun_type;
9973         else
9974                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9975
9976         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9977         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9978         bl_ptr->max_cmp_write_len = 0xff;
9979         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9980         if (lun != NULL) {
9981                 bs = lun->be_lun->blocksize;
9982                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9983                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9984                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9985                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9986                         if (lun->be_lun->ublockexp != 0) {
9987                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9988                                     bl_ptr->opt_unmap_grain);
9989                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9990                                     bl_ptr->unmap_grain_align);
9991                         }
9992                 }
9993                 scsi_ulto4b(lun->be_lun->atomicblock,
9994                     bl_ptr->max_atomic_transfer_length);
9995                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9996                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9997         }
9998         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9999
10000         ctl_set_success(ctsio);
10001         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10002         ctsio->be_move_done = ctl_config_move_done;
10003         ctl_datamove((union ctl_io *)ctsio);
10004         return (CTL_RETVAL_COMPLETE);
10005 }
10006
10007 static int
10008 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10009 {
10010         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10011         struct ctl_lun *lun;
10012         const char *value;
10013         u_int i;
10014
10015         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10016
10017         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10018         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10019         ctsio->kern_sg_entries = 0;
10020
10021         if (sizeof(*bdc_ptr) < alloc_len) {
10022                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10023                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10024                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10025         } else {
10026                 ctsio->residual = 0;
10027                 ctsio->kern_data_len = alloc_len;
10028                 ctsio->kern_total_len = alloc_len;
10029         }
10030         ctsio->kern_data_resid = 0;
10031         ctsio->kern_rel_offset = 0;
10032         ctsio->kern_sg_entries = 0;
10033
10034         /*
10035          * The control device is always connected.  The disk device, on the
10036          * other hand, may not be online all the time.  Need to change this
10037          * to figure out whether the disk device is actually online or not.
10038          */
10039         if (lun != NULL)
10040                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10041                                   lun->be_lun->lun_type;
10042         else
10043                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10044         bdc_ptr->page_code = SVPD_BDC;
10045         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10046         if (lun != NULL &&
10047             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10048                 i = strtol(value, NULL, 0);
10049         else
10050                 i = CTL_DEFAULT_ROTATION_RATE;
10051         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10052         if (lun != NULL &&
10053             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10054                 i = strtol(value, NULL, 0);
10055         else
10056                 i = 0;
10057         bdc_ptr->wab_wac_ff = (i & 0x0f);
10058         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10059
10060         ctl_set_success(ctsio);
10061         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10062         ctsio->be_move_done = ctl_config_move_done;
10063         ctl_datamove((union ctl_io *)ctsio);
10064         return (CTL_RETVAL_COMPLETE);
10065 }
10066
10067 static int
10068 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10069 {
10070         struct scsi_vpd_logical_block_prov *lbp_ptr;
10071         struct ctl_lun *lun;
10072
10073         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10074
10075         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10076         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10077         ctsio->kern_sg_entries = 0;
10078
10079         if (sizeof(*lbp_ptr) < alloc_len) {
10080                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10081                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10082                 ctsio->kern_total_len = sizeof(*lbp_ptr);
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                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10099                                   lun->be_lun->lun_type;
10100         else
10101                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10102
10103         lbp_ptr->page_code = SVPD_LBP;
10104         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10105         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10106         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10107                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10108                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10109                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10110         }
10111
10112         ctl_set_success(ctsio);
10113         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10114         ctsio->be_move_done = ctl_config_move_done;
10115         ctl_datamove((union ctl_io *)ctsio);
10116         return (CTL_RETVAL_COMPLETE);
10117 }
10118
10119 /*
10120  * INQUIRY with the EVPD bit set.
10121  */
10122 static int
10123 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10124 {
10125         struct ctl_lun *lun;
10126         struct scsi_inquiry *cdb;
10127         int alloc_len, retval;
10128
10129         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10130         cdb = (struct scsi_inquiry *)ctsio->cdb;
10131         alloc_len = scsi_2btoul(cdb->length);
10132
10133         switch (cdb->page_code) {
10134         case SVPD_SUPPORTED_PAGES:
10135                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10136                 break;
10137         case SVPD_UNIT_SERIAL_NUMBER:
10138                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10139                 break;
10140         case SVPD_DEVICE_ID:
10141                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10142                 break;
10143         case SVPD_EXTENDED_INQUIRY_DATA:
10144                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10145                 break;
10146         case SVPD_MODE_PAGE_POLICY:
10147                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10148                 break;
10149         case SVPD_SCSI_PORTS:
10150                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10151                 break;
10152         case SVPD_SCSI_TPC:
10153                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10154                 break;
10155         case SVPD_BLOCK_LIMITS:
10156                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10157                         goto err;
10158                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10159                 break;
10160         case SVPD_BDC:
10161                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10162                         goto err;
10163                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10164                 break;
10165         case SVPD_LBP:
10166                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10167                         goto err;
10168                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10169                 break;
10170         default:
10171 err:
10172                 ctl_set_invalid_field(ctsio,
10173                                       /*sks_valid*/ 1,
10174                                       /*command*/ 1,
10175                                       /*field*/ 2,
10176                                       /*bit_valid*/ 0,
10177                                       /*bit*/ 0);
10178                 ctl_done((union ctl_io *)ctsio);
10179                 retval = CTL_RETVAL_COMPLETE;
10180                 break;
10181         }
10182
10183         return (retval);
10184 }
10185
10186 /*
10187  * Standard INQUIRY data.
10188  */
10189 static int
10190 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10191 {
10192         struct scsi_inquiry_data *inq_ptr;
10193         struct scsi_inquiry *cdb;
10194         struct ctl_softc *softc;
10195         struct ctl_port *port;
10196         struct ctl_lun *lun;
10197         char *val;
10198         uint32_t alloc_len, data_len;
10199         ctl_port_type port_type;
10200
10201         softc = control_softc;
10202
10203         /*
10204          * Figure out whether we're talking to a Fibre Channel port or not.
10205          * We treat the ioctl front end, and any SCSI adapters, as packetized
10206          * SCSI front ends.
10207          */
10208         port = ctl_io_port(&ctsio->io_hdr);
10209         if (port != NULL)
10210                 port_type = port->port_type;
10211         else
10212                 port_type = CTL_PORT_SCSI;
10213         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10214                 port_type = CTL_PORT_SCSI;
10215
10216         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10217         cdb = (struct scsi_inquiry *)ctsio->cdb;
10218         alloc_len = scsi_2btoul(cdb->length);
10219
10220         /*
10221          * We malloc the full inquiry data size here and fill it
10222          * in.  If the user only asks for less, we'll give him
10223          * that much.
10224          */
10225         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10226         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10227         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10228         ctsio->kern_sg_entries = 0;
10229         ctsio->kern_data_resid = 0;
10230         ctsio->kern_rel_offset = 0;
10231
10232         if (data_len < alloc_len) {
10233                 ctsio->residual = alloc_len - data_len;
10234                 ctsio->kern_data_len = data_len;
10235                 ctsio->kern_total_len = data_len;
10236         } else {
10237                 ctsio->residual = 0;
10238                 ctsio->kern_data_len = alloc_len;
10239                 ctsio->kern_total_len = alloc_len;
10240         }
10241
10242         if (lun != NULL) {
10243                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10244                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10245                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10246                             lun->be_lun->lun_type;
10247                 } else {
10248                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10249                             lun->be_lun->lun_type;
10250                 }
10251         } else
10252                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10253
10254         /* RMB in byte 2 is 0 */
10255         inq_ptr->version = SCSI_REV_SPC4;
10256
10257         /*
10258          * According to SAM-3, even if a device only supports a single
10259          * level of LUN addressing, it should still set the HISUP bit:
10260          *
10261          * 4.9.1 Logical unit numbers overview
10262          *
10263          * All logical unit number formats described in this standard are
10264          * hierarchical in structure even when only a single level in that
10265          * hierarchy is used. The HISUP bit shall be set to one in the
10266          * standard INQUIRY data (see SPC-2) when any logical unit number
10267          * format described in this standard is used.  Non-hierarchical
10268          * formats are outside the scope of this standard.
10269          *
10270          * Therefore we set the HiSup bit here.
10271          *
10272          * The reponse format is 2, per SPC-3.
10273          */
10274         inq_ptr->response_format = SID_HiSup | 2;
10275
10276         inq_ptr->additional_length = data_len -
10277             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10278         CTL_DEBUG_PRINT(("additional_length = %d\n",
10279                          inq_ptr->additional_length));
10280
10281         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10282         /* 16 bit addressing */
10283         if (port_type == CTL_PORT_SCSI)
10284                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10285         /* XXX set the SID_MultiP bit here if we're actually going to
10286            respond on multiple ports */
10287         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10288
10289         /* 16 bit data bus, synchronous transfers */
10290         if (port_type == CTL_PORT_SCSI)
10291                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10292         /*
10293          * XXX KDM do we want to support tagged queueing on the control
10294          * device at all?
10295          */
10296         if ((lun == NULL)
10297          || (lun->be_lun->lun_type != T_PROCESSOR))
10298                 inq_ptr->flags |= SID_CmdQue;
10299         /*
10300          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10301          * We have 8 bytes for the vendor name, and 16 bytes for the device
10302          * name and 4 bytes for the revision.
10303          */
10304         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10305             "vendor")) == NULL) {
10306                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10307         } else {
10308                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10309                 strncpy(inq_ptr->vendor, val,
10310                     min(sizeof(inq_ptr->vendor), strlen(val)));
10311         }
10312         if (lun == NULL) {
10313                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10314                     sizeof(inq_ptr->product));
10315         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10316                 switch (lun->be_lun->lun_type) {
10317                 case T_DIRECT:
10318                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10319                             sizeof(inq_ptr->product));
10320                         break;
10321                 case T_PROCESSOR:
10322                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10323                             sizeof(inq_ptr->product));
10324                         break;
10325                 default:
10326                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10327                             sizeof(inq_ptr->product));
10328                         break;
10329                 }
10330         } else {
10331                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10332                 strncpy(inq_ptr->product, val,
10333                     min(sizeof(inq_ptr->product), strlen(val)));
10334         }
10335
10336         /*
10337          * XXX make this a macro somewhere so it automatically gets
10338          * incremented when we make changes.
10339          */
10340         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10341             "revision")) == NULL) {
10342                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10343         } else {
10344                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10345                 strncpy(inq_ptr->revision, val,
10346                     min(sizeof(inq_ptr->revision), strlen(val)));
10347         }
10348
10349         /*
10350          * For parallel SCSI, we support double transition and single
10351          * transition clocking.  We also support QAS (Quick Arbitration
10352          * and Selection) and Information Unit transfers on both the
10353          * control and array devices.
10354          */
10355         if (port_type == CTL_PORT_SCSI)
10356                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10357                                     SID_SPI_IUS;
10358
10359         /* SAM-5 (no version claimed) */
10360         scsi_ulto2b(0x00A0, inq_ptr->version1);
10361         /* SPC-4 (no version claimed) */
10362         scsi_ulto2b(0x0460, inq_ptr->version2);
10363         if (port_type == CTL_PORT_FC) {
10364                 /* FCP-2 ANSI INCITS.350:2003 */
10365                 scsi_ulto2b(0x0917, inq_ptr->version3);
10366         } else if (port_type == CTL_PORT_SCSI) {
10367                 /* SPI-4 ANSI INCITS.362:200x */
10368                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10369         } else if (port_type == CTL_PORT_ISCSI) {
10370                 /* iSCSI (no version claimed) */
10371                 scsi_ulto2b(0x0960, inq_ptr->version3);
10372         } else if (port_type == CTL_PORT_SAS) {
10373                 /* SAS (no version claimed) */
10374                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10375         }
10376
10377         if (lun == NULL) {
10378                 /* SBC-4 (no version claimed) */
10379                 scsi_ulto2b(0x0600, inq_ptr->version4);
10380         } else {
10381                 switch (lun->be_lun->lun_type) {
10382                 case T_DIRECT:
10383                         /* SBC-4 (no version claimed) */
10384                         scsi_ulto2b(0x0600, inq_ptr->version4);
10385                         break;
10386                 case T_PROCESSOR:
10387                 default:
10388                         break;
10389                 }
10390         }
10391
10392         ctl_set_success(ctsio);
10393         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10394         ctsio->be_move_done = ctl_config_move_done;
10395         ctl_datamove((union ctl_io *)ctsio);
10396         return (CTL_RETVAL_COMPLETE);
10397 }
10398
10399 int
10400 ctl_inquiry(struct ctl_scsiio *ctsio)
10401 {
10402         struct scsi_inquiry *cdb;
10403         int retval;
10404
10405         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10406
10407         cdb = (struct scsi_inquiry *)ctsio->cdb;
10408         if (cdb->byte2 & SI_EVPD)
10409                 retval = ctl_inquiry_evpd(ctsio);
10410         else if (cdb->page_code == 0)
10411                 retval = ctl_inquiry_std(ctsio);
10412         else {
10413                 ctl_set_invalid_field(ctsio,
10414                                       /*sks_valid*/ 1,
10415                                       /*command*/ 1,
10416                                       /*field*/ 2,
10417                                       /*bit_valid*/ 0,
10418                                       /*bit*/ 0);
10419                 ctl_done((union ctl_io *)ctsio);
10420                 return (CTL_RETVAL_COMPLETE);
10421         }
10422
10423         return (retval);
10424 }
10425
10426 /*
10427  * For known CDB types, parse the LBA and length.
10428  */
10429 static int
10430 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10431 {
10432         if (io->io_hdr.io_type != CTL_IO_SCSI)
10433                 return (1);
10434
10435         switch (io->scsiio.cdb[0]) {
10436         case COMPARE_AND_WRITE: {
10437                 struct scsi_compare_and_write *cdb;
10438
10439                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10440
10441                 *lba = scsi_8btou64(cdb->addr);
10442                 *len = cdb->length;
10443                 break;
10444         }
10445         case READ_6:
10446         case WRITE_6: {
10447                 struct scsi_rw_6 *cdb;
10448
10449                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10450
10451                 *lba = scsi_3btoul(cdb->addr);
10452                 /* only 5 bits are valid in the most significant address byte */
10453                 *lba &= 0x1fffff;
10454                 *len = cdb->length;
10455                 break;
10456         }
10457         case READ_10:
10458         case WRITE_10: {
10459                 struct scsi_rw_10 *cdb;
10460
10461                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10462
10463                 *lba = scsi_4btoul(cdb->addr);
10464                 *len = scsi_2btoul(cdb->length);
10465                 break;
10466         }
10467         case WRITE_VERIFY_10: {
10468                 struct scsi_write_verify_10 *cdb;
10469
10470                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10471
10472                 *lba = scsi_4btoul(cdb->addr);
10473                 *len = scsi_2btoul(cdb->length);
10474                 break;
10475         }
10476         case READ_12:
10477         case WRITE_12: {
10478                 struct scsi_rw_12 *cdb;
10479
10480                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10481
10482                 *lba = scsi_4btoul(cdb->addr);
10483                 *len = scsi_4btoul(cdb->length);
10484                 break;
10485         }
10486         case WRITE_VERIFY_12: {
10487                 struct scsi_write_verify_12 *cdb;
10488
10489                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10490
10491                 *lba = scsi_4btoul(cdb->addr);
10492                 *len = scsi_4btoul(cdb->length);
10493                 break;
10494         }
10495         case READ_16:
10496         case WRITE_16:
10497         case WRITE_ATOMIC_16: {
10498                 struct scsi_rw_16 *cdb;
10499
10500                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10501
10502                 *lba = scsi_8btou64(cdb->addr);
10503                 *len = scsi_4btoul(cdb->length);
10504                 break;
10505         }
10506         case WRITE_VERIFY_16: {
10507                 struct scsi_write_verify_16 *cdb;
10508
10509                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10510
10511                 *lba = scsi_8btou64(cdb->addr);
10512                 *len = scsi_4btoul(cdb->length);
10513                 break;
10514         }
10515         case WRITE_SAME_10: {
10516                 struct scsi_write_same_10 *cdb;
10517
10518                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10519
10520                 *lba = scsi_4btoul(cdb->addr);
10521                 *len = scsi_2btoul(cdb->length);
10522                 break;
10523         }
10524         case WRITE_SAME_16: {
10525                 struct scsi_write_same_16 *cdb;
10526
10527                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10528
10529                 *lba = scsi_8btou64(cdb->addr);
10530                 *len = scsi_4btoul(cdb->length);
10531                 break;
10532         }
10533         case VERIFY_10: {
10534                 struct scsi_verify_10 *cdb;
10535
10536                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10537
10538                 *lba = scsi_4btoul(cdb->addr);
10539                 *len = scsi_2btoul(cdb->length);
10540                 break;
10541         }
10542         case VERIFY_12: {
10543                 struct scsi_verify_12 *cdb;
10544
10545                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10546
10547                 *lba = scsi_4btoul(cdb->addr);
10548                 *len = scsi_4btoul(cdb->length);
10549                 break;
10550         }
10551         case VERIFY_16: {
10552                 struct scsi_verify_16 *cdb;
10553
10554                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10555
10556                 *lba = scsi_8btou64(cdb->addr);
10557                 *len = scsi_4btoul(cdb->length);
10558                 break;
10559         }
10560         case UNMAP: {
10561                 *lba = 0;
10562                 *len = UINT64_MAX;
10563                 break;
10564         }
10565         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10566                 struct scsi_get_lba_status *cdb;
10567
10568                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10569                 *lba = scsi_8btou64(cdb->addr);
10570                 *len = UINT32_MAX;
10571                 break;
10572         }
10573         default:
10574                 return (1);
10575                 break; /* NOTREACHED */
10576         }
10577
10578         return (0);
10579 }
10580
10581 static ctl_action
10582 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10583     bool seq)
10584 {
10585         uint64_t endlba1, endlba2;
10586
10587         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10588         endlba2 = lba2 + len2 - 1;
10589
10590         if ((endlba1 < lba2) || (endlba2 < lba1))
10591                 return (CTL_ACTION_PASS);
10592         else
10593                 return (CTL_ACTION_BLOCK);
10594 }
10595
10596 static int
10597 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10598 {
10599         struct ctl_ptr_len_flags *ptrlen;
10600         struct scsi_unmap_desc *buf, *end, *range;
10601         uint64_t lba;
10602         uint32_t len;
10603
10604         /* If not UNMAP -- go other way. */
10605         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10606             io->scsiio.cdb[0] != UNMAP)
10607                 return (CTL_ACTION_ERROR);
10608
10609         /* If UNMAP without data -- block and wait for data. */
10610         ptrlen = (struct ctl_ptr_len_flags *)
10611             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10612         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10613             ptrlen->ptr == NULL)
10614                 return (CTL_ACTION_BLOCK);
10615
10616         /* UNMAP with data -- check for collision. */
10617         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10618         end = buf + ptrlen->len / sizeof(*buf);
10619         for (range = buf; range < end; range++) {
10620                 lba = scsi_8btou64(range->lba);
10621                 len = scsi_4btoul(range->length);
10622                 if ((lba < lba2 + len2) && (lba + len > lba2))
10623                         return (CTL_ACTION_BLOCK);
10624         }
10625         return (CTL_ACTION_PASS);
10626 }
10627
10628 static ctl_action
10629 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10630 {
10631         uint64_t lba1, lba2;
10632         uint64_t len1, len2;
10633         int retval;
10634
10635         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10636                 return (CTL_ACTION_ERROR);
10637
10638         retval = ctl_extent_check_unmap(io1, lba2, len2);
10639         if (retval != CTL_ACTION_ERROR)
10640                 return (retval);
10641
10642         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10643                 return (CTL_ACTION_ERROR);
10644
10645         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10646                 seq = FALSE;
10647         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10648 }
10649
10650 static ctl_action
10651 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10652 {
10653         uint64_t lba1, lba2;
10654         uint64_t len1, len2;
10655
10656         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10657                 return (CTL_ACTION_PASS);
10658         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10659                 return (CTL_ACTION_ERROR);
10660         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10661                 return (CTL_ACTION_ERROR);
10662
10663         if (lba1 + len1 == lba2)
10664                 return (CTL_ACTION_BLOCK);
10665         return (CTL_ACTION_PASS);
10666 }
10667
10668 static ctl_action
10669 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10670     union ctl_io *ooa_io)
10671 {
10672         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10673         ctl_serialize_action *serialize_row;
10674
10675         /*
10676          * The initiator attempted multiple untagged commands at the same
10677          * time.  Can't do that.
10678          */
10679         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10680          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10681          && ((pending_io->io_hdr.nexus.targ_port ==
10682               ooa_io->io_hdr.nexus.targ_port)
10683           && (pending_io->io_hdr.nexus.initid ==
10684               ooa_io->io_hdr.nexus.initid))
10685          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10686               CTL_FLAG_STATUS_SENT)) == 0))
10687                 return (CTL_ACTION_OVERLAP);
10688
10689         /*
10690          * The initiator attempted to send multiple tagged commands with
10691          * the same ID.  (It's fine if different initiators have the same
10692          * tag ID.)
10693          *
10694          * Even if all of those conditions are true, we don't kill the I/O
10695          * if the command ahead of us has been aborted.  We won't end up
10696          * sending it to the FETD, and it's perfectly legal to resend a
10697          * command with the same tag number as long as the previous
10698          * instance of this tag number has been aborted somehow.
10699          */
10700         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10701          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10702          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10703          && ((pending_io->io_hdr.nexus.targ_port ==
10704               ooa_io->io_hdr.nexus.targ_port)
10705           && (pending_io->io_hdr.nexus.initid ==
10706               ooa_io->io_hdr.nexus.initid))
10707          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10708               CTL_FLAG_STATUS_SENT)) == 0))
10709                 return (CTL_ACTION_OVERLAP_TAG);
10710
10711         /*
10712          * If we get a head of queue tag, SAM-3 says that we should
10713          * immediately execute it.
10714          *
10715          * What happens if this command would normally block for some other
10716          * reason?  e.g. a request sense with a head of queue tag
10717          * immediately after a write.  Normally that would block, but this
10718          * will result in its getting executed immediately...
10719          *
10720          * We currently return "pass" instead of "skip", so we'll end up
10721          * going through the rest of the queue to check for overlapped tags.
10722          *
10723          * XXX KDM check for other types of blockage first??
10724          */
10725         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10726                 return (CTL_ACTION_PASS);
10727
10728         /*
10729          * Ordered tags have to block until all items ahead of them
10730          * have completed.  If we get called with an ordered tag, we always
10731          * block, if something else is ahead of us in the queue.
10732          */
10733         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10734                 return (CTL_ACTION_BLOCK);
10735
10736         /*
10737          * Simple tags get blocked until all head of queue and ordered tags
10738          * ahead of them have completed.  I'm lumping untagged commands in
10739          * with simple tags here.  XXX KDM is that the right thing to do?
10740          */
10741         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10742           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10743          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10744           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10745                 return (CTL_ACTION_BLOCK);
10746
10747         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10748         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10749
10750         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10751
10752         switch (serialize_row[pending_entry->seridx]) {
10753         case CTL_SER_BLOCK:
10754                 return (CTL_ACTION_BLOCK);
10755         case CTL_SER_EXTENT:
10756                 return (ctl_extent_check(ooa_io, pending_io,
10757                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10758         case CTL_SER_EXTENTOPT:
10759                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10760                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10761                         return (ctl_extent_check(ooa_io, pending_io,
10762                             (lun->be_lun &&
10763                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10764                 return (CTL_ACTION_PASS);
10765         case CTL_SER_EXTENTSEQ:
10766                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10767                         return (ctl_extent_check_seq(ooa_io, pending_io));
10768                 return (CTL_ACTION_PASS);
10769         case CTL_SER_PASS:
10770                 return (CTL_ACTION_PASS);
10771         case CTL_SER_BLOCKOPT:
10772                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10773                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10774                         return (CTL_ACTION_BLOCK);
10775                 return (CTL_ACTION_PASS);
10776         case CTL_SER_SKIP:
10777                 return (CTL_ACTION_SKIP);
10778         default:
10779                 panic("invalid serialization value %d",
10780                       serialize_row[pending_entry->seridx]);
10781         }
10782
10783         return (CTL_ACTION_ERROR);
10784 }
10785
10786 /*
10787  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10788  * Assumptions:
10789  * - pending_io is generally either incoming, or on the blocked queue
10790  * - starting I/O is the I/O we want to start the check with.
10791  */
10792 static ctl_action
10793 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10794               union ctl_io *starting_io)
10795 {
10796         union ctl_io *ooa_io;
10797         ctl_action action;
10798
10799         mtx_assert(&lun->lun_lock, MA_OWNED);
10800
10801         /*
10802          * Run back along the OOA queue, starting with the current
10803          * blocked I/O and going through every I/O before it on the
10804          * queue.  If starting_io is NULL, we'll just end up returning
10805          * CTL_ACTION_PASS.
10806          */
10807         for (ooa_io = starting_io; ooa_io != NULL;
10808              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10809              ooa_links)){
10810
10811                 /*
10812                  * This routine just checks to see whether
10813                  * cur_blocked is blocked by ooa_io, which is ahead
10814                  * of it in the queue.  It doesn't queue/dequeue
10815                  * cur_blocked.
10816                  */
10817                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10818                 switch (action) {
10819                 case CTL_ACTION_BLOCK:
10820                 case CTL_ACTION_OVERLAP:
10821                 case CTL_ACTION_OVERLAP_TAG:
10822                 case CTL_ACTION_SKIP:
10823                 case CTL_ACTION_ERROR:
10824                         return (action);
10825                         break; /* NOTREACHED */
10826                 case CTL_ACTION_PASS:
10827                         break;
10828                 default:
10829                         panic("invalid action %d", action);
10830                         break;  /* NOTREACHED */
10831                 }
10832         }
10833
10834         return (CTL_ACTION_PASS);
10835 }
10836
10837 /*
10838  * Assumptions:
10839  * - An I/O has just completed, and has been removed from the per-LUN OOA
10840  *   queue, so some items on the blocked queue may now be unblocked.
10841  */
10842 static int
10843 ctl_check_blocked(struct ctl_lun *lun)
10844 {
10845         struct ctl_softc *softc = lun->ctl_softc;
10846         union ctl_io *cur_blocked, *next_blocked;
10847
10848         mtx_assert(&lun->lun_lock, MA_OWNED);
10849
10850         /*
10851          * Run forward from the head of the blocked queue, checking each
10852          * entry against the I/Os prior to it on the OOA queue to see if
10853          * there is still any blockage.
10854          *
10855          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10856          * with our removing a variable on it while it is traversing the
10857          * list.
10858          */
10859         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10860              cur_blocked != NULL; cur_blocked = next_blocked) {
10861                 union ctl_io *prev_ooa;
10862                 ctl_action action;
10863
10864                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10865                                                           blocked_links);
10866
10867                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10868                                                       ctl_ooaq, ooa_links);
10869
10870                 /*
10871                  * If cur_blocked happens to be the first item in the OOA
10872                  * queue now, prev_ooa will be NULL, and the action
10873                  * returned will just be CTL_ACTION_PASS.
10874                  */
10875                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10876
10877                 switch (action) {
10878                 case CTL_ACTION_BLOCK:
10879                         /* Nothing to do here, still blocked */
10880                         break;
10881                 case CTL_ACTION_OVERLAP:
10882                 case CTL_ACTION_OVERLAP_TAG:
10883                         /*
10884                          * This shouldn't happen!  In theory we've already
10885                          * checked this command for overlap...
10886                          */
10887                         break;
10888                 case CTL_ACTION_PASS:
10889                 case CTL_ACTION_SKIP: {
10890                         const struct ctl_cmd_entry *entry;
10891
10892                         /*
10893                          * The skip case shouldn't happen, this transaction
10894                          * should have never made it onto the blocked queue.
10895                          */
10896                         /*
10897                          * This I/O is no longer blocked, we can remove it
10898                          * from the blocked queue.  Since this is a TAILQ
10899                          * (doubly linked list), we can do O(1) removals
10900                          * from any place on the list.
10901                          */
10902                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10903                                      blocked_links);
10904                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10905
10906                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
10907                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
10908                                 /*
10909                                  * Need to send IO back to original side to
10910                                  * run
10911                                  */
10912                                 union ctl_ha_msg msg_info;
10913
10914                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10915                                 msg_info.hdr.original_sc =
10916                                         cur_blocked->io_hdr.original_sc;
10917                                 msg_info.hdr.serializing_sc = cur_blocked;
10918                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10919                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10920                                     sizeof(msg_info.hdr), M_NOWAIT);
10921                                 break;
10922                         }
10923                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10924
10925                         /*
10926                          * Check this I/O for LUN state changes that may
10927                          * have happened while this command was blocked.
10928                          * The LUN state may have been changed by a command
10929                          * ahead of us in the queue, so we need to re-check
10930                          * for any states that can be caused by SCSI
10931                          * commands.
10932                          */
10933                         if (ctl_scsiio_lun_check(lun, entry,
10934                                                  &cur_blocked->scsiio) == 0) {
10935                                 cur_blocked->io_hdr.flags |=
10936                                                       CTL_FLAG_IS_WAS_ON_RTR;
10937                                 ctl_enqueue_rtr(cur_blocked);
10938                         } else
10939                                 ctl_done(cur_blocked);
10940                         break;
10941                 }
10942                 default:
10943                         /*
10944                          * This probably shouldn't happen -- we shouldn't
10945                          * get CTL_ACTION_ERROR, or anything else.
10946                          */
10947                         break;
10948                 }
10949         }
10950
10951         return (CTL_RETVAL_COMPLETE);
10952 }
10953
10954 /*
10955  * This routine (with one exception) checks LUN flags that can be set by
10956  * commands ahead of us in the OOA queue.  These flags have to be checked
10957  * when a command initially comes in, and when we pull a command off the
10958  * blocked queue and are preparing to execute it.  The reason we have to
10959  * check these flags for commands on the blocked queue is that the LUN
10960  * state may have been changed by a command ahead of us while we're on the
10961  * blocked queue.
10962  *
10963  * Ordering is somewhat important with these checks, so please pay
10964  * careful attention to the placement of any new checks.
10965  */
10966 static int
10967 ctl_scsiio_lun_check(struct ctl_lun *lun,
10968     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10969 {
10970         struct ctl_softc *softc = lun->ctl_softc;
10971         int retval;
10972         uint32_t residx;
10973
10974         retval = 0;
10975
10976         mtx_assert(&lun->lun_lock, MA_OWNED);
10977
10978         /*
10979          * If this shelf is a secondary shelf controller, we may have to
10980          * reject some commands disallowed by HA mode and link state.
10981          */
10982         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10983                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
10984                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10985                         ctl_set_lun_unavail(ctsio);
10986                         retval = 1;
10987                         goto bailout;
10988                 }
10989                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
10990                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10991                         ctl_set_lun_transit(ctsio);
10992                         retval = 1;
10993                         goto bailout;
10994                 }
10995                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
10996                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
10997                         ctl_set_lun_standby(ctsio);
10998                         retval = 1;
10999                         goto bailout;
11000                 }
11001
11002                 /* The rest of checks are only done on executing side */
11003                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11004                         goto bailout;
11005         }
11006
11007         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11008                 if (lun->be_lun &&
11009                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11010                         ctl_set_hw_write_protected(ctsio);
11011                         retval = 1;
11012                         goto bailout;
11013                 }
11014                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11015                     .eca_and_aen & SCP_SWP) != 0) {
11016                         ctl_set_sense(ctsio, /*current_error*/ 1,
11017                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11018                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11019                         retval = 1;
11020                         goto bailout;
11021                 }
11022         }
11023
11024         /*
11025          * Check for a reservation conflict.  If this command isn't allowed
11026          * even on reserved LUNs, and if this initiator isn't the one who
11027          * reserved us, reject the command with a reservation conflict.
11028          */
11029         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11030         if ((lun->flags & CTL_LUN_RESERVED)
11031          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11032                 if (lun->res_idx != residx) {
11033                         ctl_set_reservation_conflict(ctsio);
11034                         retval = 1;
11035                         goto bailout;
11036                 }
11037         }
11038
11039         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11040             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11041                 /* No reservation or command is allowed. */;
11042         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11043             (lun->res_type == SPR_TYPE_WR_EX ||
11044              lun->res_type == SPR_TYPE_WR_EX_RO ||
11045              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11046                 /* The command is allowed for Write Exclusive resv. */;
11047         } else {
11048                 /*
11049                  * if we aren't registered or it's a res holder type
11050                  * reservation and this isn't the res holder then set a
11051                  * conflict.
11052                  */
11053                 if (ctl_get_prkey(lun, residx) == 0
11054                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11055                         ctl_set_reservation_conflict(ctsio);
11056                         retval = 1;
11057                         goto bailout;
11058                 }
11059         }
11060
11061         if ((lun->flags & CTL_LUN_OFFLINE)
11062          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
11063                 ctl_set_lun_not_ready(ctsio);
11064                 retval = 1;
11065                 goto bailout;
11066         }
11067
11068         if ((lun->flags & CTL_LUN_STOPPED)
11069          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11070                 /* "Logical unit not ready, initializing cmd. required" */
11071                 ctl_set_lun_stopped(ctsio);
11072                 retval = 1;
11073                 goto bailout;
11074         }
11075
11076         if ((lun->flags & CTL_LUN_INOPERABLE)
11077          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11078                 /* "Medium format corrupted" */
11079                 ctl_set_medium_format_corrupted(ctsio);
11080                 retval = 1;
11081                 goto bailout;
11082         }
11083
11084 bailout:
11085         return (retval);
11086 }
11087
11088 static void
11089 ctl_failover_io(union ctl_io *io, int have_lock)
11090 {
11091         ctl_set_busy(&io->scsiio);
11092         ctl_done(io);
11093 }
11094
11095 static void
11096 ctl_failover_lun(struct ctl_lun *lun)
11097 {
11098         struct ctl_softc *softc = lun->ctl_softc;
11099         struct ctl_io_hdr *io, *next_io;
11100
11101         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
11102         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11103                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11104                         /* We are master */
11105                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11106                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11107                                         io->flags |= CTL_FLAG_ABORT;
11108                                         io->flags |= CTL_FLAG_FAILOVER;
11109                                 } else { /* This can be only due to DATAMOVE */
11110                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11111                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11112                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11113                                         io->port_status = 31340;
11114                                         ctl_enqueue_isc((union ctl_io *)io);
11115                                 }
11116                         }
11117                         /* We are slave */
11118                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11119                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11120                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11121                                         io->flags |= CTL_FLAG_FAILOVER;
11122                                 } else {
11123                                         ctl_set_busy(&((union ctl_io *)io)->
11124                                             scsiio);
11125                                         ctl_done((union ctl_io *)io);
11126                                 }
11127                         }
11128                 }
11129         } else { /* SERIALIZE modes */
11130                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11131                     next_io) {
11132                         /* We are master */
11133                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11134                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11135                                     blocked_links);
11136                                 io->flags &= ~CTL_FLAG_BLOCKED;
11137                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11138                                 ctl_free_io((union ctl_io *)io);
11139                         }
11140                 }
11141                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11142                         /* We are master */
11143                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11144                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11145                                 ctl_free_io((union ctl_io *)io);
11146                         }
11147                         /* We are slave */
11148                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11149                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11150                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11151                                         ctl_set_busy(&((union ctl_io *)io)->
11152                                             scsiio);
11153                                         ctl_done((union ctl_io *)io);
11154                                 }
11155                         }
11156                 }
11157                 ctl_check_blocked(lun);
11158         }
11159 }
11160
11161 static int
11162 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11163 {
11164         struct ctl_lun *lun;
11165         const struct ctl_cmd_entry *entry;
11166         uint32_t initidx, targ_lun;
11167         int retval;
11168
11169         retval = 0;
11170
11171         lun = NULL;
11172
11173         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11174         if ((targ_lun < CTL_MAX_LUNS)
11175          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11176                 /*
11177                  * If the LUN is invalid, pretend that it doesn't exist.
11178                  * It will go away as soon as all pending I/O has been
11179                  * completed.
11180                  */
11181                 mtx_lock(&lun->lun_lock);
11182                 if (lun->flags & CTL_LUN_DISABLED) {
11183                         mtx_unlock(&lun->lun_lock);
11184                         lun = NULL;
11185                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11186                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11187                 } else {
11188                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11189                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11190                                 lun->be_lun;
11191
11192                         /*
11193                          * Every I/O goes into the OOA queue for a
11194                          * particular LUN, and stays there until completion.
11195                          */
11196 #ifdef CTL_TIME_IO
11197                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11198                                 lun->idle_time += getsbinuptime() -
11199                                     lun->last_busy;
11200                         }
11201 #endif
11202                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11203                             ooa_links);
11204                 }
11205         } else {
11206                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11207                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11208         }
11209
11210         /* Get command entry and return error if it is unsuppotyed. */
11211         entry = ctl_validate_command(ctsio);
11212         if (entry == NULL) {
11213                 if (lun)
11214                         mtx_unlock(&lun->lun_lock);
11215                 return (retval);
11216         }
11217
11218         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11219         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11220
11221         /*
11222          * Check to see whether we can send this command to LUNs that don't
11223          * exist.  This should pretty much only be the case for inquiry
11224          * and request sense.  Further checks, below, really require having
11225          * a LUN, so we can't really check the command anymore.  Just put
11226          * it on the rtr queue.
11227          */
11228         if (lun == NULL) {
11229                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11230                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11231                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11232                         return (retval);
11233                 }
11234
11235                 ctl_set_unsupported_lun(ctsio);
11236                 ctl_done((union ctl_io *)ctsio);
11237                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11238                 return (retval);
11239         } else {
11240                 /*
11241                  * Make sure we support this particular command on this LUN.
11242                  * e.g., we don't support writes to the control LUN.
11243                  */
11244                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11245                         mtx_unlock(&lun->lun_lock);
11246                         ctl_set_invalid_opcode(ctsio);
11247                         ctl_done((union ctl_io *)ctsio);
11248                         return (retval);
11249                 }
11250         }
11251
11252         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11253
11254 #ifdef CTL_WITH_CA
11255         /*
11256          * If we've got a request sense, it'll clear the contingent
11257          * allegiance condition.  Otherwise, if we have a CA condition for
11258          * this initiator, clear it, because it sent down a command other
11259          * than request sense.
11260          */
11261         if ((ctsio->cdb[0] != REQUEST_SENSE)
11262          && (ctl_is_set(lun->have_ca, initidx)))
11263                 ctl_clear_mask(lun->have_ca, initidx);
11264 #endif
11265
11266         /*
11267          * If the command has this flag set, it handles its own unit
11268          * attention reporting, we shouldn't do anything.  Otherwise we
11269          * check for any pending unit attentions, and send them back to the
11270          * initiator.  We only do this when a command initially comes in,
11271          * not when we pull it off the blocked queue.
11272          *
11273          * According to SAM-3, section 5.3.2, the order that things get
11274          * presented back to the host is basically unit attentions caused
11275          * by some sort of reset event, busy status, reservation conflicts
11276          * or task set full, and finally any other status.
11277          *
11278          * One issue here is that some of the unit attentions we report
11279          * don't fall into the "reset" category (e.g. "reported luns data
11280          * has changed").  So reporting it here, before the reservation
11281          * check, may be technically wrong.  I guess the only thing to do
11282          * would be to check for and report the reset events here, and then
11283          * check for the other unit attention types after we check for a
11284          * reservation conflict.
11285          *
11286          * XXX KDM need to fix this
11287          */
11288         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11289                 ctl_ua_type ua_type;
11290
11291                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11292                     SSD_TYPE_NONE);
11293                 if (ua_type != CTL_UA_NONE) {
11294                         mtx_unlock(&lun->lun_lock);
11295                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11296                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11297                         ctsio->sense_len = SSD_FULL_SIZE;
11298                         ctl_done((union ctl_io *)ctsio);
11299                         return (retval);
11300                 }
11301         }
11302
11303
11304         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11305                 mtx_unlock(&lun->lun_lock);
11306                 ctl_done((union ctl_io *)ctsio);
11307                 return (retval);
11308         }
11309
11310         /*
11311          * XXX CHD this is where we want to send IO to other side if
11312          * this LUN is secondary on this SC. We will need to make a copy
11313          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11314          * the copy we send as FROM_OTHER.
11315          * We also need to stuff the address of the original IO so we can
11316          * find it easily. Something similar will need be done on the other
11317          * side so when we are done we can find the copy.
11318          */
11319         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11320             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11321             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11322                 union ctl_ha_msg msg_info;
11323                 int isc_retval;
11324
11325                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11326                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11327                 mtx_unlock(&lun->lun_lock);
11328
11329                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11330                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11331                 msg_info.hdr.serializing_sc = NULL;
11332                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11333                 msg_info.scsi.tag_num = ctsio->tag_num;
11334                 msg_info.scsi.tag_type = ctsio->tag_type;
11335                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11336                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11337
11338                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11339                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11340                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11341                         ctl_set_busy(ctsio);
11342                         ctl_done((union ctl_io *)ctsio);
11343                         return (retval);
11344                 }
11345                 return (retval);
11346         }
11347
11348         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11349                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11350                               ctl_ooaq, ooa_links))) {
11351         case CTL_ACTION_BLOCK:
11352                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11353                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11354                                   blocked_links);
11355                 mtx_unlock(&lun->lun_lock);
11356                 return (retval);
11357         case CTL_ACTION_PASS:
11358         case CTL_ACTION_SKIP:
11359                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11360                 mtx_unlock(&lun->lun_lock);
11361                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11362                 break;
11363         case CTL_ACTION_OVERLAP:
11364                 mtx_unlock(&lun->lun_lock);
11365                 ctl_set_overlapped_cmd(ctsio);
11366                 ctl_done((union ctl_io *)ctsio);
11367                 break;
11368         case CTL_ACTION_OVERLAP_TAG:
11369                 mtx_unlock(&lun->lun_lock);
11370                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11371                 ctl_done((union ctl_io *)ctsio);
11372                 break;
11373         case CTL_ACTION_ERROR:
11374         default:
11375                 mtx_unlock(&lun->lun_lock);
11376                 ctl_set_internal_failure(ctsio,
11377                                          /*sks_valid*/ 0,
11378                                          /*retry_count*/ 0);
11379                 ctl_done((union ctl_io *)ctsio);
11380                 break;
11381         }
11382         return (retval);
11383 }
11384
11385 const struct ctl_cmd_entry *
11386 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11387 {
11388         const struct ctl_cmd_entry *entry;
11389         int service_action;
11390
11391         entry = &ctl_cmd_table[ctsio->cdb[0]];
11392         if (sa)
11393                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11394         if (entry->flags & CTL_CMD_FLAG_SA5) {
11395                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11396                 entry = &((const struct ctl_cmd_entry *)
11397                     entry->execute)[service_action];
11398         }
11399         return (entry);
11400 }
11401
11402 const struct ctl_cmd_entry *
11403 ctl_validate_command(struct ctl_scsiio *ctsio)
11404 {
11405         const struct ctl_cmd_entry *entry;
11406         int i, sa;
11407         uint8_t diff;
11408
11409         entry = ctl_get_cmd_entry(ctsio, &sa);
11410         if (entry->execute == NULL) {
11411                 if (sa)
11412                         ctl_set_invalid_field(ctsio,
11413                                               /*sks_valid*/ 1,
11414                                               /*command*/ 1,
11415                                               /*field*/ 1,
11416                                               /*bit_valid*/ 1,
11417                                               /*bit*/ 4);
11418                 else
11419                         ctl_set_invalid_opcode(ctsio);
11420                 ctl_done((union ctl_io *)ctsio);
11421                 return (NULL);
11422         }
11423         KASSERT(entry->length > 0,
11424             ("Not defined length for command 0x%02x/0x%02x",
11425              ctsio->cdb[0], ctsio->cdb[1]));
11426         for (i = 1; i < entry->length; i++) {
11427                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11428                 if (diff == 0)
11429                         continue;
11430                 ctl_set_invalid_field(ctsio,
11431                                       /*sks_valid*/ 1,
11432                                       /*command*/ 1,
11433                                       /*field*/ i,
11434                                       /*bit_valid*/ 1,
11435                                       /*bit*/ fls(diff) - 1);
11436                 ctl_done((union ctl_io *)ctsio);
11437                 return (NULL);
11438         }
11439         return (entry);
11440 }
11441
11442 static int
11443 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11444 {
11445
11446         switch (lun_type) {
11447         case T_PROCESSOR:
11448                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11449                         return (0);
11450                 break;
11451         case T_DIRECT:
11452                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11453                         return (0);
11454                 break;
11455         default:
11456                 return (0);
11457         }
11458         return (1);
11459 }
11460
11461 static int
11462 ctl_scsiio(struct ctl_scsiio *ctsio)
11463 {
11464         int retval;
11465         const struct ctl_cmd_entry *entry;
11466
11467         retval = CTL_RETVAL_COMPLETE;
11468
11469         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11470
11471         entry = ctl_get_cmd_entry(ctsio, NULL);
11472
11473         /*
11474          * If this I/O has been aborted, just send it straight to
11475          * ctl_done() without executing it.
11476          */
11477         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11478                 ctl_done((union ctl_io *)ctsio);
11479                 goto bailout;
11480         }
11481
11482         /*
11483          * All the checks should have been handled by ctl_scsiio_precheck().
11484          * We should be clear now to just execute the I/O.
11485          */
11486         retval = entry->execute(ctsio);
11487
11488 bailout:
11489         return (retval);
11490 }
11491
11492 /*
11493  * Since we only implement one target right now, a bus reset simply resets
11494  * our single target.
11495  */
11496 static int
11497 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11498 {
11499         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11500 }
11501
11502 static int
11503 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11504                  ctl_ua_type ua_type)
11505 {
11506         struct ctl_port *port;
11507         struct ctl_lun *lun;
11508         int retval;
11509
11510         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11511                 union ctl_ha_msg msg_info;
11512
11513                 msg_info.hdr.nexus = io->io_hdr.nexus;
11514                 if (ua_type==CTL_UA_TARG_RESET)
11515                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11516                 else
11517                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11518                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11519                 msg_info.hdr.original_sc = NULL;
11520                 msg_info.hdr.serializing_sc = NULL;
11521                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11522                     sizeof(msg_info.task), M_WAITOK);
11523         }
11524         retval = 0;
11525
11526         mtx_lock(&softc->ctl_lock);
11527         port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11528         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11529                 if (port != NULL &&
11530                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11531                         continue;
11532                 retval += ctl_do_lun_reset(lun, io, ua_type);
11533         }
11534         mtx_unlock(&softc->ctl_lock);
11535         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11536         return (retval);
11537 }
11538
11539 /*
11540  * The LUN should always be set.  The I/O is optional, and is used to
11541  * distinguish between I/Os sent by this initiator, and by other
11542  * initiators.  We set unit attention for initiators other than this one.
11543  * SAM-3 is vague on this point.  It does say that a unit attention should
11544  * be established for other initiators when a LUN is reset (see section
11545  * 5.7.3), but it doesn't specifically say that the unit attention should
11546  * be established for this particular initiator when a LUN is reset.  Here
11547  * is the relevant text, from SAM-3 rev 8:
11548  *
11549  * 5.7.2 When a SCSI initiator port aborts its own tasks
11550  *
11551  * When a SCSI initiator port causes its own task(s) to be aborted, no
11552  * notification that the task(s) have been aborted shall be returned to
11553  * the SCSI initiator port other than the completion response for the
11554  * command or task management function action that caused the task(s) to
11555  * be aborted and notification(s) associated with related effects of the
11556  * action (e.g., a reset unit attention condition).
11557  *
11558  * XXX KDM for now, we're setting unit attention for all initiators.
11559  */
11560 static int
11561 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11562 {
11563         union ctl_io *xio;
11564 #if 0
11565         uint32_t initidx;
11566 #endif
11567 #ifdef CTL_WITH_CA
11568         int i;
11569 #endif
11570
11571         mtx_lock(&lun->lun_lock);
11572         /*
11573          * Run through the OOA queue and abort each I/O.
11574          */
11575         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11576              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11577                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11578         }
11579
11580         /*
11581          * This version sets unit attention for every
11582          */
11583 #if 0
11584         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11585         ctl_est_ua_all(lun, initidx, ua_type);
11586 #else
11587         ctl_est_ua_all(lun, -1, ua_type);
11588 #endif
11589
11590         /*
11591          * A reset (any kind, really) clears reservations established with
11592          * RESERVE/RELEASE.  It does not clear reservations established
11593          * with PERSISTENT RESERVE OUT, but we don't support that at the
11594          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11595          * reservations made with the RESERVE/RELEASE commands, because
11596          * those commands are obsolete in SPC-3.
11597          */
11598         lun->flags &= ~CTL_LUN_RESERVED;
11599
11600 #ifdef CTL_WITH_CA
11601         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11602                 ctl_clear_mask(lun->have_ca, i);
11603 #endif
11604         mtx_unlock(&lun->lun_lock);
11605
11606         return (0);
11607 }
11608
11609 static int
11610 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11611 {
11612         struct ctl_lun *lun;
11613         uint32_t targ_lun;
11614         int retval;
11615
11616         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11617         mtx_lock(&softc->ctl_lock);
11618         if ((targ_lun >= CTL_MAX_LUNS) ||
11619             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11620                 mtx_unlock(&softc->ctl_lock);
11621                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11622                 return (1);
11623         }
11624         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11625         mtx_unlock(&softc->ctl_lock);
11626         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11627
11628         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11629                 union ctl_ha_msg msg_info;
11630
11631                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11632                 msg_info.hdr.nexus = io->io_hdr.nexus;
11633                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11634                 msg_info.hdr.original_sc = NULL;
11635                 msg_info.hdr.serializing_sc = NULL;
11636                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11637                     sizeof(msg_info.task), M_WAITOK);
11638         }
11639         return (retval);
11640 }
11641
11642 static void
11643 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11644     int other_sc)
11645 {
11646         union ctl_io *xio;
11647
11648         mtx_assert(&lun->lun_lock, MA_OWNED);
11649
11650         /*
11651          * Run through the OOA queue and attempt to find the given I/O.
11652          * The target port, initiator ID, tag type and tag number have to
11653          * match the values that we got from the initiator.  If we have an
11654          * untagged command to abort, simply abort the first untagged command
11655          * we come to.  We only allow one untagged command at a time of course.
11656          */
11657         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11658              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11659
11660                 if ((targ_port == UINT32_MAX ||
11661                      targ_port == xio->io_hdr.nexus.targ_port) &&
11662                     (init_id == UINT32_MAX ||
11663                      init_id == xio->io_hdr.nexus.initid)) {
11664                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11665                             init_id != xio->io_hdr.nexus.initid)
11666                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11667                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11668                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11669                                 union ctl_ha_msg msg_info;
11670
11671                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11672                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11673                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11674                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11675                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11676                                 msg_info.hdr.original_sc = NULL;
11677                                 msg_info.hdr.serializing_sc = NULL;
11678                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11679                                     sizeof(msg_info.task), M_NOWAIT);
11680                         }
11681                 }
11682         }
11683 }
11684
11685 static int
11686 ctl_abort_task_set(union ctl_io *io)
11687 {
11688         struct ctl_softc *softc = control_softc;
11689         struct ctl_lun *lun;
11690         uint32_t targ_lun;
11691
11692         /*
11693          * Look up the LUN.
11694          */
11695         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11696         mtx_lock(&softc->ctl_lock);
11697         if ((targ_lun >= CTL_MAX_LUNS) ||
11698             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11699                 mtx_unlock(&softc->ctl_lock);
11700                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11701                 return (1);
11702         }
11703
11704         mtx_lock(&lun->lun_lock);
11705         mtx_unlock(&softc->ctl_lock);
11706         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11707                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11708                     io->io_hdr.nexus.initid,
11709                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11710         } else { /* CTL_TASK_CLEAR_TASK_SET */
11711                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11712                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11713         }
11714         mtx_unlock(&lun->lun_lock);
11715         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11716         return (0);
11717 }
11718
11719 static int
11720 ctl_i_t_nexus_reset(union ctl_io *io)
11721 {
11722         struct ctl_softc *softc = control_softc;
11723         struct ctl_lun *lun;
11724         uint32_t initidx;
11725
11726         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11727                 union ctl_ha_msg msg_info;
11728
11729                 msg_info.hdr.nexus = io->io_hdr.nexus;
11730                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11731                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11732                 msg_info.hdr.original_sc = NULL;
11733                 msg_info.hdr.serializing_sc = NULL;
11734                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11735                     sizeof(msg_info.task), M_WAITOK);
11736         }
11737
11738         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11739         mtx_lock(&softc->ctl_lock);
11740         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11741                 mtx_lock(&lun->lun_lock);
11742                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11743                     io->io_hdr.nexus.initid, 1);
11744 #ifdef CTL_WITH_CA
11745                 ctl_clear_mask(lun->have_ca, initidx);
11746 #endif
11747                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11748                         lun->flags &= ~CTL_LUN_RESERVED;
11749                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11750                 mtx_unlock(&lun->lun_lock);
11751         }
11752         mtx_unlock(&softc->ctl_lock);
11753         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11754         return (0);
11755 }
11756
11757 static int
11758 ctl_abort_task(union ctl_io *io)
11759 {
11760         union ctl_io *xio;
11761         struct ctl_lun *lun;
11762         struct ctl_softc *softc;
11763 #if 0
11764         struct sbuf sb;
11765         char printbuf[128];
11766 #endif
11767         int found;
11768         uint32_t targ_lun;
11769
11770         softc = control_softc;
11771         found = 0;
11772
11773         /*
11774          * Look up the LUN.
11775          */
11776         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11777         mtx_lock(&softc->ctl_lock);
11778         if ((targ_lun >= CTL_MAX_LUNS) ||
11779             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11780                 mtx_unlock(&softc->ctl_lock);
11781                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11782                 return (1);
11783         }
11784
11785 #if 0
11786         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11787                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11788 #endif
11789
11790         mtx_lock(&lun->lun_lock);
11791         mtx_unlock(&softc->ctl_lock);
11792         /*
11793          * Run through the OOA queue and attempt to find the given I/O.
11794          * The target port, initiator ID, tag type and tag number have to
11795          * match the values that we got from the initiator.  If we have an
11796          * untagged command to abort, simply abort the first untagged command
11797          * we come to.  We only allow one untagged command at a time of course.
11798          */
11799         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11800              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11801 #if 0
11802                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11803
11804                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11805                             lun->lun, xio->scsiio.tag_num,
11806                             xio->scsiio.tag_type,
11807                             (xio->io_hdr.blocked_links.tqe_prev
11808                             == NULL) ? "" : " BLOCKED",
11809                             (xio->io_hdr.flags &
11810                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11811                             (xio->io_hdr.flags &
11812                             CTL_FLAG_ABORT) ? " ABORT" : "",
11813                             (xio->io_hdr.flags &
11814                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11815                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11816                 sbuf_finish(&sb);
11817                 printf("%s\n", sbuf_data(&sb));
11818 #endif
11819
11820                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11821                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11822                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11823                         continue;
11824
11825                 /*
11826                  * If the abort says that the task is untagged, the
11827                  * task in the queue must be untagged.  Otherwise,
11828                  * we just check to see whether the tag numbers
11829                  * match.  This is because the QLogic firmware
11830                  * doesn't pass back the tag type in an abort
11831                  * request.
11832                  */
11833 #if 0
11834                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11835                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11836                  || (xio->scsiio.tag_num == io->taskio.tag_num))
11837 #endif
11838                 /*
11839                  * XXX KDM we've got problems with FC, because it
11840                  * doesn't send down a tag type with aborts.  So we
11841                  * can only really go by the tag number...
11842                  * This may cause problems with parallel SCSI.
11843                  * Need to figure that out!!
11844                  */
11845                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
11846                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11847                         found = 1;
11848                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11849                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11850                                 union ctl_ha_msg msg_info;
11851
11852                                 msg_info.hdr.nexus = io->io_hdr.nexus;
11853                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11854                                 msg_info.task.tag_num = io->taskio.tag_num;
11855                                 msg_info.task.tag_type = io->taskio.tag_type;
11856                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11857                                 msg_info.hdr.original_sc = NULL;
11858                                 msg_info.hdr.serializing_sc = NULL;
11859 #if 0
11860                                 printf("Sent Abort to other side\n");
11861 #endif
11862                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11863                                     sizeof(msg_info.task), M_NOWAIT);
11864                         }
11865 #if 0
11866                         printf("ctl_abort_task: found I/O to abort\n");
11867 #endif
11868                 }
11869         }
11870         mtx_unlock(&lun->lun_lock);
11871
11872         if (found == 0) {
11873                 /*
11874                  * This isn't really an error.  It's entirely possible for
11875                  * the abort and command completion to cross on the wire.
11876                  * This is more of an informative/diagnostic error.
11877                  */
11878 #if 0
11879                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11880                        "%u:%u:%u tag %d type %d\n",
11881                        io->io_hdr.nexus.initid,
11882                        io->io_hdr.nexus.targ_port,
11883                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11884                        io->taskio.tag_type);
11885 #endif
11886         }
11887         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11888         return (0);
11889 }
11890
11891 static int
11892 ctl_query_task(union ctl_io *io, int task_set)
11893 {
11894         union ctl_io *xio;
11895         struct ctl_lun *lun;
11896         struct ctl_softc *softc;
11897         int found = 0;
11898         uint32_t targ_lun;
11899
11900         softc = control_softc;
11901         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11902         mtx_lock(&softc->ctl_lock);
11903         if ((targ_lun >= CTL_MAX_LUNS) ||
11904             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11905                 mtx_unlock(&softc->ctl_lock);
11906                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11907                 return (1);
11908         }
11909         mtx_lock(&lun->lun_lock);
11910         mtx_unlock(&softc->ctl_lock);
11911         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11912              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11913
11914                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11915                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11916                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11917                         continue;
11918
11919                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11920                         found = 1;
11921                         break;
11922                 }
11923         }
11924         mtx_unlock(&lun->lun_lock);
11925         if (found)
11926                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11927         else
11928                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11929         return (0);
11930 }
11931
11932 static int
11933 ctl_query_async_event(union ctl_io *io)
11934 {
11935         struct ctl_lun *lun;
11936         struct ctl_softc *softc;
11937         ctl_ua_type ua;
11938         uint32_t targ_lun, initidx;
11939
11940         softc = control_softc;
11941         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11942         mtx_lock(&softc->ctl_lock);
11943         if ((targ_lun >= CTL_MAX_LUNS) ||
11944             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11945                 mtx_unlock(&softc->ctl_lock);
11946                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11947                 return (1);
11948         }
11949         mtx_lock(&lun->lun_lock);
11950         mtx_unlock(&softc->ctl_lock);
11951         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11952         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
11953         mtx_unlock(&lun->lun_lock);
11954         if (ua != CTL_UA_NONE)
11955                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11956         else
11957                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11958         return (0);
11959 }
11960
11961 static void
11962 ctl_run_task(union ctl_io *io)
11963 {
11964         struct ctl_softc *softc = control_softc;
11965         int retval = 1;
11966
11967         CTL_DEBUG_PRINT(("ctl_run_task\n"));
11968         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11969             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
11970         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
11971         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
11972         switch (io->taskio.task_action) {
11973         case CTL_TASK_ABORT_TASK:
11974                 retval = ctl_abort_task(io);
11975                 break;
11976         case CTL_TASK_ABORT_TASK_SET:
11977         case CTL_TASK_CLEAR_TASK_SET:
11978                 retval = ctl_abort_task_set(io);
11979                 break;
11980         case CTL_TASK_CLEAR_ACA:
11981                 break;
11982         case CTL_TASK_I_T_NEXUS_RESET:
11983                 retval = ctl_i_t_nexus_reset(io);
11984                 break;
11985         case CTL_TASK_LUN_RESET:
11986                 retval = ctl_lun_reset(softc, io);
11987                 break;
11988         case CTL_TASK_TARGET_RESET:
11989                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11990                 break;
11991         case CTL_TASK_BUS_RESET:
11992                 retval = ctl_bus_reset(softc, io);
11993                 break;
11994         case CTL_TASK_PORT_LOGIN:
11995                 break;
11996         case CTL_TASK_PORT_LOGOUT:
11997                 break;
11998         case CTL_TASK_QUERY_TASK:
11999                 retval = ctl_query_task(io, 0);
12000                 break;
12001         case CTL_TASK_QUERY_TASK_SET:
12002                 retval = ctl_query_task(io, 1);
12003                 break;
12004         case CTL_TASK_QUERY_ASYNC_EVENT:
12005                 retval = ctl_query_async_event(io);
12006                 break;
12007         default:
12008                 printf("%s: got unknown task management event %d\n",
12009                        __func__, io->taskio.task_action);
12010                 break;
12011         }
12012         if (retval == 0)
12013                 io->io_hdr.status = CTL_SUCCESS;
12014         else
12015                 io->io_hdr.status = CTL_ERROR;
12016         ctl_done(io);
12017 }
12018
12019 /*
12020  * For HA operation.  Handle commands that come in from the other
12021  * controller.
12022  */
12023 static void
12024 ctl_handle_isc(union ctl_io *io)
12025 {
12026         int free_io;
12027         struct ctl_lun *lun;
12028         struct ctl_softc *softc;
12029         uint32_t targ_lun;
12030
12031         softc = control_softc;
12032
12033         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12034         lun = softc->ctl_luns[targ_lun];
12035
12036         switch (io->io_hdr.msg_type) {
12037         case CTL_MSG_SERIALIZE:
12038                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12039                 break;
12040         case CTL_MSG_R2R: {
12041                 const struct ctl_cmd_entry *entry;
12042
12043                 /*
12044                  * This is only used in SER_ONLY mode.
12045                  */
12046                 free_io = 0;
12047                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12048                 mtx_lock(&lun->lun_lock);
12049                 if (ctl_scsiio_lun_check(lun,
12050                     entry, (struct ctl_scsiio *)io) != 0) {
12051                         mtx_unlock(&lun->lun_lock);
12052                         ctl_done(io);
12053                         break;
12054                 }
12055                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12056                 mtx_unlock(&lun->lun_lock);
12057                 ctl_enqueue_rtr(io);
12058                 break;
12059         }
12060         case CTL_MSG_FINISH_IO:
12061                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12062                         free_io = 0;
12063                         ctl_done(io);
12064                 } else {
12065                         free_io = 1;
12066                         mtx_lock(&lun->lun_lock);
12067                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12068                                      ooa_links);
12069                         ctl_check_blocked(lun);
12070                         mtx_unlock(&lun->lun_lock);
12071                 }
12072                 break;
12073         case CTL_MSG_PERS_ACTION:
12074                 ctl_hndl_per_res_out_on_other_sc(
12075                         (union ctl_ha_msg *)&io->presio.pr_msg);
12076                 free_io = 1;
12077                 break;
12078         case CTL_MSG_BAD_JUJU:
12079                 free_io = 0;
12080                 ctl_done(io);
12081                 break;
12082         case CTL_MSG_DATAMOVE:
12083                 /* Only used in XFER mode */
12084                 free_io = 0;
12085                 ctl_datamove_remote(io);
12086                 break;
12087         case CTL_MSG_DATAMOVE_DONE:
12088                 /* Only used in XFER mode */
12089                 free_io = 0;
12090                 io->scsiio.be_move_done(io);
12091                 break;
12092         case CTL_MSG_FAILOVER:
12093                 mtx_lock(&lun->lun_lock);
12094                 ctl_failover_lun(lun);
12095                 mtx_unlock(&lun->lun_lock);
12096                 free_io = 1;
12097                 break;
12098         default:
12099                 free_io = 1;
12100                 printf("%s: Invalid message type %d\n",
12101                        __func__, io->io_hdr.msg_type);
12102                 break;
12103         }
12104         if (free_io)
12105                 ctl_free_io(io);
12106
12107 }
12108
12109
12110 /*
12111  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12112  * there is no match.
12113  */
12114 static ctl_lun_error_pattern
12115 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12116 {
12117         const struct ctl_cmd_entry *entry;
12118         ctl_lun_error_pattern filtered_pattern, pattern;
12119
12120         pattern = desc->error_pattern;
12121
12122         /*
12123          * XXX KDM we need more data passed into this function to match a
12124          * custom pattern, and we actually need to implement custom pattern
12125          * matching.
12126          */
12127         if (pattern & CTL_LUN_PAT_CMD)
12128                 return (CTL_LUN_PAT_CMD);
12129
12130         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12131                 return (CTL_LUN_PAT_ANY);
12132
12133         entry = ctl_get_cmd_entry(ctsio, NULL);
12134
12135         filtered_pattern = entry->pattern & pattern;
12136
12137         /*
12138          * If the user requested specific flags in the pattern (e.g.
12139          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12140          * flags.
12141          *
12142          * If the user did not specify any flags, it doesn't matter whether
12143          * or not the command supports the flags.
12144          */
12145         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12146              (pattern & ~CTL_LUN_PAT_MASK))
12147                 return (CTL_LUN_PAT_NONE);
12148
12149         /*
12150          * If the user asked for a range check, see if the requested LBA
12151          * range overlaps with this command's LBA range.
12152          */
12153         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12154                 uint64_t lba1;
12155                 uint64_t len1;
12156                 ctl_action action;
12157                 int retval;
12158
12159                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12160                 if (retval != 0)
12161                         return (CTL_LUN_PAT_NONE);
12162
12163                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12164                                               desc->lba_range.len, FALSE);
12165                 /*
12166                  * A "pass" means that the LBA ranges don't overlap, so
12167                  * this doesn't match the user's range criteria.
12168                  */
12169                 if (action == CTL_ACTION_PASS)
12170                         return (CTL_LUN_PAT_NONE);
12171         }
12172
12173         return (filtered_pattern);
12174 }
12175
12176 static void
12177 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12178 {
12179         struct ctl_error_desc *desc, *desc2;
12180
12181         mtx_assert(&lun->lun_lock, MA_OWNED);
12182
12183         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12184                 ctl_lun_error_pattern pattern;
12185                 /*
12186                  * Check to see whether this particular command matches
12187                  * the pattern in the descriptor.
12188                  */
12189                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12190                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12191                         continue;
12192
12193                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12194                 case CTL_LUN_INJ_ABORTED:
12195                         ctl_set_aborted(&io->scsiio);
12196                         break;
12197                 case CTL_LUN_INJ_MEDIUM_ERR:
12198                         ctl_set_medium_error(&io->scsiio,
12199                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12200                              CTL_FLAG_DATA_OUT);
12201                         break;
12202                 case CTL_LUN_INJ_UA:
12203                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12204                          * OCCURRED */
12205                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12206                         break;
12207                 case CTL_LUN_INJ_CUSTOM:
12208                         /*
12209                          * We're assuming the user knows what he is doing.
12210                          * Just copy the sense information without doing
12211                          * checks.
12212                          */
12213                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12214                               MIN(sizeof(desc->custom_sense),
12215                                   sizeof(io->scsiio.sense_data)));
12216                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12217                         io->scsiio.sense_len = SSD_FULL_SIZE;
12218                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12219                         break;
12220                 case CTL_LUN_INJ_NONE:
12221                 default:
12222                         /*
12223                          * If this is an error injection type we don't know
12224                          * about, clear the continuous flag (if it is set)
12225                          * so it will get deleted below.
12226                          */
12227                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12228                         break;
12229                 }
12230                 /*
12231                  * By default, each error injection action is a one-shot
12232                  */
12233                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12234                         continue;
12235
12236                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12237
12238                 free(desc, M_CTL);
12239         }
12240 }
12241
12242 #ifdef CTL_IO_DELAY
12243 static void
12244 ctl_datamove_timer_wakeup(void *arg)
12245 {
12246         union ctl_io *io;
12247
12248         io = (union ctl_io *)arg;
12249
12250         ctl_datamove(io);
12251 }
12252 #endif /* CTL_IO_DELAY */
12253
12254 void
12255 ctl_datamove(union ctl_io *io)
12256 {
12257         struct ctl_lun *lun;
12258         void (*fe_datamove)(union ctl_io *io);
12259
12260         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12261
12262         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12263
12264         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12265 #ifdef CTL_TIME_IO
12266         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12267                 char str[256];
12268                 char path_str[64];
12269                 struct sbuf sb;
12270
12271                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12272                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12273
12274                 sbuf_cat(&sb, path_str);
12275                 switch (io->io_hdr.io_type) {
12276                 case CTL_IO_SCSI:
12277                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12278                         sbuf_printf(&sb, "\n");
12279                         sbuf_cat(&sb, path_str);
12280                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12281                                     io->scsiio.tag_num, io->scsiio.tag_type);
12282                         break;
12283                 case CTL_IO_TASK:
12284                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12285                                     "Tag Type: %d\n", io->taskio.task_action,
12286                                     io->taskio.tag_num, io->taskio.tag_type);
12287                         break;
12288                 default:
12289                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12290                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12291                         break;
12292                 }
12293                 sbuf_cat(&sb, path_str);
12294                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12295                             (intmax_t)time_uptime - io->io_hdr.start_time);
12296                 sbuf_finish(&sb);
12297                 printf("%s", sbuf_data(&sb));
12298         }
12299 #endif /* CTL_TIME_IO */
12300
12301 #ifdef CTL_IO_DELAY
12302         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12303                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12304         } else {
12305                 if ((lun != NULL)
12306                  && (lun->delay_info.datamove_delay > 0)) {
12307
12308                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12309                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12310                         callout_reset(&io->io_hdr.delay_callout,
12311                                       lun->delay_info.datamove_delay * hz,
12312                                       ctl_datamove_timer_wakeup, io);
12313                         if (lun->delay_info.datamove_type ==
12314                             CTL_DELAY_TYPE_ONESHOT)
12315                                 lun->delay_info.datamove_delay = 0;
12316                         return;
12317                 }
12318         }
12319 #endif
12320
12321         /*
12322          * This command has been aborted.  Set the port status, so we fail
12323          * the data move.
12324          */
12325         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12326                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12327                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12328                        io->io_hdr.nexus.targ_port,
12329                        io->io_hdr.nexus.targ_lun);
12330                 io->io_hdr.port_status = 31337;
12331                 /*
12332                  * Note that the backend, in this case, will get the
12333                  * callback in its context.  In other cases it may get
12334                  * called in the frontend's interrupt thread context.
12335                  */
12336                 io->scsiio.be_move_done(io);
12337                 return;
12338         }
12339
12340         /* Don't confuse frontend with zero length data move. */
12341         if (io->scsiio.kern_data_len == 0) {
12342                 io->scsiio.be_move_done(io);
12343                 return;
12344         }
12345
12346         /*
12347          * If we're in XFER mode and this I/O is from the other shelf
12348          * controller, we need to send the DMA to the other side to
12349          * actually transfer the data to/from the host.  In serialize only
12350          * mode the transfer happens below CTL and ctl_datamove() is only
12351          * called on the machine that originally received the I/O.
12352          */
12353         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12354          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12355                 union ctl_ha_msg msg;
12356                 uint32_t sg_entries_sent;
12357                 int do_sg_copy;
12358                 int i;
12359
12360                 memset(&msg, 0, sizeof(msg));
12361                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12362                 msg.hdr.original_sc = io->io_hdr.original_sc;
12363                 msg.hdr.serializing_sc = io;
12364                 msg.hdr.nexus = io->io_hdr.nexus;
12365                 msg.hdr.status = io->io_hdr.status;
12366                 msg.dt.flags = io->io_hdr.flags;
12367                 /*
12368                  * We convert everything into a S/G list here.  We can't
12369                  * pass by reference, only by value between controllers.
12370                  * So we can't pass a pointer to the S/G list, only as many
12371                  * S/G entries as we can fit in here.  If it's possible for
12372                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12373                  * then we need to break this up into multiple transfers.
12374                  */
12375                 if (io->scsiio.kern_sg_entries == 0) {
12376                         msg.dt.kern_sg_entries = 1;
12377 #if 0
12378                         /*
12379                          * Convert to a physical address if this is a
12380                          * virtual address.
12381                          */
12382                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12383                                 msg.dt.sg_list[0].addr =
12384                                         io->scsiio.kern_data_ptr;
12385                         } else {
12386                                 /*
12387                                  * XXX KDM use busdma here!
12388                                  */
12389                                 msg.dt.sg_list[0].addr = (void *)
12390                                         vtophys(io->scsiio.kern_data_ptr);
12391                         }
12392 #else
12393                         KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12394                             ("HA does not support BUS_ADDR"));
12395                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12396 #endif
12397
12398                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12399                         do_sg_copy = 0;
12400                 } else {
12401                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12402                         do_sg_copy = 1;
12403                 }
12404
12405                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12406                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12407                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12408                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12409                 msg.dt.sg_sequence = 0;
12410
12411                 /*
12412                  * Loop until we've sent all of the S/G entries.  On the
12413                  * other end, we'll recompose these S/G entries into one
12414                  * contiguous list before passing it to the
12415                  */
12416                 for (sg_entries_sent = 0; sg_entries_sent <
12417                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12418                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12419                                 sizeof(msg.dt.sg_list[0])),
12420                                 msg.dt.kern_sg_entries - sg_entries_sent);
12421
12422                         if (do_sg_copy != 0) {
12423                                 struct ctl_sg_entry *sgl;
12424                                 int j;
12425
12426                                 sgl = (struct ctl_sg_entry *)
12427                                         io->scsiio.kern_data_ptr;
12428                                 /*
12429                                  * If this is in cached memory, flush the cache
12430                                  * before we send the DMA request to the other
12431                                  * controller.  We want to do this in either
12432                                  * the * read or the write case.  The read
12433                                  * case is straightforward.  In the write
12434                                  * case, we want to make sure nothing is
12435                                  * in the local cache that could overwrite
12436                                  * the DMAed data.
12437                                  */
12438
12439                                 for (i = sg_entries_sent, j = 0;
12440                                      i < msg.dt.cur_sg_entries; i++, j++) {
12441 #if 0
12442                                         if ((io->io_hdr.flags &
12443                                              CTL_FLAG_BUS_ADDR) == 0) {
12444                                                 /*
12445                                                  * XXX KDM use busdma.
12446                                                  */
12447                                                 msg.dt.sg_list[j].addr =(void *)
12448                                                        vtophys(sgl[i].addr);
12449                                         } else {
12450                                                 msg.dt.sg_list[j].addr =
12451                                                         sgl[i].addr;
12452                                         }
12453 #else
12454                                         KASSERT((io->io_hdr.flags &
12455                                             CTL_FLAG_BUS_ADDR) == 0,
12456                                             ("HA does not support BUS_ADDR"));
12457                                         msg.dt.sg_list[j].addr = sgl[i].addr;
12458 #endif
12459                                         msg.dt.sg_list[j].len = sgl[i].len;
12460                                 }
12461                         }
12462
12463                         sg_entries_sent += msg.dt.cur_sg_entries;
12464                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12465                                 msg.dt.sg_last = 1;
12466                         else
12467                                 msg.dt.sg_last = 0;
12468
12469                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12470                             sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12471                             sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12472                             M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12473                                 io->io_hdr.port_status = 31341;
12474                                 io->scsiio.be_move_done(io);
12475                                 return;
12476                         }
12477
12478                         msg.dt.sent_sg_entries = sg_entries_sent;
12479                 }
12480
12481                 /*
12482                  * Officially handover the request from us to peer.
12483                  * If failover has just happened, then we must return error.
12484                  * If failover happen just after, then it is not our problem.
12485                  */
12486                 if (lun)
12487                         mtx_lock(&lun->lun_lock);
12488                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12489                         if (lun)
12490                                 mtx_unlock(&lun->lun_lock);
12491                         io->io_hdr.port_status = 31342;
12492                         io->scsiio.be_move_done(io);
12493                         return;
12494                 }
12495                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12496                 io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
12497                 if (lun)
12498                         mtx_unlock(&lun->lun_lock);
12499         } else {
12500
12501                 /*
12502                  * Lookup the fe_datamove() function for this particular
12503                  * front end.
12504                  */
12505                 fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12506
12507                 fe_datamove(io);
12508         }
12509 }
12510
12511 static void
12512 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12513 {
12514         union ctl_ha_msg msg;
12515
12516         memset(&msg, 0, sizeof(msg));
12517
12518         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12519         msg.hdr.original_sc = io;
12520         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12521         msg.hdr.nexus = io->io_hdr.nexus;
12522         msg.hdr.status = io->io_hdr.status;
12523         msg.scsi.tag_num = io->scsiio.tag_num;
12524         msg.scsi.tag_type = io->scsiio.tag_type;
12525         msg.scsi.scsi_status = io->scsiio.scsi_status;
12526         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12527                io->scsiio.sense_len);
12528         msg.scsi.sense_len = io->scsiio.sense_len;
12529         msg.scsi.sense_residual = io->scsiio.sense_residual;
12530         msg.scsi.fetd_status = io->io_hdr.port_status;
12531         msg.scsi.residual = io->scsiio.residual;
12532         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12533
12534         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12535                 ctl_failover_io(io, /*have_lock*/ have_lock);
12536                 return;
12537         }
12538
12539         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12540             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12541             msg.scsi.sense_len, M_WAITOK);
12542 }
12543
12544 /*
12545  * The DMA to the remote side is done, now we need to tell the other side
12546  * we're done so it can continue with its data movement.
12547  */
12548 static void
12549 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12550 {
12551         union ctl_io *io;
12552         int i;
12553
12554         io = rq->context;
12555
12556         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12557                 printf("%s: ISC DMA write failed with error %d", __func__,
12558                        rq->ret);
12559                 ctl_set_internal_failure(&io->scsiio,
12560                                          /*sks_valid*/ 1,
12561                                          /*retry_count*/ rq->ret);
12562         }
12563
12564         ctl_dt_req_free(rq);
12565
12566         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12567                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12568         free(io->io_hdr.remote_sglist, M_CTL);
12569         io->io_hdr.remote_sglist = NULL;
12570         io->io_hdr.local_sglist = NULL;
12571
12572         /*
12573          * The data is in local and remote memory, so now we need to send
12574          * status (good or back) back to the other side.
12575          */
12576         ctl_send_datamove_done(io, /*have_lock*/ 0);
12577 }
12578
12579 /*
12580  * We've moved the data from the host/controller into local memory.  Now we
12581  * need to push it over to the remote controller's memory.
12582  */
12583 static int
12584 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12585 {
12586         int retval;
12587
12588         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12589                                           ctl_datamove_remote_write_cb);
12590         return (retval);
12591 }
12592
12593 static void
12594 ctl_datamove_remote_write(union ctl_io *io)
12595 {
12596         int retval;
12597         void (*fe_datamove)(union ctl_io *io);
12598
12599         /*
12600          * - Get the data from the host/HBA into local memory.
12601          * - DMA memory from the local controller to the remote controller.
12602          * - Send status back to the remote controller.
12603          */
12604
12605         retval = ctl_datamove_remote_sgl_setup(io);
12606         if (retval != 0)
12607                 return;
12608
12609         /* Switch the pointer over so the FETD knows what to do */
12610         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12611
12612         /*
12613          * Use a custom move done callback, since we need to send completion
12614          * back to the other controller, not to the backend on this side.
12615          */
12616         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12617
12618         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12619         fe_datamove(io);
12620 }
12621
12622 static int
12623 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12624 {
12625 #if 0
12626         char str[256];
12627         char path_str[64];
12628         struct sbuf sb;
12629 #endif
12630         int i;
12631
12632         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12633                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12634         free(io->io_hdr.remote_sglist, M_CTL);
12635         io->io_hdr.remote_sglist = NULL;
12636         io->io_hdr.local_sglist = NULL;
12637
12638 #if 0
12639         scsi_path_string(io, path_str, sizeof(path_str));
12640         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12641         sbuf_cat(&sb, path_str);
12642         scsi_command_string(&io->scsiio, NULL, &sb);
12643         sbuf_printf(&sb, "\n");
12644         sbuf_cat(&sb, path_str);
12645         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12646                     io->scsiio.tag_num, io->scsiio.tag_type);
12647         sbuf_cat(&sb, path_str);
12648         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12649                     io->io_hdr.flags, io->io_hdr.status);
12650         sbuf_finish(&sb);
12651         printk("%s", sbuf_data(&sb));
12652 #endif
12653
12654
12655         /*
12656          * The read is done, now we need to send status (good or bad) back
12657          * to the other side.
12658          */
12659         ctl_send_datamove_done(io, /*have_lock*/ 0);
12660
12661         return (0);
12662 }
12663
12664 static void
12665 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12666 {
12667         union ctl_io *io;
12668         void (*fe_datamove)(union ctl_io *io);
12669
12670         io = rq->context;
12671
12672         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12673                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12674                        rq->ret);
12675                 ctl_set_internal_failure(&io->scsiio,
12676                                          /*sks_valid*/ 1,
12677                                          /*retry_count*/ rq->ret);
12678         }
12679
12680         ctl_dt_req_free(rq);
12681
12682         /* Switch the pointer over so the FETD knows what to do */
12683         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12684
12685         /*
12686          * Use a custom move done callback, since we need to send completion
12687          * back to the other controller, not to the backend on this side.
12688          */
12689         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12690
12691         /* XXX KDM add checks like the ones in ctl_datamove? */
12692
12693         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12694         fe_datamove(io);
12695 }
12696
12697 static int
12698 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12699 {
12700         struct ctl_sg_entry *local_sglist;
12701         struct ctl_softc *softc;
12702         uint32_t len_to_go;
12703         int retval;
12704         int i;
12705
12706         retval = 0;
12707         softc = control_softc;
12708         local_sglist = io->io_hdr.local_sglist;
12709         len_to_go = io->scsiio.kern_data_len;
12710
12711         /*
12712          * The difficult thing here is that the size of the various
12713          * S/G segments may be different than the size from the
12714          * remote controller.  That'll make it harder when DMAing
12715          * the data back to the other side.
12716          */
12717         for (i = 0; len_to_go > 0; i++) {
12718                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12719                 local_sglist[i].addr =
12720                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12721
12722                 len_to_go -= local_sglist[i].len;
12723         }
12724         /*
12725          * Reset the number of S/G entries accordingly.  The original
12726          * number of S/G entries is available in rem_sg_entries.
12727          */
12728         io->scsiio.kern_sg_entries = i;
12729
12730 #if 0
12731         printf("%s: kern_sg_entries = %d\n", __func__,
12732                io->scsiio.kern_sg_entries);
12733         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12734                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12735                        local_sglist[i].addr, local_sglist[i].len);
12736 #endif
12737
12738         return (retval);
12739 }
12740
12741 static int
12742 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12743                          ctl_ha_dt_cb callback)
12744 {
12745         struct ctl_ha_dt_req *rq;
12746         struct ctl_sg_entry *remote_sglist, *local_sglist;
12747         uint32_t local_used, remote_used, total_used;
12748         int i, j, isc_ret;
12749
12750         rq = ctl_dt_req_alloc();
12751
12752         /*
12753          * If we failed to allocate the request, and if the DMA didn't fail
12754          * anyway, set busy status.  This is just a resource allocation
12755          * failure.
12756          */
12757         if ((rq == NULL)
12758          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12759              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12760                 ctl_set_busy(&io->scsiio);
12761
12762         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12763             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12764
12765                 if (rq != NULL)
12766                         ctl_dt_req_free(rq);
12767
12768                 /*
12769                  * The data move failed.  We need to return status back
12770                  * to the other controller.  No point in trying to DMA
12771                  * data to the remote controller.
12772                  */
12773
12774                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12775
12776                 return (1);
12777         }
12778
12779         local_sglist = io->io_hdr.local_sglist;
12780         remote_sglist = io->io_hdr.remote_sglist;
12781         local_used = 0;
12782         remote_used = 0;
12783         total_used = 0;
12784
12785         /*
12786          * Pull/push the data over the wire from/to the other controller.
12787          * This takes into account the possibility that the local and
12788          * remote sglists may not be identical in terms of the size of
12789          * the elements and the number of elements.
12790          *
12791          * One fundamental assumption here is that the length allocated for
12792          * both the local and remote sglists is identical.  Otherwise, we've
12793          * essentially got a coding error of some sort.
12794          */
12795         isc_ret = CTL_HA_STATUS_SUCCESS;
12796         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12797                 uint32_t cur_len;
12798                 uint8_t *tmp_ptr;
12799
12800                 rq->command = command;
12801                 rq->context = io;
12802
12803                 /*
12804                  * Both pointers should be aligned.  But it is possible
12805                  * that the allocation length is not.  They should both
12806                  * also have enough slack left over at the end, though,
12807                  * to round up to the next 8 byte boundary.
12808                  */
12809                 cur_len = MIN(local_sglist[i].len - local_used,
12810                               remote_sglist[j].len - remote_used);
12811                 rq->size = cur_len;
12812
12813                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12814                 tmp_ptr += local_used;
12815
12816 #if 0
12817                 /* Use physical addresses when talking to ISC hardware */
12818                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12819                         /* XXX KDM use busdma */
12820                         rq->local = vtophys(tmp_ptr);
12821                 } else
12822                         rq->local = tmp_ptr;
12823 #else
12824                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12825                     ("HA does not support BUS_ADDR"));
12826                 rq->local = tmp_ptr;
12827 #endif
12828
12829                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12830                 tmp_ptr += remote_used;
12831                 rq->remote = tmp_ptr;
12832
12833                 rq->callback = NULL;
12834
12835                 local_used += cur_len;
12836                 if (local_used >= local_sglist[i].len) {
12837                         i++;
12838                         local_used = 0;
12839                 }
12840
12841                 remote_used += cur_len;
12842                 if (remote_used >= remote_sglist[j].len) {
12843                         j++;
12844                         remote_used = 0;
12845                 }
12846                 total_used += cur_len;
12847
12848                 if (total_used >= io->scsiio.kern_data_len)
12849                         rq->callback = callback;
12850
12851 #if 0
12852                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12853                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12854                        rq->local, rq->remote, rq->size);
12855 #endif
12856
12857                 isc_ret = ctl_dt_single(rq);
12858                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12859                         break;
12860         }
12861         if (isc_ret != CTL_HA_STATUS_WAIT) {
12862                 rq->ret = isc_ret;
12863                 callback(rq);
12864         }
12865
12866         return (0);
12867 }
12868
12869 static void
12870 ctl_datamove_remote_read(union ctl_io *io)
12871 {
12872         int retval;
12873         int i;
12874
12875         /*
12876          * This will send an error to the other controller in the case of a
12877          * failure.
12878          */
12879         retval = ctl_datamove_remote_sgl_setup(io);
12880         if (retval != 0)
12881                 return;
12882
12883         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12884                                           ctl_datamove_remote_read_cb);
12885         if (retval != 0) {
12886                 /*
12887                  * Make sure we free memory if there was an error..  The
12888                  * ctl_datamove_remote_xfer() function will send the
12889                  * datamove done message, or call the callback with an
12890                  * error if there is a problem.
12891                  */
12892                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12893                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12894                 free(io->io_hdr.remote_sglist, M_CTL);
12895                 io->io_hdr.remote_sglist = NULL;
12896                 io->io_hdr.local_sglist = NULL;
12897         }
12898 }
12899
12900 /*
12901  * Process a datamove request from the other controller.  This is used for
12902  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12903  * first.  Once that is complete, the data gets DMAed into the remote
12904  * controller's memory.  For reads, we DMA from the remote controller's
12905  * memory into our memory first, and then move it out to the FETD.
12906  */
12907 static void
12908 ctl_datamove_remote(union ctl_io *io)
12909 {
12910
12911         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12912
12913         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12914                 ctl_failover_io(io, /*have_lock*/ 0);
12915                 return;
12916         }
12917
12918         /*
12919          * Note that we look for an aborted I/O here, but don't do some of
12920          * the other checks that ctl_datamove() normally does.
12921          * We don't need to run the datamove delay code, since that should
12922          * have been done if need be on the other controller.
12923          */
12924         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12925                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12926                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12927                        io->io_hdr.nexus.targ_port,
12928                        io->io_hdr.nexus.targ_lun);
12929                 io->io_hdr.port_status = 31338;
12930                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12931                 return;
12932         }
12933
12934         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12935                 ctl_datamove_remote_write(io);
12936         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12937                 ctl_datamove_remote_read(io);
12938         else {
12939                 io->io_hdr.port_status = 31339;
12940                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12941         }
12942 }
12943
12944 static int
12945 ctl_process_done(union ctl_io *io)
12946 {
12947         struct ctl_lun *lun;
12948         struct ctl_softc *softc = control_softc;
12949         void (*fe_done)(union ctl_io *io);
12950         union ctl_ha_msg msg;
12951         uint32_t targ_port = io->io_hdr.nexus.targ_port;
12952
12953         CTL_DEBUG_PRINT(("ctl_process_done\n"));
12954
12955         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
12956                 fe_done = softc->ctl_ports[targ_port]->fe_done;
12957         else
12958                 fe_done = NULL;
12959
12960 #ifdef CTL_TIME_IO
12961         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12962                 char str[256];
12963                 char path_str[64];
12964                 struct sbuf sb;
12965
12966                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12967                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12968
12969                 sbuf_cat(&sb, path_str);
12970                 switch (io->io_hdr.io_type) {
12971                 case CTL_IO_SCSI:
12972                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12973                         sbuf_printf(&sb, "\n");
12974                         sbuf_cat(&sb, path_str);
12975                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12976                                     io->scsiio.tag_num, io->scsiio.tag_type);
12977                         break;
12978                 case CTL_IO_TASK:
12979                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12980                                     "Tag Type: %d\n", io->taskio.task_action,
12981                                     io->taskio.tag_num, io->taskio.tag_type);
12982                         break;
12983                 default:
12984                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12985                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12986                         break;
12987                 }
12988                 sbuf_cat(&sb, path_str);
12989                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12990                             (intmax_t)time_uptime - io->io_hdr.start_time);
12991                 sbuf_finish(&sb);
12992                 printf("%s", sbuf_data(&sb));
12993         }
12994 #endif /* CTL_TIME_IO */
12995
12996         switch (io->io_hdr.io_type) {
12997         case CTL_IO_SCSI:
12998                 break;
12999         case CTL_IO_TASK:
13000                 if (ctl_debug & CTL_DEBUG_INFO)
13001                         ctl_io_error_print(io, NULL);
13002                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13003                         ctl_free_io(io);
13004                 else
13005                         fe_done(io);
13006                 return (CTL_RETVAL_COMPLETE);
13007         default:
13008                 panic("ctl_process_done: invalid io type %d\n",
13009                       io->io_hdr.io_type);
13010                 break; /* NOTREACHED */
13011         }
13012
13013         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13014         if (lun == NULL) {
13015                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13016                                  io->io_hdr.nexus.targ_mapped_lun));
13017                 goto bailout;
13018         }
13019
13020         mtx_lock(&lun->lun_lock);
13021
13022         /*
13023          * Check to see if we have any errors to inject here.  We only
13024          * inject errors for commands that don't already have errors set.
13025          */
13026         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13027             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13028             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13029                 ctl_inject_error(lun, io);
13030
13031         /*
13032          * XXX KDM how do we treat commands that aren't completed
13033          * successfully?
13034          *
13035          * XXX KDM should we also track I/O latency?
13036          */
13037         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13038             io->io_hdr.io_type == CTL_IO_SCSI) {
13039 #ifdef CTL_TIME_IO
13040                 struct bintime cur_bt;
13041 #endif
13042                 int type;
13043
13044                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13045                     CTL_FLAG_DATA_IN)
13046                         type = CTL_STATS_READ;
13047                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13048                     CTL_FLAG_DATA_OUT)
13049                         type = CTL_STATS_WRITE;
13050                 else
13051                         type = CTL_STATS_NO_IO;
13052
13053                 lun->stats.ports[targ_port].bytes[type] +=
13054                     io->scsiio.kern_total_len;
13055                 lun->stats.ports[targ_port].operations[type]++;
13056 #ifdef CTL_TIME_IO
13057                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13058                    &io->io_hdr.dma_bt);
13059                 lun->stats.ports[targ_port].num_dmas[type] +=
13060                     io->io_hdr.num_dmas;
13061                 getbintime(&cur_bt);
13062                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13063                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13064 #endif
13065         }
13066
13067         /*
13068          * Remove this from the OOA queue.
13069          */
13070         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13071 #ifdef CTL_TIME_IO
13072         if (TAILQ_EMPTY(&lun->ooa_queue))
13073                 lun->last_busy = getsbinuptime();
13074 #endif
13075
13076         /*
13077          * Run through the blocked queue on this LUN and see if anything
13078          * has become unblocked, now that this transaction is done.
13079          */
13080         ctl_check_blocked(lun);
13081
13082         /*
13083          * If the LUN has been invalidated, free it if there is nothing
13084          * left on its OOA queue.
13085          */
13086         if ((lun->flags & CTL_LUN_INVALID)
13087          && TAILQ_EMPTY(&lun->ooa_queue)) {
13088                 mtx_unlock(&lun->lun_lock);
13089                 mtx_lock(&softc->ctl_lock);
13090                 ctl_free_lun(lun);
13091                 mtx_unlock(&softc->ctl_lock);
13092         } else
13093                 mtx_unlock(&lun->lun_lock);
13094
13095 bailout:
13096
13097         /*
13098          * If this command has been aborted, make sure we set the status
13099          * properly.  The FETD is responsible for freeing the I/O and doing
13100          * whatever it needs to do to clean up its state.
13101          */
13102         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13103                 ctl_set_task_aborted(&io->scsiio);
13104
13105         /*
13106          * If enabled, print command error status.
13107          */
13108         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13109             (ctl_debug & CTL_DEBUG_INFO) != 0)
13110                 ctl_io_error_print(io, NULL);
13111
13112         /*
13113          * Tell the FETD or the other shelf controller we're done with this
13114          * command.  Note that only SCSI commands get to this point.  Task
13115          * management commands are completed above.
13116          */
13117         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13118             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13119                 memset(&msg, 0, sizeof(msg));
13120                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13121                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13122                 msg.hdr.nexus = io->io_hdr.nexus;
13123                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13124                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13125                     M_WAITOK);
13126         }
13127         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13128          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13129                 memset(&msg, 0, sizeof(msg));
13130                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13131                 msg.hdr.original_sc = io->io_hdr.original_sc;
13132                 msg.hdr.nexus = io->io_hdr.nexus;
13133                 msg.hdr.status = io->io_hdr.status;
13134                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13135                 msg.scsi.tag_num = io->scsiio.tag_num;
13136                 msg.scsi.tag_type = io->scsiio.tag_type;
13137                 msg.scsi.sense_len = io->scsiio.sense_len;
13138                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13139                 msg.scsi.residual = io->scsiio.residual;
13140                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13141                        io->scsiio.sense_len);
13142
13143                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13144                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
13145                     msg.scsi.sense_len, M_WAITOK);
13146                 ctl_free_io(io);
13147         } else 
13148                 fe_done(io);
13149
13150         return (CTL_RETVAL_COMPLETE);
13151 }
13152
13153 #ifdef CTL_WITH_CA
13154 /*
13155  * Front end should call this if it doesn't do autosense.  When the request
13156  * sense comes back in from the initiator, we'll dequeue this and send it.
13157  */
13158 int
13159 ctl_queue_sense(union ctl_io *io)
13160 {
13161         struct ctl_lun *lun;
13162         struct ctl_port *port;
13163         struct ctl_softc *softc;
13164         uint32_t initidx, targ_lun;
13165
13166         softc = control_softc;
13167
13168         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13169
13170         /*
13171          * LUN lookup will likely move to the ctl_work_thread() once we
13172          * have our new queueing infrastructure (that doesn't put things on
13173          * a per-LUN queue initially).  That is so that we can handle
13174          * things like an INQUIRY to a LUN that we don't have enabled.  We
13175          * can't deal with that right now.
13176          */
13177         mtx_lock(&softc->ctl_lock);
13178
13179         /*
13180          * If we don't have a LUN for this, just toss the sense
13181          * information.
13182          */
13183         port = ctl_io_port(&ctsio->io_hdr);
13184         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13185         if ((targ_lun < CTL_MAX_LUNS)
13186          && (softc->ctl_luns[targ_lun] != NULL))
13187                 lun = softc->ctl_luns[targ_lun];
13188         else
13189                 goto bailout;
13190
13191         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13192
13193         mtx_lock(&lun->lun_lock);
13194         /*
13195          * Already have CA set for this LUN...toss the sense information.
13196          */
13197         if (ctl_is_set(lun->have_ca, initidx)) {
13198                 mtx_unlock(&lun->lun_lock);
13199                 goto bailout;
13200         }
13201
13202         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13203                MIN(sizeof(lun->pending_sense[initidx]),
13204                sizeof(io->scsiio.sense_data)));
13205         ctl_set_mask(lun->have_ca, initidx);
13206         mtx_unlock(&lun->lun_lock);
13207
13208 bailout:
13209         mtx_unlock(&softc->ctl_lock);
13210
13211         ctl_free_io(io);
13212
13213         return (CTL_RETVAL_COMPLETE);
13214 }
13215 #endif
13216
13217 /*
13218  * Primary command inlet from frontend ports.  All SCSI and task I/O
13219  * requests must go through this function.
13220  */
13221 int
13222 ctl_queue(union ctl_io *io)
13223 {
13224         struct ctl_port *port;
13225
13226         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13227
13228 #ifdef CTL_TIME_IO
13229         io->io_hdr.start_time = time_uptime;
13230         getbintime(&io->io_hdr.start_bt);
13231 #endif /* CTL_TIME_IO */
13232
13233         /* Map FE-specific LUN ID into global one. */
13234         port = ctl_io_port(&io->io_hdr);
13235         io->io_hdr.nexus.targ_mapped_lun =
13236             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13237
13238         switch (io->io_hdr.io_type) {
13239         case CTL_IO_SCSI:
13240         case CTL_IO_TASK:
13241                 if (ctl_debug & CTL_DEBUG_CDB)
13242                         ctl_io_print(io);
13243                 ctl_enqueue_incoming(io);
13244                 break;
13245         default:
13246                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13247                 return (EINVAL);
13248         }
13249
13250         return (CTL_RETVAL_COMPLETE);
13251 }
13252
13253 #ifdef CTL_IO_DELAY
13254 static void
13255 ctl_done_timer_wakeup(void *arg)
13256 {
13257         union ctl_io *io;
13258
13259         io = (union ctl_io *)arg;
13260         ctl_done(io);
13261 }
13262 #endif /* CTL_IO_DELAY */
13263
13264 void
13265 ctl_serseq_done(union ctl_io *io)
13266 {
13267         struct ctl_lun *lun;
13268
13269         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13270         if (lun->be_lun == NULL ||
13271             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13272                 return;
13273         mtx_lock(&lun->lun_lock);
13274         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13275         ctl_check_blocked(lun);
13276         mtx_unlock(&lun->lun_lock);
13277 }
13278
13279 void
13280 ctl_done(union ctl_io *io)
13281 {
13282
13283         /*
13284          * Enable this to catch duplicate completion issues.
13285          */
13286 #if 0
13287         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13288                 printf("%s: type %d msg %d cdb %x iptl: "
13289                        "%u:%u:%u tag 0x%04x "
13290                        "flag %#x status %x\n",
13291                         __func__,
13292                         io->io_hdr.io_type,
13293                         io->io_hdr.msg_type,
13294                         io->scsiio.cdb[0],
13295                         io->io_hdr.nexus.initid,
13296                         io->io_hdr.nexus.targ_port,
13297                         io->io_hdr.nexus.targ_lun,
13298                         (io->io_hdr.io_type ==
13299                         CTL_IO_TASK) ?
13300                         io->taskio.tag_num :
13301                         io->scsiio.tag_num,
13302                         io->io_hdr.flags,
13303                         io->io_hdr.status);
13304         } else
13305                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13306 #endif
13307
13308         /*
13309          * This is an internal copy of an I/O, and should not go through
13310          * the normal done processing logic.
13311          */
13312         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13313                 return;
13314
13315 #ifdef CTL_IO_DELAY
13316         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13317                 struct ctl_lun *lun;
13318
13319                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13320
13321                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13322         } else {
13323                 struct ctl_lun *lun;
13324
13325                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13326
13327                 if ((lun != NULL)
13328                  && (lun->delay_info.done_delay > 0)) {
13329
13330                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13331                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13332                         callout_reset(&io->io_hdr.delay_callout,
13333                                       lun->delay_info.done_delay * hz,
13334                                       ctl_done_timer_wakeup, io);
13335                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13336                                 lun->delay_info.done_delay = 0;
13337                         return;
13338                 }
13339         }
13340 #endif /* CTL_IO_DELAY */
13341
13342         ctl_enqueue_done(io);
13343 }
13344
13345 static void
13346 ctl_work_thread(void *arg)
13347 {
13348         struct ctl_thread *thr = (struct ctl_thread *)arg;
13349         struct ctl_softc *softc = thr->ctl_softc;
13350         union ctl_io *io;
13351         int retval;
13352
13353         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13354
13355         for (;;) {
13356                 retval = 0;
13357
13358                 /*
13359                  * We handle the queues in this order:
13360                  * - ISC
13361                  * - done queue (to free up resources, unblock other commands)
13362                  * - RtR queue
13363                  * - incoming queue
13364                  *
13365                  * If those queues are empty, we break out of the loop and
13366                  * go to sleep.
13367                  */
13368                 mtx_lock(&thr->queue_lock);
13369                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13370                 if (io != NULL) {
13371                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13372                         mtx_unlock(&thr->queue_lock);
13373                         ctl_handle_isc(io);
13374                         continue;
13375                 }
13376                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13377                 if (io != NULL) {
13378                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13379                         /* clear any blocked commands, call fe_done */
13380                         mtx_unlock(&thr->queue_lock);
13381                         retval = ctl_process_done(io);
13382                         continue;
13383                 }
13384                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13385                 if (io != NULL) {
13386                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13387                         mtx_unlock(&thr->queue_lock);
13388                         if (io->io_hdr.io_type == CTL_IO_TASK)
13389                                 ctl_run_task(io);
13390                         else
13391                                 ctl_scsiio_precheck(softc, &io->scsiio);
13392                         continue;
13393                 }
13394                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13395                 if (io != NULL) {
13396                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13397                         mtx_unlock(&thr->queue_lock);
13398                         retval = ctl_scsiio(&io->scsiio);
13399                         if (retval != CTL_RETVAL_COMPLETE)
13400                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13401                         continue;
13402                 }
13403
13404                 /* Sleep until we have something to do. */
13405                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13406         }
13407 }
13408
13409 static void
13410 ctl_lun_thread(void *arg)
13411 {
13412         struct ctl_softc *softc = (struct ctl_softc *)arg;
13413         struct ctl_be_lun *be_lun;
13414         int retval;
13415
13416         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13417
13418         for (;;) {
13419                 retval = 0;
13420                 mtx_lock(&softc->ctl_lock);
13421                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13422                 if (be_lun != NULL) {
13423                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13424                         mtx_unlock(&softc->ctl_lock);
13425                         ctl_create_lun(be_lun);
13426                         continue;
13427                 }
13428
13429                 /* Sleep until we have something to do. */
13430                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13431                     PDROP | PRIBIO, "-", 0);
13432         }
13433 }
13434
13435 static void
13436 ctl_thresh_thread(void *arg)
13437 {
13438         struct ctl_softc *softc = (struct ctl_softc *)arg;
13439         struct ctl_lun *lun;
13440         struct ctl_be_lun *be_lun;
13441         struct scsi_da_rw_recovery_page *rwpage;
13442         struct ctl_logical_block_provisioning_page *page;
13443         const char *attr;
13444         union ctl_ha_msg msg;
13445         uint64_t thres, val;
13446         int i, e, set;
13447
13448         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13449
13450         for (;;) {
13451                 mtx_lock(&softc->ctl_lock);
13452                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13453                         be_lun = lun->be_lun;
13454                         if ((lun->flags & CTL_LUN_DISABLED) ||
13455                             (lun->flags & CTL_LUN_OFFLINE) ||
13456                             lun->backend->lun_attr == NULL)
13457                                 continue;
13458                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13459                             softc->ha_mode == CTL_HA_MODE_XFER)
13460                                 continue;
13461                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13462                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13463                                 continue;
13464                         e = 0;
13465                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13466                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13467                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13468                                         continue;
13469                                 thres = scsi_4btoul(page->descr[i].count);
13470                                 thres <<= CTL_LBP_EXPONENT;
13471                                 switch (page->descr[i].resource) {
13472                                 case 0x01:
13473                                         attr = "blocksavail";
13474                                         break;
13475                                 case 0x02:
13476                                         attr = "blocksused";
13477                                         break;
13478                                 case 0xf1:
13479                                         attr = "poolblocksavail";
13480                                         break;
13481                                 case 0xf2:
13482                                         attr = "poolblocksused";
13483                                         break;
13484                                 default:
13485                                         continue;
13486                                 }
13487                                 mtx_unlock(&softc->ctl_lock); // XXX
13488                                 val = lun->backend->lun_attr(
13489                                     lun->be_lun->be_lun, attr);
13490                                 mtx_lock(&softc->ctl_lock);
13491                                 if (val == UINT64_MAX)
13492                                         continue;
13493                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13494                                     == SLBPPD_ARMING_INC)
13495                                         e = (val >= thres);
13496                                 else
13497                                         e = (val <= thres);
13498                                 if (e)
13499                                         break;
13500                         }
13501                         mtx_lock(&lun->lun_lock);
13502                         if (e) {
13503                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13504                                     (uint8_t *)page, lun->ua_tpt_info);
13505                                 if (lun->lasttpt == 0 ||
13506                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13507                                         lun->lasttpt = time_uptime;
13508                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13509                                         set = 1;
13510                                 } else
13511                                         set = 0;
13512                         } else {
13513                                 lun->lasttpt = 0;
13514                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13515                                 set = -1;
13516                         }
13517                         mtx_unlock(&lun->lun_lock);
13518                         if (set != 0 &&
13519                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13520                                 /* Send msg to other side. */
13521                                 bzero(&msg.ua, sizeof(msg.ua));
13522                                 msg.hdr.msg_type = CTL_MSG_UA;
13523                                 msg.hdr.nexus.initid = -1;
13524                                 msg.hdr.nexus.targ_port = -1;
13525                                 msg.hdr.nexus.targ_lun = lun->lun;
13526                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13527                                 msg.ua.ua_all = 1;
13528                                 msg.ua.ua_set = (set > 0);
13529                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13530                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13531                                 mtx_unlock(&softc->ctl_lock); // XXX
13532                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13533                                     sizeof(msg.ua), M_WAITOK);
13534                                 mtx_lock(&softc->ctl_lock);
13535                         }
13536                 }
13537                 mtx_unlock(&softc->ctl_lock);
13538                 pause("-", CTL_LBP_PERIOD * hz);
13539         }
13540 }
13541
13542 static void
13543 ctl_enqueue_incoming(union ctl_io *io)
13544 {
13545         struct ctl_softc *softc = control_softc;
13546         struct ctl_thread *thr;
13547         u_int idx;
13548
13549         idx = (io->io_hdr.nexus.targ_port * 127 +
13550                io->io_hdr.nexus.initid) % worker_threads;
13551         thr = &softc->threads[idx];
13552         mtx_lock(&thr->queue_lock);
13553         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13554         mtx_unlock(&thr->queue_lock);
13555         wakeup(thr);
13556 }
13557
13558 static void
13559 ctl_enqueue_rtr(union ctl_io *io)
13560 {
13561         struct ctl_softc *softc = control_softc;
13562         struct ctl_thread *thr;
13563
13564         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13565         mtx_lock(&thr->queue_lock);
13566         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13567         mtx_unlock(&thr->queue_lock);
13568         wakeup(thr);
13569 }
13570
13571 static void
13572 ctl_enqueue_done(union ctl_io *io)
13573 {
13574         struct ctl_softc *softc = control_softc;
13575         struct ctl_thread *thr;
13576
13577         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13578         mtx_lock(&thr->queue_lock);
13579         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13580         mtx_unlock(&thr->queue_lock);
13581         wakeup(thr);
13582 }
13583
13584 static void
13585 ctl_enqueue_isc(union ctl_io *io)
13586 {
13587         struct ctl_softc *softc = control_softc;
13588         struct ctl_thread *thr;
13589
13590         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13591         mtx_lock(&thr->queue_lock);
13592         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13593         mtx_unlock(&thr->queue_lock);
13594         wakeup(thr);
13595 }
13596
13597 /*
13598  *  vim: ts=8
13599  */