]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r288215: Switch I/O time accounting from system time to uptime.
[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_ha_datamove(union ctl_io *io)
521 {
522         struct ctl_lun *lun;
523         struct ctl_sg_entry *sgl;
524         union ctl_ha_msg msg;
525         uint32_t sg_entries_sent;
526         int do_sg_copy, i, j;
527
528         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
529         memset(&msg.dt, 0, sizeof(msg.dt));
530         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
531         msg.hdr.original_sc = io->io_hdr.original_sc;
532         msg.hdr.serializing_sc = io;
533         msg.hdr.nexus = io->io_hdr.nexus;
534         msg.hdr.status = io->io_hdr.status;
535         msg.dt.flags = io->io_hdr.flags;
536
537         /*
538          * We convert everything into a S/G list here.  We can't
539          * pass by reference, only by value between controllers.
540          * So we can't pass a pointer to the S/G list, only as many
541          * S/G entries as we can fit in here.  If it's possible for
542          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
543          * then we need to break this up into multiple transfers.
544          */
545         if (io->scsiio.kern_sg_entries == 0) {
546                 msg.dt.kern_sg_entries = 1;
547 #if 0
548                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
549                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
550                 } else {
551                         /* XXX KDM use busdma here! */
552                         msg.dt.sg_list[0].addr =
553                             (void *)vtophys(io->scsiio.kern_data_ptr);
554                 }
555 #else
556                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
557                     ("HA does not support BUS_ADDR"));
558                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
559 #endif
560                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
561                 do_sg_copy = 0;
562         } else {
563                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
564                 do_sg_copy = 1;
565         }
566
567         msg.dt.kern_data_len = io->scsiio.kern_data_len;
568         msg.dt.kern_total_len = io->scsiio.kern_total_len;
569         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
570         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
571         msg.dt.sg_sequence = 0;
572
573         /*
574          * Loop until we've sent all of the S/G entries.  On the
575          * other end, we'll recompose these S/G entries into one
576          * contiguous list before processing.
577          */
578         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
579             msg.dt.sg_sequence++) {
580                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
581                     sizeof(msg.dt.sg_list[0])),
582                     msg.dt.kern_sg_entries - sg_entries_sent);
583                 if (do_sg_copy != 0) {
584                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
585                         for (i = sg_entries_sent, j = 0;
586                              i < msg.dt.cur_sg_entries; i++, j++) {
587 #if 0
588                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
589                                         msg.dt.sg_list[j].addr = sgl[i].addr;
590                                 } else {
591                                         /* XXX KDM use busdma here! */
592                                         msg.dt.sg_list[j].addr =
593                                             (void *)vtophys(sgl[i].addr);
594                                 }
595 #else
596                                 KASSERT((io->io_hdr.flags &
597                                     CTL_FLAG_BUS_ADDR) == 0,
598                                     ("HA does not support BUS_ADDR"));
599                                 msg.dt.sg_list[j].addr = sgl[i].addr;
600 #endif
601                                 msg.dt.sg_list[j].len = sgl[i].len;
602                         }
603                 }
604
605                 sg_entries_sent += msg.dt.cur_sg_entries;
606                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
607                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
608                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
609                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
610                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
611                         io->io_hdr.port_status = 31341;
612                         io->scsiio.be_move_done(io);
613                         return;
614                 }
615                 msg.dt.sent_sg_entries = sg_entries_sent;
616         }
617
618         /*
619          * Officially handover the request from us to peer.
620          * If failover has just happened, then we must return error.
621          * If failover happen just after, then it is not our problem.
622          */
623         if (lun)
624                 mtx_lock(&lun->lun_lock);
625         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
626                 if (lun)
627                         mtx_unlock(&lun->lun_lock);
628                 io->io_hdr.port_status = 31342;
629                 io->scsiio.be_move_done(io);
630                 return;
631         }
632         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
633         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
634         if (lun)
635                 mtx_unlock(&lun->lun_lock);
636 }
637
638 static void
639 ctl_ha_done(union ctl_io *io)
640 {
641         union ctl_ha_msg msg;
642
643         if (io->io_hdr.io_type == CTL_IO_SCSI) {
644                 memset(&msg, 0, sizeof(msg));
645                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
646                 msg.hdr.original_sc = io->io_hdr.original_sc;
647                 msg.hdr.nexus = io->io_hdr.nexus;
648                 msg.hdr.status = io->io_hdr.status;
649                 msg.scsi.scsi_status = io->scsiio.scsi_status;
650                 msg.scsi.tag_num = io->scsiio.tag_num;
651                 msg.scsi.tag_type = io->scsiio.tag_type;
652                 msg.scsi.sense_len = io->scsiio.sense_len;
653                 msg.scsi.sense_residual = io->scsiio.sense_residual;
654                 msg.scsi.residual = io->scsiio.residual;
655                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
656                     io->scsiio.sense_len);
657                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
658                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
659                     msg.scsi.sense_len, M_WAITOK);
660         }
661         ctl_free_io(io);
662 }
663
664 static void
665 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
666                             union ctl_ha_msg *msg_info)
667 {
668         struct ctl_scsiio *ctsio;
669
670         if (msg_info->hdr.original_sc == NULL) {
671                 printf("%s: original_sc == NULL!\n", __func__);
672                 /* XXX KDM now what? */
673                 return;
674         }
675
676         ctsio = &msg_info->hdr.original_sc->scsiio;
677         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
678         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
679         ctsio->io_hdr.status = msg_info->hdr.status;
680         ctsio->scsi_status = msg_info->scsi.scsi_status;
681         ctsio->sense_len = msg_info->scsi.sense_len;
682         ctsio->sense_residual = msg_info->scsi.sense_residual;
683         ctsio->residual = msg_info->scsi.residual;
684         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
685                msg_info->scsi.sense_len);
686         ctl_enqueue_isc((union ctl_io *)ctsio);
687 }
688
689 static void
690 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
691                                 union ctl_ha_msg *msg_info)
692 {
693         struct ctl_scsiio *ctsio;
694
695         if (msg_info->hdr.serializing_sc == NULL) {
696                 printf("%s: serializing_sc == NULL!\n", __func__);
697                 /* XXX KDM now what? */
698                 return;
699         }
700
701         ctsio = &msg_info->hdr.serializing_sc->scsiio;
702         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
703         ctl_enqueue_isc((union ctl_io *)ctsio);
704 }
705
706 void
707 ctl_isc_announce_lun(struct ctl_lun *lun)
708 {
709         struct ctl_softc *softc = lun->ctl_softc;
710         union ctl_ha_msg *msg;
711         struct ctl_ha_msg_lun_pr_key pr_key;
712         int i, k;
713
714         if (softc->ha_link != CTL_HA_LINK_ONLINE)
715                 return;
716         mtx_lock(&lun->lun_lock);
717         i = sizeof(msg->lun);
718         if (lun->lun_devid)
719                 i += lun->lun_devid->len;
720         i += sizeof(pr_key) * lun->pr_key_count;
721 alloc:
722         mtx_unlock(&lun->lun_lock);
723         msg = malloc(i, M_CTL, M_WAITOK);
724         mtx_lock(&lun->lun_lock);
725         k = sizeof(msg->lun);
726         if (lun->lun_devid)
727                 k += lun->lun_devid->len;
728         k += sizeof(pr_key) * lun->pr_key_count;
729         if (i < k) {
730                 free(msg, M_CTL);
731                 i = k;
732                 goto alloc;
733         }
734         bzero(&msg->lun, sizeof(msg->lun));
735         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
736         msg->hdr.nexus.targ_lun = lun->lun;
737         msg->hdr.nexus.targ_mapped_lun = lun->lun;
738         msg->lun.flags = lun->flags;
739         msg->lun.pr_generation = lun->PRGeneration;
740         msg->lun.pr_res_idx = lun->pr_res_idx;
741         msg->lun.pr_res_type = lun->res_type;
742         msg->lun.pr_key_count = lun->pr_key_count;
743         i = 0;
744         if (lun->lun_devid) {
745                 msg->lun.lun_devid_len = lun->lun_devid->len;
746                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
747                     msg->lun.lun_devid_len);
748                 i += msg->lun.lun_devid_len;
749         }
750         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
751                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
752                         continue;
753                 pr_key.pr_iid = k;
754                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
755                 i += sizeof(pr_key);
756         }
757         mtx_unlock(&lun->lun_lock);
758         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
759             M_WAITOK);
760         free(msg, M_CTL);
761
762         if (lun->flags & CTL_LUN_PRIMARY_SC) {
763                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
764                         ctl_isc_announce_mode(lun, -1,
765                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
766                             lun->mode_pages.index[i].subpage);
767                 }
768         }
769 }
770
771 void
772 ctl_isc_announce_port(struct ctl_port *port)
773 {
774         struct ctl_softc *softc = port->ctl_softc;
775         union ctl_ha_msg *msg;
776         int i;
777
778         if (port->targ_port < softc->port_min ||
779             port->targ_port >= softc->port_max ||
780             softc->ha_link != CTL_HA_LINK_ONLINE)
781                 return;
782         i = sizeof(msg->port) + strlen(port->port_name) + 1;
783         if (port->lun_map)
784                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
785         if (port->port_devid)
786                 i += port->port_devid->len;
787         if (port->target_devid)
788                 i += port->target_devid->len;
789         if (port->init_devid)
790                 i += port->init_devid->len;
791         msg = malloc(i, M_CTL, M_WAITOK);
792         bzero(&msg->port, sizeof(msg->port));
793         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
794         msg->hdr.nexus.targ_port = port->targ_port;
795         msg->port.port_type = port->port_type;
796         msg->port.physical_port = port->physical_port;
797         msg->port.virtual_port = port->virtual_port;
798         msg->port.status = port->status;
799         i = 0;
800         msg->port.name_len = sprintf(&msg->port.data[i],
801             "%d:%s", softc->ha_id, port->port_name) + 1;
802         i += msg->port.name_len;
803         if (port->lun_map) {
804                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
805                 memcpy(&msg->port.data[i], port->lun_map,
806                     msg->port.lun_map_len);
807                 i += msg->port.lun_map_len;
808         }
809         if (port->port_devid) {
810                 msg->port.port_devid_len = port->port_devid->len;
811                 memcpy(&msg->port.data[i], port->port_devid->data,
812                     msg->port.port_devid_len);
813                 i += msg->port.port_devid_len;
814         }
815         if (port->target_devid) {
816                 msg->port.target_devid_len = port->target_devid->len;
817                 memcpy(&msg->port.data[i], port->target_devid->data,
818                     msg->port.target_devid_len);
819                 i += msg->port.target_devid_len;
820         }
821         if (port->init_devid) {
822                 msg->port.init_devid_len = port->init_devid->len;
823                 memcpy(&msg->port.data[i], port->init_devid->data,
824                     msg->port.init_devid_len);
825                 i += msg->port.init_devid_len;
826         }
827         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
828             M_WAITOK);
829         free(msg, M_CTL);
830 }
831
832 void
833 ctl_isc_announce_iid(struct ctl_port *port, int iid)
834 {
835         struct ctl_softc *softc = port->ctl_softc;
836         union ctl_ha_msg *msg;
837         int i, l;
838
839         if (port->targ_port < softc->port_min ||
840             port->targ_port >= softc->port_max ||
841             softc->ha_link != CTL_HA_LINK_ONLINE)
842                 return;
843         mtx_lock(&softc->ctl_lock);
844         i = sizeof(msg->iid);
845         l = 0;
846         if (port->wwpn_iid[iid].name)
847                 l = strlen(port->wwpn_iid[iid].name) + 1;
848         i += l;
849         msg = malloc(i, M_CTL, M_NOWAIT);
850         if (msg == NULL) {
851                 mtx_unlock(&softc->ctl_lock);
852                 return;
853         }
854         bzero(&msg->iid, sizeof(msg->iid));
855         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
856         msg->hdr.nexus.targ_port = port->targ_port;
857         msg->hdr.nexus.initid = iid;
858         msg->iid.in_use = port->wwpn_iid[iid].in_use;
859         msg->iid.name_len = l;
860         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
861         if (port->wwpn_iid[iid].name)
862                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
863         mtx_unlock(&softc->ctl_lock);
864         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
865         free(msg, M_CTL);
866 }
867
868 void
869 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
870     uint8_t page, uint8_t subpage)
871 {
872         struct ctl_softc *softc = lun->ctl_softc;
873         union ctl_ha_msg msg;
874         int i;
875
876         if (softc->ha_link != CTL_HA_LINK_ONLINE)
877                 return;
878         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
879                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
880                     page && lun->mode_pages.index[i].subpage == subpage)
881                         break;
882         }
883         if (i == CTL_NUM_MODE_PAGES)
884                 return;
885         bzero(&msg.mode, sizeof(msg.mode));
886         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
887         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
888         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
889         msg.hdr.nexus.targ_lun = lun->lun;
890         msg.hdr.nexus.targ_mapped_lun = lun->lun;
891         msg.mode.page_code = page;
892         msg.mode.subpage = subpage;
893         msg.mode.page_len = lun->mode_pages.index[i].page_len;
894         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
895             msg.mode.page_len);
896         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
897             M_WAITOK);
898 }
899
900 static void
901 ctl_isc_ha_link_up(struct ctl_softc *softc)
902 {
903         struct ctl_port *port;
904         struct ctl_lun *lun;
905         union ctl_ha_msg msg;
906         int i;
907
908         /* Announce this node parameters to peer for validation. */
909         msg.login.msg_type = CTL_MSG_LOGIN;
910         msg.login.version = CTL_HA_VERSION;
911         msg.login.ha_mode = softc->ha_mode;
912         msg.login.ha_id = softc->ha_id;
913         msg.login.max_luns = CTL_MAX_LUNS;
914         msg.login.max_ports = CTL_MAX_PORTS;
915         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
916         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
917             M_WAITOK);
918
919         STAILQ_FOREACH(port, &softc->port_list, links) {
920                 ctl_isc_announce_port(port);
921                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
922                         if (port->wwpn_iid[i].in_use)
923                                 ctl_isc_announce_iid(port, i);
924                 }
925         }
926         STAILQ_FOREACH(lun, &softc->lun_list, links)
927                 ctl_isc_announce_lun(lun);
928 }
929
930 static void
931 ctl_isc_ha_link_down(struct ctl_softc *softc)
932 {
933         struct ctl_port *port;
934         struct ctl_lun *lun;
935         union ctl_io *io;
936         int i;
937
938         mtx_lock(&softc->ctl_lock);
939         STAILQ_FOREACH(lun, &softc->lun_list, links) {
940                 mtx_lock(&lun->lun_lock);
941                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
942                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
943                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
944                 }
945                 mtx_unlock(&lun->lun_lock);
946
947                 mtx_unlock(&softc->ctl_lock);
948                 io = ctl_alloc_io(softc->othersc_pool);
949                 mtx_lock(&softc->ctl_lock);
950                 ctl_zero_io(io);
951                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
952                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
953                 ctl_enqueue_isc(io);
954         }
955
956         STAILQ_FOREACH(port, &softc->port_list, links) {
957                 if (port->targ_port >= softc->port_min &&
958                     port->targ_port < softc->port_max)
959                         continue;
960                 port->status &= ~CTL_PORT_STATUS_ONLINE;
961                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
962                         port->wwpn_iid[i].in_use = 0;
963                         free(port->wwpn_iid[i].name, M_CTL);
964                         port->wwpn_iid[i].name = NULL;
965                 }
966         }
967         mtx_unlock(&softc->ctl_lock);
968 }
969
970 static void
971 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
972 {
973         struct ctl_lun *lun;
974         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
975
976         mtx_lock(&softc->ctl_lock);
977         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
978             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
979                 mtx_lock(&lun->lun_lock);
980                 mtx_unlock(&softc->ctl_lock);
981                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
982                     msg->ua.ua_set)
983                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
984                 if (msg->ua.ua_all) {
985                         if (msg->ua.ua_set)
986                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
987                         else
988                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
989                 } else {
990                         if (msg->ua.ua_set)
991                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
992                         else
993                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
994                 }
995                 mtx_unlock(&lun->lun_lock);
996         } else
997                 mtx_unlock(&softc->ctl_lock);
998 }
999
1000 static void
1001 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1002 {
1003         struct ctl_lun *lun;
1004         struct ctl_ha_msg_lun_pr_key pr_key;
1005         int i, k;
1006         ctl_lun_flags oflags;
1007         uint32_t targ_lun;
1008
1009         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1010         mtx_lock(&softc->ctl_lock);
1011         if ((targ_lun >= CTL_MAX_LUNS) ||
1012             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1013                 mtx_unlock(&softc->ctl_lock);
1014                 return;
1015         }
1016         mtx_lock(&lun->lun_lock);
1017         mtx_unlock(&softc->ctl_lock);
1018         if (lun->flags & CTL_LUN_DISABLED) {
1019                 mtx_unlock(&lun->lun_lock);
1020                 return;
1021         }
1022         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1023         if (msg->lun.lun_devid_len != i || (i > 0 &&
1024             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1025                 mtx_unlock(&lun->lun_lock);
1026                 printf("%s: Received conflicting HA LUN %d\n",
1027                     __func__, msg->hdr.nexus.targ_lun);
1028                 return;
1029         } else {
1030                 /* Record whether peer is primary. */
1031                 oflags = lun->flags;
1032                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1033                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1034                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1035                 else
1036                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1037                 if (oflags != lun->flags)
1038                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1039
1040                 /* If peer is primary and we are not -- use data */
1041                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1042                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1043                         lun->PRGeneration = msg->lun.pr_generation;
1044                         lun->pr_res_idx = msg->lun.pr_res_idx;
1045                         lun->res_type = msg->lun.pr_res_type;
1046                         lun->pr_key_count = msg->lun.pr_key_count;
1047                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1048                                 ctl_clr_prkey(lun, k);
1049                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1050                                 memcpy(&pr_key, &msg->lun.data[i],
1051                                     sizeof(pr_key));
1052                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1053                                 ctl_set_prkey(lun, pr_key.pr_iid,
1054                                     pr_key.pr_key);
1055                                 i += sizeof(pr_key);
1056                         }
1057                 }
1058
1059                 mtx_unlock(&lun->lun_lock);
1060                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1061                     __func__, msg->hdr.nexus.targ_lun,
1062                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1063                     "primary" : "secondary"));
1064
1065                 /* If we are primary but peer doesn't know -- notify */
1066                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1067                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1068                         ctl_isc_announce_lun(lun);
1069         }
1070 }
1071
1072 static void
1073 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1074 {
1075         struct ctl_port *port;
1076         struct ctl_lun *lun;
1077         int i, new;
1078
1079         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1080         if (port == NULL) {
1081                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1082                     msg->hdr.nexus.targ_port));
1083                 new = 1;
1084                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1085                 port->frontend = &ha_frontend;
1086                 port->targ_port = msg->hdr.nexus.targ_port;
1087                 port->fe_datamove = ctl_ha_datamove;
1088                 port->fe_done = ctl_ha_done;
1089         } else if (port->frontend == &ha_frontend) {
1090                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1091                     msg->hdr.nexus.targ_port));
1092                 new = 0;
1093         } else {
1094                 printf("%s: Received conflicting HA port %d\n",
1095                     __func__, msg->hdr.nexus.targ_port);
1096                 return;
1097         }
1098         port->port_type = msg->port.port_type;
1099         port->physical_port = msg->port.physical_port;
1100         port->virtual_port = msg->port.virtual_port;
1101         port->status = msg->port.status;
1102         i = 0;
1103         free(port->port_name, M_CTL);
1104         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1105             M_CTL);
1106         i += msg->port.name_len;
1107         if (msg->port.lun_map_len != 0) {
1108                 if (port->lun_map == NULL)
1109                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1110                             M_CTL, M_WAITOK);
1111                 memcpy(port->lun_map, &msg->port.data[i],
1112                     sizeof(uint32_t) * CTL_MAX_LUNS);
1113                 i += msg->port.lun_map_len;
1114         } else {
1115                 free(port->lun_map, M_CTL);
1116                 port->lun_map = NULL;
1117         }
1118         if (msg->port.port_devid_len != 0) {
1119                 if (port->port_devid == NULL ||
1120                     port->port_devid->len != msg->port.port_devid_len) {
1121                         free(port->port_devid, M_CTL);
1122                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1123                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1124                 }
1125                 memcpy(port->port_devid->data, &msg->port.data[i],
1126                     msg->port.port_devid_len);
1127                 port->port_devid->len = msg->port.port_devid_len;
1128                 i += msg->port.port_devid_len;
1129         } else {
1130                 free(port->port_devid, M_CTL);
1131                 port->port_devid = NULL;
1132         }
1133         if (msg->port.target_devid_len != 0) {
1134                 if (port->target_devid == NULL ||
1135                     port->target_devid->len != msg->port.target_devid_len) {
1136                         free(port->target_devid, M_CTL);
1137                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1138                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1139                 }
1140                 memcpy(port->target_devid->data, &msg->port.data[i],
1141                     msg->port.target_devid_len);
1142                 port->target_devid->len = msg->port.target_devid_len;
1143                 i += msg->port.target_devid_len;
1144         } else {
1145                 free(port->target_devid, M_CTL);
1146                 port->target_devid = NULL;
1147         }
1148         if (msg->port.init_devid_len != 0) {
1149                 if (port->init_devid == NULL ||
1150                     port->init_devid->len != msg->port.init_devid_len) {
1151                         free(port->init_devid, M_CTL);
1152                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1153                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1154                 }
1155                 memcpy(port->init_devid->data, &msg->port.data[i],
1156                     msg->port.init_devid_len);
1157                 port->init_devid->len = msg->port.init_devid_len;
1158                 i += msg->port.init_devid_len;
1159         } else {
1160                 free(port->init_devid, M_CTL);
1161                 port->init_devid = NULL;
1162         }
1163         if (new) {
1164                 if (ctl_port_register(port) != 0) {
1165                         printf("%s: ctl_port_register() failed with error\n",
1166                             __func__);
1167                 }
1168         }
1169         mtx_lock(&softc->ctl_lock);
1170         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1171                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1172                         continue;
1173                 mtx_lock(&lun->lun_lock);
1174                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1175                 mtx_unlock(&lun->lun_lock);
1176         }
1177         mtx_unlock(&softc->ctl_lock);
1178 }
1179
1180 static void
1181 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1182 {
1183         struct ctl_port *port;
1184         int iid;
1185
1186         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1187         if (port == NULL) {
1188                 printf("%s: Received IID for unknown port %d\n",
1189                     __func__, msg->hdr.nexus.targ_port);
1190                 return;
1191         }
1192         iid = msg->hdr.nexus.initid;
1193         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1194         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1195         free(port->wwpn_iid[iid].name, M_CTL);
1196         if (msg->iid.name_len) {
1197                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1198                     msg->iid.name_len, M_CTL);
1199         } else
1200                 port->wwpn_iid[iid].name = NULL;
1201 }
1202
1203 static void
1204 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1205 {
1206
1207         if (msg->login.version != CTL_HA_VERSION) {
1208                 printf("CTL HA peers have different versions %d != %d\n",
1209                     msg->login.version, CTL_HA_VERSION);
1210                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1211                 return;
1212         }
1213         if (msg->login.ha_mode != softc->ha_mode) {
1214                 printf("CTL HA peers have different ha_mode %d != %d\n",
1215                     msg->login.ha_mode, softc->ha_mode);
1216                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1217                 return;
1218         }
1219         if (msg->login.ha_id == softc->ha_id) {
1220                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1221                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1222                 return;
1223         }
1224         if (msg->login.max_luns != CTL_MAX_LUNS ||
1225             msg->login.max_ports != CTL_MAX_PORTS ||
1226             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1227                 printf("CTL HA peers have different limits\n");
1228                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1229                 return;
1230         }
1231 }
1232
1233 static void
1234 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1235 {
1236         struct ctl_lun *lun;
1237         int i;
1238         uint32_t initidx, targ_lun;
1239
1240         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1241         mtx_lock(&softc->ctl_lock);
1242         if ((targ_lun >= CTL_MAX_LUNS) ||
1243             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1244                 mtx_unlock(&softc->ctl_lock);
1245                 return;
1246         }
1247         mtx_lock(&lun->lun_lock);
1248         mtx_unlock(&softc->ctl_lock);
1249         if (lun->flags & CTL_LUN_DISABLED) {
1250                 mtx_unlock(&lun->lun_lock);
1251                 return;
1252         }
1253         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1254                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1255                     msg->mode.page_code &&
1256                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1257                         break;
1258         }
1259         if (i == CTL_NUM_MODE_PAGES) {
1260                 mtx_unlock(&lun->lun_lock);
1261                 return;
1262         }
1263         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1264             lun->mode_pages.index[i].page_len);
1265         initidx = ctl_get_initindex(&msg->hdr.nexus);
1266         if (initidx != -1)
1267                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1268         mtx_unlock(&lun->lun_lock);
1269 }
1270
1271 /*
1272  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1273  * subsystem come in here.
1274  */
1275 static void
1276 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1277 {
1278         struct ctl_softc *softc = control_softc;
1279         union ctl_io *io;
1280         struct ctl_prio *presio;
1281         ctl_ha_status isc_status;
1282
1283         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1284         if (event == CTL_HA_EVT_MSG_RECV) {
1285                 union ctl_ha_msg *msg, msgbuf;
1286
1287                 if (param > sizeof(msgbuf))
1288                         msg = malloc(param, M_CTL, M_WAITOK);
1289                 else
1290                         msg = &msgbuf;
1291                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1292                     M_WAITOK);
1293                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1294                         printf("%s: Error receiving message: %d\n",
1295                             __func__, isc_status);
1296                         if (msg != &msgbuf)
1297                                 free(msg, M_CTL);
1298                         return;
1299                 }
1300
1301                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1302                 switch (msg->hdr.msg_type) {
1303                 case CTL_MSG_SERIALIZE:
1304                         io = ctl_alloc_io(softc->othersc_pool);
1305                         ctl_zero_io(io);
1306                         // populate ctsio from msg
1307                         io->io_hdr.io_type = CTL_IO_SCSI;
1308                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1309                         io->io_hdr.original_sc = msg->hdr.original_sc;
1310                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1311                                             CTL_FLAG_IO_ACTIVE;
1312                         /*
1313                          * If we're in serialization-only mode, we don't
1314                          * want to go through full done processing.  Thus
1315                          * the COPY flag.
1316                          *
1317                          * XXX KDM add another flag that is more specific.
1318                          */
1319                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1320                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1321                         io->io_hdr.nexus = msg->hdr.nexus;
1322 #if 0
1323                         printf("port %u, iid %u, lun %u\n",
1324                                io->io_hdr.nexus.targ_port,
1325                                io->io_hdr.nexus.initid,
1326                                io->io_hdr.nexus.targ_lun);
1327 #endif
1328                         io->scsiio.tag_num = msg->scsi.tag_num;
1329                         io->scsiio.tag_type = msg->scsi.tag_type;
1330 #ifdef CTL_TIME_IO
1331                         io->io_hdr.start_time = time_uptime;
1332                         getbinuptime(&io->io_hdr.start_bt);
1333 #endif /* CTL_TIME_IO */
1334                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1335                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1336                                CTL_MAX_CDBLEN);
1337                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1338                                 const struct ctl_cmd_entry *entry;
1339
1340                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1341                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1342                                 io->io_hdr.flags |=
1343                                         entry->flags & CTL_FLAG_DATA_MASK;
1344                         }
1345                         ctl_enqueue_isc(io);
1346                         break;
1347
1348                 /* Performed on the Originating SC, XFER mode only */
1349                 case CTL_MSG_DATAMOVE: {
1350                         struct ctl_sg_entry *sgl;
1351                         int i, j;
1352
1353                         io = msg->hdr.original_sc;
1354                         if (io == NULL) {
1355                                 printf("%s: original_sc == NULL!\n", __func__);
1356                                 /* XXX KDM do something here */
1357                                 break;
1358                         }
1359                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1360                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1361                         /*
1362                          * Keep track of this, we need to send it back over
1363                          * when the datamove is complete.
1364                          */
1365                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1366                         if (msg->hdr.status == CTL_SUCCESS)
1367                                 io->io_hdr.status = msg->hdr.status;
1368
1369                         if (msg->dt.sg_sequence == 0) {
1370 #ifdef CTL_TIME_IO
1371                                 getbinuptime(&io->io_hdr.dma_start_bt);
1372 #endif
1373                                 i = msg->dt.kern_sg_entries +
1374                                     msg->dt.kern_data_len /
1375                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1376                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1377                                     M_WAITOK | M_ZERO);
1378                                 io->io_hdr.remote_sglist = sgl;
1379                                 io->io_hdr.local_sglist =
1380                                     &sgl[msg->dt.kern_sg_entries];
1381
1382                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1383
1384                                 io->scsiio.kern_sg_entries =
1385                                         msg->dt.kern_sg_entries;
1386                                 io->scsiio.rem_sg_entries =
1387                                         msg->dt.kern_sg_entries;
1388                                 io->scsiio.kern_data_len =
1389                                         msg->dt.kern_data_len;
1390                                 io->scsiio.kern_total_len =
1391                                         msg->dt.kern_total_len;
1392                                 io->scsiio.kern_data_resid =
1393                                         msg->dt.kern_data_resid;
1394                                 io->scsiio.kern_rel_offset =
1395                                         msg->dt.kern_rel_offset;
1396                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1397                                 io->io_hdr.flags |= msg->dt.flags &
1398                                     CTL_FLAG_BUS_ADDR;
1399                         } else
1400                                 sgl = (struct ctl_sg_entry *)
1401                                         io->scsiio.kern_data_ptr;
1402
1403                         for (i = msg->dt.sent_sg_entries, j = 0;
1404                              i < (msg->dt.sent_sg_entries +
1405                              msg->dt.cur_sg_entries); i++, j++) {
1406                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1407                                 sgl[i].len = msg->dt.sg_list[j].len;
1408
1409 #if 0
1410                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1411                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1412 #endif
1413                         }
1414
1415                         /*
1416                          * If this is the last piece of the I/O, we've got
1417                          * the full S/G list.  Queue processing in the thread.
1418                          * Otherwise wait for the next piece.
1419                          */
1420                         if (msg->dt.sg_last != 0)
1421                                 ctl_enqueue_isc(io);
1422                         break;
1423                 }
1424                 /* Performed on the Serializing (primary) SC, XFER mode only */
1425                 case CTL_MSG_DATAMOVE_DONE: {
1426                         if (msg->hdr.serializing_sc == NULL) {
1427                                 printf("%s: serializing_sc == NULL!\n",
1428                                        __func__);
1429                                 /* XXX KDM now what? */
1430                                 break;
1431                         }
1432                         /*
1433                          * We grab the sense information here in case
1434                          * there was a failure, so we can return status
1435                          * back to the initiator.
1436                          */
1437                         io = msg->hdr.serializing_sc;
1438                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1439                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1440                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1441                         io->io_hdr.port_status = msg->scsi.fetd_status;
1442                         io->scsiio.residual = msg->scsi.residual;
1443                         if (msg->hdr.status != CTL_STATUS_NONE) {
1444                                 io->io_hdr.status = msg->hdr.status;
1445                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1446                                 io->scsiio.sense_len = msg->scsi.sense_len;
1447                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1448                                 memcpy(&io->scsiio.sense_data,
1449                                     &msg->scsi.sense_data,
1450                                     msg->scsi.sense_len);
1451                                 if (msg->hdr.status == CTL_SUCCESS)
1452                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1453                         }
1454                         ctl_enqueue_isc(io);
1455                         break;
1456                 }
1457
1458                 /* Preformed on Originating SC, SER_ONLY mode */
1459                 case CTL_MSG_R2R:
1460                         io = msg->hdr.original_sc;
1461                         if (io == NULL) {
1462                                 printf("%s: original_sc == NULL!\n",
1463                                     __func__);
1464                                 break;
1465                         }
1466                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1467                         io->io_hdr.msg_type = CTL_MSG_R2R;
1468                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1469                         ctl_enqueue_isc(io);
1470                         break;
1471
1472                 /*
1473                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1474                  * mode.
1475                  * Performed on the Originating (i.e. secondary) SC in XFER
1476                  * mode
1477                  */
1478                 case CTL_MSG_FINISH_IO:
1479                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1480                                 ctl_isc_handler_finish_xfer(softc, msg);
1481                         else
1482                                 ctl_isc_handler_finish_ser_only(softc, msg);
1483                         break;
1484
1485                 /* Preformed on Originating SC */
1486                 case CTL_MSG_BAD_JUJU:
1487                         io = msg->hdr.original_sc;
1488                         if (io == NULL) {
1489                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1490                                        __func__);
1491                                 break;
1492                         }
1493                         ctl_copy_sense_data(msg, io);
1494                         /*
1495                          * IO should have already been cleaned up on other
1496                          * SC so clear this flag so we won't send a message
1497                          * back to finish the IO there.
1498                          */
1499                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1500                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1501
1502                         /* io = msg->hdr.serializing_sc; */
1503                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1504                         ctl_enqueue_isc(io);
1505                         break;
1506
1507                 /* Handle resets sent from the other side */
1508                 case CTL_MSG_MANAGE_TASKS: {
1509                         struct ctl_taskio *taskio;
1510                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1511                             softc->othersc_pool);
1512                         ctl_zero_io((union ctl_io *)taskio);
1513                         taskio->io_hdr.io_type = CTL_IO_TASK;
1514                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1515                         taskio->io_hdr.nexus = msg->hdr.nexus;
1516                         taskio->task_action = msg->task.task_action;
1517                         taskio->tag_num = msg->task.tag_num;
1518                         taskio->tag_type = msg->task.tag_type;
1519 #ifdef CTL_TIME_IO
1520                         taskio->io_hdr.start_time = time_uptime;
1521                         getbinuptime(&taskio->io_hdr.start_bt);
1522 #endif /* CTL_TIME_IO */
1523                         ctl_run_task((union ctl_io *)taskio);
1524                         break;
1525                 }
1526                 /* Persistent Reserve action which needs attention */
1527                 case CTL_MSG_PERS_ACTION:
1528                         presio = (struct ctl_prio *)ctl_alloc_io(
1529                             softc->othersc_pool);
1530                         ctl_zero_io((union ctl_io *)presio);
1531                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1532                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1533                         presio->io_hdr.nexus = msg->hdr.nexus;
1534                         presio->pr_msg = msg->pr;
1535                         ctl_enqueue_isc((union ctl_io *)presio);
1536                         break;
1537                 case CTL_MSG_UA:
1538                         ctl_isc_ua(softc, msg, param);
1539                         break;
1540                 case CTL_MSG_PORT_SYNC:
1541                         ctl_isc_port_sync(softc, msg, param);
1542                         break;
1543                 case CTL_MSG_LUN_SYNC:
1544                         ctl_isc_lun_sync(softc, msg, param);
1545                         break;
1546                 case CTL_MSG_IID_SYNC:
1547                         ctl_isc_iid_sync(softc, msg, param);
1548                         break;
1549                 case CTL_MSG_LOGIN:
1550                         ctl_isc_login(softc, msg, param);
1551                         break;
1552                 case CTL_MSG_MODE_SYNC:
1553                         ctl_isc_mode_sync(softc, msg, param);
1554                         break;
1555                 default:
1556                         printf("Received HA message of unknown type %d\n",
1557                             msg->hdr.msg_type);
1558                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1559                         break;
1560                 }
1561                 if (msg != &msgbuf)
1562                         free(msg, M_CTL);
1563         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1564                 printf("CTL: HA link status changed from %d to %d\n",
1565                     softc->ha_link, param);
1566                 if (param == softc->ha_link)
1567                         return;
1568                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1569                         softc->ha_link = param;
1570                         ctl_isc_ha_link_down(softc);
1571                 } else {
1572                         softc->ha_link = param;
1573                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1574                                 ctl_isc_ha_link_up(softc);
1575                 }
1576                 return;
1577         } else {
1578                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1579                 return;
1580         }
1581 }
1582
1583 static void
1584 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1585 {
1586
1587         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1588             src->scsi.sense_len);
1589         dest->scsiio.scsi_status = src->scsi.scsi_status;
1590         dest->scsiio.sense_len = src->scsi.sense_len;
1591         dest->io_hdr.status = src->hdr.status;
1592 }
1593
1594 static void
1595 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1596 {
1597
1598         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1599             src->scsiio.sense_len);
1600         dest->scsi.scsi_status = src->scsiio.scsi_status;
1601         dest->scsi.sense_len = src->scsiio.sense_len;
1602         dest->hdr.status = src->io_hdr.status;
1603 }
1604
1605 void
1606 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1607 {
1608         struct ctl_softc *softc = lun->ctl_softc;
1609         ctl_ua_type *pu;
1610
1611         if (initidx < softc->init_min || initidx >= softc->init_max)
1612                 return;
1613         mtx_assert(&lun->lun_lock, MA_OWNED);
1614         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1615         if (pu == NULL)
1616                 return;
1617         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1618 }
1619
1620 void
1621 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1622 {
1623         int i;
1624
1625         mtx_assert(&lun->lun_lock, MA_OWNED);
1626         if (lun->pending_ua[port] == NULL)
1627                 return;
1628         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1629                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1630                         continue;
1631                 lun->pending_ua[port][i] |= ua;
1632         }
1633 }
1634
1635 void
1636 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1637 {
1638         struct ctl_softc *softc = lun->ctl_softc;
1639         int i;
1640
1641         mtx_assert(&lun->lun_lock, MA_OWNED);
1642         for (i = softc->port_min; i < softc->port_max; i++)
1643                 ctl_est_ua_port(lun, i, except, ua);
1644 }
1645
1646 void
1647 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1648 {
1649         struct ctl_softc *softc = lun->ctl_softc;
1650         ctl_ua_type *pu;
1651
1652         if (initidx < softc->init_min || initidx >= softc->init_max)
1653                 return;
1654         mtx_assert(&lun->lun_lock, MA_OWNED);
1655         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1656         if (pu == NULL)
1657                 return;
1658         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1659 }
1660
1661 void
1662 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1663 {
1664         struct ctl_softc *softc = lun->ctl_softc;
1665         int i, j;
1666
1667         mtx_assert(&lun->lun_lock, MA_OWNED);
1668         for (i = softc->port_min; i < softc->port_max; i++) {
1669                 if (lun->pending_ua[i] == NULL)
1670                         continue;
1671                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1672                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1673                                 continue;
1674                         lun->pending_ua[i][j] &= ~ua;
1675                 }
1676         }
1677 }
1678
1679 void
1680 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1681     ctl_ua_type ua_type)
1682 {
1683         struct ctl_lun *lun;
1684
1685         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1686         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1687                 mtx_lock(&lun->lun_lock);
1688                 ctl_clr_ua(lun, initidx, ua_type);
1689                 mtx_unlock(&lun->lun_lock);
1690         }
1691 }
1692
1693 static int
1694 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1695 {
1696         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1697         struct ctl_lun *lun;
1698         struct ctl_lun_req ireq;
1699         int error, value;
1700
1701         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1702         error = sysctl_handle_int(oidp, &value, 0, req);
1703         if ((error != 0) || (req->newptr == NULL))
1704                 return (error);
1705
1706         mtx_lock(&softc->ctl_lock);
1707         if (value == 0)
1708                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1709         else
1710                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1711         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1712                 mtx_unlock(&softc->ctl_lock);
1713                 bzero(&ireq, sizeof(ireq));
1714                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1715                 ireq.reqdata.modify.lun_id = lun->lun;
1716                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1717                     curthread);
1718                 if (ireq.status != CTL_LUN_OK) {
1719                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1720                             __func__, ireq.status, ireq.error_str);
1721                 }
1722                 mtx_lock(&softc->ctl_lock);
1723         }
1724         mtx_unlock(&softc->ctl_lock);
1725         return (0);
1726 }
1727
1728 static int
1729 ctl_init(void)
1730 {
1731         struct ctl_softc *softc;
1732         void *other_pool;
1733         int i, error, retval;
1734
1735         retval = 0;
1736         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1737                                M_WAITOK | M_ZERO);
1738
1739         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1740                               "cam/ctl");
1741         softc->dev->si_drv1 = softc;
1742
1743         sysctl_ctx_init(&softc->sysctl_ctx);
1744         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1745                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1746                 CTLFLAG_RD, 0, "CAM Target Layer");
1747
1748         if (softc->sysctl_tree == NULL) {
1749                 printf("%s: unable to allocate sysctl tree\n", __func__);
1750                 destroy_dev(softc->dev);
1751                 free(control_softc, M_DEVBUF);
1752                 control_softc = NULL;
1753                 return (ENOMEM);
1754         }
1755
1756         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1757         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1758             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1759         softc->open_count = 0;
1760
1761         /*
1762          * Default to actually sending a SYNCHRONIZE CACHE command down to
1763          * the drive.
1764          */
1765         softc->flags = CTL_FLAG_REAL_SYNC;
1766
1767         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1768             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1769             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1770
1771         /*
1772          * In Copan's HA scheme, the "master" and "slave" roles are
1773          * figured out through the slot the controller is in.  Although it
1774          * is an active/active system, someone has to be in charge.
1775          */
1776         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1777             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1778             "HA head ID (0 - no HA)");
1779         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1780                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1781                 softc->is_single = 1;
1782                 softc->port_cnt = CTL_MAX_PORTS;
1783                 softc->port_min = 0;
1784         } else {
1785                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1786                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1787         }
1788         softc->port_max = softc->port_min + softc->port_cnt;
1789         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1790         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1791
1792         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1793             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1794             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1795
1796         STAILQ_INIT(&softc->lun_list);
1797         STAILQ_INIT(&softc->pending_lun_queue);
1798         STAILQ_INIT(&softc->fe_list);
1799         STAILQ_INIT(&softc->port_list);
1800         STAILQ_INIT(&softc->be_list);
1801         ctl_tpc_init(softc);
1802
1803         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1804                             &other_pool) != 0)
1805         {
1806                 printf("ctl: can't allocate %d entry other SC pool, "
1807                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1808                 return (ENOMEM);
1809         }
1810         softc->othersc_pool = other_pool;
1811
1812         if (worker_threads <= 0)
1813                 worker_threads = max(1, mp_ncpus / 4);
1814         if (worker_threads > CTL_MAX_THREADS)
1815                 worker_threads = CTL_MAX_THREADS;
1816
1817         for (i = 0; i < worker_threads; i++) {
1818                 struct ctl_thread *thr = &softc->threads[i];
1819
1820                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1821                 thr->ctl_softc = softc;
1822                 STAILQ_INIT(&thr->incoming_queue);
1823                 STAILQ_INIT(&thr->rtr_queue);
1824                 STAILQ_INIT(&thr->done_queue);
1825                 STAILQ_INIT(&thr->isc_queue);
1826
1827                 error = kproc_kthread_add(ctl_work_thread, thr,
1828                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1829                 if (error != 0) {
1830                         printf("error creating CTL work thread!\n");
1831                         ctl_pool_free(other_pool);
1832                         return (error);
1833                 }
1834         }
1835         error = kproc_kthread_add(ctl_lun_thread, softc,
1836             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1837         if (error != 0) {
1838                 printf("error creating CTL lun thread!\n");
1839                 ctl_pool_free(other_pool);
1840                 return (error);
1841         }
1842         error = kproc_kthread_add(ctl_thresh_thread, softc,
1843             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1844         if (error != 0) {
1845                 printf("error creating CTL threshold thread!\n");
1846                 ctl_pool_free(other_pool);
1847                 return (error);
1848         }
1849
1850         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1851             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1852             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1853
1854         if (softc->is_single == 0) {
1855                 ctl_frontend_register(&ha_frontend);
1856                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1857                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1858                         softc->is_single = 1;
1859                 } else
1860                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1861                     != CTL_HA_STATUS_SUCCESS) {
1862                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1863                         softc->is_single = 1;
1864                 }
1865         }
1866         return (0);
1867 }
1868
1869 void
1870 ctl_shutdown(void)
1871 {
1872         struct ctl_softc *softc = control_softc;
1873         struct ctl_lun *lun, *next_lun;
1874
1875         if (softc->is_single == 0) {
1876                 ctl_ha_msg_shutdown(softc);
1877                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1878                     != CTL_HA_STATUS_SUCCESS)
1879                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1880                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1881                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1882                 ctl_frontend_deregister(&ha_frontend);
1883         }
1884
1885         mtx_lock(&softc->ctl_lock);
1886
1887         /*
1888          * Free up each LUN.
1889          */
1890         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1891                 next_lun = STAILQ_NEXT(lun, links);
1892                 ctl_free_lun(lun);
1893         }
1894
1895         mtx_unlock(&softc->ctl_lock);
1896
1897 #if 0
1898         ctl_shutdown_thread(softc->work_thread);
1899         mtx_destroy(&softc->queue_lock);
1900 #endif
1901
1902         ctl_tpc_shutdown(softc);
1903         uma_zdestroy(softc->io_zone);
1904         mtx_destroy(&softc->ctl_lock);
1905
1906         destroy_dev(softc->dev);
1907
1908         sysctl_ctx_free(&softc->sysctl_ctx);
1909
1910         free(control_softc, M_DEVBUF);
1911         control_softc = NULL;
1912 }
1913
1914 static int
1915 ctl_module_event_handler(module_t mod, int what, void *arg)
1916 {
1917
1918         switch (what) {
1919         case MOD_LOAD:
1920                 return (ctl_init());
1921         case MOD_UNLOAD:
1922                 return (EBUSY);
1923         default:
1924                 return (EOPNOTSUPP);
1925         }
1926 }
1927
1928 /*
1929  * XXX KDM should we do some access checks here?  Bump a reference count to
1930  * prevent a CTL module from being unloaded while someone has it open?
1931  */
1932 static int
1933 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1934 {
1935         return (0);
1936 }
1937
1938 static int
1939 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1940 {
1941         return (0);
1942 }
1943
1944 /*
1945  * Remove an initiator by port number and initiator ID.
1946  * Returns 0 for success, -1 for failure.
1947  */
1948 int
1949 ctl_remove_initiator(struct ctl_port *port, int iid)
1950 {
1951         struct ctl_softc *softc = port->ctl_softc;
1952
1953         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1954
1955         if (iid > CTL_MAX_INIT_PER_PORT) {
1956                 printf("%s: initiator ID %u > maximun %u!\n",
1957                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1958                 return (-1);
1959         }
1960
1961         mtx_lock(&softc->ctl_lock);
1962         port->wwpn_iid[iid].in_use--;
1963         port->wwpn_iid[iid].last_use = time_uptime;
1964         mtx_unlock(&softc->ctl_lock);
1965         ctl_isc_announce_iid(port, iid);
1966
1967         return (0);
1968 }
1969
1970 /*
1971  * Add an initiator to the initiator map.
1972  * Returns iid for success, < 0 for failure.
1973  */
1974 int
1975 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1976 {
1977         struct ctl_softc *softc = port->ctl_softc;
1978         time_t best_time;
1979         int i, best;
1980
1981         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1982
1983         if (iid >= CTL_MAX_INIT_PER_PORT) {
1984                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1985                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1986                 free(name, M_CTL);
1987                 return (-1);
1988         }
1989
1990         mtx_lock(&softc->ctl_lock);
1991
1992         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1993                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1994                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1995                                 iid = i;
1996                                 break;
1997                         }
1998                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1999                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2000                                 iid = i;
2001                                 break;
2002                         }
2003                 }
2004         }
2005
2006         if (iid < 0) {
2007                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2008                         if (port->wwpn_iid[i].in_use == 0 &&
2009                             port->wwpn_iid[i].wwpn == 0 &&
2010                             port->wwpn_iid[i].name == NULL) {
2011                                 iid = i;
2012                                 break;
2013                         }
2014                 }
2015         }
2016
2017         if (iid < 0) {
2018                 best = -1;
2019                 best_time = INT32_MAX;
2020                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2021                         if (port->wwpn_iid[i].in_use == 0) {
2022                                 if (port->wwpn_iid[i].last_use < best_time) {
2023                                         best = i;
2024                                         best_time = port->wwpn_iid[i].last_use;
2025                                 }
2026                         }
2027                 }
2028                 iid = best;
2029         }
2030
2031         if (iid < 0) {
2032                 mtx_unlock(&softc->ctl_lock);
2033                 free(name, M_CTL);
2034                 return (-2);
2035         }
2036
2037         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2038                 /*
2039                  * This is not an error yet.
2040                  */
2041                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2042 #if 0
2043                         printf("%s: port %d iid %u WWPN %#jx arrived"
2044                             " again\n", __func__, port->targ_port,
2045                             iid, (uintmax_t)wwpn);
2046 #endif
2047                         goto take;
2048                 }
2049                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2050                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2051 #if 0
2052                         printf("%s: port %d iid %u name '%s' arrived"
2053                             " again\n", __func__, port->targ_port,
2054                             iid, name);
2055 #endif
2056                         goto take;
2057                 }
2058
2059                 /*
2060                  * This is an error, but what do we do about it?  The
2061                  * driver is telling us we have a new WWPN for this
2062                  * initiator ID, so we pretty much need to use it.
2063                  */
2064                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2065                     " but WWPN %#jx '%s' is still at that address\n",
2066                     __func__, port->targ_port, iid, wwpn, name,
2067                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2068                     port->wwpn_iid[iid].name);
2069
2070                 /*
2071                  * XXX KDM clear have_ca and ua_pending on each LUN for
2072                  * this initiator.
2073                  */
2074         }
2075 take:
2076         free(port->wwpn_iid[iid].name, M_CTL);
2077         port->wwpn_iid[iid].name = name;
2078         port->wwpn_iid[iid].wwpn = wwpn;
2079         port->wwpn_iid[iid].in_use++;
2080         mtx_unlock(&softc->ctl_lock);
2081         ctl_isc_announce_iid(port, iid);
2082
2083         return (iid);
2084 }
2085
2086 static int
2087 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2088 {
2089         int len;
2090
2091         switch (port->port_type) {
2092         case CTL_PORT_FC:
2093         {
2094                 struct scsi_transportid_fcp *id =
2095                     (struct scsi_transportid_fcp *)buf;
2096                 if (port->wwpn_iid[iid].wwpn == 0)
2097                         return (0);
2098                 memset(id, 0, sizeof(*id));
2099                 id->format_protocol = SCSI_PROTO_FC;
2100                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2101                 return (sizeof(*id));
2102         }
2103         case CTL_PORT_ISCSI:
2104         {
2105                 struct scsi_transportid_iscsi_port *id =
2106                     (struct scsi_transportid_iscsi_port *)buf;
2107                 if (port->wwpn_iid[iid].name == NULL)
2108                         return (0);
2109                 memset(id, 0, 256);
2110                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2111                     SCSI_PROTO_ISCSI;
2112                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2113                 len = roundup2(min(len, 252), 4);
2114                 scsi_ulto2b(len, id->additional_length);
2115                 return (sizeof(*id) + len);
2116         }
2117         case CTL_PORT_SAS:
2118         {
2119                 struct scsi_transportid_sas *id =
2120                     (struct scsi_transportid_sas *)buf;
2121                 if (port->wwpn_iid[iid].wwpn == 0)
2122                         return (0);
2123                 memset(id, 0, sizeof(*id));
2124                 id->format_protocol = SCSI_PROTO_SAS;
2125                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2126                 return (sizeof(*id));
2127         }
2128         default:
2129         {
2130                 struct scsi_transportid_spi *id =
2131                     (struct scsi_transportid_spi *)buf;
2132                 memset(id, 0, sizeof(*id));
2133                 id->format_protocol = SCSI_PROTO_SPI;
2134                 scsi_ulto2b(iid, id->scsi_addr);
2135                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2136                 return (sizeof(*id));
2137         }
2138         }
2139 }
2140
2141 /*
2142  * Serialize a command that went down the "wrong" side, and so was sent to
2143  * this controller for execution.  The logic is a little different than the
2144  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2145  * sent back to the other side, but in the success case, we execute the
2146  * command on this side (XFER mode) or tell the other side to execute it
2147  * (SER_ONLY mode).
2148  */
2149 static int
2150 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2151 {
2152         struct ctl_softc *softc = control_softc;
2153         union ctl_ha_msg msg_info;
2154         struct ctl_port *port;
2155         struct ctl_lun *lun;
2156         const struct ctl_cmd_entry *entry;
2157         int retval = 0;
2158         uint32_t targ_lun;
2159
2160         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2161         mtx_lock(&softc->ctl_lock);
2162
2163         /* Make sure that we know about this port. */
2164         port = ctl_io_port(&ctsio->io_hdr);
2165         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2166                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2167                                          /*retry_count*/ 1);
2168                 goto badjuju;
2169         }
2170
2171         /* Make sure that we know about this LUN. */
2172         if ((targ_lun < CTL_MAX_LUNS) &&
2173             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2174                 mtx_lock(&lun->lun_lock);
2175                 mtx_unlock(&softc->ctl_lock);
2176                 /*
2177                  * If the LUN is invalid, pretend that it doesn't exist.
2178                  * It will go away as soon as all pending I/O has been
2179                  * completed.
2180                  */
2181                 if (lun->flags & CTL_LUN_DISABLED) {
2182                         mtx_unlock(&lun->lun_lock);
2183                         lun = NULL;
2184                 }
2185         } else {
2186                 mtx_unlock(&softc->ctl_lock);
2187                 lun = NULL;
2188         }
2189         if (lun == NULL) {
2190                 /*
2191                  * The other node would not send this request to us unless
2192                  * received announce that we are primary node for this LUN.
2193                  * If this LUN does not exist now, it is probably result of
2194                  * a race, so respond to initiator in the most opaque way.
2195                  */
2196                 ctl_set_busy(ctsio);
2197                 goto badjuju;
2198         }
2199
2200         entry = ctl_get_cmd_entry(ctsio, NULL);
2201         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2202                 mtx_unlock(&lun->lun_lock);
2203                 goto badjuju;
2204         }
2205
2206         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2207         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2208
2209         /*
2210          * Every I/O goes into the OOA queue for a
2211          * particular LUN, and stays there until completion.
2212          */
2213 #ifdef CTL_TIME_IO
2214         if (TAILQ_EMPTY(&lun->ooa_queue))
2215                 lun->idle_time += getsbinuptime() - lun->last_busy;
2216 #endif
2217         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2218
2219         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2220                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2221                  ooa_links))) {
2222         case CTL_ACTION_BLOCK:
2223                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2224                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2225                                   blocked_links);
2226                 mtx_unlock(&lun->lun_lock);
2227                 break;
2228         case CTL_ACTION_PASS:
2229         case CTL_ACTION_SKIP:
2230                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2231                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2232                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2233                         mtx_unlock(&lun->lun_lock);
2234                 } else {
2235                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2236                         mtx_unlock(&lun->lun_lock);
2237
2238                         /* send msg back to other side */
2239                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2240                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2241                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2242                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2243                             sizeof(msg_info.hdr), M_WAITOK);
2244                 }
2245                 break;
2246         case CTL_ACTION_OVERLAP:
2247                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2248                 mtx_unlock(&lun->lun_lock);
2249                 ctl_set_overlapped_cmd(ctsio);
2250                 goto badjuju;
2251         case CTL_ACTION_OVERLAP_TAG:
2252                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2253                 mtx_unlock(&lun->lun_lock);
2254                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2255                 goto badjuju;
2256         case CTL_ACTION_ERROR:
2257         default:
2258                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2259                 mtx_unlock(&lun->lun_lock);
2260
2261                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2262                                          /*retry_count*/ 0);
2263 badjuju:
2264                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2265                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2266                 msg_info.hdr.serializing_sc = NULL;
2267                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2268                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2269                     sizeof(msg_info.scsi), M_WAITOK);
2270                 retval = 1;
2271                 break;
2272         }
2273         return (retval);
2274 }
2275
2276 /*
2277  * Returns 0 for success, errno for failure.
2278  */
2279 static int
2280 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2281                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2282 {
2283         union ctl_io *io;
2284         int retval;
2285
2286         retval = 0;
2287
2288         mtx_lock(&lun->lun_lock);
2289         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2290              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2291              ooa_links)) {
2292                 struct ctl_ooa_entry *entry;
2293
2294                 /*
2295                  * If we've got more than we can fit, just count the
2296                  * remaining entries.
2297                  */
2298                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2299                         continue;
2300
2301                 entry = &kern_entries[*cur_fill_num];
2302
2303                 entry->tag_num = io->scsiio.tag_num;
2304                 entry->lun_num = lun->lun;
2305 #ifdef CTL_TIME_IO
2306                 entry->start_bt = io->io_hdr.start_bt;
2307 #endif
2308                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2309                 entry->cdb_len = io->scsiio.cdb_len;
2310                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2311                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2312
2313                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2314                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2315
2316                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2317                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2318
2319                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2320                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2321
2322                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2323                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2324         }
2325         mtx_unlock(&lun->lun_lock);
2326
2327         return (retval);
2328 }
2329
2330 static void *
2331 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2332                  size_t error_str_len)
2333 {
2334         void *kptr;
2335
2336         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2337
2338         if (copyin(user_addr, kptr, len) != 0) {
2339                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2340                          "from user address %p to kernel address %p", len,
2341                          user_addr, kptr);
2342                 free(kptr, M_CTL);
2343                 return (NULL);
2344         }
2345
2346         return (kptr);
2347 }
2348
2349 static void
2350 ctl_free_args(int num_args, struct ctl_be_arg *args)
2351 {
2352         int i;
2353
2354         if (args == NULL)
2355                 return;
2356
2357         for (i = 0; i < num_args; i++) {
2358                 free(args[i].kname, M_CTL);
2359                 free(args[i].kvalue, M_CTL);
2360         }
2361
2362         free(args, M_CTL);
2363 }
2364
2365 static struct ctl_be_arg *
2366 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2367                 char *error_str, size_t error_str_len)
2368 {
2369         struct ctl_be_arg *args;
2370         int i;
2371
2372         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2373                                 error_str, error_str_len);
2374
2375         if (args == NULL)
2376                 goto bailout;
2377
2378         for (i = 0; i < num_args; i++) {
2379                 args[i].kname = NULL;
2380                 args[i].kvalue = NULL;
2381         }
2382
2383         for (i = 0; i < num_args; i++) {
2384                 uint8_t *tmpptr;
2385
2386                 args[i].kname = ctl_copyin_alloc(args[i].name,
2387                         args[i].namelen, error_str, error_str_len);
2388                 if (args[i].kname == NULL)
2389                         goto bailout;
2390
2391                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2392                         snprintf(error_str, error_str_len, "Argument %d "
2393                                  "name is not NUL-terminated", i);
2394                         goto bailout;
2395                 }
2396
2397                 if (args[i].flags & CTL_BEARG_RD) {
2398                         tmpptr = ctl_copyin_alloc(args[i].value,
2399                                 args[i].vallen, error_str, error_str_len);
2400                         if (tmpptr == NULL)
2401                                 goto bailout;
2402                         if ((args[i].flags & CTL_BEARG_ASCII)
2403                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2404                                 snprintf(error_str, error_str_len, "Argument "
2405                                     "%d value is not NUL-terminated", i);
2406                                 goto bailout;
2407                         }
2408                         args[i].kvalue = tmpptr;
2409                 } else {
2410                         args[i].kvalue = malloc(args[i].vallen,
2411                             M_CTL, M_WAITOK | M_ZERO);
2412                 }
2413         }
2414
2415         return (args);
2416 bailout:
2417
2418         ctl_free_args(num_args, args);
2419
2420         return (NULL);
2421 }
2422
2423 static void
2424 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2425 {
2426         int i;
2427
2428         for (i = 0; i < num_args; i++) {
2429                 if (args[i].flags & CTL_BEARG_WR)
2430                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2431         }
2432 }
2433
2434 /*
2435  * Escape characters that are illegal or not recommended in XML.
2436  */
2437 int
2438 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2439 {
2440         char *end = str + size;
2441         int retval;
2442
2443         retval = 0;
2444
2445         for (; *str && str < end; str++) {
2446                 switch (*str) {
2447                 case '&':
2448                         retval = sbuf_printf(sb, "&amp;");
2449                         break;
2450                 case '>':
2451                         retval = sbuf_printf(sb, "&gt;");
2452                         break;
2453                 case '<':
2454                         retval = sbuf_printf(sb, "&lt;");
2455                         break;
2456                 default:
2457                         retval = sbuf_putc(sb, *str);
2458                         break;
2459                 }
2460
2461                 if (retval != 0)
2462                         break;
2463
2464         }
2465
2466         return (retval);
2467 }
2468
2469 static void
2470 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2471 {
2472         struct scsi_vpd_id_descriptor *desc;
2473         int i;
2474
2475         if (id == NULL || id->len < 4)
2476                 return;
2477         desc = (struct scsi_vpd_id_descriptor *)id->data;
2478         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2479         case SVPD_ID_TYPE_T10:
2480                 sbuf_printf(sb, "t10.");
2481                 break;
2482         case SVPD_ID_TYPE_EUI64:
2483                 sbuf_printf(sb, "eui.");
2484                 break;
2485         case SVPD_ID_TYPE_NAA:
2486                 sbuf_printf(sb, "naa.");
2487                 break;
2488         case SVPD_ID_TYPE_SCSI_NAME:
2489                 break;
2490         }
2491         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2492         case SVPD_ID_CODESET_BINARY:
2493                 for (i = 0; i < desc->length; i++)
2494                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2495                 break;
2496         case SVPD_ID_CODESET_ASCII:
2497                 sbuf_printf(sb, "%.*s", (int)desc->length,
2498                     (char *)desc->identifier);
2499                 break;
2500         case SVPD_ID_CODESET_UTF8:
2501                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2502                 break;
2503         }
2504 }
2505
2506 static int
2507 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2508           struct thread *td)
2509 {
2510         struct ctl_softc *softc = dev->si_drv1;
2511         struct ctl_lun *lun;
2512         int retval;
2513
2514         retval = 0;
2515
2516         switch (cmd) {
2517         case CTL_IO:
2518                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2519                 break;
2520         case CTL_ENABLE_PORT:
2521         case CTL_DISABLE_PORT:
2522         case CTL_SET_PORT_WWNS: {
2523                 struct ctl_port *port;
2524                 struct ctl_port_entry *entry;
2525
2526                 entry = (struct ctl_port_entry *)addr;
2527                 
2528                 mtx_lock(&softc->ctl_lock);
2529                 STAILQ_FOREACH(port, &softc->port_list, links) {
2530                         int action, done;
2531
2532                         if (port->targ_port < softc->port_min ||
2533                             port->targ_port >= softc->port_max)
2534                                 continue;
2535
2536                         action = 0;
2537                         done = 0;
2538                         if ((entry->port_type == CTL_PORT_NONE)
2539                          && (entry->targ_port == port->targ_port)) {
2540                                 /*
2541                                  * If the user only wants to enable or
2542                                  * disable or set WWNs on a specific port,
2543                                  * do the operation and we're done.
2544                                  */
2545                                 action = 1;
2546                                 done = 1;
2547                         } else if (entry->port_type & port->port_type) {
2548                                 /*
2549                                  * Compare the user's type mask with the
2550                                  * particular frontend type to see if we
2551                                  * have a match.
2552                                  */
2553                                 action = 1;
2554                                 done = 0;
2555
2556                                 /*
2557                                  * Make sure the user isn't trying to set
2558                                  * WWNs on multiple ports at the same time.
2559                                  */
2560                                 if (cmd == CTL_SET_PORT_WWNS) {
2561                                         printf("%s: Can't set WWNs on "
2562                                                "multiple ports\n", __func__);
2563                                         retval = EINVAL;
2564                                         break;
2565                                 }
2566                         }
2567                         if (action == 0)
2568                                 continue;
2569
2570                         /*
2571                          * XXX KDM we have to drop the lock here, because
2572                          * the online/offline operations can potentially
2573                          * block.  We need to reference count the frontends
2574                          * so they can't go away,
2575                          */
2576                         if (cmd == CTL_ENABLE_PORT) {
2577                                 mtx_unlock(&softc->ctl_lock);
2578                                 ctl_port_online(port);
2579                                 mtx_lock(&softc->ctl_lock);
2580                         } else if (cmd == CTL_DISABLE_PORT) {
2581                                 mtx_unlock(&softc->ctl_lock);
2582                                 ctl_port_offline(port);
2583                                 mtx_lock(&softc->ctl_lock);
2584                         } else if (cmd == CTL_SET_PORT_WWNS) {
2585                                 ctl_port_set_wwns(port,
2586                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2587                                     1 : 0, entry->wwnn,
2588                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2589                                     1 : 0, entry->wwpn);
2590                         }
2591                         if (done != 0)
2592                                 break;
2593                 }
2594                 mtx_unlock(&softc->ctl_lock);
2595                 break;
2596         }
2597         case CTL_GET_PORT_LIST: {
2598                 struct ctl_port *port;
2599                 struct ctl_port_list *list;
2600                 int i;
2601
2602                 list = (struct ctl_port_list *)addr;
2603
2604                 if (list->alloc_len != (list->alloc_num *
2605                     sizeof(struct ctl_port_entry))) {
2606                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2607                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2608                                "%zu\n", __func__, list->alloc_len,
2609                                list->alloc_num, sizeof(struct ctl_port_entry));
2610                         retval = EINVAL;
2611                         break;
2612                 }
2613                 list->fill_len = 0;
2614                 list->fill_num = 0;
2615                 list->dropped_num = 0;
2616                 i = 0;
2617                 mtx_lock(&softc->ctl_lock);
2618                 STAILQ_FOREACH(port, &softc->port_list, links) {
2619                         struct ctl_port_entry entry, *list_entry;
2620
2621                         if (list->fill_num >= list->alloc_num) {
2622                                 list->dropped_num++;
2623                                 continue;
2624                         }
2625
2626                         entry.port_type = port->port_type;
2627                         strlcpy(entry.port_name, port->port_name,
2628                                 sizeof(entry.port_name));
2629                         entry.targ_port = port->targ_port;
2630                         entry.physical_port = port->physical_port;
2631                         entry.virtual_port = port->virtual_port;
2632                         entry.wwnn = port->wwnn;
2633                         entry.wwpn = port->wwpn;
2634                         if (port->status & CTL_PORT_STATUS_ONLINE)
2635                                 entry.online = 1;
2636                         else
2637                                 entry.online = 0;
2638
2639                         list_entry = &list->entries[i];
2640
2641                         retval = copyout(&entry, list_entry, sizeof(entry));
2642                         if (retval != 0) {
2643                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2644                                        "returned %d\n", __func__, retval);
2645                                 break;
2646                         }
2647                         i++;
2648                         list->fill_num++;
2649                         list->fill_len += sizeof(entry);
2650                 }
2651                 mtx_unlock(&softc->ctl_lock);
2652
2653                 /*
2654                  * If this is non-zero, we had a copyout fault, so there's
2655                  * probably no point in attempting to set the status inside
2656                  * the structure.
2657                  */
2658                 if (retval != 0)
2659                         break;
2660
2661                 if (list->dropped_num > 0)
2662                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2663                 else
2664                         list->status = CTL_PORT_LIST_OK;
2665                 break;
2666         }
2667         case CTL_DUMP_OOA: {
2668                 union ctl_io *io;
2669                 char printbuf[128];
2670                 struct sbuf sb;
2671
2672                 mtx_lock(&softc->ctl_lock);
2673                 printf("Dumping OOA queues:\n");
2674                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2675                         mtx_lock(&lun->lun_lock);
2676                         for (io = (union ctl_io *)TAILQ_FIRST(
2677                              &lun->ooa_queue); io != NULL;
2678                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2679                              ooa_links)) {
2680                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2681                                          SBUF_FIXEDLEN);
2682                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2683                                             (intmax_t)lun->lun,
2684                                             io->scsiio.tag_num,
2685                                             (io->io_hdr.flags &
2686                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2687                                             (io->io_hdr.flags &
2688                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2689                                             (io->io_hdr.flags &
2690                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2691                                             (io->io_hdr.flags &
2692                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2693                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2694                                 sbuf_finish(&sb);
2695                                 printf("%s\n", sbuf_data(&sb));
2696                         }
2697                         mtx_unlock(&lun->lun_lock);
2698                 }
2699                 printf("OOA queues dump done\n");
2700                 mtx_unlock(&softc->ctl_lock);
2701                 break;
2702         }
2703         case CTL_GET_OOA: {
2704                 struct ctl_ooa *ooa_hdr;
2705                 struct ctl_ooa_entry *entries;
2706                 uint32_t cur_fill_num;
2707
2708                 ooa_hdr = (struct ctl_ooa *)addr;
2709
2710                 if ((ooa_hdr->alloc_len == 0)
2711                  || (ooa_hdr->alloc_num == 0)) {
2712                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2713                                "must be non-zero\n", __func__,
2714                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2715                         retval = EINVAL;
2716                         break;
2717                 }
2718
2719                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2720                     sizeof(struct ctl_ooa_entry))) {
2721                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2722                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2723                                __func__, ooa_hdr->alloc_len,
2724                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2725                         retval = EINVAL;
2726                         break;
2727                 }
2728
2729                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2730                 if (entries == NULL) {
2731                         printf("%s: could not allocate %d bytes for OOA "
2732                                "dump\n", __func__, ooa_hdr->alloc_len);
2733                         retval = ENOMEM;
2734                         break;
2735                 }
2736
2737                 mtx_lock(&softc->ctl_lock);
2738                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2739                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2740                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2741                         mtx_unlock(&softc->ctl_lock);
2742                         free(entries, M_CTL);
2743                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2744                                __func__, (uintmax_t)ooa_hdr->lun_num);
2745                         retval = EINVAL;
2746                         break;
2747                 }
2748
2749                 cur_fill_num = 0;
2750
2751                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2752                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2753                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2754                                         ooa_hdr, entries);
2755                                 if (retval != 0)
2756                                         break;
2757                         }
2758                         if (retval != 0) {
2759                                 mtx_unlock(&softc->ctl_lock);
2760                                 free(entries, M_CTL);
2761                                 break;
2762                         }
2763                 } else {
2764                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2765
2766                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2767                                                     entries);
2768                 }
2769                 mtx_unlock(&softc->ctl_lock);
2770
2771                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2772                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2773                         sizeof(struct ctl_ooa_entry);
2774                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2775                 if (retval != 0) {
2776                         printf("%s: error copying out %d bytes for OOA dump\n", 
2777                                __func__, ooa_hdr->fill_len);
2778                 }
2779
2780                 getbinuptime(&ooa_hdr->cur_bt);
2781
2782                 if (cur_fill_num > ooa_hdr->alloc_num) {
2783                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2784                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2785                 } else {
2786                         ooa_hdr->dropped_num = 0;
2787                         ooa_hdr->status = CTL_OOA_OK;
2788                 }
2789
2790                 free(entries, M_CTL);
2791                 break;
2792         }
2793         case CTL_CHECK_OOA: {
2794                 union ctl_io *io;
2795                 struct ctl_ooa_info *ooa_info;
2796
2797
2798                 ooa_info = (struct ctl_ooa_info *)addr;
2799
2800                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2801                         ooa_info->status = CTL_OOA_INVALID_LUN;
2802                         break;
2803                 }
2804                 mtx_lock(&softc->ctl_lock);
2805                 lun = softc->ctl_luns[ooa_info->lun_id];
2806                 if (lun == NULL) {
2807                         mtx_unlock(&softc->ctl_lock);
2808                         ooa_info->status = CTL_OOA_INVALID_LUN;
2809                         break;
2810                 }
2811                 mtx_lock(&lun->lun_lock);
2812                 mtx_unlock(&softc->ctl_lock);
2813                 ooa_info->num_entries = 0;
2814                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2815                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2816                      &io->io_hdr, ooa_links)) {
2817                         ooa_info->num_entries++;
2818                 }
2819                 mtx_unlock(&lun->lun_lock);
2820
2821                 ooa_info->status = CTL_OOA_SUCCESS;
2822
2823                 break;
2824         }
2825         case CTL_DELAY_IO: {
2826                 struct ctl_io_delay_info *delay_info;
2827
2828                 delay_info = (struct ctl_io_delay_info *)addr;
2829
2830 #ifdef CTL_IO_DELAY
2831                 mtx_lock(&softc->ctl_lock);
2832
2833                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2834                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2835                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2836                 } else {
2837                         lun = softc->ctl_luns[delay_info->lun_id];
2838                         mtx_lock(&lun->lun_lock);
2839
2840                         delay_info->status = CTL_DELAY_STATUS_OK;
2841
2842                         switch (delay_info->delay_type) {
2843                         case CTL_DELAY_TYPE_CONT:
2844                                 break;
2845                         case CTL_DELAY_TYPE_ONESHOT:
2846                                 break;
2847                         default:
2848                                 delay_info->status =
2849                                         CTL_DELAY_STATUS_INVALID_TYPE;
2850                                 break;
2851                         }
2852
2853                         switch (delay_info->delay_loc) {
2854                         case CTL_DELAY_LOC_DATAMOVE:
2855                                 lun->delay_info.datamove_type =
2856                                         delay_info->delay_type;
2857                                 lun->delay_info.datamove_delay =
2858                                         delay_info->delay_secs;
2859                                 break;
2860                         case CTL_DELAY_LOC_DONE:
2861                                 lun->delay_info.done_type =
2862                                         delay_info->delay_type;
2863                                 lun->delay_info.done_delay =
2864                                         delay_info->delay_secs;
2865                                 break;
2866                         default:
2867                                 delay_info->status =
2868                                         CTL_DELAY_STATUS_INVALID_LOC;
2869                                 break;
2870                         }
2871                         mtx_unlock(&lun->lun_lock);
2872                 }
2873
2874                 mtx_unlock(&softc->ctl_lock);
2875 #else
2876                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2877 #endif /* CTL_IO_DELAY */
2878                 break;
2879         }
2880         case CTL_REALSYNC_SET: {
2881                 int *syncstate;
2882
2883                 syncstate = (int *)addr;
2884
2885                 mtx_lock(&softc->ctl_lock);
2886                 switch (*syncstate) {
2887                 case 0:
2888                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2889                         break;
2890                 case 1:
2891                         softc->flags |= CTL_FLAG_REAL_SYNC;
2892                         break;
2893                 default:
2894                         retval = EINVAL;
2895                         break;
2896                 }
2897                 mtx_unlock(&softc->ctl_lock);
2898                 break;
2899         }
2900         case CTL_REALSYNC_GET: {
2901                 int *syncstate;
2902
2903                 syncstate = (int*)addr;
2904
2905                 mtx_lock(&softc->ctl_lock);
2906                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2907                         *syncstate = 1;
2908                 else
2909                         *syncstate = 0;
2910                 mtx_unlock(&softc->ctl_lock);
2911
2912                 break;
2913         }
2914         case CTL_SETSYNC:
2915         case CTL_GETSYNC: {
2916                 struct ctl_sync_info *sync_info;
2917
2918                 sync_info = (struct ctl_sync_info *)addr;
2919
2920                 mtx_lock(&softc->ctl_lock);
2921                 lun = softc->ctl_luns[sync_info->lun_id];
2922                 if (lun == NULL) {
2923                         mtx_unlock(&softc->ctl_lock);
2924                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2925                         break;
2926                 }
2927                 /*
2928                  * Get or set the sync interval.  We're not bounds checking
2929                  * in the set case, hopefully the user won't do something
2930                  * silly.
2931                  */
2932                 mtx_lock(&lun->lun_lock);
2933                 mtx_unlock(&softc->ctl_lock);
2934                 if (cmd == CTL_GETSYNC)
2935                         sync_info->sync_interval = lun->sync_interval;
2936                 else
2937                         lun->sync_interval = sync_info->sync_interval;
2938                 mtx_unlock(&lun->lun_lock);
2939
2940                 sync_info->status = CTL_GS_SYNC_OK;
2941
2942                 break;
2943         }
2944         case CTL_GETSTATS: {
2945                 struct ctl_stats *stats;
2946                 int i;
2947
2948                 stats = (struct ctl_stats *)addr;
2949
2950                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2951                      stats->alloc_len) {
2952                         stats->status = CTL_SS_NEED_MORE_SPACE;
2953                         stats->num_luns = softc->num_luns;
2954                         break;
2955                 }
2956                 /*
2957                  * XXX KDM no locking here.  If the LUN list changes,
2958                  * things can blow up.
2959                  */
2960                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2961                      i++, lun = STAILQ_NEXT(lun, links)) {
2962                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2963                                          sizeof(lun->stats));
2964                         if (retval != 0)
2965                                 break;
2966                 }
2967                 stats->num_luns = softc->num_luns;
2968                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2969                                  softc->num_luns;
2970                 stats->status = CTL_SS_OK;
2971 #ifdef CTL_TIME_IO
2972                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2973 #else
2974                 stats->flags = CTL_STATS_FLAG_NONE;
2975 #endif
2976                 getnanouptime(&stats->timestamp);
2977                 break;
2978         }
2979         case CTL_ERROR_INJECT: {
2980                 struct ctl_error_desc *err_desc, *new_err_desc;
2981
2982                 err_desc = (struct ctl_error_desc *)addr;
2983
2984                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2985                                       M_WAITOK | M_ZERO);
2986                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2987
2988                 mtx_lock(&softc->ctl_lock);
2989                 lun = softc->ctl_luns[err_desc->lun_id];
2990                 if (lun == NULL) {
2991                         mtx_unlock(&softc->ctl_lock);
2992                         free(new_err_desc, M_CTL);
2993                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2994                                __func__, (uintmax_t)err_desc->lun_id);
2995                         retval = EINVAL;
2996                         break;
2997                 }
2998                 mtx_lock(&lun->lun_lock);
2999                 mtx_unlock(&softc->ctl_lock);
3000
3001                 /*
3002                  * We could do some checking here to verify the validity
3003                  * of the request, but given the complexity of error
3004                  * injection requests, the checking logic would be fairly
3005                  * complex.
3006                  *
3007                  * For now, if the request is invalid, it just won't get
3008                  * executed and might get deleted.
3009                  */
3010                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3011
3012                 /*
3013                  * XXX KDM check to make sure the serial number is unique,
3014                  * in case we somehow manage to wrap.  That shouldn't
3015                  * happen for a very long time, but it's the right thing to
3016                  * do.
3017                  */
3018                 new_err_desc->serial = lun->error_serial;
3019                 err_desc->serial = lun->error_serial;
3020                 lun->error_serial++;
3021
3022                 mtx_unlock(&lun->lun_lock);
3023                 break;
3024         }
3025         case CTL_ERROR_INJECT_DELETE: {
3026                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3027                 int delete_done;
3028
3029                 delete_desc = (struct ctl_error_desc *)addr;
3030                 delete_done = 0;
3031
3032                 mtx_lock(&softc->ctl_lock);
3033                 lun = softc->ctl_luns[delete_desc->lun_id];
3034                 if (lun == NULL) {
3035                         mtx_unlock(&softc->ctl_lock);
3036                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3037                                __func__, (uintmax_t)delete_desc->lun_id);
3038                         retval = EINVAL;
3039                         break;
3040                 }
3041                 mtx_lock(&lun->lun_lock);
3042                 mtx_unlock(&softc->ctl_lock);
3043                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3044                         if (desc->serial != delete_desc->serial)
3045                                 continue;
3046
3047                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3048                                       links);
3049                         free(desc, M_CTL);
3050                         delete_done = 1;
3051                 }
3052                 mtx_unlock(&lun->lun_lock);
3053                 if (delete_done == 0) {
3054                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3055                                "error serial %ju on LUN %u\n", __func__, 
3056                                delete_desc->serial, delete_desc->lun_id);
3057                         retval = EINVAL;
3058                         break;
3059                 }
3060                 break;
3061         }
3062         case CTL_DUMP_STRUCTS: {
3063                 int i, j, k;
3064                 struct ctl_port *port;
3065                 struct ctl_frontend *fe;
3066
3067                 mtx_lock(&softc->ctl_lock);
3068                 printf("CTL Persistent Reservation information start:\n");
3069                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3070                         lun = softc->ctl_luns[i];
3071
3072                         if ((lun == NULL)
3073                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3074                                 continue;
3075
3076                         for (j = 0; j < CTL_MAX_PORTS; j++) {
3077                                 if (lun->pr_keys[j] == NULL)
3078                                         continue;
3079                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3080                                         if (lun->pr_keys[j][k] == 0)
3081                                                 continue;
3082                                         printf("  LUN %d port %d iid %d key "
3083                                                "%#jx\n", i, j, k,
3084                                                (uintmax_t)lun->pr_keys[j][k]);
3085                                 }
3086                         }
3087                 }
3088                 printf("CTL Persistent Reservation information end\n");
3089                 printf("CTL Ports:\n");
3090                 STAILQ_FOREACH(port, &softc->port_list, links) {
3091                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3092                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3093                                port->frontend->name, port->port_type,
3094                                port->physical_port, port->virtual_port,
3095                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3096                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3097                                 if (port->wwpn_iid[j].in_use == 0 &&
3098                                     port->wwpn_iid[j].wwpn == 0 &&
3099                                     port->wwpn_iid[j].name == NULL)
3100                                         continue;
3101
3102                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3103                                     j, port->wwpn_iid[j].in_use,
3104                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3105                                     port->wwpn_iid[j].name);
3106                         }
3107                 }
3108                 printf("CTL Port information end\n");
3109                 mtx_unlock(&softc->ctl_lock);
3110                 /*
3111                  * XXX KDM calling this without a lock.  We'd likely want
3112                  * to drop the lock before calling the frontend's dump
3113                  * routine anyway.
3114                  */
3115                 printf("CTL Frontends:\n");
3116                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3117                         printf("  Frontend '%s'\n", fe->name);
3118                         if (fe->fe_dump != NULL)
3119                                 fe->fe_dump();
3120                 }
3121                 printf("CTL Frontend information end\n");
3122                 break;
3123         }
3124         case CTL_LUN_REQ: {
3125                 struct ctl_lun_req *lun_req;
3126                 struct ctl_backend_driver *backend;
3127
3128                 lun_req = (struct ctl_lun_req *)addr;
3129
3130                 backend = ctl_backend_find(lun_req->backend);
3131                 if (backend == NULL) {
3132                         lun_req->status = CTL_LUN_ERROR;
3133                         snprintf(lun_req->error_str,
3134                                  sizeof(lun_req->error_str),
3135                                  "Backend \"%s\" not found.",
3136                                  lun_req->backend);
3137                         break;
3138                 }
3139                 if (lun_req->num_be_args > 0) {
3140                         lun_req->kern_be_args = ctl_copyin_args(
3141                                 lun_req->num_be_args,
3142                                 lun_req->be_args,
3143                                 lun_req->error_str,
3144                                 sizeof(lun_req->error_str));
3145                         if (lun_req->kern_be_args == NULL) {
3146                                 lun_req->status = CTL_LUN_ERROR;
3147                                 break;
3148                         }
3149                 }
3150
3151                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3152
3153                 if (lun_req->num_be_args > 0) {
3154                         ctl_copyout_args(lun_req->num_be_args,
3155                                       lun_req->kern_be_args);
3156                         ctl_free_args(lun_req->num_be_args,
3157                                       lun_req->kern_be_args);
3158                 }
3159                 break;
3160         }
3161         case CTL_LUN_LIST: {
3162                 struct sbuf *sb;
3163                 struct ctl_lun_list *list;
3164                 struct ctl_option *opt;
3165
3166                 list = (struct ctl_lun_list *)addr;
3167
3168                 /*
3169                  * Allocate a fixed length sbuf here, based on the length
3170                  * of the user's buffer.  We could allocate an auto-extending
3171                  * buffer, and then tell the user how much larger our
3172                  * amount of data is than his buffer, but that presents
3173                  * some problems:
3174                  *
3175                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3176                  *     we can't hold a lock while calling them with an
3177                  *     auto-extending buffer.
3178                  *
3179                  * 2.  There is not currently a LUN reference counting
3180                  *     mechanism, outside of outstanding transactions on
3181                  *     the LUN's OOA queue.  So a LUN could go away on us
3182                  *     while we're getting the LUN number, backend-specific
3183                  *     information, etc.  Thus, given the way things
3184                  *     currently work, we need to hold the CTL lock while
3185                  *     grabbing LUN information.
3186                  *
3187                  * So, from the user's standpoint, the best thing to do is
3188                  * allocate what he thinks is a reasonable buffer length,
3189                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3190                  * double the buffer length and try again.  (And repeat
3191                  * that until he succeeds.)
3192                  */
3193                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3194                 if (sb == NULL) {
3195                         list->status = CTL_LUN_LIST_ERROR;
3196                         snprintf(list->error_str, sizeof(list->error_str),
3197                                  "Unable to allocate %d bytes for LUN list",
3198                                  list->alloc_len);
3199                         break;
3200                 }
3201
3202                 sbuf_printf(sb, "<ctllunlist>\n");
3203
3204                 mtx_lock(&softc->ctl_lock);
3205                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3206                         mtx_lock(&lun->lun_lock);
3207                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3208                                              (uintmax_t)lun->lun);
3209
3210                         /*
3211                          * Bail out as soon as we see that we've overfilled
3212                          * the buffer.
3213                          */
3214                         if (retval != 0)
3215                                 break;
3216
3217                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3218                                              "</backend_type>\n",
3219                                              (lun->backend == NULL) ?  "none" :
3220                                              lun->backend->name);
3221
3222                         if (retval != 0)
3223                                 break;
3224
3225                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3226                                              lun->be_lun->lun_type);
3227
3228                         if (retval != 0)
3229                                 break;
3230
3231                         if (lun->backend == NULL) {
3232                                 retval = sbuf_printf(sb, "</lun>\n");
3233                                 if (retval != 0)
3234                                         break;
3235                                 continue;
3236                         }
3237
3238                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3239                                              (lun->be_lun->maxlba > 0) ?
3240                                              lun->be_lun->maxlba + 1 : 0);
3241
3242                         if (retval != 0)
3243                                 break;
3244
3245                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3246                                              lun->be_lun->blocksize);
3247
3248                         if (retval != 0)
3249                                 break;
3250
3251                         retval = sbuf_printf(sb, "\t<serial_number>");
3252
3253                         if (retval != 0)
3254                                 break;
3255
3256                         retval = ctl_sbuf_printf_esc(sb,
3257                             lun->be_lun->serial_num,
3258                             sizeof(lun->be_lun->serial_num));
3259
3260                         if (retval != 0)
3261                                 break;
3262
3263                         retval = sbuf_printf(sb, "</serial_number>\n");
3264                 
3265                         if (retval != 0)
3266                                 break;
3267
3268                         retval = sbuf_printf(sb, "\t<device_id>");
3269
3270                         if (retval != 0)
3271                                 break;
3272
3273                         retval = ctl_sbuf_printf_esc(sb,
3274                             lun->be_lun->device_id,
3275                             sizeof(lun->be_lun->device_id));
3276
3277                         if (retval != 0)
3278                                 break;
3279
3280                         retval = sbuf_printf(sb, "</device_id>\n");
3281
3282                         if (retval != 0)
3283                                 break;
3284
3285                         if (lun->backend->lun_info != NULL) {
3286                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3287                                 if (retval != 0)
3288                                         break;
3289                         }
3290                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3291                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3292                                     opt->name, opt->value, opt->name);
3293                                 if (retval != 0)
3294                                         break;
3295                         }
3296
3297                         retval = sbuf_printf(sb, "</lun>\n");
3298
3299                         if (retval != 0)
3300                                 break;
3301                         mtx_unlock(&lun->lun_lock);
3302                 }
3303                 if (lun != NULL)
3304                         mtx_unlock(&lun->lun_lock);
3305                 mtx_unlock(&softc->ctl_lock);
3306
3307                 if ((retval != 0)
3308                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3309                         retval = 0;
3310                         sbuf_delete(sb);
3311                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3312                         snprintf(list->error_str, sizeof(list->error_str),
3313                                  "Out of space, %d bytes is too small",
3314                                  list->alloc_len);
3315                         break;
3316                 }
3317
3318                 sbuf_finish(sb);
3319
3320                 retval = copyout(sbuf_data(sb), list->lun_xml,
3321                                  sbuf_len(sb) + 1);
3322
3323                 list->fill_len = sbuf_len(sb) + 1;
3324                 list->status = CTL_LUN_LIST_OK;
3325                 sbuf_delete(sb);
3326                 break;
3327         }
3328         case CTL_ISCSI: {
3329                 struct ctl_iscsi *ci;
3330                 struct ctl_frontend *fe;
3331
3332                 ci = (struct ctl_iscsi *)addr;
3333
3334                 fe = ctl_frontend_find("iscsi");
3335                 if (fe == NULL) {
3336                         ci->status = CTL_ISCSI_ERROR;
3337                         snprintf(ci->error_str, sizeof(ci->error_str),
3338                             "Frontend \"iscsi\" not found.");
3339                         break;
3340                 }
3341
3342                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3343                 break;
3344         }
3345         case CTL_PORT_REQ: {
3346                 struct ctl_req *req;
3347                 struct ctl_frontend *fe;
3348
3349                 req = (struct ctl_req *)addr;
3350
3351                 fe = ctl_frontend_find(req->driver);
3352                 if (fe == NULL) {
3353                         req->status = CTL_LUN_ERROR;
3354                         snprintf(req->error_str, sizeof(req->error_str),
3355                             "Frontend \"%s\" not found.", req->driver);
3356                         break;
3357                 }
3358                 if (req->num_args > 0) {
3359                         req->kern_args = ctl_copyin_args(req->num_args,
3360                             req->args, req->error_str, sizeof(req->error_str));
3361                         if (req->kern_args == NULL) {
3362                                 req->status = CTL_LUN_ERROR;
3363                                 break;
3364                         }
3365                 }
3366
3367                 if (fe->ioctl)
3368                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3369                 else
3370                         retval = ENODEV;
3371
3372                 if (req->num_args > 0) {
3373                         ctl_copyout_args(req->num_args, req->kern_args);
3374                         ctl_free_args(req->num_args, req->kern_args);
3375                 }
3376                 break;
3377         }
3378         case CTL_PORT_LIST: {
3379                 struct sbuf *sb;
3380                 struct ctl_port *port;
3381                 struct ctl_lun_list *list;
3382                 struct ctl_option *opt;
3383                 int j;
3384                 uint32_t plun;
3385
3386                 list = (struct ctl_lun_list *)addr;
3387
3388                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3389                 if (sb == NULL) {
3390                         list->status = CTL_LUN_LIST_ERROR;
3391                         snprintf(list->error_str, sizeof(list->error_str),
3392                                  "Unable to allocate %d bytes for LUN list",
3393                                  list->alloc_len);
3394                         break;
3395                 }
3396
3397                 sbuf_printf(sb, "<ctlportlist>\n");
3398
3399                 mtx_lock(&softc->ctl_lock);
3400                 STAILQ_FOREACH(port, &softc->port_list, links) {
3401                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3402                                              (uintmax_t)port->targ_port);
3403
3404                         /*
3405                          * Bail out as soon as we see that we've overfilled
3406                          * the buffer.
3407                          */
3408                         if (retval != 0)
3409                                 break;
3410
3411                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3412                             "</frontend_type>\n", port->frontend->name);
3413                         if (retval != 0)
3414                                 break;
3415
3416                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3417                                              port->port_type);
3418                         if (retval != 0)
3419                                 break;
3420
3421                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3422                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3423                         if (retval != 0)
3424                                 break;
3425
3426                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3427                             port->port_name);
3428                         if (retval != 0)
3429                                 break;
3430
3431                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3432                             port->physical_port);
3433                         if (retval != 0)
3434                                 break;
3435
3436                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3437                             port->virtual_port);
3438                         if (retval != 0)
3439                                 break;
3440
3441                         if (port->target_devid != NULL) {
3442                                 sbuf_printf(sb, "\t<target>");
3443                                 ctl_id_sbuf(port->target_devid, sb);
3444                                 sbuf_printf(sb, "</target>\n");
3445                         }
3446
3447                         if (port->port_devid != NULL) {
3448                                 sbuf_printf(sb, "\t<port>");
3449                                 ctl_id_sbuf(port->port_devid, sb);
3450                                 sbuf_printf(sb, "</port>\n");
3451                         }
3452
3453                         if (port->port_info != NULL) {
3454                                 retval = port->port_info(port->onoff_arg, sb);
3455                                 if (retval != 0)
3456                                         break;
3457                         }
3458                         STAILQ_FOREACH(opt, &port->options, links) {
3459                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3460                                     opt->name, opt->value, opt->name);
3461                                 if (retval != 0)
3462                                         break;
3463                         }
3464
3465                         if (port->lun_map != NULL) {
3466                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3467                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3468                                         plun = ctl_lun_map_from_port(port, j);
3469                                         if (plun >= CTL_MAX_LUNS)
3470                                                 continue;
3471                                         sbuf_printf(sb,
3472                                             "\t<lun id=\"%u\">%u</lun>\n",
3473                                             j, plun);
3474                                 }
3475                         }
3476
3477                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3478                                 if (port->wwpn_iid[j].in_use == 0 ||
3479                                     (port->wwpn_iid[j].wwpn == 0 &&
3480                                      port->wwpn_iid[j].name == NULL))
3481                                         continue;
3482
3483                                 if (port->wwpn_iid[j].name != NULL)
3484                                         retval = sbuf_printf(sb,
3485                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3486                                             j, port->wwpn_iid[j].name);
3487                                 else
3488                                         retval = sbuf_printf(sb,
3489                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3490                                             j, port->wwpn_iid[j].wwpn);
3491                                 if (retval != 0)
3492                                         break;
3493                         }
3494                         if (retval != 0)
3495                                 break;
3496
3497                         retval = sbuf_printf(sb, "</targ_port>\n");
3498                         if (retval != 0)
3499                                 break;
3500                 }
3501                 mtx_unlock(&softc->ctl_lock);
3502
3503                 if ((retval != 0)
3504                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3505                         retval = 0;
3506                         sbuf_delete(sb);
3507                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3508                         snprintf(list->error_str, sizeof(list->error_str),
3509                                  "Out of space, %d bytes is too small",
3510                                  list->alloc_len);
3511                         break;
3512                 }
3513
3514                 sbuf_finish(sb);
3515
3516                 retval = copyout(sbuf_data(sb), list->lun_xml,
3517                                  sbuf_len(sb) + 1);
3518
3519                 list->fill_len = sbuf_len(sb) + 1;
3520                 list->status = CTL_LUN_LIST_OK;
3521                 sbuf_delete(sb);
3522                 break;
3523         }
3524         case CTL_LUN_MAP: {
3525                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3526                 struct ctl_port *port;
3527
3528                 mtx_lock(&softc->ctl_lock);
3529                 if (lm->port < softc->port_min ||
3530                     lm->port >= softc->port_max ||
3531                     (port = softc->ctl_ports[lm->port]) == NULL) {
3532                         mtx_unlock(&softc->ctl_lock);
3533                         return (ENXIO);
3534                 }
3535                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3536                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3537                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3538                                     CTL_MAX_LUNS)
3539                                         continue;
3540                                 mtx_lock(&lun->lun_lock);
3541                                 ctl_est_ua_port(lun, lm->port, -1,
3542                                     CTL_UA_LUN_CHANGE);
3543                                 mtx_unlock(&lun->lun_lock);
3544                         }
3545                 }
3546                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3547                 if (lm->plun < CTL_MAX_LUNS) {
3548                         if (lm->lun == UINT32_MAX)
3549                                 retval = ctl_lun_map_unset(port, lm->plun);
3550                         else if (lm->lun < CTL_MAX_LUNS &&
3551                             softc->ctl_luns[lm->lun] != NULL)
3552                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3553                         else
3554                                 return (ENXIO);
3555                 } else if (lm->plun == UINT32_MAX) {
3556                         if (lm->lun == UINT32_MAX)
3557                                 retval = ctl_lun_map_deinit(port);
3558                         else
3559                                 retval = ctl_lun_map_init(port);
3560                 } else
3561                         return (ENXIO);
3562                 if (port->status & CTL_PORT_STATUS_ONLINE)
3563                         ctl_isc_announce_port(port);
3564                 break;
3565         }
3566         default: {
3567                 /* XXX KDM should we fix this? */
3568 #if 0
3569                 struct ctl_backend_driver *backend;
3570                 unsigned int type;
3571                 int found;
3572
3573                 found = 0;
3574
3575                 /*
3576                  * We encode the backend type as the ioctl type for backend
3577                  * ioctls.  So parse it out here, and then search for a
3578                  * backend of this type.
3579                  */
3580                 type = _IOC_TYPE(cmd);
3581
3582                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3583                         if (backend->type == type) {
3584                                 found = 1;
3585                                 break;
3586                         }
3587                 }
3588                 if (found == 0) {
3589                         printf("ctl: unknown ioctl command %#lx or backend "
3590                                "%d\n", cmd, type);
3591                         retval = EINVAL;
3592                         break;
3593                 }
3594                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3595 #endif
3596                 retval = ENOTTY;
3597                 break;
3598         }
3599         }
3600         return (retval);
3601 }
3602
3603 uint32_t
3604 ctl_get_initindex(struct ctl_nexus *nexus)
3605 {
3606         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3607 }
3608
3609 int
3610 ctl_lun_map_init(struct ctl_port *port)
3611 {
3612         struct ctl_softc *softc = port->ctl_softc;
3613         struct ctl_lun *lun;
3614         uint32_t i;
3615
3616         if (port->lun_map == NULL)
3617                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3618                     M_CTL, M_NOWAIT);
3619         if (port->lun_map == NULL)
3620                 return (ENOMEM);
3621         for (i = 0; i < CTL_MAX_LUNS; i++)
3622                 port->lun_map[i] = UINT32_MAX;
3623         if (port->status & CTL_PORT_STATUS_ONLINE) {
3624                 if (port->lun_disable != NULL) {
3625                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3626                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3627                 }
3628                 ctl_isc_announce_port(port);
3629         }
3630         return (0);
3631 }
3632
3633 int
3634 ctl_lun_map_deinit(struct ctl_port *port)
3635 {
3636         struct ctl_softc *softc = port->ctl_softc;
3637         struct ctl_lun *lun;
3638
3639         if (port->lun_map == NULL)
3640                 return (0);
3641         free(port->lun_map, M_CTL);
3642         port->lun_map = NULL;
3643         if (port->status & CTL_PORT_STATUS_ONLINE) {
3644                 if (port->lun_enable != NULL) {
3645                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3646                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3647                 }
3648                 ctl_isc_announce_port(port);
3649         }
3650         return (0);
3651 }
3652
3653 int
3654 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3655 {
3656         int status;
3657         uint32_t old;
3658
3659         if (port->lun_map == NULL) {
3660                 status = ctl_lun_map_init(port);
3661                 if (status != 0)
3662                         return (status);
3663         }
3664         old = port->lun_map[plun];
3665         port->lun_map[plun] = glun;
3666         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3667                 if (port->lun_enable != NULL)
3668                         port->lun_enable(port->targ_lun_arg, plun);
3669                 ctl_isc_announce_port(port);
3670         }
3671         return (0);
3672 }
3673
3674 int
3675 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3676 {
3677         uint32_t old;
3678
3679         if (port->lun_map == NULL)
3680                 return (0);
3681         old = port->lun_map[plun];
3682         port->lun_map[plun] = UINT32_MAX;
3683         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3684                 if (port->lun_disable != NULL)
3685                         port->lun_disable(port->targ_lun_arg, plun);
3686                 ctl_isc_announce_port(port);
3687         }
3688         return (0);
3689 }
3690
3691 uint32_t
3692 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3693 {
3694
3695         if (port == NULL)
3696                 return (UINT32_MAX);
3697         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3698                 return (lun_id);
3699         return (port->lun_map[lun_id]);
3700 }
3701
3702 uint32_t
3703 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3704 {
3705         uint32_t i;
3706
3707         if (port == NULL)
3708                 return (UINT32_MAX);
3709         if (port->lun_map == NULL)
3710                 return (lun_id);
3711         for (i = 0; i < CTL_MAX_LUNS; i++) {
3712                 if (port->lun_map[i] == lun_id)
3713                         return (i);
3714         }
3715         return (UINT32_MAX);
3716 }
3717
3718 static struct ctl_port *
3719 ctl_io_port(struct ctl_io_hdr *io_hdr)
3720 {
3721
3722         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3723 }
3724
3725 int
3726 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3727 {
3728         int i;
3729
3730         for (i = first; i < last; i++) {
3731                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3732                         return (i);
3733         }
3734         return (-1);
3735 }
3736
3737 int
3738 ctl_set_mask(uint32_t *mask, uint32_t bit)
3739 {
3740         uint32_t chunk, piece;
3741
3742         chunk = bit >> 5;
3743         piece = bit % (sizeof(uint32_t) * 8);
3744
3745         if ((mask[chunk] & (1 << piece)) != 0)
3746                 return (-1);
3747         else
3748                 mask[chunk] |= (1 << piece);
3749
3750         return (0);
3751 }
3752
3753 int
3754 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3755 {
3756         uint32_t chunk, piece;
3757
3758         chunk = bit >> 5;
3759         piece = bit % (sizeof(uint32_t) * 8);
3760
3761         if ((mask[chunk] & (1 << piece)) == 0)
3762                 return (-1);
3763         else
3764                 mask[chunk] &= ~(1 << piece);
3765
3766         return (0);
3767 }
3768
3769 int
3770 ctl_is_set(uint32_t *mask, uint32_t bit)
3771 {
3772         uint32_t chunk, piece;
3773
3774         chunk = bit >> 5;
3775         piece = bit % (sizeof(uint32_t) * 8);
3776
3777         if ((mask[chunk] & (1 << piece)) == 0)
3778                 return (0);
3779         else
3780                 return (1);
3781 }
3782
3783 static uint64_t
3784 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3785 {
3786         uint64_t *t;
3787
3788         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3789         if (t == NULL)
3790                 return (0);
3791         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3792 }
3793
3794 static void
3795 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3796 {
3797         uint64_t *t;
3798
3799         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3800         if (t == NULL)
3801                 return;
3802         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3803 }
3804
3805 static void
3806 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3807 {
3808         uint64_t *p;
3809         u_int i;
3810
3811         i = residx/CTL_MAX_INIT_PER_PORT;
3812         if (lun->pr_keys[i] != NULL)
3813                 return;
3814         mtx_unlock(&lun->lun_lock);
3815         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3816             M_WAITOK | M_ZERO);
3817         mtx_lock(&lun->lun_lock);
3818         if (lun->pr_keys[i] == NULL)
3819                 lun->pr_keys[i] = p;
3820         else
3821                 free(p, M_CTL);
3822 }
3823
3824 static void
3825 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3826 {
3827         uint64_t *t;
3828
3829         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3830         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3831         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3832 }
3833
3834 /*
3835  * ctl_softc, pool_name, total_ctl_io are passed in.
3836  * npool is passed out.
3837  */
3838 int
3839 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3840                 uint32_t total_ctl_io, void **npool)
3841 {
3842 #ifdef IO_POOLS
3843         struct ctl_io_pool *pool;
3844
3845         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3846                                             M_NOWAIT | M_ZERO);
3847         if (pool == NULL)
3848                 return (ENOMEM);
3849
3850         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3851         pool->ctl_softc = ctl_softc;
3852         pool->zone = uma_zsecond_create(pool->name, NULL,
3853             NULL, NULL, NULL, ctl_softc->io_zone);
3854         /* uma_prealloc(pool->zone, total_ctl_io); */
3855
3856         *npool = pool;
3857 #else
3858         *npool = ctl_softc->io_zone;
3859 #endif
3860         return (0);
3861 }
3862
3863 void
3864 ctl_pool_free(struct ctl_io_pool *pool)
3865 {
3866
3867         if (pool == NULL)
3868                 return;
3869
3870 #ifdef IO_POOLS
3871         uma_zdestroy(pool->zone);
3872         free(pool, M_CTL);
3873 #endif
3874 }
3875
3876 union ctl_io *
3877 ctl_alloc_io(void *pool_ref)
3878 {
3879         union ctl_io *io;
3880 #ifdef IO_POOLS
3881         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3882
3883         io = uma_zalloc(pool->zone, M_WAITOK);
3884 #else
3885         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3886 #endif
3887         if (io != NULL)
3888                 io->io_hdr.pool = pool_ref;
3889         return (io);
3890 }
3891
3892 union ctl_io *
3893 ctl_alloc_io_nowait(void *pool_ref)
3894 {
3895         union ctl_io *io;
3896 #ifdef IO_POOLS
3897         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3898
3899         io = uma_zalloc(pool->zone, M_NOWAIT);
3900 #else
3901         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3902 #endif
3903         if (io != NULL)
3904                 io->io_hdr.pool = pool_ref;
3905         return (io);
3906 }
3907
3908 void
3909 ctl_free_io(union ctl_io *io)
3910 {
3911 #ifdef IO_POOLS
3912         struct ctl_io_pool *pool;
3913 #endif
3914
3915         if (io == NULL)
3916                 return;
3917
3918 #ifdef IO_POOLS
3919         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3920         uma_zfree(pool->zone, io);
3921 #else
3922         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3923 #endif
3924 }
3925
3926 void
3927 ctl_zero_io(union ctl_io *io)
3928 {
3929         void *pool_ref;
3930
3931         if (io == NULL)
3932                 return;
3933
3934         /*
3935          * May need to preserve linked list pointers at some point too.
3936          */
3937         pool_ref = io->io_hdr.pool;
3938         memset(io, 0, sizeof(*io));
3939         io->io_hdr.pool = pool_ref;
3940 }
3941
3942 /*
3943  * This routine is currently used for internal copies of ctl_ios that need
3944  * to persist for some reason after we've already returned status to the
3945  * FETD.  (Thus the flag set.)
3946  *
3947  * XXX XXX
3948  * Note that this makes a blind copy of all fields in the ctl_io, except
3949  * for the pool reference.  This includes any memory that has been
3950  * allocated!  That memory will no longer be valid after done has been
3951  * called, so this would be VERY DANGEROUS for command that actually does
3952  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3953  * start and stop commands, which don't transfer any data, so this is not a
3954  * problem.  If it is used for anything else, the caller would also need to
3955  * allocate data buffer space and this routine would need to be modified to
3956  * copy the data buffer(s) as well.
3957  */
3958 void
3959 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3960 {
3961         void *pool_ref;
3962
3963         if ((src == NULL)
3964          || (dest == NULL))
3965                 return;
3966
3967         /*
3968          * May need to preserve linked list pointers at some point too.
3969          */
3970         pool_ref = dest->io_hdr.pool;
3971
3972         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3973
3974         dest->io_hdr.pool = pool_ref;
3975         /*
3976          * We need to know that this is an internal copy, and doesn't need
3977          * to get passed back to the FETD that allocated it.
3978          */
3979         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3980 }
3981
3982 int
3983 ctl_expand_number(const char *buf, uint64_t *num)
3984 {
3985         char *endptr;
3986         uint64_t number;
3987         unsigned shift;
3988
3989         number = strtoq(buf, &endptr, 0);
3990
3991         switch (tolower((unsigned char)*endptr)) {
3992         case 'e':
3993                 shift = 60;
3994                 break;
3995         case 'p':
3996                 shift = 50;
3997                 break;
3998         case 't':
3999                 shift = 40;
4000                 break;
4001         case 'g':
4002                 shift = 30;
4003                 break;
4004         case 'm':
4005                 shift = 20;
4006                 break;
4007         case 'k':
4008                 shift = 10;
4009                 break;
4010         case 'b':
4011         case '\0': /* No unit. */
4012                 *num = number;
4013                 return (0);
4014         default:
4015                 /* Unrecognized unit. */
4016                 return (-1);
4017         }
4018
4019         if ((number << shift) >> shift != number) {
4020                 /* Overflow */
4021                 return (-1);
4022         }
4023         *num = number << shift;
4024         return (0);
4025 }
4026
4027
4028 /*
4029  * This routine could be used in the future to load default and/or saved
4030  * mode page parameters for a particuar lun.
4031  */
4032 static int
4033 ctl_init_page_index(struct ctl_lun *lun)
4034 {
4035         int i;
4036         struct ctl_page_index *page_index;
4037         const char *value;
4038         uint64_t ival;
4039
4040         memcpy(&lun->mode_pages.index, page_index_template,
4041                sizeof(page_index_template));
4042
4043         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4044
4045                 page_index = &lun->mode_pages.index[i];
4046                 /*
4047                  * If this is a disk-only mode page, there's no point in
4048                  * setting it up.  For some pages, we have to have some
4049                  * basic information about the disk in order to calculate the
4050                  * mode page data.
4051                  */
4052                 if ((lun->be_lun->lun_type != T_DIRECT)
4053                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4054                         continue;
4055
4056                 switch (page_index->page_code & SMPH_PC_MASK) {
4057                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4058                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4059                                 panic("subpage is incorrect!");
4060                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4061                                &rw_er_page_default,
4062                                sizeof(rw_er_page_default));
4063                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4064                                &rw_er_page_changeable,
4065                                sizeof(rw_er_page_changeable));
4066                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4067                                &rw_er_page_default,
4068                                sizeof(rw_er_page_default));
4069                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4070                                &rw_er_page_default,
4071                                sizeof(rw_er_page_default));
4072                         page_index->page_data =
4073                                 (uint8_t *)lun->mode_pages.rw_er_page;
4074                         break;
4075                 }
4076                 case SMS_FORMAT_DEVICE_PAGE: {
4077                         struct scsi_format_page *format_page;
4078
4079                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4080                                 panic("subpage is incorrect!");
4081
4082                         /*
4083                          * Sectors per track are set above.  Bytes per
4084                          * sector need to be set here on a per-LUN basis.
4085                          */
4086                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4087                                &format_page_default,
4088                                sizeof(format_page_default));
4089                         memcpy(&lun->mode_pages.format_page[
4090                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4091                                sizeof(format_page_changeable));
4092                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4093                                &format_page_default,
4094                                sizeof(format_page_default));
4095                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4096                                &format_page_default,
4097                                sizeof(format_page_default));
4098
4099                         format_page = &lun->mode_pages.format_page[
4100                                 CTL_PAGE_CURRENT];
4101                         scsi_ulto2b(lun->be_lun->blocksize,
4102                                     format_page->bytes_per_sector);
4103
4104                         format_page = &lun->mode_pages.format_page[
4105                                 CTL_PAGE_DEFAULT];
4106                         scsi_ulto2b(lun->be_lun->blocksize,
4107                                     format_page->bytes_per_sector);
4108
4109                         format_page = &lun->mode_pages.format_page[
4110                                 CTL_PAGE_SAVED];
4111                         scsi_ulto2b(lun->be_lun->blocksize,
4112                                     format_page->bytes_per_sector);
4113
4114                         page_index->page_data =
4115                                 (uint8_t *)lun->mode_pages.format_page;
4116                         break;
4117                 }
4118                 case SMS_RIGID_DISK_PAGE: {
4119                         struct scsi_rigid_disk_page *rigid_disk_page;
4120                         uint32_t sectors_per_cylinder;
4121                         uint64_t cylinders;
4122 #ifndef __XSCALE__
4123                         int shift;
4124 #endif /* !__XSCALE__ */
4125
4126                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4127                                 panic("invalid subpage value %d",
4128                                       page_index->subpage);
4129
4130                         /*
4131                          * Rotation rate and sectors per track are set
4132                          * above.  We calculate the cylinders here based on
4133                          * capacity.  Due to the number of heads and
4134                          * sectors per track we're using, smaller arrays
4135                          * may turn out to have 0 cylinders.  Linux and
4136                          * FreeBSD don't pay attention to these mode pages
4137                          * to figure out capacity, but Solaris does.  It
4138                          * seems to deal with 0 cylinders just fine, and
4139                          * works out a fake geometry based on the capacity.
4140                          */
4141                         memcpy(&lun->mode_pages.rigid_disk_page[
4142                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4143                                sizeof(rigid_disk_page_default));
4144                         memcpy(&lun->mode_pages.rigid_disk_page[
4145                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4146                                sizeof(rigid_disk_page_changeable));
4147
4148                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4149                                 CTL_DEFAULT_HEADS;
4150
4151                         /*
4152                          * The divide method here will be more accurate,
4153                          * probably, but results in floating point being
4154                          * used in the kernel on i386 (__udivdi3()).  On the
4155                          * XScale, though, __udivdi3() is implemented in
4156                          * software.
4157                          *
4158                          * The shift method for cylinder calculation is
4159                          * accurate if sectors_per_cylinder is a power of
4160                          * 2.  Otherwise it might be slightly off -- you
4161                          * might have a bit of a truncation problem.
4162                          */
4163 #ifdef  __XSCALE__
4164                         cylinders = (lun->be_lun->maxlba + 1) /
4165                                 sectors_per_cylinder;
4166 #else
4167                         for (shift = 31; shift > 0; shift--) {
4168                                 if (sectors_per_cylinder & (1 << shift))
4169                                         break;
4170                         }
4171                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4172 #endif
4173
4174                         /*
4175                          * We've basically got 3 bytes, or 24 bits for the
4176                          * cylinder size in the mode page.  If we're over,
4177                          * just round down to 2^24.
4178                          */
4179                         if (cylinders > 0xffffff)
4180                                 cylinders = 0xffffff;
4181
4182                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4183                                 CTL_PAGE_DEFAULT];
4184                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4185
4186                         if ((value = ctl_get_opt(&lun->be_lun->options,
4187                             "rpm")) != NULL) {
4188                                 scsi_ulto2b(strtol(value, NULL, 0),
4189                                      rigid_disk_page->rotation_rate);
4190                         }
4191
4192                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4193                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4194                                sizeof(rigid_disk_page_default));
4195                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4196                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4197                                sizeof(rigid_disk_page_default));
4198
4199                         page_index->page_data =
4200                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4201                         break;
4202                 }
4203                 case SMS_CACHING_PAGE: {
4204                         struct scsi_caching_page *caching_page;
4205
4206                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4207                                 panic("invalid subpage value %d",
4208                                       page_index->subpage);
4209                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4210                                &caching_page_default,
4211                                sizeof(caching_page_default));
4212                         memcpy(&lun->mode_pages.caching_page[
4213                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4214                                sizeof(caching_page_changeable));
4215                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4216                                &caching_page_default,
4217                                sizeof(caching_page_default));
4218                         caching_page = &lun->mode_pages.caching_page[
4219                             CTL_PAGE_SAVED];
4220                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4221                         if (value != NULL && strcmp(value, "off") == 0)
4222                                 caching_page->flags1 &= ~SCP_WCE;
4223                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4224                         if (value != NULL && strcmp(value, "off") == 0)
4225                                 caching_page->flags1 |= SCP_RCD;
4226                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4227                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4228                                sizeof(caching_page_default));
4229                         page_index->page_data =
4230                                 (uint8_t *)lun->mode_pages.caching_page;
4231                         break;
4232                 }
4233                 case SMS_CONTROL_MODE_PAGE: {
4234                         switch (page_index->subpage) {
4235                         case SMS_SUBPAGE_PAGE_0: {
4236                                 struct scsi_control_page *control_page;
4237
4238                                 memcpy(&lun->mode_pages.control_page[
4239                                     CTL_PAGE_DEFAULT],
4240                                        &control_page_default,
4241                                        sizeof(control_page_default));
4242                                 memcpy(&lun->mode_pages.control_page[
4243                                     CTL_PAGE_CHANGEABLE],
4244                                        &control_page_changeable,
4245                                        sizeof(control_page_changeable));
4246                                 memcpy(&lun->mode_pages.control_page[
4247                                     CTL_PAGE_SAVED],
4248                                        &control_page_default,
4249                                        sizeof(control_page_default));
4250                                 control_page = &lun->mode_pages.control_page[
4251                                     CTL_PAGE_SAVED];
4252                                 value = ctl_get_opt(&lun->be_lun->options,
4253                                     "reordering");
4254                                 if (value != NULL &&
4255                                     strcmp(value, "unrestricted") == 0) {
4256                                         control_page->queue_flags &=
4257                                             ~SCP_QUEUE_ALG_MASK;
4258                                         control_page->queue_flags |=
4259                                             SCP_QUEUE_ALG_UNRESTRICTED;
4260                                 }
4261                                 memcpy(&lun->mode_pages.control_page[
4262                                     CTL_PAGE_CURRENT],
4263                                        &lun->mode_pages.control_page[
4264                                     CTL_PAGE_SAVED],
4265                                        sizeof(control_page_default));
4266                                 page_index->page_data =
4267                                     (uint8_t *)lun->mode_pages.control_page;
4268                                 break;
4269                         }
4270                         case 0x01:
4271                                 memcpy(&lun->mode_pages.control_ext_page[
4272                                     CTL_PAGE_DEFAULT],
4273                                        &control_ext_page_default,
4274                                        sizeof(control_ext_page_default));
4275                                 memcpy(&lun->mode_pages.control_ext_page[
4276                                     CTL_PAGE_CHANGEABLE],
4277                                        &control_ext_page_changeable,
4278                                        sizeof(control_ext_page_changeable));
4279                                 memcpy(&lun->mode_pages.control_ext_page[
4280                                     CTL_PAGE_SAVED],
4281                                        &control_ext_page_default,
4282                                        sizeof(control_ext_page_default));
4283                                 memcpy(&lun->mode_pages.control_ext_page[
4284                                     CTL_PAGE_CURRENT],
4285                                        &lun->mode_pages.control_ext_page[
4286                                     CTL_PAGE_SAVED],
4287                                        sizeof(control_ext_page_default));
4288                                 page_index->page_data =
4289                                     (uint8_t *)lun->mode_pages.control_ext_page;
4290                                 break;
4291                         }
4292                         break;
4293                 }
4294                 case SMS_INFO_EXCEPTIONS_PAGE: {
4295                         switch (page_index->subpage) {
4296                         case SMS_SUBPAGE_PAGE_0:
4297                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4298                                        &ie_page_default,
4299                                        sizeof(ie_page_default));
4300                                 memcpy(&lun->mode_pages.ie_page[
4301                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4302                                        sizeof(ie_page_changeable));
4303                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4304                                        &ie_page_default,
4305                                        sizeof(ie_page_default));
4306                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4307                                        &ie_page_default,
4308                                        sizeof(ie_page_default));
4309                                 page_index->page_data =
4310                                         (uint8_t *)lun->mode_pages.ie_page;
4311                                 break;
4312                         case 0x02: {
4313                                 struct ctl_logical_block_provisioning_page *page;
4314
4315                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4316                                        &lbp_page_default,
4317                                        sizeof(lbp_page_default));
4318                                 memcpy(&lun->mode_pages.lbp_page[
4319                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4320                                        sizeof(lbp_page_changeable));
4321                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4322                                        &lbp_page_default,
4323                                        sizeof(lbp_page_default));
4324                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4325                                 value = ctl_get_opt(&lun->be_lun->options,
4326                                     "avail-threshold");
4327                                 if (value != NULL &&
4328                                     ctl_expand_number(value, &ival) == 0) {
4329                                         page->descr[0].flags |= SLBPPD_ENABLED |
4330                                             SLBPPD_ARMING_DEC;
4331                                         if (lun->be_lun->blocksize)
4332                                                 ival /= lun->be_lun->blocksize;
4333                                         else
4334                                                 ival /= 512;
4335                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4336                                             page->descr[0].count);
4337                                 }
4338                                 value = ctl_get_opt(&lun->be_lun->options,
4339                                     "used-threshold");
4340                                 if (value != NULL &&
4341                                     ctl_expand_number(value, &ival) == 0) {
4342                                         page->descr[1].flags |= SLBPPD_ENABLED |
4343                                             SLBPPD_ARMING_INC;
4344                                         if (lun->be_lun->blocksize)
4345                                                 ival /= lun->be_lun->blocksize;
4346                                         else
4347                                                 ival /= 512;
4348                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4349                                             page->descr[1].count);
4350                                 }
4351                                 value = ctl_get_opt(&lun->be_lun->options,
4352                                     "pool-avail-threshold");
4353                                 if (value != NULL &&
4354                                     ctl_expand_number(value, &ival) == 0) {
4355                                         page->descr[2].flags |= SLBPPD_ENABLED |
4356                                             SLBPPD_ARMING_DEC;
4357                                         if (lun->be_lun->blocksize)
4358                                                 ival /= lun->be_lun->blocksize;
4359                                         else
4360                                                 ival /= 512;
4361                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4362                                             page->descr[2].count);
4363                                 }
4364                                 value = ctl_get_opt(&lun->be_lun->options,
4365                                     "pool-used-threshold");
4366                                 if (value != NULL &&
4367                                     ctl_expand_number(value, &ival) == 0) {
4368                                         page->descr[3].flags |= SLBPPD_ENABLED |
4369                                             SLBPPD_ARMING_INC;
4370                                         if (lun->be_lun->blocksize)
4371                                                 ival /= lun->be_lun->blocksize;
4372                                         else
4373                                                 ival /= 512;
4374                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4375                                             page->descr[3].count);
4376                                 }
4377                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4378                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4379                                        sizeof(lbp_page_default));
4380                                 page_index->page_data =
4381                                         (uint8_t *)lun->mode_pages.lbp_page;
4382                         }}
4383                         break;
4384                 }
4385                 case SMS_VENDOR_SPECIFIC_PAGE:{
4386                         switch (page_index->subpage) {
4387                         case DBGCNF_SUBPAGE_CODE: {
4388                                 struct copan_debugconf_subpage *current_page,
4389                                                                *saved_page;
4390
4391                                 memcpy(&lun->mode_pages.debugconf_subpage[
4392                                        CTL_PAGE_CURRENT],
4393                                        &debugconf_page_default,
4394                                        sizeof(debugconf_page_default));
4395                                 memcpy(&lun->mode_pages.debugconf_subpage[
4396                                        CTL_PAGE_CHANGEABLE],
4397                                        &debugconf_page_changeable,
4398                                        sizeof(debugconf_page_changeable));
4399                                 memcpy(&lun->mode_pages.debugconf_subpage[
4400                                        CTL_PAGE_DEFAULT],
4401                                        &debugconf_page_default,
4402                                        sizeof(debugconf_page_default));
4403                                 memcpy(&lun->mode_pages.debugconf_subpage[
4404                                        CTL_PAGE_SAVED],
4405                                        &debugconf_page_default,
4406                                        sizeof(debugconf_page_default));
4407                                 page_index->page_data =
4408                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4409
4410                                 current_page = (struct copan_debugconf_subpage *)
4411                                         (page_index->page_data +
4412                                          (page_index->page_len *
4413                                           CTL_PAGE_CURRENT));
4414                                 saved_page = (struct copan_debugconf_subpage *)
4415                                         (page_index->page_data +
4416                                          (page_index->page_len *
4417                                           CTL_PAGE_SAVED));
4418                                 break;
4419                         }
4420                         default:
4421                                 panic("invalid subpage value %d",
4422                                       page_index->subpage);
4423                                 break;
4424                         }
4425                         break;
4426                 }
4427                 default:
4428                         panic("invalid page value %d",
4429                               page_index->page_code & SMPH_PC_MASK);
4430                         break;
4431         }
4432         }
4433
4434         return (CTL_RETVAL_COMPLETE);
4435 }
4436
4437 static int
4438 ctl_init_log_page_index(struct ctl_lun *lun)
4439 {
4440         struct ctl_page_index *page_index;
4441         int i, j, k, prev;
4442
4443         memcpy(&lun->log_pages.index, log_page_index_template,
4444                sizeof(log_page_index_template));
4445
4446         prev = -1;
4447         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4448
4449                 page_index = &lun->log_pages.index[i];
4450                 /*
4451                  * If this is a disk-only mode page, there's no point in
4452                  * setting it up.  For some pages, we have to have some
4453                  * basic information about the disk in order to calculate the
4454                  * mode page data.
4455                  */
4456                 if ((lun->be_lun->lun_type != T_DIRECT)
4457                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4458                         continue;
4459
4460                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4461                      lun->backend->lun_attr == NULL)
4462                         continue;
4463
4464                 if (page_index->page_code != prev) {
4465                         lun->log_pages.pages_page[j] = page_index->page_code;
4466                         prev = page_index->page_code;
4467                         j++;
4468                 }
4469                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4470                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4471                 k++;
4472         }
4473         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4474         lun->log_pages.index[0].page_len = j;
4475         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4476         lun->log_pages.index[1].page_len = k * 2;
4477         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4478         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4479         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4480         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4481
4482         return (CTL_RETVAL_COMPLETE);
4483 }
4484
4485 static int
4486 hex2bin(const char *str, uint8_t *buf, int buf_size)
4487 {
4488         int i;
4489         u_char c;
4490
4491         memset(buf, 0, buf_size);
4492         while (isspace(str[0]))
4493                 str++;
4494         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4495                 str += 2;
4496         buf_size *= 2;
4497         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4498                 c = str[i];
4499                 if (isdigit(c))
4500                         c -= '0';
4501                 else if (isalpha(c))
4502                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4503                 else
4504                         break;
4505                 if (c >= 16)
4506                         break;
4507                 if ((i & 1) == 0)
4508                         buf[i / 2] |= (c << 4);
4509                 else
4510                         buf[i / 2] |= c;
4511         }
4512         return ((i + 1) / 2);
4513 }
4514
4515 /*
4516  * LUN allocation.
4517  *
4518  * Requirements:
4519  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4520  *   wants us to allocate the LUN and he can block.
4521  * - ctl_softc is always set
4522  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4523  *
4524  * Returns 0 for success, non-zero (errno) for failure.
4525  */
4526 static int
4527 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4528               struct ctl_be_lun *const be_lun)
4529 {
4530         struct ctl_lun *nlun, *lun;
4531         struct scsi_vpd_id_descriptor *desc;
4532         struct scsi_vpd_id_t10 *t10id;
4533         const char *eui, *naa, *scsiname, *vendor;
4534         int lun_number, i, lun_malloced;
4535         int devidlen, idlen1, idlen2 = 0, len;
4536
4537         if (be_lun == NULL)
4538                 return (EINVAL);
4539
4540         /*
4541          * We currently only support Direct Access or Processor LUN types.
4542          */
4543         switch (be_lun->lun_type) {
4544         case T_DIRECT:
4545                 break;
4546         case T_PROCESSOR:
4547                 break;
4548         case T_SEQUENTIAL:
4549         case T_CHANGER:
4550         default:
4551                 be_lun->lun_config_status(be_lun->be_lun,
4552                                           CTL_LUN_CONFIG_FAILURE);
4553                 break;
4554         }
4555         if (ctl_lun == NULL) {
4556                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4557                 lun_malloced = 1;
4558         } else {
4559                 lun_malloced = 0;
4560                 lun = ctl_lun;
4561         }
4562
4563         memset(lun, 0, sizeof(*lun));
4564         if (lun_malloced)
4565                 lun->flags = CTL_LUN_MALLOCED;
4566
4567         /* Generate LUN ID. */
4568         devidlen = max(CTL_DEVID_MIN_LEN,
4569             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4570         idlen1 = sizeof(*t10id) + devidlen;
4571         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4572         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4573         if (scsiname != NULL) {
4574                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4575                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4576         }
4577         eui = ctl_get_opt(&be_lun->options, "eui");
4578         if (eui != NULL) {
4579                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4580         }
4581         naa = ctl_get_opt(&be_lun->options, "naa");
4582         if (naa != NULL) {
4583                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4584         }
4585         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4586             M_CTL, M_WAITOK | M_ZERO);
4587         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4588         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4589         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4590         desc->length = idlen1;
4591         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4592         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4593         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4594                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4595         } else {
4596                 strncpy(t10id->vendor, vendor,
4597                     min(sizeof(t10id->vendor), strlen(vendor)));
4598         }
4599         strncpy((char *)t10id->vendor_spec_id,
4600             (char *)be_lun->device_id, devidlen);
4601         if (scsiname != NULL) {
4602                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4603                     desc->length);
4604                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4605                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4606                     SVPD_ID_TYPE_SCSI_NAME;
4607                 desc->length = idlen2;
4608                 strlcpy(desc->identifier, scsiname, idlen2);
4609         }
4610         if (eui != NULL) {
4611                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4612                     desc->length);
4613                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4614                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4615                     SVPD_ID_TYPE_EUI64;
4616                 desc->length = hex2bin(eui, desc->identifier, 16);
4617                 desc->length = desc->length > 12 ? 16 :
4618                     (desc->length > 8 ? 12 : 8);
4619                 len -= 16 - desc->length;
4620         }
4621         if (naa != NULL) {
4622                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4623                     desc->length);
4624                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4625                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4626                     SVPD_ID_TYPE_NAA;
4627                 desc->length = hex2bin(naa, desc->identifier, 16);
4628                 desc->length = desc->length > 8 ? 16 : 8;
4629                 len -= 16 - desc->length;
4630         }
4631         lun->lun_devid->len = len;
4632
4633         mtx_lock(&ctl_softc->ctl_lock);
4634         /*
4635          * See if the caller requested a particular LUN number.  If so, see
4636          * if it is available.  Otherwise, allocate the first available LUN.
4637          */
4638         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4639                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4640                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4641                         mtx_unlock(&ctl_softc->ctl_lock);
4642                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4643                                 printf("ctl: requested LUN ID %d is higher "
4644                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4645                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4646                         } else {
4647                                 /*
4648                                  * XXX KDM return an error, or just assign
4649                                  * another LUN ID in this case??
4650                                  */
4651                                 printf("ctl: requested LUN ID %d is already "
4652                                        "in use\n", be_lun->req_lun_id);
4653                         }
4654                         if (lun->flags & CTL_LUN_MALLOCED)
4655                                 free(lun, M_CTL);
4656                         be_lun->lun_config_status(be_lun->be_lun,
4657                                                   CTL_LUN_CONFIG_FAILURE);
4658                         return (ENOSPC);
4659                 }
4660                 lun_number = be_lun->req_lun_id;
4661         } else {
4662                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4663                 if (lun_number == -1) {
4664                         mtx_unlock(&ctl_softc->ctl_lock);
4665                         printf("ctl: can't allocate LUN, out of LUNs\n");
4666                         if (lun->flags & CTL_LUN_MALLOCED)
4667                                 free(lun, M_CTL);
4668                         be_lun->lun_config_status(be_lun->be_lun,
4669                                                   CTL_LUN_CONFIG_FAILURE);
4670                         return (ENOSPC);
4671                 }
4672         }
4673         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4674
4675         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4676         lun->lun = lun_number;
4677         lun->be_lun = be_lun;
4678         /*
4679          * The processor LUN is always enabled.  Disk LUNs come on line
4680          * disabled, and must be enabled by the backend.
4681          */
4682         lun->flags |= CTL_LUN_DISABLED;
4683         lun->backend = be_lun->be;
4684         be_lun->ctl_lun = lun;
4685         be_lun->lun_id = lun_number;
4686         atomic_add_int(&be_lun->be->num_luns, 1);
4687         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4688                 lun->flags |= CTL_LUN_OFFLINE;
4689
4690         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4691                 lun->flags |= CTL_LUN_STOPPED;
4692
4693         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4694                 lun->flags |= CTL_LUN_INOPERABLE;
4695
4696         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4697                 lun->flags |= CTL_LUN_PRIMARY_SC;
4698
4699         lun->ctl_softc = ctl_softc;
4700 #ifdef CTL_TIME_IO
4701         lun->last_busy = getsbinuptime();
4702 #endif
4703         TAILQ_INIT(&lun->ooa_queue);
4704         TAILQ_INIT(&lun->blocked_queue);
4705         STAILQ_INIT(&lun->error_list);
4706         ctl_tpc_lun_init(lun);
4707
4708         /*
4709          * Initialize the mode and log page index.
4710          */
4711         ctl_init_page_index(lun);
4712         ctl_init_log_page_index(lun);
4713
4714         /*
4715          * Now, before we insert this lun on the lun list, set the lun
4716          * inventory changed UA for all other luns.
4717          */
4718         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4719                 mtx_lock(&nlun->lun_lock);
4720                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4721                 mtx_unlock(&nlun->lun_lock);
4722         }
4723
4724         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4725
4726         ctl_softc->ctl_luns[lun_number] = lun;
4727
4728         ctl_softc->num_luns++;
4729
4730         /* Setup statistics gathering */
4731         lun->stats.device_type = be_lun->lun_type;
4732         lun->stats.lun_number = lun_number;
4733         if (lun->stats.device_type == T_DIRECT)
4734                 lun->stats.blocksize = be_lun->blocksize;
4735         else
4736                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4737         for (i = 0;i < CTL_MAX_PORTS;i++)
4738                 lun->stats.ports[i].targ_port = i;
4739
4740         mtx_unlock(&ctl_softc->ctl_lock);
4741
4742         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4743         return (0);
4744 }
4745
4746 /*
4747  * Delete a LUN.
4748  * Assumptions:
4749  * - LUN has already been marked invalid and any pending I/O has been taken
4750  *   care of.
4751  */
4752 static int
4753 ctl_free_lun(struct ctl_lun *lun)
4754 {
4755         struct ctl_softc *softc;
4756         struct ctl_lun *nlun;
4757         int i;
4758
4759         softc = lun->ctl_softc;
4760
4761         mtx_assert(&softc->ctl_lock, MA_OWNED);
4762
4763         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4764
4765         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4766
4767         softc->ctl_luns[lun->lun] = NULL;
4768
4769         if (!TAILQ_EMPTY(&lun->ooa_queue))
4770                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4771
4772         softc->num_luns--;
4773
4774         /*
4775          * Tell the backend to free resources, if this LUN has a backend.
4776          */
4777         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4778         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4779
4780         ctl_tpc_lun_shutdown(lun);
4781         mtx_destroy(&lun->lun_lock);
4782         free(lun->lun_devid, M_CTL);
4783         for (i = 0; i < CTL_MAX_PORTS; i++)
4784                 free(lun->pending_ua[i], M_CTL);
4785         for (i = 0; i < CTL_MAX_PORTS; i++)
4786                 free(lun->pr_keys[i], M_CTL);
4787         free(lun->write_buffer, M_CTL);
4788         if (lun->flags & CTL_LUN_MALLOCED)
4789                 free(lun, M_CTL);
4790
4791         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4792                 mtx_lock(&nlun->lun_lock);
4793                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4794                 mtx_unlock(&nlun->lun_lock);
4795         }
4796
4797         return (0);
4798 }
4799
4800 static void
4801 ctl_create_lun(struct ctl_be_lun *be_lun)
4802 {
4803
4804         /*
4805          * ctl_alloc_lun() should handle all potential failure cases.
4806          */
4807         ctl_alloc_lun(control_softc, NULL, be_lun);
4808 }
4809
4810 int
4811 ctl_add_lun(struct ctl_be_lun *be_lun)
4812 {
4813         struct ctl_softc *softc = control_softc;
4814
4815         mtx_lock(&softc->ctl_lock);
4816         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4817         mtx_unlock(&softc->ctl_lock);
4818         wakeup(&softc->pending_lun_queue);
4819
4820         return (0);
4821 }
4822
4823 int
4824 ctl_enable_lun(struct ctl_be_lun *be_lun)
4825 {
4826         struct ctl_softc *softc;
4827         struct ctl_port *port, *nport;
4828         struct ctl_lun *lun;
4829         int retval;
4830
4831         lun = (struct ctl_lun *)be_lun->ctl_lun;
4832         softc = lun->ctl_softc;
4833
4834         mtx_lock(&softc->ctl_lock);
4835         mtx_lock(&lun->lun_lock);
4836         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4837                 /*
4838                  * eh?  Why did we get called if the LUN is already
4839                  * enabled?
4840                  */
4841                 mtx_unlock(&lun->lun_lock);
4842                 mtx_unlock(&softc->ctl_lock);
4843                 return (0);
4844         }
4845         lun->flags &= ~CTL_LUN_DISABLED;
4846         mtx_unlock(&lun->lun_lock);
4847
4848         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4849                 nport = STAILQ_NEXT(port, links);
4850                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4851                     port->lun_map != NULL || port->lun_enable == NULL)
4852                         continue;
4853
4854                 /*
4855                  * Drop the lock while we call the FETD's enable routine.
4856                  * This can lead to a callback into CTL (at least in the
4857                  * case of the internal initiator frontend.
4858                  */
4859                 mtx_unlock(&softc->ctl_lock);
4860                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4861                 mtx_lock(&softc->ctl_lock);
4862                 if (retval != 0) {
4863                         printf("%s: FETD %s port %d returned error "
4864                                "%d for lun_enable on lun %jd\n",
4865                                __func__, port->port_name, port->targ_port,
4866                                retval, (intmax_t)lun->lun);
4867                 }
4868         }
4869
4870         mtx_unlock(&softc->ctl_lock);
4871         ctl_isc_announce_lun(lun);
4872
4873         return (0);
4874 }
4875
4876 int
4877 ctl_disable_lun(struct ctl_be_lun *be_lun)
4878 {
4879         struct ctl_softc *softc;
4880         struct ctl_port *port;
4881         struct ctl_lun *lun;
4882         int retval;
4883
4884         lun = (struct ctl_lun *)be_lun->ctl_lun;
4885         softc = lun->ctl_softc;
4886
4887         mtx_lock(&softc->ctl_lock);
4888         mtx_lock(&lun->lun_lock);
4889         if (lun->flags & CTL_LUN_DISABLED) {
4890                 mtx_unlock(&lun->lun_lock);
4891                 mtx_unlock(&softc->ctl_lock);
4892                 return (0);
4893         }
4894         lun->flags |= CTL_LUN_DISABLED;
4895         mtx_unlock(&lun->lun_lock);
4896
4897         STAILQ_FOREACH(port, &softc->port_list, links) {
4898                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4899                     port->lun_map != NULL || port->lun_disable == NULL)
4900                         continue;
4901
4902                 /*
4903                  * Drop the lock before we call the frontend's disable
4904                  * routine, to avoid lock order reversals.
4905                  *
4906                  * XXX KDM what happens if the frontend list changes while
4907                  * we're traversing it?  It's unlikely, but should be handled.
4908                  */
4909                 mtx_unlock(&softc->ctl_lock);
4910                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4911                 mtx_lock(&softc->ctl_lock);
4912                 if (retval != 0) {
4913                         printf("%s: FETD %s port %d returned error "
4914                                "%d for lun_disable on lun %jd\n",
4915                                __func__, port->port_name, port->targ_port,
4916                                retval, (intmax_t)lun->lun);
4917                 }
4918         }
4919
4920         mtx_unlock(&softc->ctl_lock);
4921         ctl_isc_announce_lun(lun);
4922
4923         return (0);
4924 }
4925
4926 int
4927 ctl_start_lun(struct ctl_be_lun *be_lun)
4928 {
4929         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4930
4931         mtx_lock(&lun->lun_lock);
4932         lun->flags &= ~CTL_LUN_STOPPED;
4933         mtx_unlock(&lun->lun_lock);
4934         return (0);
4935 }
4936
4937 int
4938 ctl_stop_lun(struct ctl_be_lun *be_lun)
4939 {
4940         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4941
4942         mtx_lock(&lun->lun_lock);
4943         lun->flags |= CTL_LUN_STOPPED;
4944         mtx_unlock(&lun->lun_lock);
4945         return (0);
4946 }
4947
4948 int
4949 ctl_lun_offline(struct ctl_be_lun *be_lun)
4950 {
4951         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4952
4953         mtx_lock(&lun->lun_lock);
4954         lun->flags |= CTL_LUN_OFFLINE;
4955         mtx_unlock(&lun->lun_lock);
4956         return (0);
4957 }
4958
4959 int
4960 ctl_lun_online(struct ctl_be_lun *be_lun)
4961 {
4962         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4963
4964         mtx_lock(&lun->lun_lock);
4965         lun->flags &= ~CTL_LUN_OFFLINE;
4966         mtx_unlock(&lun->lun_lock);
4967         return (0);
4968 }
4969
4970 int
4971 ctl_lun_primary(struct ctl_be_lun *be_lun)
4972 {
4973         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4974
4975         mtx_lock(&lun->lun_lock);
4976         lun->flags |= CTL_LUN_PRIMARY_SC;
4977         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4978         mtx_unlock(&lun->lun_lock);
4979         ctl_isc_announce_lun(lun);
4980         return (0);
4981 }
4982
4983 int
4984 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4985 {
4986         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4987
4988         mtx_lock(&lun->lun_lock);
4989         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4990         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4991         mtx_unlock(&lun->lun_lock);
4992         ctl_isc_announce_lun(lun);
4993         return (0);
4994 }
4995
4996 int
4997 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4998 {
4999         struct ctl_softc *softc;
5000         struct ctl_lun *lun;
5001
5002         lun = (struct ctl_lun *)be_lun->ctl_lun;
5003         softc = lun->ctl_softc;
5004
5005         mtx_lock(&lun->lun_lock);
5006
5007         /*
5008          * The LUN needs to be disabled before it can be marked invalid.
5009          */
5010         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5011                 mtx_unlock(&lun->lun_lock);
5012                 return (-1);
5013         }
5014         /*
5015          * Mark the LUN invalid.
5016          */
5017         lun->flags |= CTL_LUN_INVALID;
5018
5019         /*
5020          * If there is nothing in the OOA queue, go ahead and free the LUN.
5021          * If we have something in the OOA queue, we'll free it when the
5022          * last I/O completes.
5023          */
5024         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5025                 mtx_unlock(&lun->lun_lock);
5026                 mtx_lock(&softc->ctl_lock);
5027                 ctl_free_lun(lun);
5028                 mtx_unlock(&softc->ctl_lock);
5029         } else
5030                 mtx_unlock(&lun->lun_lock);
5031
5032         return (0);
5033 }
5034
5035 int
5036 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5037 {
5038         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5039
5040         mtx_lock(&lun->lun_lock);
5041         lun->flags |= CTL_LUN_INOPERABLE;
5042         mtx_unlock(&lun->lun_lock);
5043         return (0);
5044 }
5045
5046 int
5047 ctl_lun_operable(struct ctl_be_lun *be_lun)
5048 {
5049         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5050
5051         mtx_lock(&lun->lun_lock);
5052         lun->flags &= ~CTL_LUN_INOPERABLE;
5053         mtx_unlock(&lun->lun_lock);
5054         return (0);
5055 }
5056
5057 void
5058 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5059 {
5060         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5061         union ctl_ha_msg msg;
5062
5063         mtx_lock(&lun->lun_lock);
5064         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5065         mtx_unlock(&lun->lun_lock);
5066         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5067                 /* Send msg to other side. */
5068                 bzero(&msg.ua, sizeof(msg.ua));
5069                 msg.hdr.msg_type = CTL_MSG_UA;
5070                 msg.hdr.nexus.initid = -1;
5071                 msg.hdr.nexus.targ_port = -1;
5072                 msg.hdr.nexus.targ_lun = lun->lun;
5073                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
5074                 msg.ua.ua_all = 1;
5075                 msg.ua.ua_set = 1;
5076                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
5077                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5078                     M_WAITOK);
5079         }
5080 }
5081
5082 /*
5083  * Backend "memory move is complete" callback for requests that never
5084  * make it down to say RAIDCore's configuration code.
5085  */
5086 int
5087 ctl_config_move_done(union ctl_io *io)
5088 {
5089         int retval;
5090
5091         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5092         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5093             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5094
5095         if ((io->io_hdr.port_status != 0) &&
5096             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5097              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5098                 /*
5099                  * For hardware error sense keys, the sense key
5100                  * specific value is defined to be a retry count,
5101                  * but we use it to pass back an internal FETD
5102                  * error code.  XXX KDM  Hopefully the FETD is only
5103                  * using 16 bits for an error code, since that's
5104                  * all the space we have in the sks field.
5105                  */
5106                 ctl_set_internal_failure(&io->scsiio,
5107                                          /*sks_valid*/ 1,
5108                                          /*retry_count*/
5109                                          io->io_hdr.port_status);
5110         }
5111
5112         if (ctl_debug & CTL_DEBUG_CDB_DATA)
5113                 ctl_data_print(io);
5114         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5115             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5116              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5117             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5118                 /*
5119                  * XXX KDM just assuming a single pointer here, and not a
5120                  * S/G list.  If we start using S/G lists for config data,
5121                  * we'll need to know how to clean them up here as well.
5122                  */
5123                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5124                         free(io->scsiio.kern_data_ptr, M_CTL);
5125                 ctl_done(io);
5126                 retval = CTL_RETVAL_COMPLETE;
5127         } else {
5128                 /*
5129                  * XXX KDM now we need to continue data movement.  Some
5130                  * options:
5131                  * - call ctl_scsiio() again?  We don't do this for data
5132                  *   writes, because for those at least we know ahead of
5133                  *   time where the write will go and how long it is.  For
5134                  *   config writes, though, that information is largely
5135                  *   contained within the write itself, thus we need to
5136                  *   parse out the data again.
5137                  *
5138                  * - Call some other function once the data is in?
5139                  */
5140
5141                 /*
5142                  * XXX KDM call ctl_scsiio() again for now, and check flag
5143                  * bits to see whether we're allocated or not.
5144                  */
5145                 retval = ctl_scsiio(&io->scsiio);
5146         }
5147         return (retval);
5148 }
5149
5150 /*
5151  * This gets called by a backend driver when it is done with a
5152  * data_submit method.
5153  */
5154 void
5155 ctl_data_submit_done(union ctl_io *io)
5156 {
5157         /*
5158          * If the IO_CONT flag is set, we need to call the supplied
5159          * function to continue processing the I/O, instead of completing
5160          * the I/O just yet.
5161          *
5162          * If there is an error, though, we don't want to keep processing.
5163          * Instead, just send status back to the initiator.
5164          */
5165         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5166             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5167             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5168              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5169                 io->scsiio.io_cont(io);
5170                 return;
5171         }
5172         ctl_done(io);
5173 }
5174
5175 /*
5176  * This gets called by a backend driver when it is done with a
5177  * configuration write.
5178  */
5179 void
5180 ctl_config_write_done(union ctl_io *io)
5181 {
5182         uint8_t *buf;
5183
5184         /*
5185          * If the IO_CONT flag is set, we need to call the supplied
5186          * function to continue processing the I/O, instead of completing
5187          * the I/O just yet.
5188          *
5189          * If there is an error, though, we don't want to keep processing.
5190          * Instead, just send status back to the initiator.
5191          */
5192         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5193             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5194             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5195              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5196                 io->scsiio.io_cont(io);
5197                 return;
5198         }
5199         /*
5200          * Since a configuration write can be done for commands that actually
5201          * have data allocated, like write buffer, and commands that have
5202          * no data, like start/stop unit, we need to check here.
5203          */
5204         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5205                 buf = io->scsiio.kern_data_ptr;
5206         else
5207                 buf = NULL;
5208         ctl_done(io);
5209         if (buf)
5210                 free(buf, M_CTL);
5211 }
5212
5213 void
5214 ctl_config_read_done(union ctl_io *io)
5215 {
5216         uint8_t *buf;
5217
5218         /*
5219          * If there is some error -- we are done, skip data transfer.
5220          */
5221         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5222             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5223              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5224                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5225                         buf = io->scsiio.kern_data_ptr;
5226                 else
5227                         buf = NULL;
5228                 ctl_done(io);
5229                 if (buf)
5230                         free(buf, M_CTL);
5231                 return;
5232         }
5233
5234         /*
5235          * If the IO_CONT flag is set, we need to call the supplied
5236          * function to continue processing the I/O, instead of completing
5237          * the I/O just yet.
5238          */
5239         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5240                 io->scsiio.io_cont(io);
5241                 return;
5242         }
5243
5244         ctl_datamove(io);
5245 }
5246
5247 /*
5248  * SCSI release command.
5249  */
5250 int
5251 ctl_scsi_release(struct ctl_scsiio *ctsio)
5252 {
5253         int length, longid, thirdparty_id, resv_id;
5254         struct ctl_lun *lun;
5255         uint32_t residx;
5256
5257         length = 0;
5258         resv_id = 0;
5259
5260         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5261
5262         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5263         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5264
5265         switch (ctsio->cdb[0]) {
5266         case RELEASE_10: {
5267                 struct scsi_release_10 *cdb;
5268
5269                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5270
5271                 if (cdb->byte2 & SR10_LONGID)
5272                         longid = 1;
5273                 else
5274                         thirdparty_id = cdb->thirdparty_id;
5275
5276                 resv_id = cdb->resv_id;
5277                 length = scsi_2btoul(cdb->length);
5278                 break;
5279         }
5280         }
5281
5282
5283         /*
5284          * XXX KDM right now, we only support LUN reservation.  We don't
5285          * support 3rd party reservations, or extent reservations, which
5286          * might actually need the parameter list.  If we've gotten this
5287          * far, we've got a LUN reservation.  Anything else got kicked out
5288          * above.  So, according to SPC, ignore the length.
5289          */
5290         length = 0;
5291
5292         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5293          && (length > 0)) {
5294                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5295                 ctsio->kern_data_len = length;
5296                 ctsio->kern_total_len = length;
5297                 ctsio->kern_data_resid = 0;
5298                 ctsio->kern_rel_offset = 0;
5299                 ctsio->kern_sg_entries = 0;
5300                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5301                 ctsio->be_move_done = ctl_config_move_done;
5302                 ctl_datamove((union ctl_io *)ctsio);
5303
5304                 return (CTL_RETVAL_COMPLETE);
5305         }
5306
5307         if (length > 0)
5308                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5309
5310         mtx_lock(&lun->lun_lock);
5311
5312         /*
5313          * According to SPC, it is not an error for an intiator to attempt
5314          * to release a reservation on a LUN that isn't reserved, or that
5315          * is reserved by another initiator.  The reservation can only be
5316          * released, though, by the initiator who made it or by one of
5317          * several reset type events.
5318          */
5319         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5320                         lun->flags &= ~CTL_LUN_RESERVED;
5321
5322         mtx_unlock(&lun->lun_lock);
5323
5324         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5325                 free(ctsio->kern_data_ptr, M_CTL);
5326                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5327         }
5328
5329         ctl_set_success(ctsio);
5330         ctl_done((union ctl_io *)ctsio);
5331         return (CTL_RETVAL_COMPLETE);
5332 }
5333
5334 int
5335 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5336 {
5337         int extent, thirdparty, longid;
5338         int resv_id, length;
5339         uint64_t thirdparty_id;
5340         struct ctl_lun *lun;
5341         uint32_t residx;
5342
5343         extent = 0;
5344         thirdparty = 0;
5345         longid = 0;
5346         resv_id = 0;
5347         length = 0;
5348         thirdparty_id = 0;
5349
5350         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5351
5352         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5353         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5354
5355         switch (ctsio->cdb[0]) {
5356         case RESERVE_10: {
5357                 struct scsi_reserve_10 *cdb;
5358
5359                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5360
5361                 if (cdb->byte2 & SR10_LONGID)
5362                         longid = 1;
5363                 else
5364                         thirdparty_id = cdb->thirdparty_id;
5365
5366                 resv_id = cdb->resv_id;
5367                 length = scsi_2btoul(cdb->length);
5368                 break;
5369         }
5370         }
5371
5372         /*
5373          * XXX KDM right now, we only support LUN reservation.  We don't
5374          * support 3rd party reservations, or extent reservations, which
5375          * might actually need the parameter list.  If we've gotten this
5376          * far, we've got a LUN reservation.  Anything else got kicked out
5377          * above.  So, according to SPC, ignore the length.
5378          */
5379         length = 0;
5380
5381         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5382          && (length > 0)) {
5383                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5384                 ctsio->kern_data_len = length;
5385                 ctsio->kern_total_len = length;
5386                 ctsio->kern_data_resid = 0;
5387                 ctsio->kern_rel_offset = 0;
5388                 ctsio->kern_sg_entries = 0;
5389                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5390                 ctsio->be_move_done = ctl_config_move_done;
5391                 ctl_datamove((union ctl_io *)ctsio);
5392
5393                 return (CTL_RETVAL_COMPLETE);
5394         }
5395
5396         if (length > 0)
5397                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5398
5399         mtx_lock(&lun->lun_lock);
5400         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5401                 ctl_set_reservation_conflict(ctsio);
5402                 goto bailout;
5403         }
5404
5405         lun->flags |= CTL_LUN_RESERVED;
5406         lun->res_idx = residx;
5407
5408         ctl_set_success(ctsio);
5409
5410 bailout:
5411         mtx_unlock(&lun->lun_lock);
5412
5413         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5414                 free(ctsio->kern_data_ptr, M_CTL);
5415                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5416         }
5417
5418         ctl_done((union ctl_io *)ctsio);
5419         return (CTL_RETVAL_COMPLETE);
5420 }
5421
5422 int
5423 ctl_start_stop(struct ctl_scsiio *ctsio)
5424 {
5425         struct scsi_start_stop_unit *cdb;
5426         struct ctl_lun *lun;
5427         int retval;
5428
5429         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5430
5431         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5432         retval = 0;
5433
5434         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5435
5436         /*
5437          * XXX KDM
5438          * We don't support the immediate bit on a stop unit.  In order to
5439          * do that, we would need to code up a way to know that a stop is
5440          * pending, and hold off any new commands until it completes, one
5441          * way or another.  Then we could accept or reject those commands
5442          * depending on its status.  We would almost need to do the reverse
5443          * of what we do below for an immediate start -- return the copy of
5444          * the ctl_io to the FETD with status to send to the host (and to
5445          * free the copy!) and then free the original I/O once the stop
5446          * actually completes.  That way, the OOA queue mechanism can work
5447          * to block commands that shouldn't proceed.  Another alternative
5448          * would be to put the copy in the queue in place of the original,
5449          * and return the original back to the caller.  That could be
5450          * slightly safer..
5451          */
5452         if ((cdb->byte2 & SSS_IMMED)
5453          && ((cdb->how & SSS_START) == 0)) {
5454                 ctl_set_invalid_field(ctsio,
5455                                       /*sks_valid*/ 1,
5456                                       /*command*/ 1,
5457                                       /*field*/ 1,
5458                                       /*bit_valid*/ 1,
5459                                       /*bit*/ 0);
5460                 ctl_done((union ctl_io *)ctsio);
5461                 return (CTL_RETVAL_COMPLETE);
5462         }
5463
5464         if ((lun->flags & CTL_LUN_PR_RESERVED)
5465          && ((cdb->how & SSS_START)==0)) {
5466                 uint32_t residx;
5467
5468                 residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5469                 if (ctl_get_prkey(lun, residx) == 0
5470                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5471
5472                         ctl_set_reservation_conflict(ctsio);
5473                         ctl_done((union ctl_io *)ctsio);
5474                         return (CTL_RETVAL_COMPLETE);
5475                 }
5476         }
5477
5478         /*
5479          * If there is no backend on this device, we can't start or stop
5480          * it.  In theory we shouldn't get any start/stop commands in the
5481          * first place at this level if the LUN doesn't have a backend.
5482          * That should get stopped by the command decode code.
5483          */
5484         if (lun->backend == NULL) {
5485                 ctl_set_invalid_opcode(ctsio);
5486                 ctl_done((union ctl_io *)ctsio);
5487                 return (CTL_RETVAL_COMPLETE);
5488         }
5489
5490         /*
5491          * XXX KDM Copan-specific offline behavior.
5492          * Figure out a reasonable way to port this?
5493          */
5494 #ifdef NEEDTOPORT
5495         mtx_lock(&lun->lun_lock);
5496
5497         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5498          && (lun->flags & CTL_LUN_OFFLINE)) {
5499                 /*
5500                  * If the LUN is offline, and the on/offline bit isn't set,
5501                  * reject the start or stop.  Otherwise, let it through.
5502                  */
5503                 mtx_unlock(&lun->lun_lock);
5504                 ctl_set_lun_not_ready(ctsio);
5505                 ctl_done((union ctl_io *)ctsio);
5506         } else {
5507                 mtx_unlock(&lun->lun_lock);
5508 #endif /* NEEDTOPORT */
5509                 /*
5510                  * This could be a start or a stop when we're online,
5511                  * or a stop/offline or start/online.  A start or stop when
5512                  * we're offline is covered in the case above.
5513                  */
5514                 /*
5515                  * In the non-immediate case, we send the request to
5516                  * the backend and return status to the user when
5517                  * it is done.
5518                  *
5519                  * In the immediate case, we allocate a new ctl_io
5520                  * to hold a copy of the request, and send that to
5521                  * the backend.  We then set good status on the
5522                  * user's request and return it immediately.
5523                  */
5524                 if (cdb->byte2 & SSS_IMMED) {
5525                         union ctl_io *new_io;
5526
5527                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5528                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5529                         retval = lun->backend->config_write(new_io);
5530                         ctl_set_success(ctsio);
5531                         ctl_done((union ctl_io *)ctsio);
5532                 } else {
5533                         retval = lun->backend->config_write(
5534                                 (union ctl_io *)ctsio);
5535                 }
5536 #ifdef NEEDTOPORT
5537         }
5538 #endif
5539         return (retval);
5540 }
5541
5542 /*
5543  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5544  * we don't really do anything with the LBA and length fields if the user
5545  * passes them in.  Instead we'll just flush out the cache for the entire
5546  * LUN.
5547  */
5548 int
5549 ctl_sync_cache(struct ctl_scsiio *ctsio)
5550 {
5551         struct ctl_lun *lun;
5552         struct ctl_softc *softc;
5553         struct ctl_lba_len_flags *lbalen;
5554         uint64_t starting_lba;
5555         uint32_t block_count;
5556         int retval;
5557         uint8_t byte2;
5558
5559         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5560
5561         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5562         softc = lun->ctl_softc;
5563         retval = 0;
5564
5565         switch (ctsio->cdb[0]) {
5566         case SYNCHRONIZE_CACHE: {
5567                 struct scsi_sync_cache *cdb;
5568                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5569
5570                 starting_lba = scsi_4btoul(cdb->begin_lba);
5571                 block_count = scsi_2btoul(cdb->lb_count);
5572                 byte2 = cdb->byte2;
5573                 break;
5574         }
5575         case SYNCHRONIZE_CACHE_16: {
5576                 struct scsi_sync_cache_16 *cdb;
5577                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5578
5579                 starting_lba = scsi_8btou64(cdb->begin_lba);
5580                 block_count = scsi_4btoul(cdb->lb_count);
5581                 byte2 = cdb->byte2;
5582                 break;
5583         }
5584         default:
5585                 ctl_set_invalid_opcode(ctsio);
5586                 ctl_done((union ctl_io *)ctsio);
5587                 goto bailout;
5588                 break; /* NOTREACHED */
5589         }
5590
5591         /*
5592          * We check the LBA and length, but don't do anything with them.
5593          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5594          * get flushed.  This check will just help satisfy anyone who wants
5595          * to see an error for an out of range LBA.
5596          */
5597         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5598                 ctl_set_lba_out_of_range(ctsio);
5599                 ctl_done((union ctl_io *)ctsio);
5600                 goto bailout;
5601         }
5602
5603         /*
5604          * If this LUN has no backend, we can't flush the cache anyway.
5605          */
5606         if (lun->backend == NULL) {
5607                 ctl_set_invalid_opcode(ctsio);
5608                 ctl_done((union ctl_io *)ctsio);
5609                 goto bailout;
5610         }
5611
5612         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5613         lbalen->lba = starting_lba;
5614         lbalen->len = block_count;
5615         lbalen->flags = byte2;
5616
5617         /*
5618          * Check to see whether we're configured to send the SYNCHRONIZE
5619          * CACHE command directly to the back end.
5620          */
5621         mtx_lock(&lun->lun_lock);
5622         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5623          && (++(lun->sync_count) >= lun->sync_interval)) {
5624                 lun->sync_count = 0;
5625                 mtx_unlock(&lun->lun_lock);
5626                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5627         } else {
5628                 mtx_unlock(&lun->lun_lock);
5629                 ctl_set_success(ctsio);
5630                 ctl_done((union ctl_io *)ctsio);
5631         }
5632
5633 bailout:
5634
5635         return (retval);
5636 }
5637
5638 int
5639 ctl_format(struct ctl_scsiio *ctsio)
5640 {
5641         struct scsi_format *cdb;
5642         struct ctl_lun *lun;
5643         int length, defect_list_len;
5644
5645         CTL_DEBUG_PRINT(("ctl_format\n"));
5646
5647         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5648
5649         cdb = (struct scsi_format *)ctsio->cdb;
5650
5651         length = 0;
5652         if (cdb->byte2 & SF_FMTDATA) {
5653                 if (cdb->byte2 & SF_LONGLIST)
5654                         length = sizeof(struct scsi_format_header_long);
5655                 else
5656                         length = sizeof(struct scsi_format_header_short);
5657         }
5658
5659         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5660          && (length > 0)) {
5661                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5662                 ctsio->kern_data_len = length;
5663                 ctsio->kern_total_len = length;
5664                 ctsio->kern_data_resid = 0;
5665                 ctsio->kern_rel_offset = 0;
5666                 ctsio->kern_sg_entries = 0;
5667                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5668                 ctsio->be_move_done = ctl_config_move_done;
5669                 ctl_datamove((union ctl_io *)ctsio);
5670
5671                 return (CTL_RETVAL_COMPLETE);
5672         }
5673
5674         defect_list_len = 0;
5675
5676         if (cdb->byte2 & SF_FMTDATA) {
5677                 if (cdb->byte2 & SF_LONGLIST) {
5678                         struct scsi_format_header_long *header;
5679
5680                         header = (struct scsi_format_header_long *)
5681                                 ctsio->kern_data_ptr;
5682
5683                         defect_list_len = scsi_4btoul(header->defect_list_len);
5684                         if (defect_list_len != 0) {
5685                                 ctl_set_invalid_field(ctsio,
5686                                                       /*sks_valid*/ 1,
5687                                                       /*command*/ 0,
5688                                                       /*field*/ 2,
5689                                                       /*bit_valid*/ 0,
5690                                                       /*bit*/ 0);
5691                                 goto bailout;
5692                         }
5693                 } else {
5694                         struct scsi_format_header_short *header;
5695
5696                         header = (struct scsi_format_header_short *)
5697                                 ctsio->kern_data_ptr;
5698
5699                         defect_list_len = scsi_2btoul(header->defect_list_len);
5700                         if (defect_list_len != 0) {
5701                                 ctl_set_invalid_field(ctsio,
5702                                                       /*sks_valid*/ 1,
5703                                                       /*command*/ 0,
5704                                                       /*field*/ 2,
5705                                                       /*bit_valid*/ 0,
5706                                                       /*bit*/ 0);
5707                                 goto bailout;
5708                         }
5709                 }
5710         }
5711
5712         /*
5713          * The format command will clear out the "Medium format corrupted"
5714          * status if set by the configuration code.  That status is really
5715          * just a way to notify the host that we have lost the media, and
5716          * get them to issue a command that will basically make them think
5717          * they're blowing away the media.
5718          */
5719         mtx_lock(&lun->lun_lock);
5720         lun->flags &= ~CTL_LUN_INOPERABLE;
5721         mtx_unlock(&lun->lun_lock);
5722
5723         ctl_set_success(ctsio);
5724 bailout:
5725
5726         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5727                 free(ctsio->kern_data_ptr, M_CTL);
5728                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5729         }
5730
5731         ctl_done((union ctl_io *)ctsio);
5732         return (CTL_RETVAL_COMPLETE);
5733 }
5734
5735 int
5736 ctl_read_buffer(struct ctl_scsiio *ctsio)
5737 {
5738         struct ctl_lun *lun;
5739         uint64_t buffer_offset;
5740         uint32_t len;
5741         uint8_t byte2;
5742         static uint8_t descr[4];
5743         static uint8_t echo_descr[4] = { 0 };
5744
5745         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5746         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5747         switch (ctsio->cdb[0]) {
5748         case READ_BUFFER: {
5749                 struct scsi_read_buffer *cdb;
5750
5751                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5752                 buffer_offset = scsi_3btoul(cdb->offset);
5753                 len = scsi_3btoul(cdb->length);
5754                 byte2 = cdb->byte2;
5755                 break;
5756         }
5757         case READ_BUFFER_16: {
5758                 struct scsi_read_buffer_16 *cdb;
5759
5760                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5761                 buffer_offset = scsi_8btou64(cdb->offset);
5762                 len = scsi_4btoul(cdb->length);
5763                 byte2 = cdb->byte2;
5764                 break;
5765         }
5766         default: /* This shouldn't happen. */
5767                 ctl_set_invalid_opcode(ctsio);
5768                 ctl_done((union ctl_io *)ctsio);
5769                 return (CTL_RETVAL_COMPLETE);
5770         }
5771
5772         if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5773             (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5774             (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5775                 ctl_set_invalid_field(ctsio,
5776                                       /*sks_valid*/ 1,
5777                                       /*command*/ 1,
5778                                       /*field*/ 1,
5779                                       /*bit_valid*/ 1,
5780                                       /*bit*/ 4);
5781                 ctl_done((union ctl_io *)ctsio);
5782                 return (CTL_RETVAL_COMPLETE);
5783         }
5784
5785         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5786             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5787                 ctl_set_invalid_field(ctsio,
5788                                       /*sks_valid*/ 1,
5789                                       /*command*/ 1,
5790                                       /*field*/ 6,
5791                                       /*bit_valid*/ 0,
5792                                       /*bit*/ 0);
5793                 ctl_done((union ctl_io *)ctsio);
5794                 return (CTL_RETVAL_COMPLETE);
5795         }
5796
5797         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5798                 descr[0] = 0;
5799                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5800                 ctsio->kern_data_ptr = descr;
5801                 len = min(len, sizeof(descr));
5802         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5803                 ctsio->kern_data_ptr = echo_descr;
5804                 len = min(len, sizeof(echo_descr));
5805         } else {
5806                 if (lun->write_buffer == NULL) {
5807                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5808                             M_CTL, M_WAITOK);
5809                 }
5810                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5811         }
5812         ctsio->kern_data_len = len;
5813         ctsio->kern_total_len = len;
5814         ctsio->kern_data_resid = 0;
5815         ctsio->kern_rel_offset = 0;
5816         ctsio->kern_sg_entries = 0;
5817         ctl_set_success(ctsio);
5818         ctsio->be_move_done = ctl_config_move_done;
5819         ctl_datamove((union ctl_io *)ctsio);
5820         return (CTL_RETVAL_COMPLETE);
5821 }
5822
5823 int
5824 ctl_write_buffer(struct ctl_scsiio *ctsio)
5825 {
5826         struct scsi_write_buffer *cdb;
5827         struct ctl_lun *lun;
5828         int buffer_offset, len;
5829
5830         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5831
5832         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5833         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5834
5835         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5836                 ctl_set_invalid_field(ctsio,
5837                                       /*sks_valid*/ 1,
5838                                       /*command*/ 1,
5839                                       /*field*/ 1,
5840                                       /*bit_valid*/ 1,
5841                                       /*bit*/ 4);
5842                 ctl_done((union ctl_io *)ctsio);
5843                 return (CTL_RETVAL_COMPLETE);
5844         }
5845
5846         len = scsi_3btoul(cdb->length);
5847         buffer_offset = scsi_3btoul(cdb->offset);
5848
5849         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5850                 ctl_set_invalid_field(ctsio,
5851                                       /*sks_valid*/ 1,
5852                                       /*command*/ 1,
5853                                       /*field*/ 6,
5854                                       /*bit_valid*/ 0,
5855                                       /*bit*/ 0);
5856                 ctl_done((union ctl_io *)ctsio);
5857                 return (CTL_RETVAL_COMPLETE);
5858         }
5859
5860         /*
5861          * If we've got a kernel request that hasn't been malloced yet,
5862          * malloc it and tell the caller the data buffer is here.
5863          */
5864         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5865                 if (lun->write_buffer == NULL) {
5866                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5867                             M_CTL, M_WAITOK);
5868                 }
5869                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5870                 ctsio->kern_data_len = len;
5871                 ctsio->kern_total_len = len;
5872                 ctsio->kern_data_resid = 0;
5873                 ctsio->kern_rel_offset = 0;
5874                 ctsio->kern_sg_entries = 0;
5875                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5876                 ctsio->be_move_done = ctl_config_move_done;
5877                 ctl_datamove((union ctl_io *)ctsio);
5878
5879                 return (CTL_RETVAL_COMPLETE);
5880         }
5881
5882         ctl_set_success(ctsio);
5883         ctl_done((union ctl_io *)ctsio);
5884         return (CTL_RETVAL_COMPLETE);
5885 }
5886
5887 int
5888 ctl_write_same(struct ctl_scsiio *ctsio)
5889 {
5890         struct ctl_lun *lun;
5891         struct ctl_lba_len_flags *lbalen;
5892         uint64_t lba;
5893         uint32_t num_blocks;
5894         int len, retval;
5895         uint8_t byte2;
5896
5897         retval = CTL_RETVAL_COMPLETE;
5898
5899         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5900
5901         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5902
5903         switch (ctsio->cdb[0]) {
5904         case WRITE_SAME_10: {
5905                 struct scsi_write_same_10 *cdb;
5906
5907                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5908
5909                 lba = scsi_4btoul(cdb->addr);
5910                 num_blocks = scsi_2btoul(cdb->length);
5911                 byte2 = cdb->byte2;
5912                 break;
5913         }
5914         case WRITE_SAME_16: {
5915                 struct scsi_write_same_16 *cdb;
5916
5917                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5918
5919                 lba = scsi_8btou64(cdb->addr);
5920                 num_blocks = scsi_4btoul(cdb->length);
5921                 byte2 = cdb->byte2;
5922                 break;
5923         }
5924         default:
5925                 /*
5926                  * We got a command we don't support.  This shouldn't
5927                  * happen, commands should be filtered out above us.
5928                  */
5929                 ctl_set_invalid_opcode(ctsio);
5930                 ctl_done((union ctl_io *)ctsio);
5931
5932                 return (CTL_RETVAL_COMPLETE);
5933                 break; /* NOTREACHED */
5934         }
5935
5936         /* ANCHOR flag can be used only together with UNMAP */
5937         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5938                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5939                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5940                 ctl_done((union ctl_io *)ctsio);
5941                 return (CTL_RETVAL_COMPLETE);
5942         }
5943
5944         /*
5945          * The first check is to make sure we're in bounds, the second
5946          * check is to catch wrap-around problems.  If the lba + num blocks
5947          * is less than the lba, then we've wrapped around and the block
5948          * range is invalid anyway.
5949          */
5950         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5951          || ((lba + num_blocks) < lba)) {
5952                 ctl_set_lba_out_of_range(ctsio);
5953                 ctl_done((union ctl_io *)ctsio);
5954                 return (CTL_RETVAL_COMPLETE);
5955         }
5956
5957         /* Zero number of blocks means "to the last logical block" */
5958         if (num_blocks == 0) {
5959                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5960                         ctl_set_invalid_field(ctsio,
5961                                               /*sks_valid*/ 0,
5962                                               /*command*/ 1,
5963                                               /*field*/ 0,
5964                                               /*bit_valid*/ 0,
5965                                               /*bit*/ 0);
5966                         ctl_done((union ctl_io *)ctsio);
5967                         return (CTL_RETVAL_COMPLETE);
5968                 }
5969                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5970         }
5971
5972         len = lun->be_lun->blocksize;
5973
5974         /*
5975          * If we've got a kernel request that hasn't been malloced yet,
5976          * malloc it and tell the caller the data buffer is here.
5977          */
5978         if ((byte2 & SWS_NDOB) == 0 &&
5979             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5980                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5981                 ctsio->kern_data_len = len;
5982                 ctsio->kern_total_len = len;
5983                 ctsio->kern_data_resid = 0;
5984                 ctsio->kern_rel_offset = 0;
5985                 ctsio->kern_sg_entries = 0;
5986                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5987                 ctsio->be_move_done = ctl_config_move_done;
5988                 ctl_datamove((union ctl_io *)ctsio);
5989
5990                 return (CTL_RETVAL_COMPLETE);
5991         }
5992
5993         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5994         lbalen->lba = lba;
5995         lbalen->len = num_blocks;
5996         lbalen->flags = byte2;
5997         retval = lun->backend->config_write((union ctl_io *)ctsio);
5998
5999         return (retval);
6000 }
6001
6002 int
6003 ctl_unmap(struct ctl_scsiio *ctsio)
6004 {
6005         struct ctl_lun *lun;
6006         struct scsi_unmap *cdb;
6007         struct ctl_ptr_len_flags *ptrlen;
6008         struct scsi_unmap_header *hdr;
6009         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6010         uint64_t lba;
6011         uint32_t num_blocks;
6012         int len, retval;
6013         uint8_t byte2;
6014
6015         retval = CTL_RETVAL_COMPLETE;
6016
6017         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6018
6019         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6020         cdb = (struct scsi_unmap *)ctsio->cdb;
6021
6022         len = scsi_2btoul(cdb->length);
6023         byte2 = cdb->byte2;
6024
6025         /*
6026          * If we've got a kernel request that hasn't been malloced yet,
6027          * malloc it and tell the caller the data buffer is here.
6028          */
6029         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6030                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6031                 ctsio->kern_data_len = len;
6032                 ctsio->kern_total_len = len;
6033                 ctsio->kern_data_resid = 0;
6034                 ctsio->kern_rel_offset = 0;
6035                 ctsio->kern_sg_entries = 0;
6036                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6037                 ctsio->be_move_done = ctl_config_move_done;
6038                 ctl_datamove((union ctl_io *)ctsio);
6039
6040                 return (CTL_RETVAL_COMPLETE);
6041         }
6042
6043         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6044         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6045         if (len < sizeof (*hdr) ||
6046             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6047             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6048             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6049                 ctl_set_invalid_field(ctsio,
6050                                       /*sks_valid*/ 0,
6051                                       /*command*/ 0,
6052                                       /*field*/ 0,
6053                                       /*bit_valid*/ 0,
6054                                       /*bit*/ 0);
6055                 goto done;
6056         }
6057         len = scsi_2btoul(hdr->desc_length);
6058         buf = (struct scsi_unmap_desc *)(hdr + 1);
6059         end = buf + len / sizeof(*buf);
6060
6061         endnz = buf;
6062         for (range = buf; range < end; range++) {
6063                 lba = scsi_8btou64(range->lba);
6064                 num_blocks = scsi_4btoul(range->length);
6065                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6066                  || ((lba + num_blocks) < lba)) {
6067                         ctl_set_lba_out_of_range(ctsio);
6068                         ctl_done((union ctl_io *)ctsio);
6069                         return (CTL_RETVAL_COMPLETE);
6070                 }
6071                 if (num_blocks != 0)
6072                         endnz = range + 1;
6073         }
6074
6075         /*
6076          * Block backend can not handle zero last range.
6077          * Filter it out and return if there is nothing left.
6078          */
6079         len = (uint8_t *)endnz - (uint8_t *)buf;
6080         if (len == 0) {
6081                 ctl_set_success(ctsio);
6082                 goto done;
6083         }
6084
6085         mtx_lock(&lun->lun_lock);
6086         ptrlen = (struct ctl_ptr_len_flags *)
6087             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6088         ptrlen->ptr = (void *)buf;
6089         ptrlen->len = len;
6090         ptrlen->flags = byte2;
6091         ctl_check_blocked(lun);
6092         mtx_unlock(&lun->lun_lock);
6093
6094         retval = lun->backend->config_write((union ctl_io *)ctsio);
6095         return (retval);
6096
6097 done:
6098         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6099                 free(ctsio->kern_data_ptr, M_CTL);
6100                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6101         }
6102         ctl_done((union ctl_io *)ctsio);
6103         return (CTL_RETVAL_COMPLETE);
6104 }
6105
6106 /*
6107  * Note that this function currently doesn't actually do anything inside
6108  * CTL to enforce things if the DQue bit is turned on.
6109  *
6110  * Also note that this function can't be used in the default case, because
6111  * the DQue bit isn't set in the changeable mask for the control mode page
6112  * anyway.  This is just here as an example for how to implement a page
6113  * handler, and a placeholder in case we want to allow the user to turn
6114  * tagged queueing on and off.
6115  *
6116  * The D_SENSE bit handling is functional, however, and will turn
6117  * descriptor sense on and off for a given LUN.
6118  */
6119 int
6120 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6121                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6122 {
6123         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6124         struct ctl_lun *lun;
6125         int set_ua;
6126         uint32_t initidx;
6127
6128         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6129         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6130         set_ua = 0;
6131
6132         user_cp = (struct scsi_control_page *)page_ptr;
6133         current_cp = (struct scsi_control_page *)
6134                 (page_index->page_data + (page_index->page_len *
6135                 CTL_PAGE_CURRENT));
6136         saved_cp = (struct scsi_control_page *)
6137                 (page_index->page_data + (page_index->page_len *
6138                 CTL_PAGE_SAVED));
6139
6140         mtx_lock(&lun->lun_lock);
6141         if (((current_cp->rlec & SCP_DSENSE) == 0)
6142          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6143                 /*
6144                  * Descriptor sense is currently turned off and the user
6145                  * wants to turn it on.
6146                  */
6147                 current_cp->rlec |= SCP_DSENSE;
6148                 saved_cp->rlec |= SCP_DSENSE;
6149                 lun->flags |= CTL_LUN_SENSE_DESC;
6150                 set_ua = 1;
6151         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6152                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6153                 /*
6154                  * Descriptor sense is currently turned on, and the user
6155                  * wants to turn it off.
6156                  */
6157                 current_cp->rlec &= ~SCP_DSENSE;
6158                 saved_cp->rlec &= ~SCP_DSENSE;
6159                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6160                 set_ua = 1;
6161         }
6162         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6163             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6164                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6165                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6166                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6167                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6168                 set_ua = 1;
6169         }
6170         if ((current_cp->eca_and_aen & SCP_SWP) !=
6171             (user_cp->eca_and_aen & SCP_SWP)) {
6172                 current_cp->eca_and_aen &= ~SCP_SWP;
6173                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6174                 saved_cp->eca_and_aen &= ~SCP_SWP;
6175                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6176                 set_ua = 1;
6177         }
6178         if (set_ua != 0)
6179                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6180         mtx_unlock(&lun->lun_lock);
6181         if (set_ua) {
6182                 ctl_isc_announce_mode(lun,
6183                     ctl_get_initindex(&ctsio->io_hdr.nexus),
6184                     page_index->page_code, page_index->subpage);
6185         }
6186         return (0);
6187 }
6188
6189 int
6190 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6191                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6192 {
6193         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6194         struct ctl_lun *lun;
6195         int set_ua;
6196         uint32_t initidx;
6197
6198         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6199         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6200         set_ua = 0;
6201
6202         user_cp = (struct scsi_caching_page *)page_ptr;
6203         current_cp = (struct scsi_caching_page *)
6204                 (page_index->page_data + (page_index->page_len *
6205                 CTL_PAGE_CURRENT));
6206         saved_cp = (struct scsi_caching_page *)
6207                 (page_index->page_data + (page_index->page_len *
6208                 CTL_PAGE_SAVED));
6209
6210         mtx_lock(&lun->lun_lock);
6211         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6212             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6213                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6214                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6215                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6216                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6217                 set_ua = 1;
6218         }
6219         if (set_ua != 0)
6220                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6221         mtx_unlock(&lun->lun_lock);
6222         if (set_ua) {
6223                 ctl_isc_announce_mode(lun,
6224                     ctl_get_initindex(&ctsio->io_hdr.nexus),
6225                     page_index->page_code, page_index->subpage);
6226         }
6227         return (0);
6228 }
6229
6230 int
6231 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6232                                 struct ctl_page_index *page_index,
6233                                 uint8_t *page_ptr)
6234 {
6235         uint8_t *c;
6236         int i;
6237
6238         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6239         ctl_time_io_secs =
6240                 (c[0] << 8) |
6241                 (c[1] << 0) |
6242                 0;
6243         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6244         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6245         printf("page data:");
6246         for (i=0; i<8; i++)
6247                 printf(" %.2x",page_ptr[i]);
6248         printf("\n");
6249         return (0);
6250 }
6251
6252 int
6253 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6254                                struct ctl_page_index *page_index,
6255                                int pc)
6256 {
6257         struct copan_debugconf_subpage *page;
6258
6259         page = (struct copan_debugconf_subpage *)page_index->page_data +
6260                 (page_index->page_len * pc);
6261
6262         switch (pc) {
6263         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6264         case SMS_PAGE_CTRL_DEFAULT >> 6:
6265         case SMS_PAGE_CTRL_SAVED >> 6:
6266                 /*
6267                  * We don't update the changable or default bits for this page.
6268                  */
6269                 break;
6270         case SMS_PAGE_CTRL_CURRENT >> 6:
6271                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6272                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6273                 break;
6274         default:
6275 #ifdef NEEDTOPORT
6276                 EPRINT(0, "Invalid PC %d!!", pc);
6277 #endif /* NEEDTOPORT */
6278                 break;
6279         }
6280         return (0);
6281 }
6282
6283
6284 static int
6285 ctl_do_mode_select(union ctl_io *io)
6286 {
6287         struct scsi_mode_page_header *page_header;
6288         struct ctl_page_index *page_index;
6289         struct ctl_scsiio *ctsio;
6290         int control_dev, page_len;
6291         int page_len_offset, page_len_size;
6292         union ctl_modepage_info *modepage_info;
6293         struct ctl_lun *lun;
6294         int *len_left, *len_used;
6295         int retval, i;
6296
6297         ctsio = &io->scsiio;
6298         page_index = NULL;
6299         page_len = 0;
6300         retval = CTL_RETVAL_COMPLETE;
6301
6302         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6303
6304         if (lun->be_lun->lun_type != T_DIRECT)
6305                 control_dev = 1;
6306         else
6307                 control_dev = 0;
6308
6309         modepage_info = (union ctl_modepage_info *)
6310                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6311         len_left = &modepage_info->header.len_left;
6312         len_used = &modepage_info->header.len_used;
6313
6314 do_next_page:
6315
6316         page_header = (struct scsi_mode_page_header *)
6317                 (ctsio->kern_data_ptr + *len_used);
6318
6319         if (*len_left == 0) {
6320                 free(ctsio->kern_data_ptr, M_CTL);
6321                 ctl_set_success(ctsio);
6322                 ctl_done((union ctl_io *)ctsio);
6323                 return (CTL_RETVAL_COMPLETE);
6324         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6325
6326                 free(ctsio->kern_data_ptr, M_CTL);
6327                 ctl_set_param_len_error(ctsio);
6328                 ctl_done((union ctl_io *)ctsio);
6329                 return (CTL_RETVAL_COMPLETE);
6330
6331         } else if ((page_header->page_code & SMPH_SPF)
6332                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6333
6334                 free(ctsio->kern_data_ptr, M_CTL);
6335                 ctl_set_param_len_error(ctsio);
6336                 ctl_done((union ctl_io *)ctsio);
6337                 return (CTL_RETVAL_COMPLETE);
6338         }
6339
6340
6341         /*
6342          * XXX KDM should we do something with the block descriptor?
6343          */
6344         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6345
6346                 if ((control_dev != 0)
6347                  && (lun->mode_pages.index[i].page_flags &
6348                      CTL_PAGE_FLAG_DISK_ONLY))
6349                         continue;
6350
6351                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6352                     (page_header->page_code & SMPH_PC_MASK))
6353                         continue;
6354
6355                 /*
6356                  * If neither page has a subpage code, then we've got a
6357                  * match.
6358                  */
6359                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6360                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6361                         page_index = &lun->mode_pages.index[i];
6362                         page_len = page_header->page_length;
6363                         break;
6364                 }
6365
6366                 /*
6367                  * If both pages have subpages, then the subpage numbers
6368                  * have to match.
6369                  */
6370                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6371                   && (page_header->page_code & SMPH_SPF)) {
6372                         struct scsi_mode_page_header_sp *sph;
6373
6374                         sph = (struct scsi_mode_page_header_sp *)page_header;
6375
6376                         if (lun->mode_pages.index[i].subpage ==
6377                             sph->subpage) {
6378                                 page_index = &lun->mode_pages.index[i];
6379                                 page_len = scsi_2btoul(sph->page_length);
6380                                 break;
6381                         }
6382                 }
6383         }
6384
6385         /*
6386          * If we couldn't find the page, or if we don't have a mode select
6387          * handler for it, send back an error to the user.
6388          */
6389         if ((page_index == NULL)
6390          || (page_index->select_handler == NULL)) {
6391                 ctl_set_invalid_field(ctsio,
6392                                       /*sks_valid*/ 1,
6393                                       /*command*/ 0,
6394                                       /*field*/ *len_used,
6395                                       /*bit_valid*/ 0,
6396                                       /*bit*/ 0);
6397                 free(ctsio->kern_data_ptr, M_CTL);
6398                 ctl_done((union ctl_io *)ctsio);
6399                 return (CTL_RETVAL_COMPLETE);
6400         }
6401
6402         if (page_index->page_code & SMPH_SPF) {
6403                 page_len_offset = 2;
6404                 page_len_size = 2;
6405         } else {
6406                 page_len_size = 1;
6407                 page_len_offset = 1;
6408         }
6409
6410         /*
6411          * If the length the initiator gives us isn't the one we specify in
6412          * the mode page header, or if they didn't specify enough data in
6413          * the CDB to avoid truncating this page, kick out the request.
6414          */
6415         if ((page_len != (page_index->page_len - page_len_offset -
6416                           page_len_size))
6417          || (*len_left < page_index->page_len)) {
6418
6419
6420                 ctl_set_invalid_field(ctsio,
6421                                       /*sks_valid*/ 1,
6422                                       /*command*/ 0,
6423                                       /*field*/ *len_used + page_len_offset,
6424                                       /*bit_valid*/ 0,
6425                                       /*bit*/ 0);
6426                 free(ctsio->kern_data_ptr, M_CTL);
6427                 ctl_done((union ctl_io *)ctsio);
6428                 return (CTL_RETVAL_COMPLETE);
6429         }
6430
6431         /*
6432          * Run through the mode page, checking to make sure that the bits
6433          * the user changed are actually legal for him to change.
6434          */
6435         for (i = 0; i < page_index->page_len; i++) {
6436                 uint8_t *user_byte, *change_mask, *current_byte;
6437                 int bad_bit;
6438                 int j;
6439
6440                 user_byte = (uint8_t *)page_header + i;
6441                 change_mask = page_index->page_data +
6442                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6443                 current_byte = page_index->page_data +
6444                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6445
6446                 /*
6447                  * Check to see whether the user set any bits in this byte
6448                  * that he is not allowed to set.
6449                  */
6450                 if ((*user_byte & ~(*change_mask)) ==
6451                     (*current_byte & ~(*change_mask)))
6452                         continue;
6453
6454                 /*
6455                  * Go through bit by bit to determine which one is illegal.
6456                  */
6457                 bad_bit = 0;
6458                 for (j = 7; j >= 0; j--) {
6459                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6460                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6461                                 bad_bit = i;
6462                                 break;
6463                         }
6464                 }
6465                 ctl_set_invalid_field(ctsio,
6466                                       /*sks_valid*/ 1,
6467                                       /*command*/ 0,
6468                                       /*field*/ *len_used + i,
6469                                       /*bit_valid*/ 1,
6470                                       /*bit*/ bad_bit);
6471                 free(ctsio->kern_data_ptr, M_CTL);
6472                 ctl_done((union ctl_io *)ctsio);
6473                 return (CTL_RETVAL_COMPLETE);
6474         }
6475
6476         /*
6477          * Decrement these before we call the page handler, since we may
6478          * end up getting called back one way or another before the handler
6479          * returns to this context.
6480          */
6481         *len_left -= page_index->page_len;
6482         *len_used += page_index->page_len;
6483
6484         retval = page_index->select_handler(ctsio, page_index,
6485                                             (uint8_t *)page_header);
6486
6487         /*
6488          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6489          * wait until this queued command completes to finish processing
6490          * the mode page.  If it returns anything other than
6491          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6492          * already set the sense information, freed the data pointer, and
6493          * completed the io for us.
6494          */
6495         if (retval != CTL_RETVAL_COMPLETE)
6496                 goto bailout_no_done;
6497
6498         /*
6499          * If the initiator sent us more than one page, parse the next one.
6500          */
6501         if (*len_left > 0)
6502                 goto do_next_page;
6503
6504         ctl_set_success(ctsio);
6505         free(ctsio->kern_data_ptr, M_CTL);
6506         ctl_done((union ctl_io *)ctsio);
6507
6508 bailout_no_done:
6509
6510         return (CTL_RETVAL_COMPLETE);
6511
6512 }
6513
6514 int
6515 ctl_mode_select(struct ctl_scsiio *ctsio)
6516 {
6517         int param_len, pf, sp;
6518         int header_size, bd_len;
6519         int len_left, len_used;
6520         struct ctl_page_index *page_index;
6521         struct ctl_lun *lun;
6522         int control_dev, page_len;
6523         union ctl_modepage_info *modepage_info;
6524         int retval;
6525
6526         pf = 0;
6527         sp = 0;
6528         page_len = 0;
6529         len_used = 0;
6530         len_left = 0;
6531         retval = 0;
6532         bd_len = 0;
6533         page_index = NULL;
6534
6535         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6536
6537         if (lun->be_lun->lun_type != T_DIRECT)
6538                 control_dev = 1;
6539         else
6540                 control_dev = 0;
6541
6542         switch (ctsio->cdb[0]) {
6543         case MODE_SELECT_6: {
6544                 struct scsi_mode_select_6 *cdb;
6545
6546                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6547
6548                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6549                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6550
6551                 param_len = cdb->length;
6552                 header_size = sizeof(struct scsi_mode_header_6);
6553                 break;
6554         }
6555         case MODE_SELECT_10: {
6556                 struct scsi_mode_select_10 *cdb;
6557
6558                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6559
6560                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6561                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6562
6563                 param_len = scsi_2btoul(cdb->length);
6564                 header_size = sizeof(struct scsi_mode_header_10);
6565                 break;
6566         }
6567         default:
6568                 ctl_set_invalid_opcode(ctsio);
6569                 ctl_done((union ctl_io *)ctsio);
6570                 return (CTL_RETVAL_COMPLETE);
6571                 break; /* NOTREACHED */
6572         }
6573
6574         /*
6575          * From SPC-3:
6576          * "A parameter list length of zero indicates that the Data-Out Buffer
6577          * shall be empty. This condition shall not be considered as an error."
6578          */
6579         if (param_len == 0) {
6580                 ctl_set_success(ctsio);
6581                 ctl_done((union ctl_io *)ctsio);
6582                 return (CTL_RETVAL_COMPLETE);
6583         }
6584
6585         /*
6586          * Since we'll hit this the first time through, prior to
6587          * allocation, we don't need to free a data buffer here.
6588          */
6589         if (param_len < header_size) {
6590                 ctl_set_param_len_error(ctsio);
6591                 ctl_done((union ctl_io *)ctsio);
6592                 return (CTL_RETVAL_COMPLETE);
6593         }
6594
6595         /*
6596          * Allocate the data buffer and grab the user's data.  In theory,
6597          * we shouldn't have to sanity check the parameter list length here
6598          * because the maximum size is 64K.  We should be able to malloc
6599          * that much without too many problems.
6600          */
6601         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6602                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6603                 ctsio->kern_data_len = param_len;
6604                 ctsio->kern_total_len = param_len;
6605                 ctsio->kern_data_resid = 0;
6606                 ctsio->kern_rel_offset = 0;
6607                 ctsio->kern_sg_entries = 0;
6608                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6609                 ctsio->be_move_done = ctl_config_move_done;
6610                 ctl_datamove((union ctl_io *)ctsio);
6611
6612                 return (CTL_RETVAL_COMPLETE);
6613         }
6614
6615         switch (ctsio->cdb[0]) {
6616         case MODE_SELECT_6: {
6617                 struct scsi_mode_header_6 *mh6;
6618
6619                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6620                 bd_len = mh6->blk_desc_len;
6621                 break;
6622         }
6623         case MODE_SELECT_10: {
6624                 struct scsi_mode_header_10 *mh10;
6625
6626                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6627                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6628                 break;
6629         }
6630         default:
6631                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6632                 break;
6633         }
6634
6635         if (param_len < (header_size + bd_len)) {
6636                 free(ctsio->kern_data_ptr, M_CTL);
6637                 ctl_set_param_len_error(ctsio);
6638                 ctl_done((union ctl_io *)ctsio);
6639                 return (CTL_RETVAL_COMPLETE);
6640         }
6641
6642         /*
6643          * Set the IO_CONT flag, so that if this I/O gets passed to
6644          * ctl_config_write_done(), it'll get passed back to
6645          * ctl_do_mode_select() for further processing, or completion if
6646          * we're all done.
6647          */
6648         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6649         ctsio->io_cont = ctl_do_mode_select;
6650
6651         modepage_info = (union ctl_modepage_info *)
6652                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6653
6654         memset(modepage_info, 0, sizeof(*modepage_info));
6655
6656         len_left = param_len - header_size - bd_len;
6657         len_used = header_size + bd_len;
6658
6659         modepage_info->header.len_left = len_left;
6660         modepage_info->header.len_used = len_used;
6661
6662         return (ctl_do_mode_select((union ctl_io *)ctsio));
6663 }
6664
6665 int
6666 ctl_mode_sense(struct ctl_scsiio *ctsio)
6667 {
6668         struct ctl_lun *lun;
6669         int pc, page_code, dbd, llba, subpage;
6670         int alloc_len, page_len, header_len, total_len;
6671         struct scsi_mode_block_descr *block_desc;
6672         struct ctl_page_index *page_index;
6673         int control_dev;
6674
6675         dbd = 0;
6676         llba = 0;
6677         block_desc = NULL;
6678         page_index = NULL;
6679
6680         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6681
6682         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6683
6684         if (lun->be_lun->lun_type != T_DIRECT)
6685                 control_dev = 1;
6686         else
6687                 control_dev = 0;
6688
6689         switch (ctsio->cdb[0]) {
6690         case MODE_SENSE_6: {
6691                 struct scsi_mode_sense_6 *cdb;
6692
6693                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6694
6695                 header_len = sizeof(struct scsi_mode_hdr_6);
6696                 if (cdb->byte2 & SMS_DBD)
6697                         dbd = 1;
6698                 else
6699                         header_len += sizeof(struct scsi_mode_block_descr);
6700
6701                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6702                 page_code = cdb->page & SMS_PAGE_CODE;
6703                 subpage = cdb->subpage;
6704                 alloc_len = cdb->length;
6705                 break;
6706         }
6707         case MODE_SENSE_10: {
6708                 struct scsi_mode_sense_10 *cdb;
6709
6710                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6711
6712                 header_len = sizeof(struct scsi_mode_hdr_10);
6713
6714                 if (cdb->byte2 & SMS_DBD)
6715                         dbd = 1;
6716                 else
6717                         header_len += sizeof(struct scsi_mode_block_descr);
6718                 if (cdb->byte2 & SMS10_LLBAA)
6719                         llba = 1;
6720                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6721                 page_code = cdb->page & SMS_PAGE_CODE;
6722                 subpage = cdb->subpage;
6723                 alloc_len = scsi_2btoul(cdb->length);
6724                 break;
6725         }
6726         default:
6727                 ctl_set_invalid_opcode(ctsio);
6728                 ctl_done((union ctl_io *)ctsio);
6729                 return (CTL_RETVAL_COMPLETE);
6730                 break; /* NOTREACHED */
6731         }
6732
6733         /*
6734          * We have to make a first pass through to calculate the size of
6735          * the pages that match the user's query.  Then we allocate enough
6736          * memory to hold it, and actually copy the data into the buffer.
6737          */
6738         switch (page_code) {
6739         case SMS_ALL_PAGES_PAGE: {
6740                 int i;
6741
6742                 page_len = 0;
6743
6744                 /*
6745                  * At the moment, values other than 0 and 0xff here are
6746                  * reserved according to SPC-3.
6747                  */
6748                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6749                  && (subpage != SMS_SUBPAGE_ALL)) {
6750                         ctl_set_invalid_field(ctsio,
6751                                               /*sks_valid*/ 1,
6752                                               /*command*/ 1,
6753                                               /*field*/ 3,
6754                                               /*bit_valid*/ 0,
6755                                               /*bit*/ 0);
6756                         ctl_done((union ctl_io *)ctsio);
6757                         return (CTL_RETVAL_COMPLETE);
6758                 }
6759
6760                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6761                         if ((control_dev != 0)
6762                          && (lun->mode_pages.index[i].page_flags &
6763                              CTL_PAGE_FLAG_DISK_ONLY))
6764                                 continue;
6765
6766                         /*
6767                          * We don't use this subpage if the user didn't
6768                          * request all subpages.
6769                          */
6770                         if ((lun->mode_pages.index[i].subpage != 0)
6771                          && (subpage == SMS_SUBPAGE_PAGE_0))
6772                                 continue;
6773
6774 #if 0
6775                         printf("found page %#x len %d\n",
6776                                lun->mode_pages.index[i].page_code &
6777                                SMPH_PC_MASK,
6778                                lun->mode_pages.index[i].page_len);
6779 #endif
6780                         page_len += lun->mode_pages.index[i].page_len;
6781                 }
6782                 break;
6783         }
6784         default: {
6785                 int i;
6786
6787                 page_len = 0;
6788
6789                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6790                         /* Look for the right page code */
6791                         if ((lun->mode_pages.index[i].page_code &
6792                              SMPH_PC_MASK) != page_code)
6793                                 continue;
6794
6795                         /* Look for the right subpage or the subpage wildcard*/
6796                         if ((lun->mode_pages.index[i].subpage != subpage)
6797                          && (subpage != SMS_SUBPAGE_ALL))
6798                                 continue;
6799
6800                         /* Make sure the page is supported for this dev type */
6801                         if ((control_dev != 0)
6802                          && (lun->mode_pages.index[i].page_flags &
6803                              CTL_PAGE_FLAG_DISK_ONLY))
6804                                 continue;
6805
6806 #if 0
6807                         printf("found page %#x len %d\n",
6808                                lun->mode_pages.index[i].page_code &
6809                                SMPH_PC_MASK,
6810                                lun->mode_pages.index[i].page_len);
6811 #endif
6812
6813                         page_len += lun->mode_pages.index[i].page_len;
6814                 }
6815
6816                 if (page_len == 0) {
6817                         ctl_set_invalid_field(ctsio,
6818                                               /*sks_valid*/ 1,
6819                                               /*command*/ 1,
6820                                               /*field*/ 2,
6821                                               /*bit_valid*/ 1,
6822                                               /*bit*/ 5);
6823                         ctl_done((union ctl_io *)ctsio);
6824                         return (CTL_RETVAL_COMPLETE);
6825                 }
6826                 break;
6827         }
6828         }
6829
6830         total_len = header_len + page_len;
6831 #if 0
6832         printf("header_len = %d, page_len = %d, total_len = %d\n",
6833                header_len, page_len, total_len);
6834 #endif
6835
6836         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6837         ctsio->kern_sg_entries = 0;
6838         ctsio->kern_data_resid = 0;
6839         ctsio->kern_rel_offset = 0;
6840         if (total_len < alloc_len) {
6841                 ctsio->residual = alloc_len - total_len;
6842                 ctsio->kern_data_len = total_len;
6843                 ctsio->kern_total_len = total_len;
6844         } else {
6845                 ctsio->residual = 0;
6846                 ctsio->kern_data_len = alloc_len;
6847                 ctsio->kern_total_len = alloc_len;
6848         }
6849
6850         switch (ctsio->cdb[0]) {
6851         case MODE_SENSE_6: {
6852                 struct scsi_mode_hdr_6 *header;
6853
6854                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6855
6856                 header->datalen = MIN(total_len - 1, 254);
6857                 if (control_dev == 0) {
6858                         header->dev_specific = 0x10; /* DPOFUA */
6859                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6860                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6861                             .eca_and_aen & SCP_SWP) != 0)
6862                                     header->dev_specific |= 0x80; /* WP */
6863                 }
6864                 if (dbd)
6865                         header->block_descr_len = 0;
6866                 else
6867                         header->block_descr_len =
6868                                 sizeof(struct scsi_mode_block_descr);
6869                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6870                 break;
6871         }
6872         case MODE_SENSE_10: {
6873                 struct scsi_mode_hdr_10 *header;
6874                 int datalen;
6875
6876                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6877
6878                 datalen = MIN(total_len - 2, 65533);
6879                 scsi_ulto2b(datalen, header->datalen);
6880                 if (control_dev == 0) {
6881                         header->dev_specific = 0x10; /* DPOFUA */
6882                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6883                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6884                             .eca_and_aen & SCP_SWP) != 0)
6885                                     header->dev_specific |= 0x80; /* WP */
6886                 }
6887                 if (dbd)
6888                         scsi_ulto2b(0, header->block_descr_len);
6889                 else
6890                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6891                                     header->block_descr_len);
6892                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6893                 break;
6894         }
6895         default:
6896                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6897                 break; /* NOTREACHED */
6898         }
6899
6900         /*
6901          * If we've got a disk, use its blocksize in the block
6902          * descriptor.  Otherwise, just set it to 0.
6903          */
6904         if (dbd == 0) {
6905                 if (control_dev == 0)
6906                         scsi_ulto3b(lun->be_lun->blocksize,
6907                                     block_desc->block_len);
6908                 else
6909                         scsi_ulto3b(0, block_desc->block_len);
6910         }
6911
6912         switch (page_code) {
6913         case SMS_ALL_PAGES_PAGE: {
6914                 int i, data_used;
6915
6916                 data_used = header_len;
6917                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6918                         struct ctl_page_index *page_index;
6919
6920                         page_index = &lun->mode_pages.index[i];
6921
6922                         if ((control_dev != 0)
6923                          && (page_index->page_flags &
6924                             CTL_PAGE_FLAG_DISK_ONLY))
6925                                 continue;
6926
6927                         /*
6928                          * We don't use this subpage if the user didn't
6929                          * request all subpages.  We already checked (above)
6930                          * to make sure the user only specified a subpage
6931                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6932                          */
6933                         if ((page_index->subpage != 0)
6934                          && (subpage == SMS_SUBPAGE_PAGE_0))
6935                                 continue;
6936
6937                         /*
6938                          * Call the handler, if it exists, to update the
6939                          * page to the latest values.
6940                          */
6941                         if (page_index->sense_handler != NULL)
6942                                 page_index->sense_handler(ctsio, page_index,pc);
6943
6944                         memcpy(ctsio->kern_data_ptr + data_used,
6945                                page_index->page_data +
6946                                (page_index->page_len * pc),
6947                                page_index->page_len);
6948                         data_used += page_index->page_len;
6949                 }
6950                 break;
6951         }
6952         default: {
6953                 int i, data_used;
6954
6955                 data_used = header_len;
6956
6957                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6958                         struct ctl_page_index *page_index;
6959
6960                         page_index = &lun->mode_pages.index[i];
6961
6962                         /* Look for the right page code */
6963                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6964                                 continue;
6965
6966                         /* Look for the right subpage or the subpage wildcard*/
6967                         if ((page_index->subpage != subpage)
6968                          && (subpage != SMS_SUBPAGE_ALL))
6969                                 continue;
6970
6971                         /* Make sure the page is supported for this dev type */
6972                         if ((control_dev != 0)
6973                          && (page_index->page_flags &
6974                              CTL_PAGE_FLAG_DISK_ONLY))
6975                                 continue;
6976
6977                         /*
6978                          * Call the handler, if it exists, to update the
6979                          * page to the latest values.
6980                          */
6981                         if (page_index->sense_handler != NULL)
6982                                 page_index->sense_handler(ctsio, page_index,pc);
6983
6984                         memcpy(ctsio->kern_data_ptr + data_used,
6985                                page_index->page_data +
6986                                (page_index->page_len * pc),
6987                                page_index->page_len);
6988                         data_used += page_index->page_len;
6989                 }
6990                 break;
6991         }
6992         }
6993
6994         ctl_set_success(ctsio);
6995         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6996         ctsio->be_move_done = ctl_config_move_done;
6997         ctl_datamove((union ctl_io *)ctsio);
6998         return (CTL_RETVAL_COMPLETE);
6999 }
7000
7001 int
7002 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
7003                                struct ctl_page_index *page_index,
7004                                int pc)
7005 {
7006         struct ctl_lun *lun;
7007         struct scsi_log_param_header *phdr;
7008         uint8_t *data;
7009         uint64_t val;
7010
7011         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7012         data = page_index->page_data;
7013
7014         if (lun->backend->lun_attr != NULL &&
7015             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
7016              != UINT64_MAX) {
7017                 phdr = (struct scsi_log_param_header *)data;
7018                 scsi_ulto2b(0x0001, phdr->param_code);
7019                 phdr->param_control = SLP_LBIN | SLP_LP;
7020                 phdr->param_len = 8;
7021                 data = (uint8_t *)(phdr + 1);
7022                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7023                 data[4] = 0x02; /* per-pool */
7024                 data += phdr->param_len;
7025         }
7026
7027         if (lun->backend->lun_attr != NULL &&
7028             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
7029              != UINT64_MAX) {
7030                 phdr = (struct scsi_log_param_header *)data;
7031                 scsi_ulto2b(0x0002, phdr->param_code);
7032                 phdr->param_control = SLP_LBIN | SLP_LP;
7033                 phdr->param_len = 8;
7034                 data = (uint8_t *)(phdr + 1);
7035                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7036                 data[4] = 0x01; /* per-LUN */
7037                 data += phdr->param_len;
7038         }
7039
7040         if (lun->backend->lun_attr != NULL &&
7041             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
7042              != UINT64_MAX) {
7043                 phdr = (struct scsi_log_param_header *)data;
7044                 scsi_ulto2b(0x00f1, phdr->param_code);
7045                 phdr->param_control = SLP_LBIN | SLP_LP;
7046                 phdr->param_len = 8;
7047                 data = (uint8_t *)(phdr + 1);
7048                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7049                 data[4] = 0x02; /* per-pool */
7050                 data += phdr->param_len;
7051         }
7052
7053         if (lun->backend->lun_attr != NULL &&
7054             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7055              != UINT64_MAX) {
7056                 phdr = (struct scsi_log_param_header *)data;
7057                 scsi_ulto2b(0x00f2, phdr->param_code);
7058                 phdr->param_control = SLP_LBIN | SLP_LP;
7059                 phdr->param_len = 8;
7060                 data = (uint8_t *)(phdr + 1);
7061                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7062                 data[4] = 0x02; /* per-pool */
7063                 data += phdr->param_len;
7064         }
7065
7066         page_index->page_len = data - page_index->page_data;
7067         return (0);
7068 }
7069
7070 int
7071 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
7072                                struct ctl_page_index *page_index,
7073                                int pc)
7074 {
7075         struct ctl_lun *lun;
7076         struct stat_page *data;
7077         uint64_t rn, wn, rb, wb;
7078         struct bintime rt, wt;
7079         int i;
7080
7081         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7082         data = (struct stat_page *)page_index->page_data;
7083
7084         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
7085         data->sap.hdr.param_control = SLP_LBIN;
7086         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
7087             sizeof(struct scsi_log_param_header);
7088         rn = wn = rb = wb = 0;
7089         bintime_clear(&rt);
7090         bintime_clear(&wt);
7091         for (i = 0; i < CTL_MAX_PORTS; i++) {
7092                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
7093                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
7094                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
7095                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
7096                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
7097                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
7098         }
7099         scsi_u64to8b(rn, data->sap.read_num);
7100         scsi_u64to8b(wn, data->sap.write_num);
7101         if (lun->stats.blocksize > 0) {
7102                 scsi_u64to8b(wb / lun->stats.blocksize,
7103                     data->sap.recvieved_lba);
7104                 scsi_u64to8b(rb / lun->stats.blocksize,
7105                     data->sap.transmitted_lba);
7106         }
7107         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
7108             data->sap.read_int);
7109         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
7110             data->sap.write_int);
7111         scsi_u64to8b(0, data->sap.weighted_num);
7112         scsi_u64to8b(0, data->sap.weighted_int);
7113         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
7114         data->it.hdr.param_control = SLP_LBIN;
7115         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
7116             sizeof(struct scsi_log_param_header);
7117 #ifdef CTL_TIME_IO
7118         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
7119 #endif
7120         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
7121         data->it.hdr.param_control = SLP_LBIN;
7122         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
7123             sizeof(struct scsi_log_param_header);
7124         scsi_ulto4b(3, data->ti.exponent);
7125         scsi_ulto4b(1, data->ti.integer);
7126
7127         page_index->page_len = sizeof(*data);
7128         return (0);
7129 }
7130
7131 int
7132 ctl_log_sense(struct ctl_scsiio *ctsio)
7133 {
7134         struct ctl_lun *lun;
7135         int i, pc, page_code, subpage;
7136         int alloc_len, total_len;
7137         struct ctl_page_index *page_index;
7138         struct scsi_log_sense *cdb;
7139         struct scsi_log_header *header;
7140
7141         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7142
7143         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7144         cdb = (struct scsi_log_sense *)ctsio->cdb;
7145         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7146         page_code = cdb->page & SLS_PAGE_CODE;
7147         subpage = cdb->subpage;
7148         alloc_len = scsi_2btoul(cdb->length);
7149
7150         page_index = NULL;
7151         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7152                 page_index = &lun->log_pages.index[i];
7153
7154                 /* Look for the right page code */
7155                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7156                         continue;
7157
7158                 /* Look for the right subpage or the subpage wildcard*/
7159                 if (page_index->subpage != subpage)
7160                         continue;
7161
7162                 break;
7163         }
7164         if (i >= CTL_NUM_LOG_PAGES) {
7165                 ctl_set_invalid_field(ctsio,
7166                                       /*sks_valid*/ 1,
7167                                       /*command*/ 1,
7168                                       /*field*/ 2,
7169                                       /*bit_valid*/ 0,
7170                                       /*bit*/ 0);
7171                 ctl_done((union ctl_io *)ctsio);
7172                 return (CTL_RETVAL_COMPLETE);
7173         }
7174
7175         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7176
7177         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7178         ctsio->kern_sg_entries = 0;
7179         ctsio->kern_data_resid = 0;
7180         ctsio->kern_rel_offset = 0;
7181         if (total_len < alloc_len) {
7182                 ctsio->residual = alloc_len - total_len;
7183                 ctsio->kern_data_len = total_len;
7184                 ctsio->kern_total_len = total_len;
7185         } else {
7186                 ctsio->residual = 0;
7187                 ctsio->kern_data_len = alloc_len;
7188                 ctsio->kern_total_len = alloc_len;
7189         }
7190
7191         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7192         header->page = page_index->page_code;
7193         if (page_index->subpage) {
7194                 header->page |= SL_SPF;
7195                 header->subpage = page_index->subpage;
7196         }
7197         scsi_ulto2b(page_index->page_len, header->datalen);
7198
7199         /*
7200          * Call the handler, if it exists, to update the
7201          * page to the latest values.
7202          */
7203         if (page_index->sense_handler != NULL)
7204                 page_index->sense_handler(ctsio, page_index, pc);
7205
7206         memcpy(header + 1, page_index->page_data, page_index->page_len);
7207
7208         ctl_set_success(ctsio);
7209         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7210         ctsio->be_move_done = ctl_config_move_done;
7211         ctl_datamove((union ctl_io *)ctsio);
7212         return (CTL_RETVAL_COMPLETE);
7213 }
7214
7215 int
7216 ctl_read_capacity(struct ctl_scsiio *ctsio)
7217 {
7218         struct scsi_read_capacity *cdb;
7219         struct scsi_read_capacity_data *data;
7220         struct ctl_lun *lun;
7221         uint32_t lba;
7222
7223         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7224
7225         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7226
7227         lba = scsi_4btoul(cdb->addr);
7228         if (((cdb->pmi & SRC_PMI) == 0)
7229          && (lba != 0)) {
7230                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7231                                       /*sks_valid*/ 1,
7232                                       /*command*/ 1,
7233                                       /*field*/ 2,
7234                                       /*bit_valid*/ 0,
7235                                       /*bit*/ 0);
7236                 ctl_done((union ctl_io *)ctsio);
7237                 return (CTL_RETVAL_COMPLETE);
7238         }
7239
7240         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7241
7242         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7243         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7244         ctsio->residual = 0;
7245         ctsio->kern_data_len = sizeof(*data);
7246         ctsio->kern_total_len = sizeof(*data);
7247         ctsio->kern_data_resid = 0;
7248         ctsio->kern_rel_offset = 0;
7249         ctsio->kern_sg_entries = 0;
7250
7251         /*
7252          * If the maximum LBA is greater than 0xfffffffe, the user must
7253          * issue a SERVICE ACTION IN (16) command, with the read capacity
7254          * serivce action set.
7255          */
7256         if (lun->be_lun->maxlba > 0xfffffffe)
7257                 scsi_ulto4b(0xffffffff, data->addr);
7258         else
7259                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7260
7261         /*
7262          * XXX KDM this may not be 512 bytes...
7263          */
7264         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7265
7266         ctl_set_success(ctsio);
7267         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7268         ctsio->be_move_done = ctl_config_move_done;
7269         ctl_datamove((union ctl_io *)ctsio);
7270         return (CTL_RETVAL_COMPLETE);
7271 }
7272
7273 int
7274 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7275 {
7276         struct scsi_read_capacity_16 *cdb;
7277         struct scsi_read_capacity_data_long *data;
7278         struct ctl_lun *lun;
7279         uint64_t lba;
7280         uint32_t alloc_len;
7281
7282         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7283
7284         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7285
7286         alloc_len = scsi_4btoul(cdb->alloc_len);
7287         lba = scsi_8btou64(cdb->addr);
7288
7289         if ((cdb->reladr & SRC16_PMI)
7290          && (lba != 0)) {
7291                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7292                                       /*sks_valid*/ 1,
7293                                       /*command*/ 1,
7294                                       /*field*/ 2,
7295                                       /*bit_valid*/ 0,
7296                                       /*bit*/ 0);
7297                 ctl_done((union ctl_io *)ctsio);
7298                 return (CTL_RETVAL_COMPLETE);
7299         }
7300
7301         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7302
7303         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7304         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7305
7306         if (sizeof(*data) < alloc_len) {
7307                 ctsio->residual = alloc_len - sizeof(*data);
7308                 ctsio->kern_data_len = sizeof(*data);
7309                 ctsio->kern_total_len = sizeof(*data);
7310         } else {
7311                 ctsio->residual = 0;
7312                 ctsio->kern_data_len = alloc_len;
7313                 ctsio->kern_total_len = alloc_len;
7314         }
7315         ctsio->kern_data_resid = 0;
7316         ctsio->kern_rel_offset = 0;
7317         ctsio->kern_sg_entries = 0;
7318
7319         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7320         /* XXX KDM this may not be 512 bytes... */
7321         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7322         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7323         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7324         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7325                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7326
7327         ctl_set_success(ctsio);
7328         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7329         ctsio->be_move_done = ctl_config_move_done;
7330         ctl_datamove((union ctl_io *)ctsio);
7331         return (CTL_RETVAL_COMPLETE);
7332 }
7333
7334 int
7335 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7336 {
7337         struct scsi_get_lba_status *cdb;
7338         struct scsi_get_lba_status_data *data;
7339         struct ctl_lun *lun;
7340         struct ctl_lba_len_flags *lbalen;
7341         uint64_t lba;
7342         uint32_t alloc_len, total_len;
7343         int retval;
7344
7345         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7346
7347         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7348         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7349         lba = scsi_8btou64(cdb->addr);
7350         alloc_len = scsi_4btoul(cdb->alloc_len);
7351
7352         if (lba > lun->be_lun->maxlba) {
7353                 ctl_set_lba_out_of_range(ctsio);
7354                 ctl_done((union ctl_io *)ctsio);
7355                 return (CTL_RETVAL_COMPLETE);
7356         }
7357
7358         total_len = sizeof(*data) + sizeof(data->descr[0]);
7359         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7360         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7361
7362         if (total_len < alloc_len) {
7363                 ctsio->residual = alloc_len - total_len;
7364                 ctsio->kern_data_len = total_len;
7365                 ctsio->kern_total_len = total_len;
7366         } else {
7367                 ctsio->residual = 0;
7368                 ctsio->kern_data_len = alloc_len;
7369                 ctsio->kern_total_len = alloc_len;
7370         }
7371         ctsio->kern_data_resid = 0;
7372         ctsio->kern_rel_offset = 0;
7373         ctsio->kern_sg_entries = 0;
7374
7375         /* Fill dummy data in case backend can't tell anything. */
7376         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7377         scsi_u64to8b(lba, data->descr[0].addr);
7378         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7379             data->descr[0].length);
7380         data->descr[0].status = 0; /* Mapped or unknown. */
7381
7382         ctl_set_success(ctsio);
7383         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7384         ctsio->be_move_done = ctl_config_move_done;
7385
7386         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7387         lbalen->lba = lba;
7388         lbalen->len = total_len;
7389         lbalen->flags = 0;
7390         retval = lun->backend->config_read((union ctl_io *)ctsio);
7391         return (CTL_RETVAL_COMPLETE);
7392 }
7393
7394 int
7395 ctl_read_defect(struct ctl_scsiio *ctsio)
7396 {
7397         struct scsi_read_defect_data_10 *ccb10;
7398         struct scsi_read_defect_data_12 *ccb12;
7399         struct scsi_read_defect_data_hdr_10 *data10;
7400         struct scsi_read_defect_data_hdr_12 *data12;
7401         uint32_t alloc_len, data_len;
7402         uint8_t format;
7403
7404         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7405
7406         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7407                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7408                 format = ccb10->format;
7409                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7410                 data_len = sizeof(*data10);
7411         } else {
7412                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7413                 format = ccb12->format;
7414                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7415                 data_len = sizeof(*data12);
7416         }
7417         if (alloc_len == 0) {
7418                 ctl_set_success(ctsio);
7419                 ctl_done((union ctl_io *)ctsio);
7420                 return (CTL_RETVAL_COMPLETE);
7421         }
7422
7423         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7424         if (data_len < alloc_len) {
7425                 ctsio->residual = alloc_len - data_len;
7426                 ctsio->kern_data_len = data_len;
7427                 ctsio->kern_total_len = data_len;
7428         } else {
7429                 ctsio->residual = 0;
7430                 ctsio->kern_data_len = alloc_len;
7431                 ctsio->kern_total_len = alloc_len;
7432         }
7433         ctsio->kern_data_resid = 0;
7434         ctsio->kern_rel_offset = 0;
7435         ctsio->kern_sg_entries = 0;
7436
7437         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7438                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7439                     ctsio->kern_data_ptr;
7440                 data10->format = format;
7441                 scsi_ulto2b(0, data10->length);
7442         } else {
7443                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7444                     ctsio->kern_data_ptr;
7445                 data12->format = format;
7446                 scsi_ulto2b(0, data12->generation);
7447                 scsi_ulto4b(0, data12->length);
7448         }
7449
7450         ctl_set_success(ctsio);
7451         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7452         ctsio->be_move_done = ctl_config_move_done;
7453         ctl_datamove((union ctl_io *)ctsio);
7454         return (CTL_RETVAL_COMPLETE);
7455 }
7456
7457 int
7458 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7459 {
7460         struct scsi_maintenance_in *cdb;
7461         int retval;
7462         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7463         int num_target_port_groups, num_target_ports;
7464         struct ctl_lun *lun;
7465         struct ctl_softc *softc;
7466         struct ctl_port *port;
7467         struct scsi_target_group_data *rtg_ptr;
7468         struct scsi_target_group_data_extended *rtg_ext_ptr;
7469         struct scsi_target_port_group_descriptor *tpg_desc;
7470
7471         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7472
7473         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7474         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7475         softc = lun->ctl_softc;
7476
7477         retval = CTL_RETVAL_COMPLETE;
7478
7479         switch (cdb->byte2 & STG_PDF_MASK) {
7480         case STG_PDF_LENGTH:
7481                 ext = 0;
7482                 break;
7483         case STG_PDF_EXTENDED:
7484                 ext = 1;
7485                 break;
7486         default:
7487                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7488                                       /*sks_valid*/ 1,
7489                                       /*command*/ 1,
7490                                       /*field*/ 2,
7491                                       /*bit_valid*/ 1,
7492                                       /*bit*/ 5);
7493                 ctl_done((union ctl_io *)ctsio);
7494                 return(retval);
7495         }
7496
7497         if (softc->is_single)
7498                 num_target_port_groups = 1;
7499         else
7500                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7501         num_target_ports = 0;
7502         mtx_lock(&softc->ctl_lock);
7503         STAILQ_FOREACH(port, &softc->port_list, links) {
7504                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7505                         continue;
7506                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7507                         continue;
7508                 num_target_ports++;
7509         }
7510         mtx_unlock(&softc->ctl_lock);
7511
7512         if (ext)
7513                 total_len = sizeof(struct scsi_target_group_data_extended);
7514         else
7515                 total_len = sizeof(struct scsi_target_group_data);
7516         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7517                 num_target_port_groups +
7518             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7519
7520         alloc_len = scsi_4btoul(cdb->length);
7521
7522         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7523
7524         ctsio->kern_sg_entries = 0;
7525
7526         if (total_len < alloc_len) {
7527                 ctsio->residual = alloc_len - total_len;
7528                 ctsio->kern_data_len = total_len;
7529                 ctsio->kern_total_len = total_len;
7530         } else {
7531                 ctsio->residual = 0;
7532                 ctsio->kern_data_len = alloc_len;
7533                 ctsio->kern_total_len = alloc_len;
7534         }
7535         ctsio->kern_data_resid = 0;
7536         ctsio->kern_rel_offset = 0;
7537
7538         if (ext) {
7539                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7540                     ctsio->kern_data_ptr;
7541                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7542                 rtg_ext_ptr->format_type = 0x10;
7543                 rtg_ext_ptr->implicit_transition_time = 0;
7544                 tpg_desc = &rtg_ext_ptr->groups[0];
7545         } else {
7546                 rtg_ptr = (struct scsi_target_group_data *)
7547                     ctsio->kern_data_ptr;
7548                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7549                 tpg_desc = &rtg_ptr->groups[0];
7550         }
7551
7552         mtx_lock(&softc->ctl_lock);
7553         pg = softc->port_min / softc->port_cnt;
7554         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7555                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7556         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7557                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7558         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7559                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7560         else
7561                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7562         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7563                 os = gs;
7564                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7565         } else
7566                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7567         for (g = 0; g < num_target_port_groups; g++) {
7568                 tpg_desc->pref_state = (g == pg) ? gs : os;
7569                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7570                     TPG_U_SUP | TPG_T_SUP;
7571                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7572                 tpg_desc->status = TPG_IMPLICIT;
7573                 pc = 0;
7574                 STAILQ_FOREACH(port, &softc->port_list, links) {
7575                         if (port->targ_port < g * softc->port_cnt ||
7576                             port->targ_port >= (g + 1) * softc->port_cnt)
7577                                 continue;
7578                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7579                                 continue;
7580                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7581                                 continue;
7582                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7583                             relative_target_port_identifier);
7584                         pc++;
7585                 }
7586                 tpg_desc->target_port_count = pc;
7587                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7588                     &tpg_desc->descriptors[pc];
7589         }
7590         mtx_unlock(&softc->ctl_lock);
7591
7592         ctl_set_success(ctsio);
7593         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7594         ctsio->be_move_done = ctl_config_move_done;
7595         ctl_datamove((union ctl_io *)ctsio);
7596         return(retval);
7597 }
7598
7599 int
7600 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7601 {
7602         struct ctl_lun *lun;
7603         struct scsi_report_supported_opcodes *cdb;
7604         const struct ctl_cmd_entry *entry, *sentry;
7605         struct scsi_report_supported_opcodes_all *all;
7606         struct scsi_report_supported_opcodes_descr *descr;
7607         struct scsi_report_supported_opcodes_one *one;
7608         int retval;
7609         int alloc_len, total_len;
7610         int opcode, service_action, i, j, num;
7611
7612         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7613
7614         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7615         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7616
7617         retval = CTL_RETVAL_COMPLETE;
7618
7619         opcode = cdb->requested_opcode;
7620         service_action = scsi_2btoul(cdb->requested_service_action);
7621         switch (cdb->options & RSO_OPTIONS_MASK) {
7622         case RSO_OPTIONS_ALL:
7623                 num = 0;
7624                 for (i = 0; i < 256; i++) {
7625                         entry = &ctl_cmd_table[i];
7626                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7627                                 for (j = 0; j < 32; j++) {
7628                                         sentry = &((const struct ctl_cmd_entry *)
7629                                             entry->execute)[j];
7630                                         if (ctl_cmd_applicable(
7631                                             lun->be_lun->lun_type, sentry))
7632                                                 num++;
7633                                 }
7634                         } else {
7635                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7636                                     entry))
7637                                         num++;
7638                         }
7639                 }
7640                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7641                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7642                 break;
7643         case RSO_OPTIONS_OC:
7644                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7645                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7646                                               /*sks_valid*/ 1,
7647                                               /*command*/ 1,
7648                                               /*field*/ 2,
7649                                               /*bit_valid*/ 1,
7650                                               /*bit*/ 2);
7651                         ctl_done((union ctl_io *)ctsio);
7652                         return (CTL_RETVAL_COMPLETE);
7653                 }
7654                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7655                 break;
7656         case RSO_OPTIONS_OC_SA:
7657                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7658                     service_action >= 32) {
7659                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7660                                               /*sks_valid*/ 1,
7661                                               /*command*/ 1,
7662                                               /*field*/ 2,
7663                                               /*bit_valid*/ 1,
7664                                               /*bit*/ 2);
7665                         ctl_done((union ctl_io *)ctsio);
7666                         return (CTL_RETVAL_COMPLETE);
7667                 }
7668                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7669                 break;
7670         default:
7671                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7672                                       /*sks_valid*/ 1,
7673                                       /*command*/ 1,
7674                                       /*field*/ 2,
7675                                       /*bit_valid*/ 1,
7676                                       /*bit*/ 2);
7677                 ctl_done((union ctl_io *)ctsio);
7678                 return (CTL_RETVAL_COMPLETE);
7679         }
7680
7681         alloc_len = scsi_4btoul(cdb->length);
7682
7683         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7684
7685         ctsio->kern_sg_entries = 0;
7686
7687         if (total_len < alloc_len) {
7688                 ctsio->residual = alloc_len - total_len;
7689                 ctsio->kern_data_len = total_len;
7690                 ctsio->kern_total_len = total_len;
7691         } else {
7692                 ctsio->residual = 0;
7693                 ctsio->kern_data_len = alloc_len;
7694                 ctsio->kern_total_len = alloc_len;
7695         }
7696         ctsio->kern_data_resid = 0;
7697         ctsio->kern_rel_offset = 0;
7698
7699         switch (cdb->options & RSO_OPTIONS_MASK) {
7700         case RSO_OPTIONS_ALL:
7701                 all = (struct scsi_report_supported_opcodes_all *)
7702                     ctsio->kern_data_ptr;
7703                 num = 0;
7704                 for (i = 0; i < 256; i++) {
7705                         entry = &ctl_cmd_table[i];
7706                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7707                                 for (j = 0; j < 32; j++) {
7708                                         sentry = &((const struct ctl_cmd_entry *)
7709                                             entry->execute)[j];
7710                                         if (!ctl_cmd_applicable(
7711                                             lun->be_lun->lun_type, sentry))
7712                                                 continue;
7713                                         descr = &all->descr[num++];
7714                                         descr->opcode = i;
7715                                         scsi_ulto2b(j, descr->service_action);
7716                                         descr->flags = RSO_SERVACTV;
7717                                         scsi_ulto2b(sentry->length,
7718                                             descr->cdb_length);
7719                                 }
7720                         } else {
7721                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7722                                     entry))
7723                                         continue;
7724                                 descr = &all->descr[num++];
7725                                 descr->opcode = i;
7726                                 scsi_ulto2b(0, descr->service_action);
7727                                 descr->flags = 0;
7728                                 scsi_ulto2b(entry->length, descr->cdb_length);
7729                         }
7730                 }
7731                 scsi_ulto4b(
7732                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7733                     all->length);
7734                 break;
7735         case RSO_OPTIONS_OC:
7736                 one = (struct scsi_report_supported_opcodes_one *)
7737                     ctsio->kern_data_ptr;
7738                 entry = &ctl_cmd_table[opcode];
7739                 goto fill_one;
7740         case RSO_OPTIONS_OC_SA:
7741                 one = (struct scsi_report_supported_opcodes_one *)
7742                     ctsio->kern_data_ptr;
7743                 entry = &ctl_cmd_table[opcode];
7744                 entry = &((const struct ctl_cmd_entry *)
7745                     entry->execute)[service_action];
7746 fill_one:
7747                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7748                         one->support = 3;
7749                         scsi_ulto2b(entry->length, one->cdb_length);
7750                         one->cdb_usage[0] = opcode;
7751                         memcpy(&one->cdb_usage[1], entry->usage,
7752                             entry->length - 1);
7753                 } else
7754                         one->support = 1;
7755                 break;
7756         }
7757
7758         ctl_set_success(ctsio);
7759         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7760         ctsio->be_move_done = ctl_config_move_done;
7761         ctl_datamove((union ctl_io *)ctsio);
7762         return(retval);
7763 }
7764
7765 int
7766 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7767 {
7768         struct scsi_report_supported_tmf *cdb;
7769         struct scsi_report_supported_tmf_data *data;
7770         int retval;
7771         int alloc_len, total_len;
7772
7773         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7774
7775         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7776
7777         retval = CTL_RETVAL_COMPLETE;
7778
7779         total_len = sizeof(struct scsi_report_supported_tmf_data);
7780         alloc_len = scsi_4btoul(cdb->length);
7781
7782         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7783
7784         ctsio->kern_sg_entries = 0;
7785
7786         if (total_len < alloc_len) {
7787                 ctsio->residual = alloc_len - total_len;
7788                 ctsio->kern_data_len = total_len;
7789                 ctsio->kern_total_len = total_len;
7790         } else {
7791                 ctsio->residual = 0;
7792                 ctsio->kern_data_len = alloc_len;
7793                 ctsio->kern_total_len = alloc_len;
7794         }
7795         ctsio->kern_data_resid = 0;
7796         ctsio->kern_rel_offset = 0;
7797
7798         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7799         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7800             RST_TRS;
7801         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7802
7803         ctl_set_success(ctsio);
7804         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7805         ctsio->be_move_done = ctl_config_move_done;
7806         ctl_datamove((union ctl_io *)ctsio);
7807         return (retval);
7808 }
7809
7810 int
7811 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7812 {
7813         struct scsi_report_timestamp *cdb;
7814         struct scsi_report_timestamp_data *data;
7815         struct timeval tv;
7816         int64_t timestamp;
7817         int retval;
7818         int alloc_len, total_len;
7819
7820         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7821
7822         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7823
7824         retval = CTL_RETVAL_COMPLETE;
7825
7826         total_len = sizeof(struct scsi_report_timestamp_data);
7827         alloc_len = scsi_4btoul(cdb->length);
7828
7829         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7830
7831         ctsio->kern_sg_entries = 0;
7832
7833         if (total_len < alloc_len) {
7834                 ctsio->residual = alloc_len - total_len;
7835                 ctsio->kern_data_len = total_len;
7836                 ctsio->kern_total_len = total_len;
7837         } else {
7838                 ctsio->residual = 0;
7839                 ctsio->kern_data_len = alloc_len;
7840                 ctsio->kern_total_len = alloc_len;
7841         }
7842         ctsio->kern_data_resid = 0;
7843         ctsio->kern_rel_offset = 0;
7844
7845         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7846         scsi_ulto2b(sizeof(*data) - 2, data->length);
7847         data->origin = RTS_ORIG_OUTSIDE;
7848         getmicrotime(&tv);
7849         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7850         scsi_ulto4b(timestamp >> 16, data->timestamp);
7851         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7852
7853         ctl_set_success(ctsio);
7854         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7855         ctsio->be_move_done = ctl_config_move_done;
7856         ctl_datamove((union ctl_io *)ctsio);
7857         return (retval);
7858 }
7859
7860 int
7861 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7862 {
7863         struct scsi_per_res_in *cdb;
7864         int alloc_len, total_len = 0;
7865         /* struct scsi_per_res_in_rsrv in_data; */
7866         struct ctl_lun *lun;
7867         struct ctl_softc *softc;
7868         uint64_t key;
7869
7870         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7871
7872         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7873
7874         alloc_len = scsi_2btoul(cdb->length);
7875
7876         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7877         softc = lun->ctl_softc;
7878
7879 retry:
7880         mtx_lock(&lun->lun_lock);
7881         switch (cdb->action) {
7882         case SPRI_RK: /* read keys */
7883                 total_len = sizeof(struct scsi_per_res_in_keys) +
7884                         lun->pr_key_count *
7885                         sizeof(struct scsi_per_res_key);
7886                 break;
7887         case SPRI_RR: /* read reservation */
7888                 if (lun->flags & CTL_LUN_PR_RESERVED)
7889                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7890                 else
7891                         total_len = sizeof(struct scsi_per_res_in_header);
7892                 break;
7893         case SPRI_RC: /* report capabilities */
7894                 total_len = sizeof(struct scsi_per_res_cap);
7895                 break;
7896         case SPRI_RS: /* read full status */
7897                 total_len = sizeof(struct scsi_per_res_in_header) +
7898                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7899                     lun->pr_key_count;
7900                 break;
7901         default:
7902                 panic("Invalid PR type %x", cdb->action);
7903         }
7904         mtx_unlock(&lun->lun_lock);
7905
7906         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7907
7908         if (total_len < alloc_len) {
7909                 ctsio->residual = alloc_len - total_len;
7910                 ctsio->kern_data_len = total_len;
7911                 ctsio->kern_total_len = total_len;
7912         } else {
7913                 ctsio->residual = 0;
7914                 ctsio->kern_data_len = alloc_len;
7915                 ctsio->kern_total_len = alloc_len;
7916         }
7917
7918         ctsio->kern_data_resid = 0;
7919         ctsio->kern_rel_offset = 0;
7920         ctsio->kern_sg_entries = 0;
7921
7922         mtx_lock(&lun->lun_lock);
7923         switch (cdb->action) {
7924         case SPRI_RK: { // read keys
7925         struct scsi_per_res_in_keys *res_keys;
7926                 int i, key_count;
7927
7928                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7929
7930                 /*
7931                  * We had to drop the lock to allocate our buffer, which
7932                  * leaves time for someone to come in with another
7933                  * persistent reservation.  (That is unlikely, though,
7934                  * since this should be the only persistent reservation
7935                  * command active right now.)
7936                  */
7937                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7938                     (lun->pr_key_count *
7939                      sizeof(struct scsi_per_res_key)))){
7940                         mtx_unlock(&lun->lun_lock);
7941                         free(ctsio->kern_data_ptr, M_CTL);
7942                         printf("%s: reservation length changed, retrying\n",
7943                                __func__);
7944                         goto retry;
7945                 }
7946
7947                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7948
7949                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7950                              lun->pr_key_count, res_keys->header.length);
7951
7952                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7953                         if ((key = ctl_get_prkey(lun, i)) == 0)
7954                                 continue;
7955
7956                         /*
7957                          * We used lun->pr_key_count to calculate the
7958                          * size to allocate.  If it turns out the number of
7959                          * initiators with the registered flag set is
7960                          * larger than that (i.e. they haven't been kept in
7961                          * sync), we've got a problem.
7962                          */
7963                         if (key_count >= lun->pr_key_count) {
7964 #ifdef NEEDTOPORT
7965                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7966                                             CTL_PR_ERROR,
7967                                             csevent_LogType_Fault,
7968                                             csevent_AlertLevel_Yellow,
7969                                             csevent_FRU_ShelfController,
7970                                             csevent_FRU_Firmware,
7971                                         csevent_FRU_Unknown,
7972                                             "registered keys %d >= key "
7973                                             "count %d", key_count,
7974                                             lun->pr_key_count);
7975 #endif
7976                                 key_count++;
7977                                 continue;
7978                         }
7979                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7980                         key_count++;
7981                 }
7982                 break;
7983         }
7984         case SPRI_RR: { // read reservation
7985                 struct scsi_per_res_in_rsrv *res;
7986                 int tmp_len, header_only;
7987
7988                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7989
7990                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7991
7992                 if (lun->flags & CTL_LUN_PR_RESERVED)
7993                 {
7994                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7995                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7996                                     res->header.length);
7997                         header_only = 0;
7998                 } else {
7999                         tmp_len = sizeof(struct scsi_per_res_in_header);
8000                         scsi_ulto4b(0, res->header.length);
8001                         header_only = 1;
8002                 }
8003
8004                 /*
8005                  * We had to drop the lock to allocate our buffer, which
8006                  * leaves time for someone to come in with another
8007                  * persistent reservation.  (That is unlikely, though,
8008                  * since this should be the only persistent reservation
8009                  * command active right now.)
8010                  */
8011                 if (tmp_len != total_len) {
8012                         mtx_unlock(&lun->lun_lock);
8013                         free(ctsio->kern_data_ptr, M_CTL);
8014                         printf("%s: reservation status changed, retrying\n",
8015                                __func__);
8016                         goto retry;
8017                 }
8018
8019                 /*
8020                  * No reservation held, so we're done.
8021                  */
8022                 if (header_only != 0)
8023                         break;
8024
8025                 /*
8026                  * If the registration is an All Registrants type, the key
8027                  * is 0, since it doesn't really matter.
8028                  */
8029                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8030                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
8031                             res->data.reservation);
8032                 }
8033                 res->data.scopetype = lun->res_type;
8034                 break;
8035         }
8036         case SPRI_RC:     //report capabilities
8037         {
8038                 struct scsi_per_res_cap *res_cap;
8039                 uint16_t type_mask;
8040
8041                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8042                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8043                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8044                 type_mask = SPRI_TM_WR_EX_AR |
8045                             SPRI_TM_EX_AC_RO |
8046                             SPRI_TM_WR_EX_RO |
8047                             SPRI_TM_EX_AC |
8048                             SPRI_TM_WR_EX |
8049                             SPRI_TM_EX_AC_AR;
8050                 scsi_ulto2b(type_mask, res_cap->type_mask);
8051                 break;
8052         }
8053         case SPRI_RS: { // read full status
8054                 struct scsi_per_res_in_full *res_status;
8055                 struct scsi_per_res_in_full_desc *res_desc;
8056                 struct ctl_port *port;
8057                 int i, len;
8058
8059                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8060
8061                 /*
8062                  * We had to drop the lock to allocate our buffer, which
8063                  * leaves time for someone to come in with another
8064                  * persistent reservation.  (That is unlikely, though,
8065                  * since this should be the only persistent reservation
8066                  * command active right now.)
8067                  */
8068                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
8069                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8070                      lun->pr_key_count)){
8071                         mtx_unlock(&lun->lun_lock);
8072                         free(ctsio->kern_data_ptr, M_CTL);
8073                         printf("%s: reservation length changed, retrying\n",
8074                                __func__);
8075                         goto retry;
8076                 }
8077
8078                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8079
8080                 res_desc = &res_status->desc[0];
8081                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8082                         if ((key = ctl_get_prkey(lun, i)) == 0)
8083                                 continue;
8084
8085                         scsi_u64to8b(key, res_desc->res_key.key);
8086                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8087                             (lun->pr_res_idx == i ||
8088                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8089                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8090                                 res_desc->scopetype = lun->res_type;
8091                         }
8092                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8093                             res_desc->rel_trgt_port_id);
8094                         len = 0;
8095                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
8096                         if (port != NULL)
8097                                 len = ctl_create_iid(port,
8098                                     i % CTL_MAX_INIT_PER_PORT,
8099                                     res_desc->transport_id);
8100                         scsi_ulto4b(len, res_desc->additional_length);
8101                         res_desc = (struct scsi_per_res_in_full_desc *)
8102                             &res_desc->transport_id[len];
8103                 }
8104                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8105                     res_status->header.length);
8106                 break;
8107         }
8108         default:
8109                 /*
8110                  * This is a bug, because we just checked for this above,
8111                  * and should have returned an error.
8112                  */
8113                 panic("Invalid PR type %x", cdb->action);
8114                 break; /* NOTREACHED */
8115         }
8116         mtx_unlock(&lun->lun_lock);
8117
8118         ctl_set_success(ctsio);
8119         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8120         ctsio->be_move_done = ctl_config_move_done;
8121         ctl_datamove((union ctl_io *)ctsio);
8122         return (CTL_RETVAL_COMPLETE);
8123 }
8124
8125 /*
8126  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8127  * it should return.
8128  */
8129 static int
8130 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8131                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8132                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8133                 struct scsi_per_res_out_parms* param)
8134 {
8135         union ctl_ha_msg persis_io;
8136         int i;
8137
8138         mtx_lock(&lun->lun_lock);
8139         if (sa_res_key == 0) {
8140                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8141                         /* validate scope and type */
8142                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8143                              SPR_LU_SCOPE) {
8144                                 mtx_unlock(&lun->lun_lock);
8145                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8146                                                       /*sks_valid*/ 1,
8147                                                       /*command*/ 1,
8148                                                       /*field*/ 2,
8149                                                       /*bit_valid*/ 1,
8150                                                       /*bit*/ 4);
8151                                 ctl_done((union ctl_io *)ctsio);
8152                                 return (1);
8153                         }
8154
8155                         if (type>8 || type==2 || type==4 || type==0) {
8156                                 mtx_unlock(&lun->lun_lock);
8157                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8158                                                       /*sks_valid*/ 1,
8159                                                       /*command*/ 1,
8160                                                       /*field*/ 2,
8161                                                       /*bit_valid*/ 1,
8162                                                       /*bit*/ 0);
8163                                 ctl_done((union ctl_io *)ctsio);
8164                                 return (1);
8165                         }
8166
8167                         /*
8168                          * Unregister everybody else and build UA for
8169                          * them
8170                          */
8171                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8172                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8173                                         continue;
8174
8175                                 ctl_clr_prkey(lun, i);
8176                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8177                         }
8178                         lun->pr_key_count = 1;
8179                         lun->res_type = type;
8180                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8181                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8182                                 lun->pr_res_idx = residx;
8183                         lun->PRGeneration++;
8184                         mtx_unlock(&lun->lun_lock);
8185
8186                         /* send msg to other side */
8187                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8188                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8189                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8190                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8191                         persis_io.pr.pr_info.res_type = type;
8192                         memcpy(persis_io.pr.pr_info.sa_res_key,
8193                                param->serv_act_res_key,
8194                                sizeof(param->serv_act_res_key));
8195                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8196                             sizeof(persis_io.pr), M_WAITOK);
8197                 } else {
8198                         /* not all registrants */
8199                         mtx_unlock(&lun->lun_lock);
8200                         free(ctsio->kern_data_ptr, M_CTL);
8201                         ctl_set_invalid_field(ctsio,
8202                                               /*sks_valid*/ 1,
8203                                               /*command*/ 0,
8204                                               /*field*/ 8,
8205                                               /*bit_valid*/ 0,
8206                                               /*bit*/ 0);
8207                         ctl_done((union ctl_io *)ctsio);
8208                         return (1);
8209                 }
8210         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8211                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8212                 int found = 0;
8213
8214                 if (res_key == sa_res_key) {
8215                         /* special case */
8216                         /*
8217                          * The spec implies this is not good but doesn't
8218                          * say what to do. There are two choices either
8219                          * generate a res conflict or check condition
8220                          * with illegal field in parameter data. Since
8221                          * that is what is done when the sa_res_key is
8222                          * zero I'll take that approach since this has
8223                          * to do with the sa_res_key.
8224                          */
8225                         mtx_unlock(&lun->lun_lock);
8226                         free(ctsio->kern_data_ptr, M_CTL);
8227                         ctl_set_invalid_field(ctsio,
8228                                               /*sks_valid*/ 1,
8229                                               /*command*/ 0,
8230                                               /*field*/ 8,
8231                                               /*bit_valid*/ 0,
8232                                               /*bit*/ 0);
8233                         ctl_done((union ctl_io *)ctsio);
8234                         return (1);
8235                 }
8236
8237                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8238                         if (ctl_get_prkey(lun, i) != sa_res_key)
8239                                 continue;
8240
8241                         found = 1;
8242                         ctl_clr_prkey(lun, i);
8243                         lun->pr_key_count--;
8244                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8245                 }
8246                 if (!found) {
8247                         mtx_unlock(&lun->lun_lock);
8248                         free(ctsio->kern_data_ptr, M_CTL);
8249                         ctl_set_reservation_conflict(ctsio);
8250                         ctl_done((union ctl_io *)ctsio);
8251                         return (CTL_RETVAL_COMPLETE);
8252                 }
8253                 lun->PRGeneration++;
8254                 mtx_unlock(&lun->lun_lock);
8255
8256                 /* send msg to other side */
8257                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8258                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8259                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8260                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8261                 persis_io.pr.pr_info.res_type = type;
8262                 memcpy(persis_io.pr.pr_info.sa_res_key,
8263                        param->serv_act_res_key,
8264                        sizeof(param->serv_act_res_key));
8265                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8266                     sizeof(persis_io.pr), M_WAITOK);
8267         } else {
8268                 /* Reserved but not all registrants */
8269                 /* sa_res_key is res holder */
8270                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8271                         /* validate scope and type */
8272                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8273                              SPR_LU_SCOPE) {
8274                                 mtx_unlock(&lun->lun_lock);
8275                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8276                                                       /*sks_valid*/ 1,
8277                                                       /*command*/ 1,
8278                                                       /*field*/ 2,
8279                                                       /*bit_valid*/ 1,
8280                                                       /*bit*/ 4);
8281                                 ctl_done((union ctl_io *)ctsio);
8282                                 return (1);
8283                         }
8284
8285                         if (type>8 || type==2 || type==4 || type==0) {
8286                                 mtx_unlock(&lun->lun_lock);
8287                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8288                                                       /*sks_valid*/ 1,
8289                                                       /*command*/ 1,
8290                                                       /*field*/ 2,
8291                                                       /*bit_valid*/ 1,
8292                                                       /*bit*/ 0);
8293                                 ctl_done((union ctl_io *)ctsio);
8294                                 return (1);
8295                         }
8296
8297                         /*
8298                          * Do the following:
8299                          * if sa_res_key != res_key remove all
8300                          * registrants w/sa_res_key and generate UA
8301                          * for these registrants(Registrations
8302                          * Preempted) if it wasn't an exclusive
8303                          * reservation generate UA(Reservations
8304                          * Preempted) for all other registered nexuses
8305                          * if the type has changed. Establish the new
8306                          * reservation and holder. If res_key and
8307                          * sa_res_key are the same do the above
8308                          * except don't unregister the res holder.
8309                          */
8310
8311                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8312                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8313                                         continue;
8314
8315                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8316                                         ctl_clr_prkey(lun, i);
8317                                         lun->pr_key_count--;
8318                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8319                                 } else if (type != lun->res_type
8320                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8321                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8322                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8323                                 }
8324                         }
8325                         lun->res_type = type;
8326                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8327                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8328                                 lun->pr_res_idx = residx;
8329                         else
8330                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8331                         lun->PRGeneration++;
8332                         mtx_unlock(&lun->lun_lock);
8333
8334                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8335                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8336                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8337                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8338                         persis_io.pr.pr_info.res_type = type;
8339                         memcpy(persis_io.pr.pr_info.sa_res_key,
8340                                param->serv_act_res_key,
8341                                sizeof(param->serv_act_res_key));
8342                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8343                             sizeof(persis_io.pr), M_WAITOK);
8344                 } else {
8345                         /*
8346                          * sa_res_key is not the res holder just
8347                          * remove registrants
8348                          */
8349                         int found=0;
8350
8351                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8352                                 if (sa_res_key != ctl_get_prkey(lun, i))
8353                                         continue;
8354
8355                                 found = 1;
8356                                 ctl_clr_prkey(lun, i);
8357                                 lun->pr_key_count--;
8358                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8359                         }
8360
8361                         if (!found) {
8362                                 mtx_unlock(&lun->lun_lock);
8363                                 free(ctsio->kern_data_ptr, M_CTL);
8364                                 ctl_set_reservation_conflict(ctsio);
8365                                 ctl_done((union ctl_io *)ctsio);
8366                                 return (1);
8367                         }
8368                         lun->PRGeneration++;
8369                         mtx_unlock(&lun->lun_lock);
8370
8371                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8372                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8373                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8374                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8375                         persis_io.pr.pr_info.res_type = type;
8376                         memcpy(persis_io.pr.pr_info.sa_res_key,
8377                                param->serv_act_res_key,
8378                                sizeof(param->serv_act_res_key));
8379                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8380                             sizeof(persis_io.pr), M_WAITOK);
8381                 }
8382         }
8383         return (0);
8384 }
8385
8386 static void
8387 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8388 {
8389         uint64_t sa_res_key;
8390         int i;
8391
8392         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8393
8394         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8395          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8396          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8397                 if (sa_res_key == 0) {
8398                         /*
8399                          * Unregister everybody else and build UA for
8400                          * them
8401                          */
8402                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8403                                 if (i == msg->pr.pr_info.residx ||
8404                                     ctl_get_prkey(lun, i) == 0)
8405                                         continue;
8406
8407                                 ctl_clr_prkey(lun, i);
8408                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8409                         }
8410
8411                         lun->pr_key_count = 1;
8412                         lun->res_type = msg->pr.pr_info.res_type;
8413                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8414                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8415                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8416                 } else {
8417                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8418                                 if (sa_res_key == ctl_get_prkey(lun, i))
8419                                         continue;
8420
8421                                 ctl_clr_prkey(lun, i);
8422                                 lun->pr_key_count--;
8423                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8424                         }
8425                 }
8426         } else {
8427                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8428                         if (i == msg->pr.pr_info.residx ||
8429                             ctl_get_prkey(lun, i) == 0)
8430                                 continue;
8431
8432                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8433                                 ctl_clr_prkey(lun, i);
8434                                 lun->pr_key_count--;
8435                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8436                         } else if (msg->pr.pr_info.res_type != lun->res_type
8437                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8438                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8439                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8440                         }
8441                 }
8442                 lun->res_type = msg->pr.pr_info.res_type;
8443                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8444                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8445                         lun->pr_res_idx = msg->pr.pr_info.residx;
8446                 else
8447                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8448         }
8449         lun->PRGeneration++;
8450
8451 }
8452
8453
8454 int
8455 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8456 {
8457         int retval;
8458         u_int32_t param_len;
8459         struct scsi_per_res_out *cdb;
8460         struct ctl_lun *lun;
8461         struct scsi_per_res_out_parms* param;
8462         struct ctl_softc *softc;
8463         uint32_t residx;
8464         uint64_t res_key, sa_res_key, key;
8465         uint8_t type;
8466         union ctl_ha_msg persis_io;
8467         int    i;
8468
8469         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8470
8471         retval = CTL_RETVAL_COMPLETE;
8472
8473         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8474         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8475         softc = lun->ctl_softc;
8476
8477         /*
8478          * We only support whole-LUN scope.  The scope & type are ignored for
8479          * register, register and ignore existing key and clear.
8480          * We sometimes ignore scope and type on preempts too!!
8481          * Verify reservation type here as well.
8482          */
8483         type = cdb->scope_type & SPR_TYPE_MASK;
8484         if ((cdb->action == SPRO_RESERVE)
8485          || (cdb->action == SPRO_RELEASE)) {
8486                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8487                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8488                                               /*sks_valid*/ 1,
8489                                               /*command*/ 1,
8490                                               /*field*/ 2,
8491                                               /*bit_valid*/ 1,
8492                                               /*bit*/ 4);
8493                         ctl_done((union ctl_io *)ctsio);
8494                         return (CTL_RETVAL_COMPLETE);
8495                 }
8496
8497                 if (type>8 || type==2 || type==4 || type==0) {
8498                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8499                                               /*sks_valid*/ 1,
8500                                               /*command*/ 1,
8501                                               /*field*/ 2,
8502                                               /*bit_valid*/ 1,
8503                                               /*bit*/ 0);
8504                         ctl_done((union ctl_io *)ctsio);
8505                         return (CTL_RETVAL_COMPLETE);
8506                 }
8507         }
8508
8509         param_len = scsi_4btoul(cdb->length);
8510
8511         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8512                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8513                 ctsio->kern_data_len = param_len;
8514                 ctsio->kern_total_len = param_len;
8515                 ctsio->kern_data_resid = 0;
8516                 ctsio->kern_rel_offset = 0;
8517                 ctsio->kern_sg_entries = 0;
8518                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8519                 ctsio->be_move_done = ctl_config_move_done;
8520                 ctl_datamove((union ctl_io *)ctsio);
8521
8522                 return (CTL_RETVAL_COMPLETE);
8523         }
8524
8525         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8526
8527         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8528         res_key = scsi_8btou64(param->res_key.key);
8529         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8530
8531         /*
8532          * Validate the reservation key here except for SPRO_REG_IGNO
8533          * This must be done for all other service actions
8534          */
8535         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8536                 mtx_lock(&lun->lun_lock);
8537                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8538                         if (res_key != key) {
8539                                 /*
8540                                  * The current key passed in doesn't match
8541                                  * the one the initiator previously
8542                                  * registered.
8543                                  */
8544                                 mtx_unlock(&lun->lun_lock);
8545                                 free(ctsio->kern_data_ptr, M_CTL);
8546                                 ctl_set_reservation_conflict(ctsio);
8547                                 ctl_done((union ctl_io *)ctsio);
8548                                 return (CTL_RETVAL_COMPLETE);
8549                         }
8550                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8551                         /*
8552                          * We are not registered
8553                          */
8554                         mtx_unlock(&lun->lun_lock);
8555                         free(ctsio->kern_data_ptr, M_CTL);
8556                         ctl_set_reservation_conflict(ctsio);
8557                         ctl_done((union ctl_io *)ctsio);
8558                         return (CTL_RETVAL_COMPLETE);
8559                 } else if (res_key != 0) {
8560                         /*
8561                          * We are not registered and trying to register but
8562                          * the register key isn't zero.
8563                          */
8564                         mtx_unlock(&lun->lun_lock);
8565                         free(ctsio->kern_data_ptr, M_CTL);
8566                         ctl_set_reservation_conflict(ctsio);
8567                         ctl_done((union ctl_io *)ctsio);
8568                         return (CTL_RETVAL_COMPLETE);
8569                 }
8570                 mtx_unlock(&lun->lun_lock);
8571         }
8572
8573         switch (cdb->action & SPRO_ACTION_MASK) {
8574         case SPRO_REGISTER:
8575         case SPRO_REG_IGNO: {
8576
8577 #if 0
8578                 printf("Registration received\n");
8579 #endif
8580
8581                 /*
8582                  * We don't support any of these options, as we report in
8583                  * the read capabilities request (see
8584                  * ctl_persistent_reserve_in(), above).
8585                  */
8586                 if ((param->flags & SPR_SPEC_I_PT)
8587                  || (param->flags & SPR_ALL_TG_PT)
8588                  || (param->flags & SPR_APTPL)) {
8589                         int bit_ptr;
8590
8591                         if (param->flags & SPR_APTPL)
8592                                 bit_ptr = 0;
8593                         else if (param->flags & SPR_ALL_TG_PT)
8594                                 bit_ptr = 2;
8595                         else /* SPR_SPEC_I_PT */
8596                                 bit_ptr = 3;
8597
8598                         free(ctsio->kern_data_ptr, M_CTL);
8599                         ctl_set_invalid_field(ctsio,
8600                                               /*sks_valid*/ 1,
8601                                               /*command*/ 0,
8602                                               /*field*/ 20,
8603                                               /*bit_valid*/ 1,
8604                                               /*bit*/ bit_ptr);
8605                         ctl_done((union ctl_io *)ctsio);
8606                         return (CTL_RETVAL_COMPLETE);
8607                 }
8608
8609                 mtx_lock(&lun->lun_lock);
8610
8611                 /*
8612                  * The initiator wants to clear the
8613                  * key/unregister.
8614                  */
8615                 if (sa_res_key == 0) {
8616                         if ((res_key == 0
8617                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8618                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8619                           && ctl_get_prkey(lun, residx) == 0)) {
8620                                 mtx_unlock(&lun->lun_lock);
8621                                 goto done;
8622                         }
8623
8624                         ctl_clr_prkey(lun, residx);
8625                         lun->pr_key_count--;
8626
8627                         if (residx == lun->pr_res_idx) {
8628                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8629                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8630
8631                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8632                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8633                                  && lun->pr_key_count) {
8634                                         /*
8635                                          * If the reservation is a registrants
8636                                          * only type we need to generate a UA
8637                                          * for other registered inits.  The
8638                                          * sense code should be RESERVATIONS
8639                                          * RELEASED
8640                                          */
8641
8642                                         for (i = softc->init_min; i < softc->init_max; i++){
8643                                                 if (ctl_get_prkey(lun, i) == 0)
8644                                                         continue;
8645                                                 ctl_est_ua(lun, i,
8646                                                     CTL_UA_RES_RELEASE);
8647                                         }
8648                                 }
8649                                 lun->res_type = 0;
8650                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8651                                 if (lun->pr_key_count==0) {
8652                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8653                                         lun->res_type = 0;
8654                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8655                                 }
8656                         }
8657                         lun->PRGeneration++;
8658                         mtx_unlock(&lun->lun_lock);
8659
8660                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8661                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8662                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8663                         persis_io.pr.pr_info.residx = residx;
8664                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8665                             sizeof(persis_io.pr), M_WAITOK);
8666                 } else /* sa_res_key != 0 */ {
8667
8668                         /*
8669                          * If we aren't registered currently then increment
8670                          * the key count and set the registered flag.
8671                          */
8672                         ctl_alloc_prkey(lun, residx);
8673                         if (ctl_get_prkey(lun, residx) == 0)
8674                                 lun->pr_key_count++;
8675                         ctl_set_prkey(lun, residx, sa_res_key);
8676                         lun->PRGeneration++;
8677                         mtx_unlock(&lun->lun_lock);
8678
8679                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8680                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8681                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8682                         persis_io.pr.pr_info.residx = residx;
8683                         memcpy(persis_io.pr.pr_info.sa_res_key,
8684                                param->serv_act_res_key,
8685                                sizeof(param->serv_act_res_key));
8686                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8687                             sizeof(persis_io.pr), M_WAITOK);
8688                 }
8689
8690                 break;
8691         }
8692         case SPRO_RESERVE:
8693 #if 0
8694                 printf("Reserve executed type %d\n", type);
8695 #endif
8696                 mtx_lock(&lun->lun_lock);
8697                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8698                         /*
8699                          * if this isn't the reservation holder and it's
8700                          * not a "all registrants" type or if the type is
8701                          * different then we have a conflict
8702                          */
8703                         if ((lun->pr_res_idx != residx
8704                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8705                          || lun->res_type != type) {
8706                                 mtx_unlock(&lun->lun_lock);
8707                                 free(ctsio->kern_data_ptr, M_CTL);
8708                                 ctl_set_reservation_conflict(ctsio);
8709                                 ctl_done((union ctl_io *)ctsio);
8710                                 return (CTL_RETVAL_COMPLETE);
8711                         }
8712                         mtx_unlock(&lun->lun_lock);
8713                 } else /* create a reservation */ {
8714                         /*
8715                          * If it's not an "all registrants" type record
8716                          * reservation holder
8717                          */
8718                         if (type != SPR_TYPE_WR_EX_AR
8719                          && type != SPR_TYPE_EX_AC_AR)
8720                                 lun->pr_res_idx = residx; /* Res holder */
8721                         else
8722                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8723
8724                         lun->flags |= CTL_LUN_PR_RESERVED;
8725                         lun->res_type = type;
8726
8727                         mtx_unlock(&lun->lun_lock);
8728
8729                         /* send msg to other side */
8730                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8731                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8732                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8733                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8734                         persis_io.pr.pr_info.res_type = type;
8735                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8736                             sizeof(persis_io.pr), M_WAITOK);
8737                 }
8738                 break;
8739
8740         case SPRO_RELEASE:
8741                 mtx_lock(&lun->lun_lock);
8742                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8743                         /* No reservation exists return good status */
8744                         mtx_unlock(&lun->lun_lock);
8745                         goto done;
8746                 }
8747                 /*
8748                  * Is this nexus a reservation holder?
8749                  */
8750                 if (lun->pr_res_idx != residx
8751                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8752                         /*
8753                          * not a res holder return good status but
8754                          * do nothing
8755                          */
8756                         mtx_unlock(&lun->lun_lock);
8757                         goto done;
8758                 }
8759
8760                 if (lun->res_type != type) {
8761                         mtx_unlock(&lun->lun_lock);
8762                         free(ctsio->kern_data_ptr, M_CTL);
8763                         ctl_set_illegal_pr_release(ctsio);
8764                         ctl_done((union ctl_io *)ctsio);
8765                         return (CTL_RETVAL_COMPLETE);
8766                 }
8767
8768                 /* okay to release */
8769                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8770                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8771                 lun->res_type = 0;
8772
8773                 /*
8774                  * if this isn't an exclusive access
8775                  * res generate UA for all other
8776                  * registrants.
8777                  */
8778                 if (type != SPR_TYPE_EX_AC
8779                  && type != SPR_TYPE_WR_EX) {
8780                         for (i = softc->init_min; i < softc->init_max; i++) {
8781                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8782                                         continue;
8783                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8784                         }
8785                 }
8786                 mtx_unlock(&lun->lun_lock);
8787
8788                 /* Send msg to other side */
8789                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8790                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8791                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8792                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8793                      sizeof(persis_io.pr), M_WAITOK);
8794                 break;
8795
8796         case SPRO_CLEAR:
8797                 /* send msg to other side */
8798
8799                 mtx_lock(&lun->lun_lock);
8800                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8801                 lun->res_type = 0;
8802                 lun->pr_key_count = 0;
8803                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8804
8805                 ctl_clr_prkey(lun, residx);
8806                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8807                         if (ctl_get_prkey(lun, i) != 0) {
8808                                 ctl_clr_prkey(lun, i);
8809                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8810                         }
8811                 lun->PRGeneration++;
8812                 mtx_unlock(&lun->lun_lock);
8813
8814                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8815                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8816                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8817                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8818                      sizeof(persis_io.pr), M_WAITOK);
8819                 break;
8820
8821         case SPRO_PREEMPT:
8822         case SPRO_PRE_ABO: {
8823                 int nretval;
8824
8825                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8826                                           residx, ctsio, cdb, param);
8827                 if (nretval != 0)
8828                         return (CTL_RETVAL_COMPLETE);
8829                 break;
8830         }
8831         default:
8832                 panic("Invalid PR type %x", cdb->action);
8833         }
8834
8835 done:
8836         free(ctsio->kern_data_ptr, M_CTL);
8837         ctl_set_success(ctsio);
8838         ctl_done((union ctl_io *)ctsio);
8839
8840         return (retval);
8841 }
8842
8843 /*
8844  * This routine is for handling a message from the other SC pertaining to
8845  * persistent reserve out. All the error checking will have been done
8846  * so only perorming the action need be done here to keep the two
8847  * in sync.
8848  */
8849 static void
8850 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8851 {
8852         struct ctl_softc *softc = control_softc;
8853         struct ctl_lun *lun;
8854         int i;
8855         uint32_t residx, targ_lun;
8856
8857         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8858         mtx_lock(&softc->ctl_lock);
8859         if ((targ_lun >= CTL_MAX_LUNS) ||
8860             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8861                 mtx_unlock(&softc->ctl_lock);
8862                 return;
8863         }
8864         mtx_lock(&lun->lun_lock);
8865         mtx_unlock(&softc->ctl_lock);
8866         if (lun->flags & CTL_LUN_DISABLED) {
8867                 mtx_unlock(&lun->lun_lock);
8868                 return;
8869         }
8870         residx = ctl_get_initindex(&msg->hdr.nexus);
8871         switch(msg->pr.pr_info.action) {
8872         case CTL_PR_REG_KEY:
8873                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8874                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8875                         lun->pr_key_count++;
8876                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8877                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8878                 lun->PRGeneration++;
8879                 break;
8880
8881         case CTL_PR_UNREG_KEY:
8882                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8883                 lun->pr_key_count--;
8884
8885                 /* XXX Need to see if the reservation has been released */
8886                 /* if so do we need to generate UA? */
8887                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8888                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8889                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8890
8891                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8892                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8893                          && lun->pr_key_count) {
8894                                 /*
8895                                  * If the reservation is a registrants
8896                                  * only type we need to generate a UA
8897                                  * for other registered inits.  The
8898                                  * sense code should be RESERVATIONS
8899                                  * RELEASED
8900                                  */
8901
8902                                 for (i = softc->init_min; i < softc->init_max; i++) {
8903                                         if (ctl_get_prkey(lun, i) == 0)
8904                                                 continue;
8905
8906                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8907                                 }
8908                         }
8909                         lun->res_type = 0;
8910                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8911                         if (lun->pr_key_count==0) {
8912                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8913                                 lun->res_type = 0;
8914                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8915                         }
8916                 }
8917                 lun->PRGeneration++;
8918                 break;
8919
8920         case CTL_PR_RESERVE:
8921                 lun->flags |= CTL_LUN_PR_RESERVED;
8922                 lun->res_type = msg->pr.pr_info.res_type;
8923                 lun->pr_res_idx = msg->pr.pr_info.residx;
8924
8925                 break;
8926
8927         case CTL_PR_RELEASE:
8928                 /*
8929                  * if this isn't an exclusive access res generate UA for all
8930                  * other registrants.
8931                  */
8932                 if (lun->res_type != SPR_TYPE_EX_AC
8933                  && lun->res_type != SPR_TYPE_WR_EX) {
8934                         for (i = softc->init_min; i < softc->init_max; i++)
8935                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8936                                         continue;
8937                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8938                 }
8939
8940                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8941                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8942                 lun->res_type = 0;
8943                 break;
8944
8945         case CTL_PR_PREEMPT:
8946                 ctl_pro_preempt_other(lun, msg);
8947                 break;
8948         case CTL_PR_CLEAR:
8949                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8950                 lun->res_type = 0;
8951                 lun->pr_key_count = 0;
8952                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8953
8954                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8955                         if (ctl_get_prkey(lun, i) == 0)
8956                                 continue;
8957                         ctl_clr_prkey(lun, i);
8958                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8959                 }
8960                 lun->PRGeneration++;
8961                 break;
8962         }
8963
8964         mtx_unlock(&lun->lun_lock);
8965 }
8966
8967 int
8968 ctl_read_write(struct ctl_scsiio *ctsio)
8969 {
8970         struct ctl_lun *lun;
8971         struct ctl_lba_len_flags *lbalen;
8972         uint64_t lba;
8973         uint32_t num_blocks;
8974         int flags, retval;
8975         int isread;
8976
8977         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8978
8979         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8980
8981         flags = 0;
8982         retval = CTL_RETVAL_COMPLETE;
8983
8984         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8985               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8986         switch (ctsio->cdb[0]) {
8987         case READ_6:
8988         case WRITE_6: {
8989                 struct scsi_rw_6 *cdb;
8990
8991                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8992
8993                 lba = scsi_3btoul(cdb->addr);
8994                 /* only 5 bits are valid in the most significant address byte */
8995                 lba &= 0x1fffff;
8996                 num_blocks = cdb->length;
8997                 /*
8998                  * This is correct according to SBC-2.
8999                  */
9000                 if (num_blocks == 0)
9001                         num_blocks = 256;
9002                 break;
9003         }
9004         case READ_10:
9005         case WRITE_10: {
9006                 struct scsi_rw_10 *cdb;
9007
9008                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9009                 if (cdb->byte2 & SRW10_FUA)
9010                         flags |= CTL_LLF_FUA;
9011                 if (cdb->byte2 & SRW10_DPO)
9012                         flags |= CTL_LLF_DPO;
9013                 lba = scsi_4btoul(cdb->addr);
9014                 num_blocks = scsi_2btoul(cdb->length);
9015                 break;
9016         }
9017         case WRITE_VERIFY_10: {
9018                 struct scsi_write_verify_10 *cdb;
9019
9020                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9021                 flags |= CTL_LLF_FUA;
9022                 if (cdb->byte2 & SWV_DPO)
9023                         flags |= CTL_LLF_DPO;
9024                 lba = scsi_4btoul(cdb->addr);
9025                 num_blocks = scsi_2btoul(cdb->length);
9026                 break;
9027         }
9028         case READ_12:
9029         case WRITE_12: {
9030                 struct scsi_rw_12 *cdb;
9031
9032                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9033                 if (cdb->byte2 & SRW12_FUA)
9034                         flags |= CTL_LLF_FUA;
9035                 if (cdb->byte2 & SRW12_DPO)
9036                         flags |= CTL_LLF_DPO;
9037                 lba = scsi_4btoul(cdb->addr);
9038                 num_blocks = scsi_4btoul(cdb->length);
9039                 break;
9040         }
9041         case WRITE_VERIFY_12: {
9042                 struct scsi_write_verify_12 *cdb;
9043
9044                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9045                 flags |= CTL_LLF_FUA;
9046                 if (cdb->byte2 & SWV_DPO)
9047                         flags |= CTL_LLF_DPO;
9048                 lba = scsi_4btoul(cdb->addr);
9049                 num_blocks = scsi_4btoul(cdb->length);
9050                 break;
9051         }
9052         case READ_16:
9053         case WRITE_16: {
9054                 struct scsi_rw_16 *cdb;
9055
9056                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9057                 if (cdb->byte2 & SRW12_FUA)
9058                         flags |= CTL_LLF_FUA;
9059                 if (cdb->byte2 & SRW12_DPO)
9060                         flags |= CTL_LLF_DPO;
9061                 lba = scsi_8btou64(cdb->addr);
9062                 num_blocks = scsi_4btoul(cdb->length);
9063                 break;
9064         }
9065         case WRITE_ATOMIC_16: {
9066                 struct scsi_write_atomic_16 *cdb;
9067
9068                 if (lun->be_lun->atomicblock == 0) {
9069                         ctl_set_invalid_opcode(ctsio);
9070                         ctl_done((union ctl_io *)ctsio);
9071                         return (CTL_RETVAL_COMPLETE);
9072                 }
9073
9074                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
9075                 if (cdb->byte2 & SRW12_FUA)
9076                         flags |= CTL_LLF_FUA;
9077                 if (cdb->byte2 & SRW12_DPO)
9078                         flags |= CTL_LLF_DPO;
9079                 lba = scsi_8btou64(cdb->addr);
9080                 num_blocks = scsi_2btoul(cdb->length);
9081                 if (num_blocks > lun->be_lun->atomicblock) {
9082                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9083                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9084                             /*bit*/ 0);
9085                         ctl_done((union ctl_io *)ctsio);
9086                         return (CTL_RETVAL_COMPLETE);
9087                 }
9088                 break;
9089         }
9090         case WRITE_VERIFY_16: {
9091                 struct scsi_write_verify_16 *cdb;
9092
9093                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9094                 flags |= CTL_LLF_FUA;
9095                 if (cdb->byte2 & SWV_DPO)
9096                         flags |= CTL_LLF_DPO;
9097                 lba = scsi_8btou64(cdb->addr);
9098                 num_blocks = scsi_4btoul(cdb->length);
9099                 break;
9100         }
9101         default:
9102                 /*
9103                  * We got a command we don't support.  This shouldn't
9104                  * happen, commands should be filtered out above us.
9105                  */
9106                 ctl_set_invalid_opcode(ctsio);
9107                 ctl_done((union ctl_io *)ctsio);
9108
9109                 return (CTL_RETVAL_COMPLETE);
9110                 break; /* NOTREACHED */
9111         }
9112
9113         /*
9114          * The first check is to make sure we're in bounds, the second
9115          * check is to catch wrap-around problems.  If the lba + num blocks
9116          * is less than the lba, then we've wrapped around and the block
9117          * range is invalid anyway.
9118          */
9119         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9120          || ((lba + num_blocks) < lba)) {
9121                 ctl_set_lba_out_of_range(ctsio);
9122                 ctl_done((union ctl_io *)ctsio);
9123                 return (CTL_RETVAL_COMPLETE);
9124         }
9125
9126         /*
9127          * According to SBC-3, a transfer length of 0 is not an error.
9128          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9129          * translates to 256 blocks for those commands.
9130          */
9131         if (num_blocks == 0) {
9132                 ctl_set_success(ctsio);
9133                 ctl_done((union ctl_io *)ctsio);
9134                 return (CTL_RETVAL_COMPLETE);
9135         }
9136
9137         /* Set FUA and/or DPO if caches are disabled. */
9138         if (isread) {
9139                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9140                     SCP_RCD) != 0)
9141                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9142         } else {
9143                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9144                     SCP_WCE) == 0)
9145                         flags |= CTL_LLF_FUA;
9146         }
9147
9148         lbalen = (struct ctl_lba_len_flags *)
9149             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9150         lbalen->lba = lba;
9151         lbalen->len = num_blocks;
9152         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9153
9154         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9155         ctsio->kern_rel_offset = 0;
9156
9157         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9158
9159         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9160
9161         return (retval);
9162 }
9163
9164 static int
9165 ctl_cnw_cont(union ctl_io *io)
9166 {
9167         struct ctl_scsiio *ctsio;
9168         struct ctl_lun *lun;
9169         struct ctl_lba_len_flags *lbalen;
9170         int retval;
9171
9172         ctsio = &io->scsiio;
9173         ctsio->io_hdr.status = CTL_STATUS_NONE;
9174         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9175         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9176         lbalen = (struct ctl_lba_len_flags *)
9177             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9178         lbalen->flags &= ~CTL_LLF_COMPARE;
9179         lbalen->flags |= CTL_LLF_WRITE;
9180
9181         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9182         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9183         return (retval);
9184 }
9185
9186 int
9187 ctl_cnw(struct ctl_scsiio *ctsio)
9188 {
9189         struct ctl_lun *lun;
9190         struct ctl_lba_len_flags *lbalen;
9191         uint64_t lba;
9192         uint32_t num_blocks;
9193         int flags, retval;
9194
9195         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9196
9197         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9198
9199         flags = 0;
9200         retval = CTL_RETVAL_COMPLETE;
9201
9202         switch (ctsio->cdb[0]) {
9203         case COMPARE_AND_WRITE: {
9204                 struct scsi_compare_and_write *cdb;
9205
9206                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9207                 if (cdb->byte2 & SRW10_FUA)
9208                         flags |= CTL_LLF_FUA;
9209                 if (cdb->byte2 & SRW10_DPO)
9210                         flags |= CTL_LLF_DPO;
9211                 lba = scsi_8btou64(cdb->addr);
9212                 num_blocks = cdb->length;
9213                 break;
9214         }
9215         default:
9216                 /*
9217                  * We got a command we don't support.  This shouldn't
9218                  * happen, commands should be filtered out above us.
9219                  */
9220                 ctl_set_invalid_opcode(ctsio);
9221                 ctl_done((union ctl_io *)ctsio);
9222
9223                 return (CTL_RETVAL_COMPLETE);
9224                 break; /* NOTREACHED */
9225         }
9226
9227         /*
9228          * The first check is to make sure we're in bounds, the second
9229          * check is to catch wrap-around problems.  If the lba + num blocks
9230          * is less than the lba, then we've wrapped around and the block
9231          * range is invalid anyway.
9232          */
9233         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9234          || ((lba + num_blocks) < lba)) {
9235                 ctl_set_lba_out_of_range(ctsio);
9236                 ctl_done((union ctl_io *)ctsio);
9237                 return (CTL_RETVAL_COMPLETE);
9238         }
9239
9240         /*
9241          * According to SBC-3, a transfer length of 0 is not an error.
9242          */
9243         if (num_blocks == 0) {
9244                 ctl_set_success(ctsio);
9245                 ctl_done((union ctl_io *)ctsio);
9246                 return (CTL_RETVAL_COMPLETE);
9247         }
9248
9249         /* Set FUA if write cache is disabled. */
9250         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9251             SCP_WCE) == 0)
9252                 flags |= CTL_LLF_FUA;
9253
9254         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9255         ctsio->kern_rel_offset = 0;
9256
9257         /*
9258          * Set the IO_CONT flag, so that if this I/O gets passed to
9259          * ctl_data_submit_done(), it'll get passed back to
9260          * ctl_ctl_cnw_cont() for further processing.
9261          */
9262         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9263         ctsio->io_cont = ctl_cnw_cont;
9264
9265         lbalen = (struct ctl_lba_len_flags *)
9266             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9267         lbalen->lba = lba;
9268         lbalen->len = num_blocks;
9269         lbalen->flags = CTL_LLF_COMPARE | flags;
9270
9271         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9272         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9273         return (retval);
9274 }
9275
9276 int
9277 ctl_verify(struct ctl_scsiio *ctsio)
9278 {
9279         struct ctl_lun *lun;
9280         struct ctl_lba_len_flags *lbalen;
9281         uint64_t lba;
9282         uint32_t num_blocks;
9283         int bytchk, flags;
9284         int retval;
9285
9286         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9287
9288         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9289
9290         bytchk = 0;
9291         flags = CTL_LLF_FUA;
9292         retval = CTL_RETVAL_COMPLETE;
9293
9294         switch (ctsio->cdb[0]) {
9295         case VERIFY_10: {
9296                 struct scsi_verify_10 *cdb;
9297
9298                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9299                 if (cdb->byte2 & SVFY_BYTCHK)
9300                         bytchk = 1;
9301                 if (cdb->byte2 & SVFY_DPO)
9302                         flags |= CTL_LLF_DPO;
9303                 lba = scsi_4btoul(cdb->addr);
9304                 num_blocks = scsi_2btoul(cdb->length);
9305                 break;
9306         }
9307         case VERIFY_12: {
9308                 struct scsi_verify_12 *cdb;
9309
9310                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9311                 if (cdb->byte2 & SVFY_BYTCHK)
9312                         bytchk = 1;
9313                 if (cdb->byte2 & SVFY_DPO)
9314                         flags |= CTL_LLF_DPO;
9315                 lba = scsi_4btoul(cdb->addr);
9316                 num_blocks = scsi_4btoul(cdb->length);
9317                 break;
9318         }
9319         case VERIFY_16: {
9320                 struct scsi_rw_16 *cdb;
9321
9322                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9323                 if (cdb->byte2 & SVFY_BYTCHK)
9324                         bytchk = 1;
9325                 if (cdb->byte2 & SVFY_DPO)
9326                         flags |= CTL_LLF_DPO;
9327                 lba = scsi_8btou64(cdb->addr);
9328                 num_blocks = scsi_4btoul(cdb->length);
9329                 break;
9330         }
9331         default:
9332                 /*
9333                  * We got a command we don't support.  This shouldn't
9334                  * happen, commands should be filtered out above us.
9335                  */
9336                 ctl_set_invalid_opcode(ctsio);
9337                 ctl_done((union ctl_io *)ctsio);
9338                 return (CTL_RETVAL_COMPLETE);
9339         }
9340
9341         /*
9342          * The first check is to make sure we're in bounds, the second
9343          * check is to catch wrap-around problems.  If the lba + num blocks
9344          * is less than the lba, then we've wrapped around and the block
9345          * range is invalid anyway.
9346          */
9347         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9348          || ((lba + num_blocks) < lba)) {
9349                 ctl_set_lba_out_of_range(ctsio);
9350                 ctl_done((union ctl_io *)ctsio);
9351                 return (CTL_RETVAL_COMPLETE);
9352         }
9353
9354         /*
9355          * According to SBC-3, a transfer length of 0 is not an error.
9356          */
9357         if (num_blocks == 0) {
9358                 ctl_set_success(ctsio);
9359                 ctl_done((union ctl_io *)ctsio);
9360                 return (CTL_RETVAL_COMPLETE);
9361         }
9362
9363         lbalen = (struct ctl_lba_len_flags *)
9364             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9365         lbalen->lba = lba;
9366         lbalen->len = num_blocks;
9367         if (bytchk) {
9368                 lbalen->flags = CTL_LLF_COMPARE | flags;
9369                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9370         } else {
9371                 lbalen->flags = CTL_LLF_VERIFY | flags;
9372                 ctsio->kern_total_len = 0;
9373         }
9374         ctsio->kern_rel_offset = 0;
9375
9376         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9377         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9378         return (retval);
9379 }
9380
9381 int
9382 ctl_report_luns(struct ctl_scsiio *ctsio)
9383 {
9384         struct ctl_softc *softc;
9385         struct scsi_report_luns *cdb;
9386         struct scsi_report_luns_data *lun_data;
9387         struct ctl_lun *lun, *request_lun;
9388         struct ctl_port *port;
9389         int num_luns, retval;
9390         uint32_t alloc_len, lun_datalen;
9391         int num_filled;
9392         uint32_t initidx, targ_lun_id, lun_id;
9393
9394         retval = CTL_RETVAL_COMPLETE;
9395         cdb = (struct scsi_report_luns *)ctsio->cdb;
9396         port = ctl_io_port(&ctsio->io_hdr);
9397         softc = port->ctl_softc;
9398
9399         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9400
9401         mtx_lock(&softc->ctl_lock);
9402         num_luns = 0;
9403         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9404                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9405                         num_luns++;
9406         }
9407         mtx_unlock(&softc->ctl_lock);
9408
9409         switch (cdb->select_report) {
9410         case RPL_REPORT_DEFAULT:
9411         case RPL_REPORT_ALL:
9412         case RPL_REPORT_NONSUBSID:
9413                 break;
9414         case RPL_REPORT_WELLKNOWN:
9415         case RPL_REPORT_ADMIN:
9416         case RPL_REPORT_CONGLOM:
9417                 num_luns = 0;
9418                 break;
9419         default:
9420                 ctl_set_invalid_field(ctsio,
9421                                       /*sks_valid*/ 1,
9422                                       /*command*/ 1,
9423                                       /*field*/ 2,
9424                                       /*bit_valid*/ 0,
9425                                       /*bit*/ 0);
9426                 ctl_done((union ctl_io *)ctsio);
9427                 return (retval);
9428                 break; /* NOTREACHED */
9429         }
9430
9431         alloc_len = scsi_4btoul(cdb->length);
9432         /*
9433          * The initiator has to allocate at least 16 bytes for this request,
9434          * so he can at least get the header and the first LUN.  Otherwise
9435          * we reject the request (per SPC-3 rev 14, section 6.21).
9436          */
9437         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9438             sizeof(struct scsi_report_luns_lundata))) {
9439                 ctl_set_invalid_field(ctsio,
9440                                       /*sks_valid*/ 1,
9441                                       /*command*/ 1,
9442                                       /*field*/ 6,
9443                                       /*bit_valid*/ 0,
9444                                       /*bit*/ 0);
9445                 ctl_done((union ctl_io *)ctsio);
9446                 return (retval);
9447         }
9448
9449         request_lun = (struct ctl_lun *)
9450                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9451
9452         lun_datalen = sizeof(*lun_data) +
9453                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9454
9455         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9456         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9457         ctsio->kern_sg_entries = 0;
9458
9459         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9460
9461         mtx_lock(&softc->ctl_lock);
9462         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9463                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9464                 if (lun_id >= CTL_MAX_LUNS)
9465                         continue;
9466                 lun = softc->ctl_luns[lun_id];
9467                 if (lun == NULL)
9468                         continue;
9469
9470                 if (targ_lun_id <= 0xff) {
9471                         /*
9472                          * Peripheral addressing method, bus number 0.
9473                          */
9474                         lun_data->luns[num_filled].lundata[0] =
9475                                 RPL_LUNDATA_ATYP_PERIPH;
9476                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9477                         num_filled++;
9478                 } else if (targ_lun_id <= 0x3fff) {
9479                         /*
9480                          * Flat addressing method.
9481                          */
9482                         lun_data->luns[num_filled].lundata[0] =
9483                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9484                         lun_data->luns[num_filled].lundata[1] =
9485                                 (targ_lun_id & 0xff);
9486                         num_filled++;
9487                 } else if (targ_lun_id <= 0xffffff) {
9488                         /*
9489                          * Extended flat addressing method.
9490                          */
9491                         lun_data->luns[num_filled].lundata[0] =
9492                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9493                         scsi_ulto3b(targ_lun_id,
9494                             &lun_data->luns[num_filled].lundata[1]);
9495                         num_filled++;
9496                 } else {
9497                         printf("ctl_report_luns: bogus LUN number %jd, "
9498                                "skipping\n", (intmax_t)targ_lun_id);
9499                 }
9500                 /*
9501                  * According to SPC-3, rev 14 section 6.21:
9502                  *
9503                  * "The execution of a REPORT LUNS command to any valid and
9504                  * installed logical unit shall clear the REPORTED LUNS DATA
9505                  * HAS CHANGED unit attention condition for all logical
9506                  * units of that target with respect to the requesting
9507                  * initiator. A valid and installed logical unit is one
9508                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9509                  * INQUIRY data (see 6.4.2)."
9510                  *
9511                  * If request_lun is NULL, the LUN this report luns command
9512                  * was issued to is either disabled or doesn't exist. In that
9513                  * case, we shouldn't clear any pending lun change unit
9514                  * attention.
9515                  */
9516                 if (request_lun != NULL) {
9517                         mtx_lock(&lun->lun_lock);
9518                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9519                         mtx_unlock(&lun->lun_lock);
9520                 }
9521         }
9522         mtx_unlock(&softc->ctl_lock);
9523
9524         /*
9525          * It's quite possible that we've returned fewer LUNs than we allocated
9526          * space for.  Trim it.
9527          */
9528         lun_datalen = sizeof(*lun_data) +
9529                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9530
9531         if (lun_datalen < alloc_len) {
9532                 ctsio->residual = alloc_len - lun_datalen;
9533                 ctsio->kern_data_len = lun_datalen;
9534                 ctsio->kern_total_len = lun_datalen;
9535         } else {
9536                 ctsio->residual = 0;
9537                 ctsio->kern_data_len = alloc_len;
9538                 ctsio->kern_total_len = alloc_len;
9539         }
9540         ctsio->kern_data_resid = 0;
9541         ctsio->kern_rel_offset = 0;
9542         ctsio->kern_sg_entries = 0;
9543
9544         /*
9545          * We set this to the actual data length, regardless of how much
9546          * space we actually have to return results.  If the user looks at
9547          * this value, he'll know whether or not he allocated enough space
9548          * and reissue the command if necessary.  We don't support well
9549          * known logical units, so if the user asks for that, return none.
9550          */
9551         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9552
9553         /*
9554          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9555          * this request.
9556          */
9557         ctl_set_success(ctsio);
9558         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9559         ctsio->be_move_done = ctl_config_move_done;
9560         ctl_datamove((union ctl_io *)ctsio);
9561         return (retval);
9562 }
9563
9564 int
9565 ctl_request_sense(struct ctl_scsiio *ctsio)
9566 {
9567         struct scsi_request_sense *cdb;
9568         struct scsi_sense_data *sense_ptr;
9569         struct ctl_softc *ctl_softc;
9570         struct ctl_lun *lun;
9571         uint32_t initidx;
9572         int have_error;
9573         scsi_sense_data_type sense_format;
9574         ctl_ua_type ua_type;
9575
9576         cdb = (struct scsi_request_sense *)ctsio->cdb;
9577
9578         ctl_softc = control_softc;
9579         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9580
9581         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9582
9583         /*
9584          * Determine which sense format the user wants.
9585          */
9586         if (cdb->byte2 & SRS_DESC)
9587                 sense_format = SSD_TYPE_DESC;
9588         else
9589                 sense_format = SSD_TYPE_FIXED;
9590
9591         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9592         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9593         ctsio->kern_sg_entries = 0;
9594
9595         /*
9596          * struct scsi_sense_data, which is currently set to 256 bytes, is
9597          * larger than the largest allowed value for the length field in the
9598          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9599          */
9600         ctsio->residual = 0;
9601         ctsio->kern_data_len = cdb->length;
9602         ctsio->kern_total_len = cdb->length;
9603
9604         ctsio->kern_data_resid = 0;
9605         ctsio->kern_rel_offset = 0;
9606         ctsio->kern_sg_entries = 0;
9607
9608         /*
9609          * If we don't have a LUN, we don't have any pending sense.
9610          */
9611         if (lun == NULL)
9612                 goto no_sense;
9613
9614         have_error = 0;
9615         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9616         /*
9617          * Check for pending sense, and then for pending unit attentions.
9618          * Pending sense gets returned first, then pending unit attentions.
9619          */
9620         mtx_lock(&lun->lun_lock);
9621 #ifdef CTL_WITH_CA
9622         if (ctl_is_set(lun->have_ca, initidx)) {
9623                 scsi_sense_data_type stored_format;
9624
9625                 /*
9626                  * Check to see which sense format was used for the stored
9627                  * sense data.
9628                  */
9629                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9630
9631                 /*
9632                  * If the user requested a different sense format than the
9633                  * one we stored, then we need to convert it to the other
9634                  * format.  If we're going from descriptor to fixed format
9635                  * sense data, we may lose things in translation, depending
9636                  * on what options were used.
9637                  *
9638                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9639                  * for some reason we'll just copy it out as-is.
9640                  */
9641                 if ((stored_format == SSD_TYPE_FIXED)
9642                  && (sense_format == SSD_TYPE_DESC))
9643                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9644                             &lun->pending_sense[initidx],
9645                             (struct scsi_sense_data_desc *)sense_ptr);
9646                 else if ((stored_format == SSD_TYPE_DESC)
9647                       && (sense_format == SSD_TYPE_FIXED))
9648                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9649                             &lun->pending_sense[initidx],
9650                             (struct scsi_sense_data_fixed *)sense_ptr);
9651                 else
9652                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9653                                MIN(sizeof(*sense_ptr),
9654                                sizeof(lun->pending_sense[initidx])));
9655
9656                 ctl_clear_mask(lun->have_ca, initidx);
9657                 have_error = 1;
9658         } else
9659 #endif
9660         {
9661                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9662                 if (ua_type != CTL_UA_NONE)
9663                         have_error = 1;
9664                 if (ua_type == CTL_UA_LUN_CHANGE) {
9665                         mtx_unlock(&lun->lun_lock);
9666                         mtx_lock(&ctl_softc->ctl_lock);
9667                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9668                         mtx_unlock(&ctl_softc->ctl_lock);
9669                         mtx_lock(&lun->lun_lock);
9670                 }
9671
9672         }
9673         mtx_unlock(&lun->lun_lock);
9674
9675         /*
9676          * We already have a pending error, return it.
9677          */
9678         if (have_error != 0) {
9679                 /*
9680                  * We report the SCSI status as OK, since the status of the
9681                  * request sense command itself is OK.
9682                  * We report 0 for the sense length, because we aren't doing
9683                  * autosense in this case.  We're reporting sense as
9684                  * parameter data.
9685                  */
9686                 ctl_set_success(ctsio);
9687                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9688                 ctsio->be_move_done = ctl_config_move_done;
9689                 ctl_datamove((union ctl_io *)ctsio);
9690                 return (CTL_RETVAL_COMPLETE);
9691         }
9692
9693 no_sense:
9694
9695         /*
9696          * No sense information to report, so we report that everything is
9697          * okay.
9698          */
9699         ctl_set_sense_data(sense_ptr,
9700                            lun,
9701                            sense_format,
9702                            /*current_error*/ 1,
9703                            /*sense_key*/ SSD_KEY_NO_SENSE,
9704                            /*asc*/ 0x00,
9705                            /*ascq*/ 0x00,
9706                            SSD_ELEM_NONE);
9707
9708         /*
9709          * We report 0 for the sense length, because we aren't doing
9710          * autosense in this case.  We're reporting sense as parameter data.
9711          */
9712         ctl_set_success(ctsio);
9713         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9714         ctsio->be_move_done = ctl_config_move_done;
9715         ctl_datamove((union ctl_io *)ctsio);
9716         return (CTL_RETVAL_COMPLETE);
9717 }
9718
9719 int
9720 ctl_tur(struct ctl_scsiio *ctsio)
9721 {
9722
9723         CTL_DEBUG_PRINT(("ctl_tur\n"));
9724
9725         ctl_set_success(ctsio);
9726         ctl_done((union ctl_io *)ctsio);
9727
9728         return (CTL_RETVAL_COMPLETE);
9729 }
9730
9731 /*
9732  * SCSI VPD page 0x00, the Supported VPD Pages page.
9733  */
9734 static int
9735 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9736 {
9737         struct scsi_vpd_supported_pages *pages;
9738         int sup_page_size;
9739         struct ctl_lun *lun;
9740         int p;
9741
9742         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9743
9744         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9745             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9746         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9747         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9748         ctsio->kern_sg_entries = 0;
9749
9750         if (sup_page_size < alloc_len) {
9751                 ctsio->residual = alloc_len - sup_page_size;
9752                 ctsio->kern_data_len = sup_page_size;
9753                 ctsio->kern_total_len = sup_page_size;
9754         } else {
9755                 ctsio->residual = 0;
9756                 ctsio->kern_data_len = alloc_len;
9757                 ctsio->kern_total_len = alloc_len;
9758         }
9759         ctsio->kern_data_resid = 0;
9760         ctsio->kern_rel_offset = 0;
9761         ctsio->kern_sg_entries = 0;
9762
9763         /*
9764          * The control device is always connected.  The disk device, on the
9765          * other hand, may not be online all the time.  Need to change this
9766          * to figure out whether the disk device is actually online or not.
9767          */
9768         if (lun != NULL)
9769                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9770                                 lun->be_lun->lun_type;
9771         else
9772                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9773
9774         p = 0;
9775         /* Supported VPD pages */
9776         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9777         /* Serial Number */
9778         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9779         /* Device Identification */
9780         pages->page_list[p++] = SVPD_DEVICE_ID;
9781         /* Extended INQUIRY Data */
9782         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9783         /* Mode Page Policy */
9784         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9785         /* SCSI Ports */
9786         pages->page_list[p++] = SVPD_SCSI_PORTS;
9787         /* Third-party Copy */
9788         pages->page_list[p++] = SVPD_SCSI_TPC;
9789         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9790                 /* Block limits */
9791                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9792                 /* Block Device Characteristics */
9793                 pages->page_list[p++] = SVPD_BDC;
9794                 /* Logical Block Provisioning */
9795                 pages->page_list[p++] = SVPD_LBP;
9796         }
9797         pages->length = p;
9798
9799         ctl_set_success(ctsio);
9800         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9801         ctsio->be_move_done = ctl_config_move_done;
9802         ctl_datamove((union ctl_io *)ctsio);
9803         return (CTL_RETVAL_COMPLETE);
9804 }
9805
9806 /*
9807  * SCSI VPD page 0x80, the Unit Serial Number page.
9808  */
9809 static int
9810 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9811 {
9812         struct scsi_vpd_unit_serial_number *sn_ptr;
9813         struct ctl_lun *lun;
9814         int data_len;
9815
9816         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9817
9818         data_len = 4 + CTL_SN_LEN;
9819         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9820         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9821         if (data_len < alloc_len) {
9822                 ctsio->residual = alloc_len - data_len;
9823                 ctsio->kern_data_len = data_len;
9824                 ctsio->kern_total_len = data_len;
9825         } else {
9826                 ctsio->residual = 0;
9827                 ctsio->kern_data_len = alloc_len;
9828                 ctsio->kern_total_len = alloc_len;
9829         }
9830         ctsio->kern_data_resid = 0;
9831         ctsio->kern_rel_offset = 0;
9832         ctsio->kern_sg_entries = 0;
9833
9834         /*
9835          * The control device is always connected.  The disk device, on the
9836          * other hand, may not be online all the time.  Need to change this
9837          * to figure out whether the disk device is actually online or not.
9838          */
9839         if (lun != NULL)
9840                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9841                                   lun->be_lun->lun_type;
9842         else
9843                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9844
9845         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9846         sn_ptr->length = CTL_SN_LEN;
9847         /*
9848          * If we don't have a LUN, we just leave the serial number as
9849          * all spaces.
9850          */
9851         if (lun != NULL) {
9852                 strncpy((char *)sn_ptr->serial_num,
9853                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9854         } else
9855                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9856
9857         ctl_set_success(ctsio);
9858         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9859         ctsio->be_move_done = ctl_config_move_done;
9860         ctl_datamove((union ctl_io *)ctsio);
9861         return (CTL_RETVAL_COMPLETE);
9862 }
9863
9864
9865 /*
9866  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9867  */
9868 static int
9869 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9870 {
9871         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9872         struct ctl_lun *lun;
9873         int data_len;
9874
9875         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9876
9877         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9878         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9879         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9880         ctsio->kern_sg_entries = 0;
9881
9882         if (data_len < alloc_len) {
9883                 ctsio->residual = alloc_len - data_len;
9884                 ctsio->kern_data_len = data_len;
9885                 ctsio->kern_total_len = data_len;
9886         } else {
9887                 ctsio->residual = 0;
9888                 ctsio->kern_data_len = alloc_len;
9889                 ctsio->kern_total_len = alloc_len;
9890         }
9891         ctsio->kern_data_resid = 0;
9892         ctsio->kern_rel_offset = 0;
9893         ctsio->kern_sg_entries = 0;
9894
9895         /*
9896          * The control device is always connected.  The disk device, on the
9897          * other hand, may not be online all the time.
9898          */
9899         if (lun != NULL)
9900                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9901                                      lun->be_lun->lun_type;
9902         else
9903                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9904         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9905         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9906         /*
9907          * We support head of queue, ordered and simple tags.
9908          */
9909         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9910         /*
9911          * Volatile cache supported.
9912          */
9913         eid_ptr->flags3 = SVPD_EID_V_SUP;
9914
9915         /*
9916          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9917          * attention for a particular IT nexus on all LUNs once we report
9918          * it to that nexus once.  This bit is required as of SPC-4.
9919          */
9920         eid_ptr->flags4 = SVPD_EID_LUICLT;
9921
9922         /*
9923          * XXX KDM in order to correctly answer this, we would need
9924          * information from the SIM to determine how much sense data it
9925          * can send.  So this would really be a path inquiry field, most
9926          * likely.  This can be set to a maximum of 252 according to SPC-4,
9927          * but the hardware may or may not be able to support that much.
9928          * 0 just means that the maximum sense data length is not reported.
9929          */
9930         eid_ptr->max_sense_length = 0;
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_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9941 {
9942         struct scsi_vpd_mode_page_policy *mpp_ptr;
9943         struct ctl_lun *lun;
9944         int data_len;
9945
9946         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9947
9948         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9949             sizeof(struct scsi_vpd_mode_page_policy_descr);
9950
9951         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9952         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9953         ctsio->kern_sg_entries = 0;
9954
9955         if (data_len < alloc_len) {
9956                 ctsio->residual = alloc_len - data_len;
9957                 ctsio->kern_data_len = data_len;
9958                 ctsio->kern_total_len = data_len;
9959         } else {
9960                 ctsio->residual = 0;
9961                 ctsio->kern_data_len = alloc_len;
9962                 ctsio->kern_total_len = alloc_len;
9963         }
9964         ctsio->kern_data_resid = 0;
9965         ctsio->kern_rel_offset = 0;
9966         ctsio->kern_sg_entries = 0;
9967
9968         /*
9969          * The control device is always connected.  The disk device, on the
9970          * other hand, may not be online all the time.
9971          */
9972         if (lun != NULL)
9973                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9974                                      lun->be_lun->lun_type;
9975         else
9976                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9977         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9978         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9979         mpp_ptr->descr[0].page_code = 0x3f;
9980         mpp_ptr->descr[0].subpage_code = 0xff;
9981         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9982
9983         ctl_set_success(ctsio);
9984         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9985         ctsio->be_move_done = ctl_config_move_done;
9986         ctl_datamove((union ctl_io *)ctsio);
9987         return (CTL_RETVAL_COMPLETE);
9988 }
9989
9990 /*
9991  * SCSI VPD page 0x83, the Device Identification page.
9992  */
9993 static int
9994 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9995 {
9996         struct scsi_vpd_device_id *devid_ptr;
9997         struct scsi_vpd_id_descriptor *desc;
9998         struct ctl_softc *softc;
9999         struct ctl_lun *lun;
10000         struct ctl_port *port;
10001         int data_len;
10002         uint8_t proto;
10003
10004         softc = control_softc;
10005
10006         port = ctl_io_port(&ctsio->io_hdr);
10007         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10008
10009         data_len = sizeof(struct scsi_vpd_device_id) +
10010             sizeof(struct scsi_vpd_id_descriptor) +
10011                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10012             sizeof(struct scsi_vpd_id_descriptor) +
10013                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10014         if (lun && lun->lun_devid)
10015                 data_len += lun->lun_devid->len;
10016         if (port && port->port_devid)
10017                 data_len += port->port_devid->len;
10018         if (port && port->target_devid)
10019                 data_len += port->target_devid->len;
10020
10021         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10022         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10023         ctsio->kern_sg_entries = 0;
10024
10025         if (data_len < alloc_len) {
10026                 ctsio->residual = alloc_len - data_len;
10027                 ctsio->kern_data_len = data_len;
10028                 ctsio->kern_total_len = data_len;
10029         } else {
10030                 ctsio->residual = 0;
10031                 ctsio->kern_data_len = alloc_len;
10032                 ctsio->kern_total_len = alloc_len;
10033         }
10034         ctsio->kern_data_resid = 0;
10035         ctsio->kern_rel_offset = 0;
10036         ctsio->kern_sg_entries = 0;
10037
10038         /*
10039          * The control device is always connected.  The disk device, on the
10040          * other hand, may not be online all the time.
10041          */
10042         if (lun != NULL)
10043                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10044                                      lun->be_lun->lun_type;
10045         else
10046                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10047         devid_ptr->page_code = SVPD_DEVICE_ID;
10048         scsi_ulto2b(data_len - 4, devid_ptr->length);
10049
10050         if (port && port->port_type == CTL_PORT_FC)
10051                 proto = SCSI_PROTO_FC << 4;
10052         else if (port && port->port_type == CTL_PORT_ISCSI)
10053                 proto = SCSI_PROTO_ISCSI << 4;
10054         else
10055                 proto = SCSI_PROTO_SPI << 4;
10056         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10057
10058         /*
10059          * We're using a LUN association here.  i.e., this device ID is a
10060          * per-LUN identifier.
10061          */
10062         if (lun && lun->lun_devid) {
10063                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10064                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10065                     lun->lun_devid->len);
10066         }
10067
10068         /*
10069          * This is for the WWPN which is a port association.
10070          */
10071         if (port && port->port_devid) {
10072                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10073                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10074                     port->port_devid->len);
10075         }
10076
10077         /*
10078          * This is for the Relative Target Port(type 4h) identifier
10079          */
10080         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10081         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10082             SVPD_ID_TYPE_RELTARG;
10083         desc->length = 4;
10084         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10085         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10086             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10087
10088         /*
10089          * This is for the Target Port Group(type 5h) identifier
10090          */
10091         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10092         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10093             SVPD_ID_TYPE_TPORTGRP;
10094         desc->length = 4;
10095         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
10096             &desc->identifier[2]);
10097         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10098             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10099
10100         /*
10101          * This is for the Target identifier
10102          */
10103         if (port && port->target_devid) {
10104                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10105         }
10106
10107         ctl_set_success(ctsio);
10108         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10109         ctsio->be_move_done = ctl_config_move_done;
10110         ctl_datamove((union ctl_io *)ctsio);
10111         return (CTL_RETVAL_COMPLETE);
10112 }
10113
10114 static int
10115 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10116 {
10117         struct ctl_softc *softc = control_softc;
10118         struct scsi_vpd_scsi_ports *sp;
10119         struct scsi_vpd_port_designation *pd;
10120         struct scsi_vpd_port_designation_cont *pdc;
10121         struct ctl_lun *lun;
10122         struct ctl_port *port;
10123         int data_len, num_target_ports, iid_len, id_len;
10124
10125         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10126
10127         num_target_ports = 0;
10128         iid_len = 0;
10129         id_len = 0;
10130         mtx_lock(&softc->ctl_lock);
10131         STAILQ_FOREACH(port, &softc->port_list, links) {
10132                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10133                         continue;
10134                 if (lun != NULL &&
10135                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10136                         continue;
10137                 num_target_ports++;
10138                 if (port->init_devid)
10139                         iid_len += port->init_devid->len;
10140                 if (port->port_devid)
10141                         id_len += port->port_devid->len;
10142         }
10143         mtx_unlock(&softc->ctl_lock);
10144
10145         data_len = sizeof(struct scsi_vpd_scsi_ports) +
10146             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10147              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10148         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10149         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10150         ctsio->kern_sg_entries = 0;
10151
10152         if (data_len < alloc_len) {
10153                 ctsio->residual = alloc_len - data_len;
10154                 ctsio->kern_data_len = data_len;
10155                 ctsio->kern_total_len = data_len;
10156         } else {
10157                 ctsio->residual = 0;
10158                 ctsio->kern_data_len = alloc_len;
10159                 ctsio->kern_total_len = alloc_len;
10160         }
10161         ctsio->kern_data_resid = 0;
10162         ctsio->kern_rel_offset = 0;
10163         ctsio->kern_sg_entries = 0;
10164
10165         /*
10166          * The control device is always connected.  The disk device, on the
10167          * other hand, may not be online all the time.  Need to change this
10168          * to figure out whether the disk device is actually online or not.
10169          */
10170         if (lun != NULL)
10171                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10172                                   lun->be_lun->lun_type;
10173         else
10174                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10175
10176         sp->page_code = SVPD_SCSI_PORTS;
10177         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10178             sp->page_length);
10179         pd = &sp->design[0];
10180
10181         mtx_lock(&softc->ctl_lock);
10182         STAILQ_FOREACH(port, &softc->port_list, links) {
10183                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10184                         continue;
10185                 if (lun != NULL &&
10186                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10187                         continue;
10188                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
10189                 if (port->init_devid) {
10190                         iid_len = port->init_devid->len;
10191                         memcpy(pd->initiator_transportid,
10192                             port->init_devid->data, port->init_devid->len);
10193                 } else
10194                         iid_len = 0;
10195                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10196                 pdc = (struct scsi_vpd_port_designation_cont *)
10197                     (&pd->initiator_transportid[iid_len]);
10198                 if (port->port_devid) {
10199                         id_len = port->port_devid->len;
10200                         memcpy(pdc->target_port_descriptors,
10201                             port->port_devid->data, port->port_devid->len);
10202                 } else
10203                         id_len = 0;
10204                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10205                 pd = (struct scsi_vpd_port_designation *)
10206                     ((uint8_t *)pdc->target_port_descriptors + id_len);
10207         }
10208         mtx_unlock(&softc->ctl_lock);
10209
10210         ctl_set_success(ctsio);
10211         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10212         ctsio->be_move_done = ctl_config_move_done;
10213         ctl_datamove((union ctl_io *)ctsio);
10214         return (CTL_RETVAL_COMPLETE);
10215 }
10216
10217 static int
10218 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10219 {
10220         struct scsi_vpd_block_limits *bl_ptr;
10221         struct ctl_lun *lun;
10222         int bs;
10223
10224         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10225
10226         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10227         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10228         ctsio->kern_sg_entries = 0;
10229
10230         if (sizeof(*bl_ptr) < alloc_len) {
10231                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10232                 ctsio->kern_data_len = sizeof(*bl_ptr);
10233                 ctsio->kern_total_len = sizeof(*bl_ptr);
10234         } else {
10235                 ctsio->residual = 0;
10236                 ctsio->kern_data_len = alloc_len;
10237                 ctsio->kern_total_len = alloc_len;
10238         }
10239         ctsio->kern_data_resid = 0;
10240         ctsio->kern_rel_offset = 0;
10241         ctsio->kern_sg_entries = 0;
10242
10243         /*
10244          * The control device is always connected.  The disk device, on the
10245          * other hand, may not be online all the time.  Need to change this
10246          * to figure out whether the disk device is actually online or not.
10247          */
10248         if (lun != NULL)
10249                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10250                                   lun->be_lun->lun_type;
10251         else
10252                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10253
10254         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10255         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10256         bl_ptr->max_cmp_write_len = 0xff;
10257         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10258         if (lun != NULL) {
10259                 bs = lun->be_lun->blocksize;
10260                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10261                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10262                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10263                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10264                         if (lun->be_lun->ublockexp != 0) {
10265                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10266                                     bl_ptr->opt_unmap_grain);
10267                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10268                                     bl_ptr->unmap_grain_align);
10269                         }
10270                 }
10271                 scsi_ulto4b(lun->be_lun->atomicblock,
10272                     bl_ptr->max_atomic_transfer_length);
10273                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10274                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10275                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
10276                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
10277         }
10278         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10279
10280         ctl_set_success(ctsio);
10281         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10282         ctsio->be_move_done = ctl_config_move_done;
10283         ctl_datamove((union ctl_io *)ctsio);
10284         return (CTL_RETVAL_COMPLETE);
10285 }
10286
10287 static int
10288 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10289 {
10290         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10291         struct ctl_lun *lun;
10292         const char *value;
10293         u_int i;
10294
10295         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10296
10297         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10298         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10299         ctsio->kern_sg_entries = 0;
10300
10301         if (sizeof(*bdc_ptr) < alloc_len) {
10302                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10303                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10304                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10305         } else {
10306                 ctsio->residual = 0;
10307                 ctsio->kern_data_len = alloc_len;
10308                 ctsio->kern_total_len = alloc_len;
10309         }
10310         ctsio->kern_data_resid = 0;
10311         ctsio->kern_rel_offset = 0;
10312         ctsio->kern_sg_entries = 0;
10313
10314         /*
10315          * The control device is always connected.  The disk device, on the
10316          * other hand, may not be online all the time.  Need to change this
10317          * to figure out whether the disk device is actually online or not.
10318          */
10319         if (lun != NULL)
10320                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10321                                   lun->be_lun->lun_type;
10322         else
10323                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10324         bdc_ptr->page_code = SVPD_BDC;
10325         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10326         if (lun != NULL &&
10327             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10328                 i = strtol(value, NULL, 0);
10329         else
10330                 i = CTL_DEFAULT_ROTATION_RATE;
10331         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10332         if (lun != NULL &&
10333             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10334                 i = strtol(value, NULL, 0);
10335         else
10336                 i = 0;
10337         bdc_ptr->wab_wac_ff = (i & 0x0f);
10338         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10339
10340         ctl_set_success(ctsio);
10341         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10342         ctsio->be_move_done = ctl_config_move_done;
10343         ctl_datamove((union ctl_io *)ctsio);
10344         return (CTL_RETVAL_COMPLETE);
10345 }
10346
10347 static int
10348 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10349 {
10350         struct scsi_vpd_logical_block_prov *lbp_ptr;
10351         struct ctl_lun *lun;
10352
10353         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10354
10355         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10356         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10357         ctsio->kern_sg_entries = 0;
10358
10359         if (sizeof(*lbp_ptr) < alloc_len) {
10360                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10361                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10362                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10363         } else {
10364                 ctsio->residual = 0;
10365                 ctsio->kern_data_len = alloc_len;
10366                 ctsio->kern_total_len = alloc_len;
10367         }
10368         ctsio->kern_data_resid = 0;
10369         ctsio->kern_rel_offset = 0;
10370         ctsio->kern_sg_entries = 0;
10371
10372         /*
10373          * The control device is always connected.  The disk device, on the
10374          * other hand, may not be online all the time.  Need to change this
10375          * to figure out whether the disk device is actually online or not.
10376          */
10377         if (lun != NULL)
10378                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10379                                   lun->be_lun->lun_type;
10380         else
10381                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10382
10383         lbp_ptr->page_code = SVPD_LBP;
10384         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10385         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10386         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10387                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10388                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10389                 lbp_ptr->prov_type = SVPD_LBP_THIN;
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 /*
10400  * INQUIRY with the EVPD bit set.
10401  */
10402 static int
10403 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10404 {
10405         struct ctl_lun *lun;
10406         struct scsi_inquiry *cdb;
10407         int alloc_len, retval;
10408
10409         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10410         cdb = (struct scsi_inquiry *)ctsio->cdb;
10411         alloc_len = scsi_2btoul(cdb->length);
10412
10413         switch (cdb->page_code) {
10414         case SVPD_SUPPORTED_PAGES:
10415                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10416                 break;
10417         case SVPD_UNIT_SERIAL_NUMBER:
10418                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10419                 break;
10420         case SVPD_DEVICE_ID:
10421                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10422                 break;
10423         case SVPD_EXTENDED_INQUIRY_DATA:
10424                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10425                 break;
10426         case SVPD_MODE_PAGE_POLICY:
10427                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10428                 break;
10429         case SVPD_SCSI_PORTS:
10430                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10431                 break;
10432         case SVPD_SCSI_TPC:
10433                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10434                 break;
10435         case SVPD_BLOCK_LIMITS:
10436                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10437                         goto err;
10438                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10439                 break;
10440         case SVPD_BDC:
10441                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10442                         goto err;
10443                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10444                 break;
10445         case SVPD_LBP:
10446                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10447                         goto err;
10448                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10449                 break;
10450         default:
10451 err:
10452                 ctl_set_invalid_field(ctsio,
10453                                       /*sks_valid*/ 1,
10454                                       /*command*/ 1,
10455                                       /*field*/ 2,
10456                                       /*bit_valid*/ 0,
10457                                       /*bit*/ 0);
10458                 ctl_done((union ctl_io *)ctsio);
10459                 retval = CTL_RETVAL_COMPLETE;
10460                 break;
10461         }
10462
10463         return (retval);
10464 }
10465
10466 /*
10467  * Standard INQUIRY data.
10468  */
10469 static int
10470 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10471 {
10472         struct scsi_inquiry_data *inq_ptr;
10473         struct scsi_inquiry *cdb;
10474         struct ctl_softc *softc = control_softc;
10475         struct ctl_port *port;
10476         struct ctl_lun *lun;
10477         char *val;
10478         uint32_t alloc_len, data_len;
10479         ctl_port_type port_type;
10480
10481         port = ctl_io_port(&ctsio->io_hdr);
10482         port_type = port->port_type;
10483         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10484                 port_type = CTL_PORT_SCSI;
10485
10486         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10487         cdb = (struct scsi_inquiry *)ctsio->cdb;
10488         alloc_len = scsi_2btoul(cdb->length);
10489
10490         /*
10491          * We malloc the full inquiry data size here and fill it
10492          * in.  If the user only asks for less, we'll give him
10493          * that much.
10494          */
10495         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10496         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10497         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10498         ctsio->kern_sg_entries = 0;
10499         ctsio->kern_data_resid = 0;
10500         ctsio->kern_rel_offset = 0;
10501
10502         if (data_len < alloc_len) {
10503                 ctsio->residual = alloc_len - data_len;
10504                 ctsio->kern_data_len = data_len;
10505                 ctsio->kern_total_len = data_len;
10506         } else {
10507                 ctsio->residual = 0;
10508                 ctsio->kern_data_len = alloc_len;
10509                 ctsio->kern_total_len = alloc_len;
10510         }
10511
10512         if (lun != NULL) {
10513                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10514                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10515                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10516                             lun->be_lun->lun_type;
10517                 } else {
10518                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10519                             lun->be_lun->lun_type;
10520                 }
10521         } else
10522                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10523
10524         /* RMB in byte 2 is 0 */
10525         inq_ptr->version = SCSI_REV_SPC4;
10526
10527         /*
10528          * According to SAM-3, even if a device only supports a single
10529          * level of LUN addressing, it should still set the HISUP bit:
10530          *
10531          * 4.9.1 Logical unit numbers overview
10532          *
10533          * All logical unit number formats described in this standard are
10534          * hierarchical in structure even when only a single level in that
10535          * hierarchy is used. The HISUP bit shall be set to one in the
10536          * standard INQUIRY data (see SPC-2) when any logical unit number
10537          * format described in this standard is used.  Non-hierarchical
10538          * formats are outside the scope of this standard.
10539          *
10540          * Therefore we set the HiSup bit here.
10541          *
10542          * The reponse format is 2, per SPC-3.
10543          */
10544         inq_ptr->response_format = SID_HiSup | 2;
10545
10546         inq_ptr->additional_length = data_len -
10547             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10548         CTL_DEBUG_PRINT(("additional_length = %d\n",
10549                          inq_ptr->additional_length));
10550
10551         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10552         /* 16 bit addressing */
10553         if (port_type == CTL_PORT_SCSI)
10554                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10555         /* XXX set the SID_MultiP bit here if we're actually going to
10556            respond on multiple ports */
10557         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10558
10559         /* 16 bit data bus, synchronous transfers */
10560         if (port_type == CTL_PORT_SCSI)
10561                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10562         /*
10563          * XXX KDM do we want to support tagged queueing on the control
10564          * device at all?
10565          */
10566         if ((lun == NULL)
10567          || (lun->be_lun->lun_type != T_PROCESSOR))
10568                 inq_ptr->flags |= SID_CmdQue;
10569         /*
10570          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10571          * We have 8 bytes for the vendor name, and 16 bytes for the device
10572          * name and 4 bytes for the revision.
10573          */
10574         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10575             "vendor")) == NULL) {
10576                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10577         } else {
10578                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10579                 strncpy(inq_ptr->vendor, val,
10580                     min(sizeof(inq_ptr->vendor), strlen(val)));
10581         }
10582         if (lun == NULL) {
10583                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10584                     sizeof(inq_ptr->product));
10585         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10586                 switch (lun->be_lun->lun_type) {
10587                 case T_DIRECT:
10588                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10589                             sizeof(inq_ptr->product));
10590                         break;
10591                 case T_PROCESSOR:
10592                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10593                             sizeof(inq_ptr->product));
10594                         break;
10595                 default:
10596                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10597                             sizeof(inq_ptr->product));
10598                         break;
10599                 }
10600         } else {
10601                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10602                 strncpy(inq_ptr->product, val,
10603                     min(sizeof(inq_ptr->product), strlen(val)));
10604         }
10605
10606         /*
10607          * XXX make this a macro somewhere so it automatically gets
10608          * incremented when we make changes.
10609          */
10610         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10611             "revision")) == NULL) {
10612                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10613         } else {
10614                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10615                 strncpy(inq_ptr->revision, val,
10616                     min(sizeof(inq_ptr->revision), strlen(val)));
10617         }
10618
10619         /*
10620          * For parallel SCSI, we support double transition and single
10621          * transition clocking.  We also support QAS (Quick Arbitration
10622          * and Selection) and Information Unit transfers on both the
10623          * control and array devices.
10624          */
10625         if (port_type == CTL_PORT_SCSI)
10626                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10627                                     SID_SPI_IUS;
10628
10629         /* SAM-5 (no version claimed) */
10630         scsi_ulto2b(0x00A0, inq_ptr->version1);
10631         /* SPC-4 (no version claimed) */
10632         scsi_ulto2b(0x0460, inq_ptr->version2);
10633         if (port_type == CTL_PORT_FC) {
10634                 /* FCP-2 ANSI INCITS.350:2003 */
10635                 scsi_ulto2b(0x0917, inq_ptr->version3);
10636         } else if (port_type == CTL_PORT_SCSI) {
10637                 /* SPI-4 ANSI INCITS.362:200x */
10638                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10639         } else if (port_type == CTL_PORT_ISCSI) {
10640                 /* iSCSI (no version claimed) */
10641                 scsi_ulto2b(0x0960, inq_ptr->version3);
10642         } else if (port_type == CTL_PORT_SAS) {
10643                 /* SAS (no version claimed) */
10644                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10645         }
10646
10647         if (lun == NULL) {
10648                 /* SBC-4 (no version claimed) */
10649                 scsi_ulto2b(0x0600, inq_ptr->version4);
10650         } else {
10651                 switch (lun->be_lun->lun_type) {
10652                 case T_DIRECT:
10653                         /* SBC-4 (no version claimed) */
10654                         scsi_ulto2b(0x0600, inq_ptr->version4);
10655                         break;
10656                 case T_PROCESSOR:
10657                 default:
10658                         break;
10659                 }
10660         }
10661
10662         ctl_set_success(ctsio);
10663         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10664         ctsio->be_move_done = ctl_config_move_done;
10665         ctl_datamove((union ctl_io *)ctsio);
10666         return (CTL_RETVAL_COMPLETE);
10667 }
10668
10669 int
10670 ctl_inquiry(struct ctl_scsiio *ctsio)
10671 {
10672         struct scsi_inquiry *cdb;
10673         int retval;
10674
10675         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10676
10677         cdb = (struct scsi_inquiry *)ctsio->cdb;
10678         if (cdb->byte2 & SI_EVPD)
10679                 retval = ctl_inquiry_evpd(ctsio);
10680         else if (cdb->page_code == 0)
10681                 retval = ctl_inquiry_std(ctsio);
10682         else {
10683                 ctl_set_invalid_field(ctsio,
10684                                       /*sks_valid*/ 1,
10685                                       /*command*/ 1,
10686                                       /*field*/ 2,
10687                                       /*bit_valid*/ 0,
10688                                       /*bit*/ 0);
10689                 ctl_done((union ctl_io *)ctsio);
10690                 return (CTL_RETVAL_COMPLETE);
10691         }
10692
10693         return (retval);
10694 }
10695
10696 /*
10697  * For known CDB types, parse the LBA and length.
10698  */
10699 static int
10700 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10701 {
10702         if (io->io_hdr.io_type != CTL_IO_SCSI)
10703                 return (1);
10704
10705         switch (io->scsiio.cdb[0]) {
10706         case COMPARE_AND_WRITE: {
10707                 struct scsi_compare_and_write *cdb;
10708
10709                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10710
10711                 *lba = scsi_8btou64(cdb->addr);
10712                 *len = cdb->length;
10713                 break;
10714         }
10715         case READ_6:
10716         case WRITE_6: {
10717                 struct scsi_rw_6 *cdb;
10718
10719                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10720
10721                 *lba = scsi_3btoul(cdb->addr);
10722                 /* only 5 bits are valid in the most significant address byte */
10723                 *lba &= 0x1fffff;
10724                 *len = cdb->length;
10725                 break;
10726         }
10727         case READ_10:
10728         case WRITE_10: {
10729                 struct scsi_rw_10 *cdb;
10730
10731                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10732
10733                 *lba = scsi_4btoul(cdb->addr);
10734                 *len = scsi_2btoul(cdb->length);
10735                 break;
10736         }
10737         case WRITE_VERIFY_10: {
10738                 struct scsi_write_verify_10 *cdb;
10739
10740                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10741
10742                 *lba = scsi_4btoul(cdb->addr);
10743                 *len = scsi_2btoul(cdb->length);
10744                 break;
10745         }
10746         case READ_12:
10747         case WRITE_12: {
10748                 struct scsi_rw_12 *cdb;
10749
10750                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10751
10752                 *lba = scsi_4btoul(cdb->addr);
10753                 *len = scsi_4btoul(cdb->length);
10754                 break;
10755         }
10756         case WRITE_VERIFY_12: {
10757                 struct scsi_write_verify_12 *cdb;
10758
10759                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10760
10761                 *lba = scsi_4btoul(cdb->addr);
10762                 *len = scsi_4btoul(cdb->length);
10763                 break;
10764         }
10765         case READ_16:
10766         case WRITE_16: {
10767                 struct scsi_rw_16 *cdb;
10768
10769                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10770
10771                 *lba = scsi_8btou64(cdb->addr);
10772                 *len = scsi_4btoul(cdb->length);
10773                 break;
10774         }
10775         case WRITE_ATOMIC_16: {
10776                 struct scsi_write_atomic_16 *cdb;
10777
10778                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10779
10780                 *lba = scsi_8btou64(cdb->addr);
10781                 *len = scsi_2btoul(cdb->length);
10782                 break;
10783         }
10784         case WRITE_VERIFY_16: {
10785                 struct scsi_write_verify_16 *cdb;
10786
10787                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10788
10789                 *lba = scsi_8btou64(cdb->addr);
10790                 *len = scsi_4btoul(cdb->length);
10791                 break;
10792         }
10793         case WRITE_SAME_10: {
10794                 struct scsi_write_same_10 *cdb;
10795
10796                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10797
10798                 *lba = scsi_4btoul(cdb->addr);
10799                 *len = scsi_2btoul(cdb->length);
10800                 break;
10801         }
10802         case WRITE_SAME_16: {
10803                 struct scsi_write_same_16 *cdb;
10804
10805                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10806
10807                 *lba = scsi_8btou64(cdb->addr);
10808                 *len = scsi_4btoul(cdb->length);
10809                 break;
10810         }
10811         case VERIFY_10: {
10812                 struct scsi_verify_10 *cdb;
10813
10814                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10815
10816                 *lba = scsi_4btoul(cdb->addr);
10817                 *len = scsi_2btoul(cdb->length);
10818                 break;
10819         }
10820         case VERIFY_12: {
10821                 struct scsi_verify_12 *cdb;
10822
10823                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10824
10825                 *lba = scsi_4btoul(cdb->addr);
10826                 *len = scsi_4btoul(cdb->length);
10827                 break;
10828         }
10829         case VERIFY_16: {
10830                 struct scsi_verify_16 *cdb;
10831
10832                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10833
10834                 *lba = scsi_8btou64(cdb->addr);
10835                 *len = scsi_4btoul(cdb->length);
10836                 break;
10837         }
10838         case UNMAP: {
10839                 *lba = 0;
10840                 *len = UINT64_MAX;
10841                 break;
10842         }
10843         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10844                 struct scsi_get_lba_status *cdb;
10845
10846                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10847                 *lba = scsi_8btou64(cdb->addr);
10848                 *len = UINT32_MAX;
10849                 break;
10850         }
10851         default:
10852                 return (1);
10853                 break; /* NOTREACHED */
10854         }
10855
10856         return (0);
10857 }
10858
10859 static ctl_action
10860 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10861     bool seq)
10862 {
10863         uint64_t endlba1, endlba2;
10864
10865         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10866         endlba2 = lba2 + len2 - 1;
10867
10868         if ((endlba1 < lba2) || (endlba2 < lba1))
10869                 return (CTL_ACTION_PASS);
10870         else
10871                 return (CTL_ACTION_BLOCK);
10872 }
10873
10874 static int
10875 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10876 {
10877         struct ctl_ptr_len_flags *ptrlen;
10878         struct scsi_unmap_desc *buf, *end, *range;
10879         uint64_t lba;
10880         uint32_t len;
10881
10882         /* If not UNMAP -- go other way. */
10883         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10884             io->scsiio.cdb[0] != UNMAP)
10885                 return (CTL_ACTION_ERROR);
10886
10887         /* If UNMAP without data -- block and wait for data. */
10888         ptrlen = (struct ctl_ptr_len_flags *)
10889             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10890         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10891             ptrlen->ptr == NULL)
10892                 return (CTL_ACTION_BLOCK);
10893
10894         /* UNMAP with data -- check for collision. */
10895         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10896         end = buf + ptrlen->len / sizeof(*buf);
10897         for (range = buf; range < end; range++) {
10898                 lba = scsi_8btou64(range->lba);
10899                 len = scsi_4btoul(range->length);
10900                 if ((lba < lba2 + len2) && (lba + len > lba2))
10901                         return (CTL_ACTION_BLOCK);
10902         }
10903         return (CTL_ACTION_PASS);
10904 }
10905
10906 static ctl_action
10907 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10908 {
10909         uint64_t lba1, lba2;
10910         uint64_t len1, len2;
10911         int retval;
10912
10913         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10914                 return (CTL_ACTION_ERROR);
10915
10916         retval = ctl_extent_check_unmap(io1, lba2, len2);
10917         if (retval != CTL_ACTION_ERROR)
10918                 return (retval);
10919
10920         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10921                 return (CTL_ACTION_ERROR);
10922
10923         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10924                 seq = FALSE;
10925         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10926 }
10927
10928 static ctl_action
10929 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10930 {
10931         uint64_t lba1, lba2;
10932         uint64_t len1, len2;
10933
10934         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10935                 return (CTL_ACTION_PASS);
10936         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10937                 return (CTL_ACTION_ERROR);
10938         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10939                 return (CTL_ACTION_ERROR);
10940
10941         if (lba1 + len1 == lba2)
10942                 return (CTL_ACTION_BLOCK);
10943         return (CTL_ACTION_PASS);
10944 }
10945
10946 static ctl_action
10947 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10948     union ctl_io *ooa_io)
10949 {
10950         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10951         ctl_serialize_action *serialize_row;
10952
10953         /*
10954          * The initiator attempted multiple untagged commands at the same
10955          * time.  Can't do that.
10956          */
10957         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10958          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10959          && ((pending_io->io_hdr.nexus.targ_port ==
10960               ooa_io->io_hdr.nexus.targ_port)
10961           && (pending_io->io_hdr.nexus.initid ==
10962               ooa_io->io_hdr.nexus.initid))
10963          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10964               CTL_FLAG_STATUS_SENT)) == 0))
10965                 return (CTL_ACTION_OVERLAP);
10966
10967         /*
10968          * The initiator attempted to send multiple tagged commands with
10969          * the same ID.  (It's fine if different initiators have the same
10970          * tag ID.)
10971          *
10972          * Even if all of those conditions are true, we don't kill the I/O
10973          * if the command ahead of us has been aborted.  We won't end up
10974          * sending it to the FETD, and it's perfectly legal to resend a
10975          * command with the same tag number as long as the previous
10976          * instance of this tag number has been aborted somehow.
10977          */
10978         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10979          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10980          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10981          && ((pending_io->io_hdr.nexus.targ_port ==
10982               ooa_io->io_hdr.nexus.targ_port)
10983           && (pending_io->io_hdr.nexus.initid ==
10984               ooa_io->io_hdr.nexus.initid))
10985          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10986               CTL_FLAG_STATUS_SENT)) == 0))
10987                 return (CTL_ACTION_OVERLAP_TAG);
10988
10989         /*
10990          * If we get a head of queue tag, SAM-3 says that we should
10991          * immediately execute it.
10992          *
10993          * What happens if this command would normally block for some other
10994          * reason?  e.g. a request sense with a head of queue tag
10995          * immediately after a write.  Normally that would block, but this
10996          * will result in its getting executed immediately...
10997          *
10998          * We currently return "pass" instead of "skip", so we'll end up
10999          * going through the rest of the queue to check for overlapped tags.
11000          *
11001          * XXX KDM check for other types of blockage first??
11002          */
11003         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11004                 return (CTL_ACTION_PASS);
11005
11006         /*
11007          * Ordered tags have to block until all items ahead of them
11008          * have completed.  If we get called with an ordered tag, we always
11009          * block, if something else is ahead of us in the queue.
11010          */
11011         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11012                 return (CTL_ACTION_BLOCK);
11013
11014         /*
11015          * Simple tags get blocked until all head of queue and ordered tags
11016          * ahead of them have completed.  I'm lumping untagged commands in
11017          * with simple tags here.  XXX KDM is that the right thing to do?
11018          */
11019         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11020           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11021          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11022           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11023                 return (CTL_ACTION_BLOCK);
11024
11025         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11026         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11027
11028         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11029
11030         switch (serialize_row[pending_entry->seridx]) {
11031         case CTL_SER_BLOCK:
11032                 return (CTL_ACTION_BLOCK);
11033         case CTL_SER_EXTENT:
11034                 return (ctl_extent_check(ooa_io, pending_io,
11035                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11036         case CTL_SER_EXTENTOPT:
11037                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11038                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11039                         return (ctl_extent_check(ooa_io, pending_io,
11040                             (lun->be_lun &&
11041                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11042                 return (CTL_ACTION_PASS);
11043         case CTL_SER_EXTENTSEQ:
11044                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11045                         return (ctl_extent_check_seq(ooa_io, pending_io));
11046                 return (CTL_ACTION_PASS);
11047         case CTL_SER_PASS:
11048                 return (CTL_ACTION_PASS);
11049         case CTL_SER_BLOCKOPT:
11050                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11051                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11052                         return (CTL_ACTION_BLOCK);
11053                 return (CTL_ACTION_PASS);
11054         case CTL_SER_SKIP:
11055                 return (CTL_ACTION_SKIP);
11056         default:
11057                 panic("invalid serialization value %d",
11058                       serialize_row[pending_entry->seridx]);
11059         }
11060
11061         return (CTL_ACTION_ERROR);
11062 }
11063
11064 /*
11065  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11066  * Assumptions:
11067  * - pending_io is generally either incoming, or on the blocked queue
11068  * - starting I/O is the I/O we want to start the check with.
11069  */
11070 static ctl_action
11071 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11072               union ctl_io *starting_io)
11073 {
11074         union ctl_io *ooa_io;
11075         ctl_action action;
11076
11077         mtx_assert(&lun->lun_lock, MA_OWNED);
11078
11079         /*
11080          * Run back along the OOA queue, starting with the current
11081          * blocked I/O and going through every I/O before it on the
11082          * queue.  If starting_io is NULL, we'll just end up returning
11083          * CTL_ACTION_PASS.
11084          */
11085         for (ooa_io = starting_io; ooa_io != NULL;
11086              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11087              ooa_links)){
11088
11089                 /*
11090                  * This routine just checks to see whether
11091                  * cur_blocked is blocked by ooa_io, which is ahead
11092                  * of it in the queue.  It doesn't queue/dequeue
11093                  * cur_blocked.
11094                  */
11095                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11096                 switch (action) {
11097                 case CTL_ACTION_BLOCK:
11098                 case CTL_ACTION_OVERLAP:
11099                 case CTL_ACTION_OVERLAP_TAG:
11100                 case CTL_ACTION_SKIP:
11101                 case CTL_ACTION_ERROR:
11102                         return (action);
11103                         break; /* NOTREACHED */
11104                 case CTL_ACTION_PASS:
11105                         break;
11106                 default:
11107                         panic("invalid action %d", action);
11108                         break;  /* NOTREACHED */
11109                 }
11110         }
11111
11112         return (CTL_ACTION_PASS);
11113 }
11114
11115 /*
11116  * Assumptions:
11117  * - An I/O has just completed, and has been removed from the per-LUN OOA
11118  *   queue, so some items on the blocked queue may now be unblocked.
11119  */
11120 static int
11121 ctl_check_blocked(struct ctl_lun *lun)
11122 {
11123         struct ctl_softc *softc = lun->ctl_softc;
11124         union ctl_io *cur_blocked, *next_blocked;
11125
11126         mtx_assert(&lun->lun_lock, MA_OWNED);
11127
11128         /*
11129          * Run forward from the head of the blocked queue, checking each
11130          * entry against the I/Os prior to it on the OOA queue to see if
11131          * there is still any blockage.
11132          *
11133          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11134          * with our removing a variable on it while it is traversing the
11135          * list.
11136          */
11137         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11138              cur_blocked != NULL; cur_blocked = next_blocked) {
11139                 union ctl_io *prev_ooa;
11140                 ctl_action action;
11141
11142                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11143                                                           blocked_links);
11144
11145                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11146                                                       ctl_ooaq, ooa_links);
11147
11148                 /*
11149                  * If cur_blocked happens to be the first item in the OOA
11150                  * queue now, prev_ooa will be NULL, and the action
11151                  * returned will just be CTL_ACTION_PASS.
11152                  */
11153                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11154
11155                 switch (action) {
11156                 case CTL_ACTION_BLOCK:
11157                         /* Nothing to do here, still blocked */
11158                         break;
11159                 case CTL_ACTION_OVERLAP:
11160                 case CTL_ACTION_OVERLAP_TAG:
11161                         /*
11162                          * This shouldn't happen!  In theory we've already
11163                          * checked this command for overlap...
11164                          */
11165                         break;
11166                 case CTL_ACTION_PASS:
11167                 case CTL_ACTION_SKIP: {
11168                         const struct ctl_cmd_entry *entry;
11169
11170                         /*
11171                          * The skip case shouldn't happen, this transaction
11172                          * should have never made it onto the blocked queue.
11173                          */
11174                         /*
11175                          * This I/O is no longer blocked, we can remove it
11176                          * from the blocked queue.  Since this is a TAILQ
11177                          * (doubly linked list), we can do O(1) removals
11178                          * from any place on the list.
11179                          */
11180                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11181                                      blocked_links);
11182                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11183
11184                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11185                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11186                                 /*
11187                                  * Need to send IO back to original side to
11188                                  * run
11189                                  */
11190                                 union ctl_ha_msg msg_info;
11191
11192                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11193                                 msg_info.hdr.original_sc =
11194                                         cur_blocked->io_hdr.original_sc;
11195                                 msg_info.hdr.serializing_sc = cur_blocked;
11196                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11197                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11198                                     sizeof(msg_info.hdr), M_NOWAIT);
11199                                 break;
11200                         }
11201                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11202
11203                         /*
11204                          * Check this I/O for LUN state changes that may
11205                          * have happened while this command was blocked.
11206                          * The LUN state may have been changed by a command
11207                          * ahead of us in the queue, so we need to re-check
11208                          * for any states that can be caused by SCSI
11209                          * commands.
11210                          */
11211                         if (ctl_scsiio_lun_check(lun, entry,
11212                                                  &cur_blocked->scsiio) == 0) {
11213                                 cur_blocked->io_hdr.flags |=
11214                                                       CTL_FLAG_IS_WAS_ON_RTR;
11215                                 ctl_enqueue_rtr(cur_blocked);
11216                         } else
11217                                 ctl_done(cur_blocked);
11218                         break;
11219                 }
11220                 default:
11221                         /*
11222                          * This probably shouldn't happen -- we shouldn't
11223                          * get CTL_ACTION_ERROR, or anything else.
11224                          */
11225                         break;
11226                 }
11227         }
11228
11229         return (CTL_RETVAL_COMPLETE);
11230 }
11231
11232 /*
11233  * This routine (with one exception) checks LUN flags that can be set by
11234  * commands ahead of us in the OOA queue.  These flags have to be checked
11235  * when a command initially comes in, and when we pull a command off the
11236  * blocked queue and are preparing to execute it.  The reason we have to
11237  * check these flags for commands on the blocked queue is that the LUN
11238  * state may have been changed by a command ahead of us while we're on the
11239  * blocked queue.
11240  *
11241  * Ordering is somewhat important with these checks, so please pay
11242  * careful attention to the placement of any new checks.
11243  */
11244 static int
11245 ctl_scsiio_lun_check(struct ctl_lun *lun,
11246     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11247 {
11248         struct ctl_softc *softc = lun->ctl_softc;
11249         int retval;
11250         uint32_t residx;
11251
11252         retval = 0;
11253
11254         mtx_assert(&lun->lun_lock, MA_OWNED);
11255
11256         /*
11257          * If this shelf is a secondary shelf controller, we may have to
11258          * reject some commands disallowed by HA mode and link state.
11259          */
11260         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11261                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11262                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11263                         ctl_set_lun_unavail(ctsio);
11264                         retval = 1;
11265                         goto bailout;
11266                 }
11267                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11268                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11269                         ctl_set_lun_transit(ctsio);
11270                         retval = 1;
11271                         goto bailout;
11272                 }
11273                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11274                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11275                         ctl_set_lun_standby(ctsio);
11276                         retval = 1;
11277                         goto bailout;
11278                 }
11279
11280                 /* The rest of checks are only done on executing side */
11281                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11282                         goto bailout;
11283         }
11284
11285         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11286                 if (lun->be_lun &&
11287                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11288                         ctl_set_hw_write_protected(ctsio);
11289                         retval = 1;
11290                         goto bailout;
11291                 }
11292                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11293                     .eca_and_aen & SCP_SWP) != 0) {
11294                         ctl_set_sense(ctsio, /*current_error*/ 1,
11295                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11296                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11297                         retval = 1;
11298                         goto bailout;
11299                 }
11300         }
11301
11302         /*
11303          * Check for a reservation conflict.  If this command isn't allowed
11304          * even on reserved LUNs, and if this initiator isn't the one who
11305          * reserved us, reject the command with a reservation conflict.
11306          */
11307         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11308         if ((lun->flags & CTL_LUN_RESERVED)
11309          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11310                 if (lun->res_idx != residx) {
11311                         ctl_set_reservation_conflict(ctsio);
11312                         retval = 1;
11313                         goto bailout;
11314                 }
11315         }
11316
11317         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11318             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11319                 /* No reservation or command is allowed. */;
11320         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11321             (lun->res_type == SPR_TYPE_WR_EX ||
11322              lun->res_type == SPR_TYPE_WR_EX_RO ||
11323              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11324                 /* The command is allowed for Write Exclusive resv. */;
11325         } else {
11326                 /*
11327                  * if we aren't registered or it's a res holder type
11328                  * reservation and this isn't the res holder then set a
11329                  * conflict.
11330                  */
11331                 if (ctl_get_prkey(lun, residx) == 0
11332                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11333                         ctl_set_reservation_conflict(ctsio);
11334                         retval = 1;
11335                         goto bailout;
11336                 }
11337         }
11338
11339         if ((lun->flags & CTL_LUN_OFFLINE)
11340          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
11341                 ctl_set_lun_not_ready(ctsio);
11342                 retval = 1;
11343                 goto bailout;
11344         }
11345
11346         if ((lun->flags & CTL_LUN_STOPPED)
11347          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11348                 /* "Logical unit not ready, initializing cmd. required" */
11349                 ctl_set_lun_stopped(ctsio);
11350                 retval = 1;
11351                 goto bailout;
11352         }
11353
11354         if ((lun->flags & CTL_LUN_INOPERABLE)
11355          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11356                 /* "Medium format corrupted" */
11357                 ctl_set_medium_format_corrupted(ctsio);
11358                 retval = 1;
11359                 goto bailout;
11360         }
11361
11362 bailout:
11363         return (retval);
11364 }
11365
11366 static void
11367 ctl_failover_io(union ctl_io *io, int have_lock)
11368 {
11369         ctl_set_busy(&io->scsiio);
11370         ctl_done(io);
11371 }
11372
11373 static void
11374 ctl_failover_lun(struct ctl_lun *lun)
11375 {
11376         struct ctl_softc *softc = lun->ctl_softc;
11377         struct ctl_io_hdr *io, *next_io;
11378
11379         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
11380         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11381                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11382                         /* We are master */
11383                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11384                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11385                                         io->flags |= CTL_FLAG_ABORT;
11386                                         io->flags |= CTL_FLAG_FAILOVER;
11387                                 } else { /* This can be only due to DATAMOVE */
11388                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11389                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11390                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11391                                         io->port_status = 31340;
11392                                         ctl_enqueue_isc((union ctl_io *)io);
11393                                 }
11394                         }
11395                         /* We are slave */
11396                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11397                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11398                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11399                                         io->flags |= CTL_FLAG_FAILOVER;
11400                                 } else {
11401                                         ctl_set_busy(&((union ctl_io *)io)->
11402                                             scsiio);
11403                                         ctl_done((union ctl_io *)io);
11404                                 }
11405                         }
11406                 }
11407         } else { /* SERIALIZE modes */
11408                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11409                     next_io) {
11410                         /* We are master */
11411                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11412                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11413                                     blocked_links);
11414                                 io->flags &= ~CTL_FLAG_BLOCKED;
11415                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11416                                 ctl_free_io((union ctl_io *)io);
11417                         }
11418                 }
11419                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11420                         /* We are master */
11421                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11422                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11423                                 ctl_free_io((union ctl_io *)io);
11424                         }
11425                         /* We are slave */
11426                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11427                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11428                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11429                                         ctl_set_busy(&((union ctl_io *)io)->
11430                                             scsiio);
11431                                         ctl_done((union ctl_io *)io);
11432                                 }
11433                         }
11434                 }
11435                 ctl_check_blocked(lun);
11436         }
11437 }
11438
11439 static int
11440 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11441 {
11442         struct ctl_lun *lun;
11443         const struct ctl_cmd_entry *entry;
11444         uint32_t initidx, targ_lun;
11445         int retval;
11446
11447         retval = 0;
11448
11449         lun = NULL;
11450
11451         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11452         if ((targ_lun < CTL_MAX_LUNS)
11453          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11454                 /*
11455                  * If the LUN is invalid, pretend that it doesn't exist.
11456                  * It will go away as soon as all pending I/O has been
11457                  * completed.
11458                  */
11459                 mtx_lock(&lun->lun_lock);
11460                 if (lun->flags & CTL_LUN_DISABLED) {
11461                         mtx_unlock(&lun->lun_lock);
11462                         lun = NULL;
11463                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11464                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11465                 } else {
11466                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11467                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11468                                 lun->be_lun;
11469
11470                         /*
11471                          * Every I/O goes into the OOA queue for a
11472                          * particular LUN, and stays there until completion.
11473                          */
11474 #ifdef CTL_TIME_IO
11475                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11476                                 lun->idle_time += getsbinuptime() -
11477                                     lun->last_busy;
11478                         }
11479 #endif
11480                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11481                             ooa_links);
11482                 }
11483         } else {
11484                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11485                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11486         }
11487
11488         /* Get command entry and return error if it is unsuppotyed. */
11489         entry = ctl_validate_command(ctsio);
11490         if (entry == NULL) {
11491                 if (lun)
11492                         mtx_unlock(&lun->lun_lock);
11493                 return (retval);
11494         }
11495
11496         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11497         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11498
11499         /*
11500          * Check to see whether we can send this command to LUNs that don't
11501          * exist.  This should pretty much only be the case for inquiry
11502          * and request sense.  Further checks, below, really require having
11503          * a LUN, so we can't really check the command anymore.  Just put
11504          * it on the rtr queue.
11505          */
11506         if (lun == NULL) {
11507                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11508                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11509                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11510                         return (retval);
11511                 }
11512
11513                 ctl_set_unsupported_lun(ctsio);
11514                 ctl_done((union ctl_io *)ctsio);
11515                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11516                 return (retval);
11517         } else {
11518                 /*
11519                  * Make sure we support this particular command on this LUN.
11520                  * e.g., we don't support writes to the control LUN.
11521                  */
11522                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11523                         mtx_unlock(&lun->lun_lock);
11524                         ctl_set_invalid_opcode(ctsio);
11525                         ctl_done((union ctl_io *)ctsio);
11526                         return (retval);
11527                 }
11528         }
11529
11530         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11531
11532 #ifdef CTL_WITH_CA
11533         /*
11534          * If we've got a request sense, it'll clear the contingent
11535          * allegiance condition.  Otherwise, if we have a CA condition for
11536          * this initiator, clear it, because it sent down a command other
11537          * than request sense.
11538          */
11539         if ((ctsio->cdb[0] != REQUEST_SENSE)
11540          && (ctl_is_set(lun->have_ca, initidx)))
11541                 ctl_clear_mask(lun->have_ca, initidx);
11542 #endif
11543
11544         /*
11545          * If the command has this flag set, it handles its own unit
11546          * attention reporting, we shouldn't do anything.  Otherwise we
11547          * check for any pending unit attentions, and send them back to the
11548          * initiator.  We only do this when a command initially comes in,
11549          * not when we pull it off the blocked queue.
11550          *
11551          * According to SAM-3, section 5.3.2, the order that things get
11552          * presented back to the host is basically unit attentions caused
11553          * by some sort of reset event, busy status, reservation conflicts
11554          * or task set full, and finally any other status.
11555          *
11556          * One issue here is that some of the unit attentions we report
11557          * don't fall into the "reset" category (e.g. "reported luns data
11558          * has changed").  So reporting it here, before the reservation
11559          * check, may be technically wrong.  I guess the only thing to do
11560          * would be to check for and report the reset events here, and then
11561          * check for the other unit attention types after we check for a
11562          * reservation conflict.
11563          *
11564          * XXX KDM need to fix this
11565          */
11566         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11567                 ctl_ua_type ua_type;
11568
11569                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11570                     SSD_TYPE_NONE);
11571                 if (ua_type != CTL_UA_NONE) {
11572                         mtx_unlock(&lun->lun_lock);
11573                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11574                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11575                         ctsio->sense_len = SSD_FULL_SIZE;
11576                         ctl_done((union ctl_io *)ctsio);
11577                         return (retval);
11578                 }
11579         }
11580
11581
11582         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11583                 mtx_unlock(&lun->lun_lock);
11584                 ctl_done((union ctl_io *)ctsio);
11585                 return (retval);
11586         }
11587
11588         /*
11589          * XXX CHD this is where we want to send IO to other side if
11590          * this LUN is secondary on this SC. We will need to make a copy
11591          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11592          * the copy we send as FROM_OTHER.
11593          * We also need to stuff the address of the original IO so we can
11594          * find it easily. Something similar will need be done on the other
11595          * side so when we are done we can find the copy.
11596          */
11597         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11598             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11599             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11600                 union ctl_ha_msg msg_info;
11601                 int isc_retval;
11602
11603                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11604                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11605                 mtx_unlock(&lun->lun_lock);
11606
11607                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11608                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11609                 msg_info.hdr.serializing_sc = NULL;
11610                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11611                 msg_info.scsi.tag_num = ctsio->tag_num;
11612                 msg_info.scsi.tag_type = ctsio->tag_type;
11613                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11614                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11615
11616                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11617                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11618                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11619                         ctl_set_busy(ctsio);
11620                         ctl_done((union ctl_io *)ctsio);
11621                         return (retval);
11622                 }
11623                 return (retval);
11624         }
11625
11626         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11627                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11628                               ctl_ooaq, ooa_links))) {
11629         case CTL_ACTION_BLOCK:
11630                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11631                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11632                                   blocked_links);
11633                 mtx_unlock(&lun->lun_lock);
11634                 return (retval);
11635         case CTL_ACTION_PASS:
11636         case CTL_ACTION_SKIP:
11637                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11638                 mtx_unlock(&lun->lun_lock);
11639                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11640                 break;
11641         case CTL_ACTION_OVERLAP:
11642                 mtx_unlock(&lun->lun_lock);
11643                 ctl_set_overlapped_cmd(ctsio);
11644                 ctl_done((union ctl_io *)ctsio);
11645                 break;
11646         case CTL_ACTION_OVERLAP_TAG:
11647                 mtx_unlock(&lun->lun_lock);
11648                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11649                 ctl_done((union ctl_io *)ctsio);
11650                 break;
11651         case CTL_ACTION_ERROR:
11652         default:
11653                 mtx_unlock(&lun->lun_lock);
11654                 ctl_set_internal_failure(ctsio,
11655                                          /*sks_valid*/ 0,
11656                                          /*retry_count*/ 0);
11657                 ctl_done((union ctl_io *)ctsio);
11658                 break;
11659         }
11660         return (retval);
11661 }
11662
11663 const struct ctl_cmd_entry *
11664 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11665 {
11666         const struct ctl_cmd_entry *entry;
11667         int service_action;
11668
11669         entry = &ctl_cmd_table[ctsio->cdb[0]];
11670         if (sa)
11671                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11672         if (entry->flags & CTL_CMD_FLAG_SA5) {
11673                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11674                 entry = &((const struct ctl_cmd_entry *)
11675                     entry->execute)[service_action];
11676         }
11677         return (entry);
11678 }
11679
11680 const struct ctl_cmd_entry *
11681 ctl_validate_command(struct ctl_scsiio *ctsio)
11682 {
11683         const struct ctl_cmd_entry *entry;
11684         int i, sa;
11685         uint8_t diff;
11686
11687         entry = ctl_get_cmd_entry(ctsio, &sa);
11688         if (entry->execute == NULL) {
11689                 if (sa)
11690                         ctl_set_invalid_field(ctsio,
11691                                               /*sks_valid*/ 1,
11692                                               /*command*/ 1,
11693                                               /*field*/ 1,
11694                                               /*bit_valid*/ 1,
11695                                               /*bit*/ 4);
11696                 else
11697                         ctl_set_invalid_opcode(ctsio);
11698                 ctl_done((union ctl_io *)ctsio);
11699                 return (NULL);
11700         }
11701         KASSERT(entry->length > 0,
11702             ("Not defined length for command 0x%02x/0x%02x",
11703              ctsio->cdb[0], ctsio->cdb[1]));
11704         for (i = 1; i < entry->length; i++) {
11705                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11706                 if (diff == 0)
11707                         continue;
11708                 ctl_set_invalid_field(ctsio,
11709                                       /*sks_valid*/ 1,
11710                                       /*command*/ 1,
11711                                       /*field*/ i,
11712                                       /*bit_valid*/ 1,
11713                                       /*bit*/ fls(diff) - 1);
11714                 ctl_done((union ctl_io *)ctsio);
11715                 return (NULL);
11716         }
11717         return (entry);
11718 }
11719
11720 static int
11721 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11722 {
11723
11724         switch (lun_type) {
11725         case T_PROCESSOR:
11726                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11727                         return (0);
11728                 break;
11729         case T_DIRECT:
11730                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11731                         return (0);
11732                 break;
11733         default:
11734                 return (0);
11735         }
11736         return (1);
11737 }
11738
11739 static int
11740 ctl_scsiio(struct ctl_scsiio *ctsio)
11741 {
11742         int retval;
11743         const struct ctl_cmd_entry *entry;
11744
11745         retval = CTL_RETVAL_COMPLETE;
11746
11747         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11748
11749         entry = ctl_get_cmd_entry(ctsio, NULL);
11750
11751         /*
11752          * If this I/O has been aborted, just send it straight to
11753          * ctl_done() without executing it.
11754          */
11755         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11756                 ctl_done((union ctl_io *)ctsio);
11757                 goto bailout;
11758         }
11759
11760         /*
11761          * All the checks should have been handled by ctl_scsiio_precheck().
11762          * We should be clear now to just execute the I/O.
11763          */
11764         retval = entry->execute(ctsio);
11765
11766 bailout:
11767         return (retval);
11768 }
11769
11770 /*
11771  * Since we only implement one target right now, a bus reset simply resets
11772  * our single target.
11773  */
11774 static int
11775 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11776 {
11777         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11778 }
11779
11780 static int
11781 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11782                  ctl_ua_type ua_type)
11783 {
11784         struct ctl_port *port;
11785         struct ctl_lun *lun;
11786         int retval;
11787
11788         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11789                 union ctl_ha_msg msg_info;
11790
11791                 msg_info.hdr.nexus = io->io_hdr.nexus;
11792                 if (ua_type==CTL_UA_TARG_RESET)
11793                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11794                 else
11795                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11796                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11797                 msg_info.hdr.original_sc = NULL;
11798                 msg_info.hdr.serializing_sc = NULL;
11799                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11800                     sizeof(msg_info.task), M_WAITOK);
11801         }
11802         retval = 0;
11803
11804         mtx_lock(&softc->ctl_lock);
11805         port = ctl_io_port(&io->io_hdr);
11806         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11807                 if (port != NULL &&
11808                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11809                         continue;
11810                 retval += ctl_do_lun_reset(lun, io, ua_type);
11811         }
11812         mtx_unlock(&softc->ctl_lock);
11813         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11814         return (retval);
11815 }
11816
11817 /*
11818  * The LUN should always be set.  The I/O is optional, and is used to
11819  * distinguish between I/Os sent by this initiator, and by other
11820  * initiators.  We set unit attention for initiators other than this one.
11821  * SAM-3 is vague on this point.  It does say that a unit attention should
11822  * be established for other initiators when a LUN is reset (see section
11823  * 5.7.3), but it doesn't specifically say that the unit attention should
11824  * be established for this particular initiator when a LUN is reset.  Here
11825  * is the relevant text, from SAM-3 rev 8:
11826  *
11827  * 5.7.2 When a SCSI initiator port aborts its own tasks
11828  *
11829  * When a SCSI initiator port causes its own task(s) to be aborted, no
11830  * notification that the task(s) have been aborted shall be returned to
11831  * the SCSI initiator port other than the completion response for the
11832  * command or task management function action that caused the task(s) to
11833  * be aborted and notification(s) associated with related effects of the
11834  * action (e.g., a reset unit attention condition).
11835  *
11836  * XXX KDM for now, we're setting unit attention for all initiators.
11837  */
11838 static int
11839 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11840 {
11841         union ctl_io *xio;
11842 #if 0
11843         uint32_t initidx;
11844 #endif
11845 #ifdef CTL_WITH_CA
11846         int i;
11847 #endif
11848
11849         mtx_lock(&lun->lun_lock);
11850         /*
11851          * Run through the OOA queue and abort each I/O.
11852          */
11853         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11854              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11855                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11856         }
11857
11858         /*
11859          * This version sets unit attention for every
11860          */
11861 #if 0
11862         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11863         ctl_est_ua_all(lun, initidx, ua_type);
11864 #else
11865         ctl_est_ua_all(lun, -1, ua_type);
11866 #endif
11867
11868         /*
11869          * A reset (any kind, really) clears reservations established with
11870          * RESERVE/RELEASE.  It does not clear reservations established
11871          * with PERSISTENT RESERVE OUT, but we don't support that at the
11872          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11873          * reservations made with the RESERVE/RELEASE commands, because
11874          * those commands are obsolete in SPC-3.
11875          */
11876         lun->flags &= ~CTL_LUN_RESERVED;
11877
11878 #ifdef CTL_WITH_CA
11879         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11880                 ctl_clear_mask(lun->have_ca, i);
11881 #endif
11882         mtx_unlock(&lun->lun_lock);
11883
11884         return (0);
11885 }
11886
11887 static int
11888 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11889 {
11890         struct ctl_lun *lun;
11891         uint32_t targ_lun;
11892         int retval;
11893
11894         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11895         mtx_lock(&softc->ctl_lock);
11896         if ((targ_lun >= CTL_MAX_LUNS) ||
11897             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11898                 mtx_unlock(&softc->ctl_lock);
11899                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11900                 return (1);
11901         }
11902         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11903         mtx_unlock(&softc->ctl_lock);
11904         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11905
11906         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11907                 union ctl_ha_msg msg_info;
11908
11909                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11910                 msg_info.hdr.nexus = io->io_hdr.nexus;
11911                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11912                 msg_info.hdr.original_sc = NULL;
11913                 msg_info.hdr.serializing_sc = NULL;
11914                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11915                     sizeof(msg_info.task), M_WAITOK);
11916         }
11917         return (retval);
11918 }
11919
11920 static void
11921 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11922     int other_sc)
11923 {
11924         union ctl_io *xio;
11925
11926         mtx_assert(&lun->lun_lock, MA_OWNED);
11927
11928         /*
11929          * Run through the OOA queue and attempt to find the given I/O.
11930          * The target port, initiator ID, tag type and tag number have to
11931          * match the values that we got from the initiator.  If we have an
11932          * untagged command to abort, simply abort the first untagged command
11933          * we come to.  We only allow one untagged command at a time of course.
11934          */
11935         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11936              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11937
11938                 if ((targ_port == UINT32_MAX ||
11939                      targ_port == xio->io_hdr.nexus.targ_port) &&
11940                     (init_id == UINT32_MAX ||
11941                      init_id == xio->io_hdr.nexus.initid)) {
11942                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11943                             init_id != xio->io_hdr.nexus.initid)
11944                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11945                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11946                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11947                                 union ctl_ha_msg msg_info;
11948
11949                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11950                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11951                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11952                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11953                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11954                                 msg_info.hdr.original_sc = NULL;
11955                                 msg_info.hdr.serializing_sc = NULL;
11956                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11957                                     sizeof(msg_info.task), M_NOWAIT);
11958                         }
11959                 }
11960         }
11961 }
11962
11963 static int
11964 ctl_abort_task_set(union ctl_io *io)
11965 {
11966         struct ctl_softc *softc = control_softc;
11967         struct ctl_lun *lun;
11968         uint32_t targ_lun;
11969
11970         /*
11971          * Look up the LUN.
11972          */
11973         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11974         mtx_lock(&softc->ctl_lock);
11975         if ((targ_lun >= CTL_MAX_LUNS) ||
11976             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11977                 mtx_unlock(&softc->ctl_lock);
11978                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11979                 return (1);
11980         }
11981
11982         mtx_lock(&lun->lun_lock);
11983         mtx_unlock(&softc->ctl_lock);
11984         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11985                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11986                     io->io_hdr.nexus.initid,
11987                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11988         } else { /* CTL_TASK_CLEAR_TASK_SET */
11989                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11990                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11991         }
11992         mtx_unlock(&lun->lun_lock);
11993         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11994         return (0);
11995 }
11996
11997 static int
11998 ctl_i_t_nexus_reset(union ctl_io *io)
11999 {
12000         struct ctl_softc *softc = control_softc;
12001         struct ctl_lun *lun;
12002         uint32_t initidx;
12003
12004         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12005                 union ctl_ha_msg msg_info;
12006
12007                 msg_info.hdr.nexus = io->io_hdr.nexus;
12008                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12009                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12010                 msg_info.hdr.original_sc = NULL;
12011                 msg_info.hdr.serializing_sc = NULL;
12012                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12013                     sizeof(msg_info.task), M_WAITOK);
12014         }
12015
12016         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12017         mtx_lock(&softc->ctl_lock);
12018         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12019                 mtx_lock(&lun->lun_lock);
12020                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12021                     io->io_hdr.nexus.initid, 1);
12022 #ifdef CTL_WITH_CA
12023                 ctl_clear_mask(lun->have_ca, initidx);
12024 #endif
12025                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12026                         lun->flags &= ~CTL_LUN_RESERVED;
12027                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12028                 mtx_unlock(&lun->lun_lock);
12029         }
12030         mtx_unlock(&softc->ctl_lock);
12031         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12032         return (0);
12033 }
12034
12035 static int
12036 ctl_abort_task(union ctl_io *io)
12037 {
12038         union ctl_io *xio;
12039         struct ctl_lun *lun;
12040         struct ctl_softc *softc;
12041 #if 0
12042         struct sbuf sb;
12043         char printbuf[128];
12044 #endif
12045         int found;
12046         uint32_t targ_lun;
12047
12048         softc = control_softc;
12049         found = 0;
12050
12051         /*
12052          * Look up the LUN.
12053          */
12054         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12055         mtx_lock(&softc->ctl_lock);
12056         if ((targ_lun >= CTL_MAX_LUNS) ||
12057             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12058                 mtx_unlock(&softc->ctl_lock);
12059                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12060                 return (1);
12061         }
12062
12063 #if 0
12064         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12065                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12066 #endif
12067
12068         mtx_lock(&lun->lun_lock);
12069         mtx_unlock(&softc->ctl_lock);
12070         /*
12071          * Run through the OOA queue and attempt to find the given I/O.
12072          * The target port, initiator ID, tag type and tag number have to
12073          * match the values that we got from the initiator.  If we have an
12074          * untagged command to abort, simply abort the first untagged command
12075          * we come to.  We only allow one untagged command at a time of course.
12076          */
12077         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12078              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12079 #if 0
12080                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12081
12082                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12083                             lun->lun, xio->scsiio.tag_num,
12084                             xio->scsiio.tag_type,
12085                             (xio->io_hdr.blocked_links.tqe_prev
12086                             == NULL) ? "" : " BLOCKED",
12087                             (xio->io_hdr.flags &
12088                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12089                             (xio->io_hdr.flags &
12090                             CTL_FLAG_ABORT) ? " ABORT" : "",
12091                             (xio->io_hdr.flags &
12092                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12093                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12094                 sbuf_finish(&sb);
12095                 printf("%s\n", sbuf_data(&sb));
12096 #endif
12097
12098                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12099                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12100                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12101                         continue;
12102
12103                 /*
12104                  * If the abort says that the task is untagged, the
12105                  * task in the queue must be untagged.  Otherwise,
12106                  * we just check to see whether the tag numbers
12107                  * match.  This is because the QLogic firmware
12108                  * doesn't pass back the tag type in an abort
12109                  * request.
12110                  */
12111 #if 0
12112                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12113                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12114                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12115 #endif
12116                 /*
12117                  * XXX KDM we've got problems with FC, because it
12118                  * doesn't send down a tag type with aborts.  So we
12119                  * can only really go by the tag number...
12120                  * This may cause problems with parallel SCSI.
12121                  * Need to figure that out!!
12122                  */
12123                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12124                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12125                         found = 1;
12126                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12127                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12128                                 union ctl_ha_msg msg_info;
12129
12130                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12131                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12132                                 msg_info.task.tag_num = io->taskio.tag_num;
12133                                 msg_info.task.tag_type = io->taskio.tag_type;
12134                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12135                                 msg_info.hdr.original_sc = NULL;
12136                                 msg_info.hdr.serializing_sc = NULL;
12137 #if 0
12138                                 printf("Sent Abort to other side\n");
12139 #endif
12140                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12141                                     sizeof(msg_info.task), M_NOWAIT);
12142                         }
12143 #if 0
12144                         printf("ctl_abort_task: found I/O to abort\n");
12145 #endif
12146                 }
12147         }
12148         mtx_unlock(&lun->lun_lock);
12149
12150         if (found == 0) {
12151                 /*
12152                  * This isn't really an error.  It's entirely possible for
12153                  * the abort and command completion to cross on the wire.
12154                  * This is more of an informative/diagnostic error.
12155                  */
12156 #if 0
12157                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12158                        "%u:%u:%u tag %d type %d\n",
12159                        io->io_hdr.nexus.initid,
12160                        io->io_hdr.nexus.targ_port,
12161                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12162                        io->taskio.tag_type);
12163 #endif
12164         }
12165         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12166         return (0);
12167 }
12168
12169 static int
12170 ctl_query_task(union ctl_io *io, int task_set)
12171 {
12172         union ctl_io *xio;
12173         struct ctl_lun *lun;
12174         struct ctl_softc *softc;
12175         int found = 0;
12176         uint32_t targ_lun;
12177
12178         softc = control_softc;
12179         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12180         mtx_lock(&softc->ctl_lock);
12181         if ((targ_lun >= CTL_MAX_LUNS) ||
12182             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12183                 mtx_unlock(&softc->ctl_lock);
12184                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12185                 return (1);
12186         }
12187         mtx_lock(&lun->lun_lock);
12188         mtx_unlock(&softc->ctl_lock);
12189         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12190              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12191
12192                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12193                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12194                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12195                         continue;
12196
12197                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12198                         found = 1;
12199                         break;
12200                 }
12201         }
12202         mtx_unlock(&lun->lun_lock);
12203         if (found)
12204                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12205         else
12206                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12207         return (0);
12208 }
12209
12210 static int
12211 ctl_query_async_event(union ctl_io *io)
12212 {
12213         struct ctl_lun *lun;
12214         struct ctl_softc *softc;
12215         ctl_ua_type ua;
12216         uint32_t targ_lun, initidx;
12217
12218         softc = control_softc;
12219         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12220         mtx_lock(&softc->ctl_lock);
12221         if ((targ_lun >= CTL_MAX_LUNS) ||
12222             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12223                 mtx_unlock(&softc->ctl_lock);
12224                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12225                 return (1);
12226         }
12227         mtx_lock(&lun->lun_lock);
12228         mtx_unlock(&softc->ctl_lock);
12229         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12230         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12231         mtx_unlock(&lun->lun_lock);
12232         if (ua != CTL_UA_NONE)
12233                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12234         else
12235                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12236         return (0);
12237 }
12238
12239 static void
12240 ctl_run_task(union ctl_io *io)
12241 {
12242         struct ctl_softc *softc = control_softc;
12243         int retval = 1;
12244
12245         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12246         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12247             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12248         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12249         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12250         switch (io->taskio.task_action) {
12251         case CTL_TASK_ABORT_TASK:
12252                 retval = ctl_abort_task(io);
12253                 break;
12254         case CTL_TASK_ABORT_TASK_SET:
12255         case CTL_TASK_CLEAR_TASK_SET:
12256                 retval = ctl_abort_task_set(io);
12257                 break;
12258         case CTL_TASK_CLEAR_ACA:
12259                 break;
12260         case CTL_TASK_I_T_NEXUS_RESET:
12261                 retval = ctl_i_t_nexus_reset(io);
12262                 break;
12263         case CTL_TASK_LUN_RESET:
12264                 retval = ctl_lun_reset(softc, io);
12265                 break;
12266         case CTL_TASK_TARGET_RESET:
12267                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12268                 break;
12269         case CTL_TASK_BUS_RESET:
12270                 retval = ctl_bus_reset(softc, io);
12271                 break;
12272         case CTL_TASK_PORT_LOGIN:
12273                 break;
12274         case CTL_TASK_PORT_LOGOUT:
12275                 break;
12276         case CTL_TASK_QUERY_TASK:
12277                 retval = ctl_query_task(io, 0);
12278                 break;
12279         case CTL_TASK_QUERY_TASK_SET:
12280                 retval = ctl_query_task(io, 1);
12281                 break;
12282         case CTL_TASK_QUERY_ASYNC_EVENT:
12283                 retval = ctl_query_async_event(io);
12284                 break;
12285         default:
12286                 printf("%s: got unknown task management event %d\n",
12287                        __func__, io->taskio.task_action);
12288                 break;
12289         }
12290         if (retval == 0)
12291                 io->io_hdr.status = CTL_SUCCESS;
12292         else
12293                 io->io_hdr.status = CTL_ERROR;
12294         ctl_done(io);
12295 }
12296
12297 /*
12298  * For HA operation.  Handle commands that come in from the other
12299  * controller.
12300  */
12301 static void
12302 ctl_handle_isc(union ctl_io *io)
12303 {
12304         int free_io;
12305         struct ctl_lun *lun;
12306         struct ctl_softc *softc = control_softc;
12307         uint32_t targ_lun;
12308
12309         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12310         lun = softc->ctl_luns[targ_lun];
12311
12312         switch (io->io_hdr.msg_type) {
12313         case CTL_MSG_SERIALIZE:
12314                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12315                 break;
12316         case CTL_MSG_R2R: {
12317                 const struct ctl_cmd_entry *entry;
12318
12319                 /*
12320                  * This is only used in SER_ONLY mode.
12321                  */
12322                 free_io = 0;
12323                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12324                 mtx_lock(&lun->lun_lock);
12325                 if (ctl_scsiio_lun_check(lun,
12326                     entry, (struct ctl_scsiio *)io) != 0) {
12327                         mtx_unlock(&lun->lun_lock);
12328                         ctl_done(io);
12329                         break;
12330                 }
12331                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12332                 mtx_unlock(&lun->lun_lock);
12333                 ctl_enqueue_rtr(io);
12334                 break;
12335         }
12336         case CTL_MSG_FINISH_IO:
12337                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12338                         free_io = 0;
12339                         ctl_done(io);
12340                 } else {
12341                         free_io = 1;
12342                         mtx_lock(&lun->lun_lock);
12343                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12344                                      ooa_links);
12345                         ctl_check_blocked(lun);
12346                         mtx_unlock(&lun->lun_lock);
12347                 }
12348                 break;
12349         case CTL_MSG_PERS_ACTION:
12350                 ctl_hndl_per_res_out_on_other_sc(
12351                         (union ctl_ha_msg *)&io->presio.pr_msg);
12352                 free_io = 1;
12353                 break;
12354         case CTL_MSG_BAD_JUJU:
12355                 free_io = 0;
12356                 ctl_done(io);
12357                 break;
12358         case CTL_MSG_DATAMOVE:
12359                 /* Only used in XFER mode */
12360                 free_io = 0;
12361                 ctl_datamove_remote(io);
12362                 break;
12363         case CTL_MSG_DATAMOVE_DONE:
12364                 /* Only used in XFER mode */
12365                 free_io = 0;
12366                 io->scsiio.be_move_done(io);
12367                 break;
12368         case CTL_MSG_FAILOVER:
12369                 mtx_lock(&lun->lun_lock);
12370                 ctl_failover_lun(lun);
12371                 mtx_unlock(&lun->lun_lock);
12372                 free_io = 1;
12373                 break;
12374         default:
12375                 free_io = 1;
12376                 printf("%s: Invalid message type %d\n",
12377                        __func__, io->io_hdr.msg_type);
12378                 break;
12379         }
12380         if (free_io)
12381                 ctl_free_io(io);
12382
12383 }
12384
12385
12386 /*
12387  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12388  * there is no match.
12389  */
12390 static ctl_lun_error_pattern
12391 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12392 {
12393         const struct ctl_cmd_entry *entry;
12394         ctl_lun_error_pattern filtered_pattern, pattern;
12395
12396         pattern = desc->error_pattern;
12397
12398         /*
12399          * XXX KDM we need more data passed into this function to match a
12400          * custom pattern, and we actually need to implement custom pattern
12401          * matching.
12402          */
12403         if (pattern & CTL_LUN_PAT_CMD)
12404                 return (CTL_LUN_PAT_CMD);
12405
12406         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12407                 return (CTL_LUN_PAT_ANY);
12408
12409         entry = ctl_get_cmd_entry(ctsio, NULL);
12410
12411         filtered_pattern = entry->pattern & pattern;
12412
12413         /*
12414          * If the user requested specific flags in the pattern (e.g.
12415          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12416          * flags.
12417          *
12418          * If the user did not specify any flags, it doesn't matter whether
12419          * or not the command supports the flags.
12420          */
12421         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12422              (pattern & ~CTL_LUN_PAT_MASK))
12423                 return (CTL_LUN_PAT_NONE);
12424
12425         /*
12426          * If the user asked for a range check, see if the requested LBA
12427          * range overlaps with this command's LBA range.
12428          */
12429         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12430                 uint64_t lba1;
12431                 uint64_t len1;
12432                 ctl_action action;
12433                 int retval;
12434
12435                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12436                 if (retval != 0)
12437                         return (CTL_LUN_PAT_NONE);
12438
12439                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12440                                               desc->lba_range.len, FALSE);
12441                 /*
12442                  * A "pass" means that the LBA ranges don't overlap, so
12443                  * this doesn't match the user's range criteria.
12444                  */
12445                 if (action == CTL_ACTION_PASS)
12446                         return (CTL_LUN_PAT_NONE);
12447         }
12448
12449         return (filtered_pattern);
12450 }
12451
12452 static void
12453 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12454 {
12455         struct ctl_error_desc *desc, *desc2;
12456
12457         mtx_assert(&lun->lun_lock, MA_OWNED);
12458
12459         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12460                 ctl_lun_error_pattern pattern;
12461                 /*
12462                  * Check to see whether this particular command matches
12463                  * the pattern in the descriptor.
12464                  */
12465                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12466                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12467                         continue;
12468
12469                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12470                 case CTL_LUN_INJ_ABORTED:
12471                         ctl_set_aborted(&io->scsiio);
12472                         break;
12473                 case CTL_LUN_INJ_MEDIUM_ERR:
12474                         ctl_set_medium_error(&io->scsiio,
12475                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12476                              CTL_FLAG_DATA_OUT);
12477                         break;
12478                 case CTL_LUN_INJ_UA:
12479                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12480                          * OCCURRED */
12481                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12482                         break;
12483                 case CTL_LUN_INJ_CUSTOM:
12484                         /*
12485                          * We're assuming the user knows what he is doing.
12486                          * Just copy the sense information without doing
12487                          * checks.
12488                          */
12489                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12490                               MIN(sizeof(desc->custom_sense),
12491                                   sizeof(io->scsiio.sense_data)));
12492                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12493                         io->scsiio.sense_len = SSD_FULL_SIZE;
12494                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12495                         break;
12496                 case CTL_LUN_INJ_NONE:
12497                 default:
12498                         /*
12499                          * If this is an error injection type we don't know
12500                          * about, clear the continuous flag (if it is set)
12501                          * so it will get deleted below.
12502                          */
12503                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12504                         break;
12505                 }
12506                 /*
12507                  * By default, each error injection action is a one-shot
12508                  */
12509                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12510                         continue;
12511
12512                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12513
12514                 free(desc, M_CTL);
12515         }
12516 }
12517
12518 #ifdef CTL_IO_DELAY
12519 static void
12520 ctl_datamove_timer_wakeup(void *arg)
12521 {
12522         union ctl_io *io;
12523
12524         io = (union ctl_io *)arg;
12525
12526         ctl_datamove(io);
12527 }
12528 #endif /* CTL_IO_DELAY */
12529
12530 void
12531 ctl_datamove(union ctl_io *io)
12532 {
12533         struct ctl_lun *lun;
12534         void (*fe_datamove)(union ctl_io *io);
12535
12536         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12537
12538         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12539
12540         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12541 #ifdef CTL_TIME_IO
12542         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12543                 char str[256];
12544                 char path_str[64];
12545                 struct sbuf sb;
12546
12547                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12548                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12549
12550                 sbuf_cat(&sb, path_str);
12551                 switch (io->io_hdr.io_type) {
12552                 case CTL_IO_SCSI:
12553                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12554                         sbuf_printf(&sb, "\n");
12555                         sbuf_cat(&sb, path_str);
12556                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12557                                     io->scsiio.tag_num, io->scsiio.tag_type);
12558                         break;
12559                 case CTL_IO_TASK:
12560                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12561                                     "Tag Type: %d\n", io->taskio.task_action,
12562                                     io->taskio.tag_num, io->taskio.tag_type);
12563                         break;
12564                 default:
12565                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12566                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12567                         break;
12568                 }
12569                 sbuf_cat(&sb, path_str);
12570                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12571                             (intmax_t)time_uptime - io->io_hdr.start_time);
12572                 sbuf_finish(&sb);
12573                 printf("%s", sbuf_data(&sb));
12574         }
12575 #endif /* CTL_TIME_IO */
12576
12577 #ifdef CTL_IO_DELAY
12578         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12579                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12580         } else {
12581                 if ((lun != NULL)
12582                  && (lun->delay_info.datamove_delay > 0)) {
12583
12584                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12585                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12586                         callout_reset(&io->io_hdr.delay_callout,
12587                                       lun->delay_info.datamove_delay * hz,
12588                                       ctl_datamove_timer_wakeup, io);
12589                         if (lun->delay_info.datamove_type ==
12590                             CTL_DELAY_TYPE_ONESHOT)
12591                                 lun->delay_info.datamove_delay = 0;
12592                         return;
12593                 }
12594         }
12595 #endif
12596
12597         /*
12598          * This command has been aborted.  Set the port status, so we fail
12599          * the data move.
12600          */
12601         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12602                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12603                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12604                        io->io_hdr.nexus.targ_port,
12605                        io->io_hdr.nexus.targ_lun);
12606                 io->io_hdr.port_status = 31337;
12607                 /*
12608                  * Note that the backend, in this case, will get the
12609                  * callback in its context.  In other cases it may get
12610                  * called in the frontend's interrupt thread context.
12611                  */
12612                 io->scsiio.be_move_done(io);
12613                 return;
12614         }
12615
12616         /* Don't confuse frontend with zero length data move. */
12617         if (io->scsiio.kern_data_len == 0) {
12618                 io->scsiio.be_move_done(io);
12619                 return;
12620         }
12621
12622         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12623         fe_datamove(io);
12624 }
12625
12626 static void
12627 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12628 {
12629         union ctl_ha_msg msg;
12630 #ifdef CTL_TIME_IO
12631         struct bintime cur_bt;
12632 #endif
12633
12634         memset(&msg, 0, sizeof(msg));
12635         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12636         msg.hdr.original_sc = io;
12637         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12638         msg.hdr.nexus = io->io_hdr.nexus;
12639         msg.hdr.status = io->io_hdr.status;
12640         msg.scsi.tag_num = io->scsiio.tag_num;
12641         msg.scsi.tag_type = io->scsiio.tag_type;
12642         msg.scsi.scsi_status = io->scsiio.scsi_status;
12643         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12644                io->scsiio.sense_len);
12645         msg.scsi.sense_len = io->scsiio.sense_len;
12646         msg.scsi.sense_residual = io->scsiio.sense_residual;
12647         msg.scsi.fetd_status = io->io_hdr.port_status;
12648         msg.scsi.residual = io->scsiio.residual;
12649         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12650         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12651                 ctl_failover_io(io, /*have_lock*/ have_lock);
12652                 return;
12653         }
12654         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12655             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12656             msg.scsi.sense_len, M_WAITOK);
12657
12658 #ifdef CTL_TIME_IO
12659         getbinuptime(&cur_bt);
12660         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12661         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12662 #endif
12663         io->io_hdr.num_dmas++;
12664 }
12665
12666 /*
12667  * The DMA to the remote side is done, now we need to tell the other side
12668  * we're done so it can continue with its data movement.
12669  */
12670 static void
12671 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12672 {
12673         union ctl_io *io;
12674         int i;
12675
12676         io = rq->context;
12677
12678         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12679                 printf("%s: ISC DMA write failed with error %d", __func__,
12680                        rq->ret);
12681                 ctl_set_internal_failure(&io->scsiio,
12682                                          /*sks_valid*/ 1,
12683                                          /*retry_count*/ rq->ret);
12684         }
12685
12686         ctl_dt_req_free(rq);
12687
12688         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12689                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12690         free(io->io_hdr.remote_sglist, M_CTL);
12691         io->io_hdr.remote_sglist = NULL;
12692         io->io_hdr.local_sglist = NULL;
12693
12694         /*
12695          * The data is in local and remote memory, so now we need to send
12696          * status (good or back) back to the other side.
12697          */
12698         ctl_send_datamove_done(io, /*have_lock*/ 0);
12699 }
12700
12701 /*
12702  * We've moved the data from the host/controller into local memory.  Now we
12703  * need to push it over to the remote controller's memory.
12704  */
12705 static int
12706 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12707 {
12708         int retval;
12709
12710         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12711                                           ctl_datamove_remote_write_cb);
12712         return (retval);
12713 }
12714
12715 static void
12716 ctl_datamove_remote_write(union ctl_io *io)
12717 {
12718         int retval;
12719         void (*fe_datamove)(union ctl_io *io);
12720
12721         /*
12722          * - Get the data from the host/HBA into local memory.
12723          * - DMA memory from the local controller to the remote controller.
12724          * - Send status back to the remote controller.
12725          */
12726
12727         retval = ctl_datamove_remote_sgl_setup(io);
12728         if (retval != 0)
12729                 return;
12730
12731         /* Switch the pointer over so the FETD knows what to do */
12732         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12733
12734         /*
12735          * Use a custom move done callback, since we need to send completion
12736          * back to the other controller, not to the backend on this side.
12737          */
12738         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12739
12740         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12741         fe_datamove(io);
12742 }
12743
12744 static int
12745 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12746 {
12747 #if 0
12748         char str[256];
12749         char path_str[64];
12750         struct sbuf sb;
12751 #endif
12752         int i;
12753
12754         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12755                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12756         free(io->io_hdr.remote_sglist, M_CTL);
12757         io->io_hdr.remote_sglist = NULL;
12758         io->io_hdr.local_sglist = NULL;
12759
12760 #if 0
12761         scsi_path_string(io, path_str, sizeof(path_str));
12762         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12763         sbuf_cat(&sb, path_str);
12764         scsi_command_string(&io->scsiio, NULL, &sb);
12765         sbuf_printf(&sb, "\n");
12766         sbuf_cat(&sb, path_str);
12767         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12768                     io->scsiio.tag_num, io->scsiio.tag_type);
12769         sbuf_cat(&sb, path_str);
12770         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12771                     io->io_hdr.flags, io->io_hdr.status);
12772         sbuf_finish(&sb);
12773         printk("%s", sbuf_data(&sb));
12774 #endif
12775
12776
12777         /*
12778          * The read is done, now we need to send status (good or bad) back
12779          * to the other side.
12780          */
12781         ctl_send_datamove_done(io, /*have_lock*/ 0);
12782
12783         return (0);
12784 }
12785
12786 static void
12787 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12788 {
12789         union ctl_io *io;
12790         void (*fe_datamove)(union ctl_io *io);
12791
12792         io = rq->context;
12793
12794         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12795                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12796                        rq->ret);
12797                 ctl_set_internal_failure(&io->scsiio,
12798                                          /*sks_valid*/ 1,
12799                                          /*retry_count*/ rq->ret);
12800         }
12801
12802         ctl_dt_req_free(rq);
12803
12804         /* Switch the pointer over so the FETD knows what to do */
12805         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12806
12807         /*
12808          * Use a custom move done callback, since we need to send completion
12809          * back to the other controller, not to the backend on this side.
12810          */
12811         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12812
12813         /* XXX KDM add checks like the ones in ctl_datamove? */
12814
12815         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12816         fe_datamove(io);
12817 }
12818
12819 static int
12820 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12821 {
12822         struct ctl_sg_entry *local_sglist;
12823         uint32_t len_to_go;
12824         int retval;
12825         int i;
12826
12827         retval = 0;
12828         local_sglist = io->io_hdr.local_sglist;
12829         len_to_go = io->scsiio.kern_data_len;
12830
12831         /*
12832          * The difficult thing here is that the size of the various
12833          * S/G segments may be different than the size from the
12834          * remote controller.  That'll make it harder when DMAing
12835          * the data back to the other side.
12836          */
12837         for (i = 0; len_to_go > 0; i++) {
12838                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12839                 local_sglist[i].addr =
12840                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12841
12842                 len_to_go -= local_sglist[i].len;
12843         }
12844         /*
12845          * Reset the number of S/G entries accordingly.  The original
12846          * number of S/G entries is available in rem_sg_entries.
12847          */
12848         io->scsiio.kern_sg_entries = i;
12849
12850 #if 0
12851         printf("%s: kern_sg_entries = %d\n", __func__,
12852                io->scsiio.kern_sg_entries);
12853         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12854                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12855                        local_sglist[i].addr, local_sglist[i].len);
12856 #endif
12857
12858         return (retval);
12859 }
12860
12861 static int
12862 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12863                          ctl_ha_dt_cb callback)
12864 {
12865         struct ctl_ha_dt_req *rq;
12866         struct ctl_sg_entry *remote_sglist, *local_sglist;
12867         uint32_t local_used, remote_used, total_used;
12868         int i, j, isc_ret;
12869
12870         rq = ctl_dt_req_alloc();
12871
12872         /*
12873          * If we failed to allocate the request, and if the DMA didn't fail
12874          * anyway, set busy status.  This is just a resource allocation
12875          * failure.
12876          */
12877         if ((rq == NULL)
12878          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12879              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12880                 ctl_set_busy(&io->scsiio);
12881
12882         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12883             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12884
12885                 if (rq != NULL)
12886                         ctl_dt_req_free(rq);
12887
12888                 /*
12889                  * The data move failed.  We need to return status back
12890                  * to the other controller.  No point in trying to DMA
12891                  * data to the remote controller.
12892                  */
12893
12894                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12895
12896                 return (1);
12897         }
12898
12899         local_sglist = io->io_hdr.local_sglist;
12900         remote_sglist = io->io_hdr.remote_sglist;
12901         local_used = 0;
12902         remote_used = 0;
12903         total_used = 0;
12904
12905         /*
12906          * Pull/push the data over the wire from/to the other controller.
12907          * This takes into account the possibility that the local and
12908          * remote sglists may not be identical in terms of the size of
12909          * the elements and the number of elements.
12910          *
12911          * One fundamental assumption here is that the length allocated for
12912          * both the local and remote sglists is identical.  Otherwise, we've
12913          * essentially got a coding error of some sort.
12914          */
12915         isc_ret = CTL_HA_STATUS_SUCCESS;
12916         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12917                 uint32_t cur_len;
12918                 uint8_t *tmp_ptr;
12919
12920                 rq->command = command;
12921                 rq->context = io;
12922
12923                 /*
12924                  * Both pointers should be aligned.  But it is possible
12925                  * that the allocation length is not.  They should both
12926                  * also have enough slack left over at the end, though,
12927                  * to round up to the next 8 byte boundary.
12928                  */
12929                 cur_len = MIN(local_sglist[i].len - local_used,
12930                               remote_sglist[j].len - remote_used);
12931                 rq->size = cur_len;
12932
12933                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12934                 tmp_ptr += local_used;
12935
12936 #if 0
12937                 /* Use physical addresses when talking to ISC hardware */
12938                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12939                         /* XXX KDM use busdma */
12940                         rq->local = vtophys(tmp_ptr);
12941                 } else
12942                         rq->local = tmp_ptr;
12943 #else
12944                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12945                     ("HA does not support BUS_ADDR"));
12946                 rq->local = tmp_ptr;
12947 #endif
12948
12949                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12950                 tmp_ptr += remote_used;
12951                 rq->remote = tmp_ptr;
12952
12953                 rq->callback = NULL;
12954
12955                 local_used += cur_len;
12956                 if (local_used >= local_sglist[i].len) {
12957                         i++;
12958                         local_used = 0;
12959                 }
12960
12961                 remote_used += cur_len;
12962                 if (remote_used >= remote_sglist[j].len) {
12963                         j++;
12964                         remote_used = 0;
12965                 }
12966                 total_used += cur_len;
12967
12968                 if (total_used >= io->scsiio.kern_data_len)
12969                         rq->callback = callback;
12970
12971 #if 0
12972                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12973                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12974                        rq->local, rq->remote, rq->size);
12975 #endif
12976
12977                 isc_ret = ctl_dt_single(rq);
12978                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12979                         break;
12980         }
12981         if (isc_ret != CTL_HA_STATUS_WAIT) {
12982                 rq->ret = isc_ret;
12983                 callback(rq);
12984         }
12985
12986         return (0);
12987 }
12988
12989 static void
12990 ctl_datamove_remote_read(union ctl_io *io)
12991 {
12992         int retval;
12993         int i;
12994
12995         /*
12996          * This will send an error to the other controller in the case of a
12997          * failure.
12998          */
12999         retval = ctl_datamove_remote_sgl_setup(io);
13000         if (retval != 0)
13001                 return;
13002
13003         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13004                                           ctl_datamove_remote_read_cb);
13005         if (retval != 0) {
13006                 /*
13007                  * Make sure we free memory if there was an error..  The
13008                  * ctl_datamove_remote_xfer() function will send the
13009                  * datamove done message, or call the callback with an
13010                  * error if there is a problem.
13011                  */
13012                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13013                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13014                 free(io->io_hdr.remote_sglist, M_CTL);
13015                 io->io_hdr.remote_sglist = NULL;
13016                 io->io_hdr.local_sglist = NULL;
13017         }
13018 }
13019
13020 /*
13021  * Process a datamove request from the other controller.  This is used for
13022  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13023  * first.  Once that is complete, the data gets DMAed into the remote
13024  * controller's memory.  For reads, we DMA from the remote controller's
13025  * memory into our memory first, and then move it out to the FETD.
13026  */
13027 static void
13028 ctl_datamove_remote(union ctl_io *io)
13029 {
13030
13031         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13032
13033         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13034                 ctl_failover_io(io, /*have_lock*/ 0);
13035                 return;
13036         }
13037
13038         /*
13039          * Note that we look for an aborted I/O here, but don't do some of
13040          * the other checks that ctl_datamove() normally does.
13041          * We don't need to run the datamove delay code, since that should
13042          * have been done if need be on the other controller.
13043          */
13044         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13045                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13046                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13047                        io->io_hdr.nexus.targ_port,
13048                        io->io_hdr.nexus.targ_lun);
13049                 io->io_hdr.port_status = 31338;
13050                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13051                 return;
13052         }
13053
13054         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13055                 ctl_datamove_remote_write(io);
13056         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13057                 ctl_datamove_remote_read(io);
13058         else {
13059                 io->io_hdr.port_status = 31339;
13060                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13061         }
13062 }
13063
13064 static int
13065 ctl_process_done(union ctl_io *io)
13066 {
13067         struct ctl_lun *lun;
13068         struct ctl_softc *softc = control_softc;
13069         void (*fe_done)(union ctl_io *io);
13070         union ctl_ha_msg msg;
13071         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13072
13073         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13074         fe_done = softc->ctl_ports[targ_port]->fe_done;
13075
13076 #ifdef CTL_TIME_IO
13077         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13078                 char str[256];
13079                 char path_str[64];
13080                 struct sbuf sb;
13081
13082                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13083                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13084
13085                 sbuf_cat(&sb, path_str);
13086                 switch (io->io_hdr.io_type) {
13087                 case CTL_IO_SCSI:
13088                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13089                         sbuf_printf(&sb, "\n");
13090                         sbuf_cat(&sb, path_str);
13091                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13092                                     io->scsiio.tag_num, io->scsiio.tag_type);
13093                         break;
13094                 case CTL_IO_TASK:
13095                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13096                                     "Tag Type: %d\n", io->taskio.task_action,
13097                                     io->taskio.tag_num, io->taskio.tag_type);
13098                         break;
13099                 default:
13100                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13101                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13102                         break;
13103                 }
13104                 sbuf_cat(&sb, path_str);
13105                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13106                             (intmax_t)time_uptime - io->io_hdr.start_time);
13107                 sbuf_finish(&sb);
13108                 printf("%s", sbuf_data(&sb));
13109         }
13110 #endif /* CTL_TIME_IO */
13111
13112         switch (io->io_hdr.io_type) {
13113         case CTL_IO_SCSI:
13114                 break;
13115         case CTL_IO_TASK:
13116                 if (ctl_debug & CTL_DEBUG_INFO)
13117                         ctl_io_error_print(io, NULL);
13118                 fe_done(io);
13119                 return (CTL_RETVAL_COMPLETE);
13120         default:
13121                 panic("ctl_process_done: invalid io type %d\n",
13122                       io->io_hdr.io_type);
13123                 break; /* NOTREACHED */
13124         }
13125
13126         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13127         if (lun == NULL) {
13128                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13129                                  io->io_hdr.nexus.targ_mapped_lun));
13130                 goto bailout;
13131         }
13132
13133         mtx_lock(&lun->lun_lock);
13134
13135         /*
13136          * Check to see if we have any errors to inject here.  We only
13137          * inject errors for commands that don't already have errors set.
13138          */
13139         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13140             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13141             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13142                 ctl_inject_error(lun, io);
13143
13144         /*
13145          * XXX KDM how do we treat commands that aren't completed
13146          * successfully?
13147          *
13148          * XXX KDM should we also track I/O latency?
13149          */
13150         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13151             io->io_hdr.io_type == CTL_IO_SCSI) {
13152 #ifdef CTL_TIME_IO
13153                 struct bintime cur_bt;
13154 #endif
13155                 int type;
13156
13157                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13158                     CTL_FLAG_DATA_IN)
13159                         type = CTL_STATS_READ;
13160                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13161                     CTL_FLAG_DATA_OUT)
13162                         type = CTL_STATS_WRITE;
13163                 else
13164                         type = CTL_STATS_NO_IO;
13165
13166                 lun->stats.ports[targ_port].bytes[type] +=
13167                     io->scsiio.kern_total_len;
13168                 lun->stats.ports[targ_port].operations[type]++;
13169 #ifdef CTL_TIME_IO
13170                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13171                    &io->io_hdr.dma_bt);
13172                 getbinuptime(&cur_bt);
13173                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13174                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13175 #endif
13176                 lun->stats.ports[targ_port].num_dmas[type] +=
13177                     io->io_hdr.num_dmas;
13178         }
13179
13180         /*
13181          * Remove this from the OOA queue.
13182          */
13183         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13184 #ifdef CTL_TIME_IO
13185         if (TAILQ_EMPTY(&lun->ooa_queue))
13186                 lun->last_busy = getsbinuptime();
13187 #endif
13188
13189         /*
13190          * Run through the blocked queue on this LUN and see if anything
13191          * has become unblocked, now that this transaction is done.
13192          */
13193         ctl_check_blocked(lun);
13194
13195         /*
13196          * If the LUN has been invalidated, free it if there is nothing
13197          * left on its OOA queue.
13198          */
13199         if ((lun->flags & CTL_LUN_INVALID)
13200          && TAILQ_EMPTY(&lun->ooa_queue)) {
13201                 mtx_unlock(&lun->lun_lock);
13202                 mtx_lock(&softc->ctl_lock);
13203                 ctl_free_lun(lun);
13204                 mtx_unlock(&softc->ctl_lock);
13205         } else
13206                 mtx_unlock(&lun->lun_lock);
13207
13208 bailout:
13209
13210         /*
13211          * If this command has been aborted, make sure we set the status
13212          * properly.  The FETD is responsible for freeing the I/O and doing
13213          * whatever it needs to do to clean up its state.
13214          */
13215         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13216                 ctl_set_task_aborted(&io->scsiio);
13217
13218         /*
13219          * If enabled, print command error status.
13220          */
13221         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13222             (ctl_debug & CTL_DEBUG_INFO) != 0)
13223                 ctl_io_error_print(io, NULL);
13224
13225         /*
13226          * Tell the FETD or the other shelf controller we're done with this
13227          * command.  Note that only SCSI commands get to this point.  Task
13228          * management commands are completed above.
13229          */
13230         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13231             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13232                 memset(&msg, 0, sizeof(msg));
13233                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13234                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13235                 msg.hdr.nexus = io->io_hdr.nexus;
13236                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13237                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13238                     M_WAITOK);
13239         }
13240
13241         fe_done(io);
13242         return (CTL_RETVAL_COMPLETE);
13243 }
13244
13245 #ifdef CTL_WITH_CA
13246 /*
13247  * Front end should call this if it doesn't do autosense.  When the request
13248  * sense comes back in from the initiator, we'll dequeue this and send it.
13249  */
13250 int
13251 ctl_queue_sense(union ctl_io *io)
13252 {
13253         struct ctl_lun *lun;
13254         struct ctl_port *port;
13255         struct ctl_softc *softc;
13256         uint32_t initidx, targ_lun;
13257
13258         softc = control_softc;
13259
13260         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13261
13262         /*
13263          * LUN lookup will likely move to the ctl_work_thread() once we
13264          * have our new queueing infrastructure (that doesn't put things on
13265          * a per-LUN queue initially).  That is so that we can handle
13266          * things like an INQUIRY to a LUN that we don't have enabled.  We
13267          * can't deal with that right now.
13268          */
13269         mtx_lock(&softc->ctl_lock);
13270
13271         /*
13272          * If we don't have a LUN for this, just toss the sense
13273          * information.
13274          */
13275         port = ctl_io_port(&ctsio->io_hdr);
13276         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13277         if ((targ_lun < CTL_MAX_LUNS)
13278          && (softc->ctl_luns[targ_lun] != NULL))
13279                 lun = softc->ctl_luns[targ_lun];
13280         else
13281                 goto bailout;
13282
13283         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13284
13285         mtx_lock(&lun->lun_lock);
13286         /*
13287          * Already have CA set for this LUN...toss the sense information.
13288          */
13289         if (ctl_is_set(lun->have_ca, initidx)) {
13290                 mtx_unlock(&lun->lun_lock);
13291                 goto bailout;
13292         }
13293
13294         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13295                MIN(sizeof(lun->pending_sense[initidx]),
13296                sizeof(io->scsiio.sense_data)));
13297         ctl_set_mask(lun->have_ca, initidx);
13298         mtx_unlock(&lun->lun_lock);
13299
13300 bailout:
13301         mtx_unlock(&softc->ctl_lock);
13302
13303         ctl_free_io(io);
13304
13305         return (CTL_RETVAL_COMPLETE);
13306 }
13307 #endif
13308
13309 /*
13310  * Primary command inlet from frontend ports.  All SCSI and task I/O
13311  * requests must go through this function.
13312  */
13313 int
13314 ctl_queue(union ctl_io *io)
13315 {
13316         struct ctl_port *port;
13317
13318         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13319
13320 #ifdef CTL_TIME_IO
13321         io->io_hdr.start_time = time_uptime;
13322         getbinuptime(&io->io_hdr.start_bt);
13323 #endif /* CTL_TIME_IO */
13324
13325         /* Map FE-specific LUN ID into global one. */
13326         port = ctl_io_port(&io->io_hdr);
13327         io->io_hdr.nexus.targ_mapped_lun =
13328             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13329
13330         switch (io->io_hdr.io_type) {
13331         case CTL_IO_SCSI:
13332         case CTL_IO_TASK:
13333                 if (ctl_debug & CTL_DEBUG_CDB)
13334                         ctl_io_print(io);
13335                 ctl_enqueue_incoming(io);
13336                 break;
13337         default:
13338                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13339                 return (EINVAL);
13340         }
13341
13342         return (CTL_RETVAL_COMPLETE);
13343 }
13344
13345 #ifdef CTL_IO_DELAY
13346 static void
13347 ctl_done_timer_wakeup(void *arg)
13348 {
13349         union ctl_io *io;
13350
13351         io = (union ctl_io *)arg;
13352         ctl_done(io);
13353 }
13354 #endif /* CTL_IO_DELAY */
13355
13356 void
13357 ctl_serseq_done(union ctl_io *io)
13358 {
13359         struct ctl_lun *lun;
13360
13361         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13362         if (lun->be_lun == NULL ||
13363             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13364                 return;
13365         mtx_lock(&lun->lun_lock);
13366         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13367         ctl_check_blocked(lun);
13368         mtx_unlock(&lun->lun_lock);
13369 }
13370
13371 void
13372 ctl_done(union ctl_io *io)
13373 {
13374
13375         /*
13376          * Enable this to catch duplicate completion issues.
13377          */
13378 #if 0
13379         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13380                 printf("%s: type %d msg %d cdb %x iptl: "
13381                        "%u:%u:%u tag 0x%04x "
13382                        "flag %#x status %x\n",
13383                         __func__,
13384                         io->io_hdr.io_type,
13385                         io->io_hdr.msg_type,
13386                         io->scsiio.cdb[0],
13387                         io->io_hdr.nexus.initid,
13388                         io->io_hdr.nexus.targ_port,
13389                         io->io_hdr.nexus.targ_lun,
13390                         (io->io_hdr.io_type ==
13391                         CTL_IO_TASK) ?
13392                         io->taskio.tag_num :
13393                         io->scsiio.tag_num,
13394                         io->io_hdr.flags,
13395                         io->io_hdr.status);
13396         } else
13397                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13398 #endif
13399
13400         /*
13401          * This is an internal copy of an I/O, and should not go through
13402          * the normal done processing logic.
13403          */
13404         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13405                 return;
13406
13407 #ifdef CTL_IO_DELAY
13408         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13409                 struct ctl_lun *lun;
13410
13411                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13412
13413                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13414         } else {
13415                 struct ctl_lun *lun;
13416
13417                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13418
13419                 if ((lun != NULL)
13420                  && (lun->delay_info.done_delay > 0)) {
13421
13422                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13423                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13424                         callout_reset(&io->io_hdr.delay_callout,
13425                                       lun->delay_info.done_delay * hz,
13426                                       ctl_done_timer_wakeup, io);
13427                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13428                                 lun->delay_info.done_delay = 0;
13429                         return;
13430                 }
13431         }
13432 #endif /* CTL_IO_DELAY */
13433
13434         ctl_enqueue_done(io);
13435 }
13436
13437 static void
13438 ctl_work_thread(void *arg)
13439 {
13440         struct ctl_thread *thr = (struct ctl_thread *)arg;
13441         struct ctl_softc *softc = thr->ctl_softc;
13442         union ctl_io *io;
13443         int retval;
13444
13445         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13446
13447         for (;;) {
13448                 retval = 0;
13449
13450                 /*
13451                  * We handle the queues in this order:
13452                  * - ISC
13453                  * - done queue (to free up resources, unblock other commands)
13454                  * - RtR queue
13455                  * - incoming queue
13456                  *
13457                  * If those queues are empty, we break out of the loop and
13458                  * go to sleep.
13459                  */
13460                 mtx_lock(&thr->queue_lock);
13461                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13462                 if (io != NULL) {
13463                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13464                         mtx_unlock(&thr->queue_lock);
13465                         ctl_handle_isc(io);
13466                         continue;
13467                 }
13468                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13469                 if (io != NULL) {
13470                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13471                         /* clear any blocked commands, call fe_done */
13472                         mtx_unlock(&thr->queue_lock);
13473                         retval = ctl_process_done(io);
13474                         continue;
13475                 }
13476                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13477                 if (io != NULL) {
13478                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13479                         mtx_unlock(&thr->queue_lock);
13480                         if (io->io_hdr.io_type == CTL_IO_TASK)
13481                                 ctl_run_task(io);
13482                         else
13483                                 ctl_scsiio_precheck(softc, &io->scsiio);
13484                         continue;
13485                 }
13486                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13487                 if (io != NULL) {
13488                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13489                         mtx_unlock(&thr->queue_lock);
13490                         retval = ctl_scsiio(&io->scsiio);
13491                         if (retval != CTL_RETVAL_COMPLETE)
13492                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13493                         continue;
13494                 }
13495
13496                 /* Sleep until we have something to do. */
13497                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13498         }
13499 }
13500
13501 static void
13502 ctl_lun_thread(void *arg)
13503 {
13504         struct ctl_softc *softc = (struct ctl_softc *)arg;
13505         struct ctl_be_lun *be_lun;
13506         int retval;
13507
13508         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13509
13510         for (;;) {
13511                 retval = 0;
13512                 mtx_lock(&softc->ctl_lock);
13513                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13514                 if (be_lun != NULL) {
13515                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13516                         mtx_unlock(&softc->ctl_lock);
13517                         ctl_create_lun(be_lun);
13518                         continue;
13519                 }
13520
13521                 /* Sleep until we have something to do. */
13522                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13523                     PDROP | PRIBIO, "-", 0);
13524         }
13525 }
13526
13527 static void
13528 ctl_thresh_thread(void *arg)
13529 {
13530         struct ctl_softc *softc = (struct ctl_softc *)arg;
13531         struct ctl_lun *lun;
13532         struct ctl_be_lun *be_lun;
13533         struct scsi_da_rw_recovery_page *rwpage;
13534         struct ctl_logical_block_provisioning_page *page;
13535         const char *attr;
13536         union ctl_ha_msg msg;
13537         uint64_t thres, val;
13538         int i, e, set;
13539
13540         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13541
13542         for (;;) {
13543                 mtx_lock(&softc->ctl_lock);
13544                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13545                         be_lun = lun->be_lun;
13546                         if ((lun->flags & CTL_LUN_DISABLED) ||
13547                             (lun->flags & CTL_LUN_OFFLINE) ||
13548                             lun->backend->lun_attr == NULL)
13549                                 continue;
13550                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13551                             softc->ha_mode == CTL_HA_MODE_XFER)
13552                                 continue;
13553                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13554                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13555                                 continue;
13556                         e = 0;
13557                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13558                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13559                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13560                                         continue;
13561                                 thres = scsi_4btoul(page->descr[i].count);
13562                                 thres <<= CTL_LBP_EXPONENT;
13563                                 switch (page->descr[i].resource) {
13564                                 case 0x01:
13565                                         attr = "blocksavail";
13566                                         break;
13567                                 case 0x02:
13568                                         attr = "blocksused";
13569                                         break;
13570                                 case 0xf1:
13571                                         attr = "poolblocksavail";
13572                                         break;
13573                                 case 0xf2:
13574                                         attr = "poolblocksused";
13575                                         break;
13576                                 default:
13577                                         continue;
13578                                 }
13579                                 mtx_unlock(&softc->ctl_lock); // XXX
13580                                 val = lun->backend->lun_attr(
13581                                     lun->be_lun->be_lun, attr);
13582                                 mtx_lock(&softc->ctl_lock);
13583                                 if (val == UINT64_MAX)
13584                                         continue;
13585                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13586                                     == SLBPPD_ARMING_INC)
13587                                         e = (val >= thres);
13588                                 else
13589                                         e = (val <= thres);
13590                                 if (e)
13591                                         break;
13592                         }
13593                         mtx_lock(&lun->lun_lock);
13594                         if (e) {
13595                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13596                                     (uint8_t *)page, lun->ua_tpt_info);
13597                                 if (lun->lasttpt == 0 ||
13598                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13599                                         lun->lasttpt = time_uptime;
13600                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13601                                         set = 1;
13602                                 } else
13603                                         set = 0;
13604                         } else {
13605                                 lun->lasttpt = 0;
13606                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13607                                 set = -1;
13608                         }
13609                         mtx_unlock(&lun->lun_lock);
13610                         if (set != 0 &&
13611                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13612                                 /* Send msg to other side. */
13613                                 bzero(&msg.ua, sizeof(msg.ua));
13614                                 msg.hdr.msg_type = CTL_MSG_UA;
13615                                 msg.hdr.nexus.initid = -1;
13616                                 msg.hdr.nexus.targ_port = -1;
13617                                 msg.hdr.nexus.targ_lun = lun->lun;
13618                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13619                                 msg.ua.ua_all = 1;
13620                                 msg.ua.ua_set = (set > 0);
13621                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13622                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13623                                 mtx_unlock(&softc->ctl_lock); // XXX
13624                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13625                                     sizeof(msg.ua), M_WAITOK);
13626                                 mtx_lock(&softc->ctl_lock);
13627                         }
13628                 }
13629                 mtx_unlock(&softc->ctl_lock);
13630                 pause("-", CTL_LBP_PERIOD * hz);
13631         }
13632 }
13633
13634 static void
13635 ctl_enqueue_incoming(union ctl_io *io)
13636 {
13637         struct ctl_softc *softc = control_softc;
13638         struct ctl_thread *thr;
13639         u_int idx;
13640
13641         idx = (io->io_hdr.nexus.targ_port * 127 +
13642                io->io_hdr.nexus.initid) % worker_threads;
13643         thr = &softc->threads[idx];
13644         mtx_lock(&thr->queue_lock);
13645         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13646         mtx_unlock(&thr->queue_lock);
13647         wakeup(thr);
13648 }
13649
13650 static void
13651 ctl_enqueue_rtr(union ctl_io *io)
13652 {
13653         struct ctl_softc *softc = control_softc;
13654         struct ctl_thread *thr;
13655
13656         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13657         mtx_lock(&thr->queue_lock);
13658         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13659         mtx_unlock(&thr->queue_lock);
13660         wakeup(thr);
13661 }
13662
13663 static void
13664 ctl_enqueue_done(union ctl_io *io)
13665 {
13666         struct ctl_softc *softc = control_softc;
13667         struct ctl_thread *thr;
13668
13669         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13670         mtx_lock(&thr->queue_lock);
13671         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13672         mtx_unlock(&thr->queue_lock);
13673         wakeup(thr);
13674 }
13675
13676 static void
13677 ctl_enqueue_isc(union ctl_io *io)
13678 {
13679         struct ctl_softc *softc = control_softc;
13680         struct ctl_thread *thr;
13681
13682         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13683         mtx_lock(&thr->queue_lock);
13684         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13685         mtx_unlock(&thr->queue_lock);
13686         wakeup(thr);
13687 }
13688
13689 /*
13690  *  vim: ts=8
13691  */