]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl.c
MFV r337586: lua: Update to 5.3.5
[FreeBSD/FreeBSD.git] / sys / cam / ctl / ctl.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
46
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/sysctl.h>
70 #include <sys/nv.h>
71 #include <sys/dnv.h>
72 #include <vm/uma.h>
73
74 #include <cam/cam.h>
75 #include <cam/scsi/scsi_all.h>
76 #include <cam/scsi/scsi_cd.h>
77 #include <cam/scsi/scsi_da.h>
78 #include <cam/ctl/ctl_io.h>
79 #include <cam/ctl/ctl.h>
80 #include <cam/ctl/ctl_frontend.h>
81 #include <cam/ctl/ctl_util.h>
82 #include <cam/ctl/ctl_backend.h>
83 #include <cam/ctl/ctl_ioctl.h>
84 #include <cam/ctl/ctl_ha.h>
85 #include <cam/ctl/ctl_private.h>
86 #include <cam/ctl/ctl_debug.h>
87 #include <cam/ctl/ctl_scsi_all.h>
88 #include <cam/ctl/ctl_error.h>
89
90 struct ctl_softc *control_softc = NULL;
91
92 /*
93  * Template mode pages.
94  */
95
96 /*
97  * Note that these are default values only.  The actual values will be
98  * filled in when the user does a mode sense.
99  */
100 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
101         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
102         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
103         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
104         /*read_retry_count*/0,
105         /*correction_span*/0,
106         /*head_offset_count*/0,
107         /*data_strobe_offset_cnt*/0,
108         /*byte8*/SMS_RWER_LBPERE,
109         /*write_retry_count*/0,
110         /*reserved2*/0,
111         /*recovery_time_limit*/{0, 0},
112 };
113
114 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
115         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117         /*byte3*/SMS_RWER_PER,
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_format_page format_page_default = {
129         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
130         /*page_length*/sizeof(struct scsi_format_page) - 2,
131         /*tracks_per_zone*/ {0, 0},
132         /*alt_sectors_per_zone*/ {0, 0},
133         /*alt_tracks_per_zone*/ {0, 0},
134         /*alt_tracks_per_lun*/ {0, 0},
135         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
136                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
137         /*bytes_per_sector*/ {0, 0},
138         /*interleave*/ {0, 0},
139         /*track_skew*/ {0, 0},
140         /*cylinder_skew*/ {0, 0},
141         /*flags*/ SFP_HSEC,
142         /*reserved*/ {0, 0, 0}
143 };
144
145 const static struct scsi_format_page format_page_changeable = {
146         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
147         /*page_length*/sizeof(struct scsi_format_page) - 2,
148         /*tracks_per_zone*/ {0, 0},
149         /*alt_sectors_per_zone*/ {0, 0},
150         /*alt_tracks_per_zone*/ {0, 0},
151         /*alt_tracks_per_lun*/ {0, 0},
152         /*sectors_per_track*/ {0, 0},
153         /*bytes_per_sector*/ {0, 0},
154         /*interleave*/ {0, 0},
155         /*track_skew*/ {0, 0},
156         /*cylinder_skew*/ {0, 0},
157         /*flags*/ 0,
158         /*reserved*/ {0, 0, 0}
159 };
160
161 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
162         /*page_code*/SMS_RIGID_DISK_PAGE,
163         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
164         /*cylinders*/ {0, 0, 0},
165         /*heads*/ CTL_DEFAULT_HEADS,
166         /*start_write_precomp*/ {0, 0, 0},
167         /*start_reduced_current*/ {0, 0, 0},
168         /*step_rate*/ {0, 0},
169         /*landing_zone_cylinder*/ {0, 0, 0},
170         /*rpl*/ SRDP_RPL_DISABLED,
171         /*rotational_offset*/ 0,
172         /*reserved1*/ 0,
173         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
174                            CTL_DEFAULT_ROTATION_RATE & 0xff},
175         /*reserved2*/ {0, 0}
176 };
177
178 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
179         /*page_code*/SMS_RIGID_DISK_PAGE,
180         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
181         /*cylinders*/ {0, 0, 0},
182         /*heads*/ 0,
183         /*start_write_precomp*/ {0, 0, 0},
184         /*start_reduced_current*/ {0, 0, 0},
185         /*step_rate*/ {0, 0},
186         /*landing_zone_cylinder*/ {0, 0, 0},
187         /*rpl*/ 0,
188         /*rotational_offset*/ 0,
189         /*reserved1*/ 0,
190         /*rotation_rate*/ {0, 0},
191         /*reserved2*/ {0, 0}
192 };
193
194 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
195         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
196         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
197         /*byte3*/0,
198         /*read_retry_count*/0,
199         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
200         /*recovery_time_limit*/{0, 0},
201 };
202
203 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
204         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
205         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
206         /*byte3*/SMS_VER_PER,
207         /*read_retry_count*/0,
208         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
209         /*recovery_time_limit*/{0, 0},
210 };
211
212 const static struct scsi_caching_page caching_page_default = {
213         /*page_code*/SMS_CACHING_PAGE,
214         /*page_length*/sizeof(struct scsi_caching_page) - 2,
215         /*flags1*/ SCP_DISC | SCP_WCE,
216         /*ret_priority*/ 0,
217         /*disable_pf_transfer_len*/ {0xff, 0xff},
218         /*min_prefetch*/ {0, 0},
219         /*max_prefetch*/ {0xff, 0xff},
220         /*max_pf_ceiling*/ {0xff, 0xff},
221         /*flags2*/ 0,
222         /*cache_segments*/ 0,
223         /*cache_seg_size*/ {0, 0},
224         /*reserved*/ 0,
225         /*non_cache_seg_size*/ {0, 0, 0}
226 };
227
228 const static struct scsi_caching_page caching_page_changeable = {
229         /*page_code*/SMS_CACHING_PAGE,
230         /*page_length*/sizeof(struct scsi_caching_page) - 2,
231         /*flags1*/ SCP_WCE | SCP_RCD,
232         /*ret_priority*/ 0,
233         /*disable_pf_transfer_len*/ {0, 0},
234         /*min_prefetch*/ {0, 0},
235         /*max_prefetch*/ {0, 0},
236         /*max_pf_ceiling*/ {0, 0},
237         /*flags2*/ 0,
238         /*cache_segments*/ 0,
239         /*cache_seg_size*/ {0, 0},
240         /*reserved*/ 0,
241         /*non_cache_seg_size*/ {0, 0, 0}
242 };
243
244 const static struct scsi_control_page control_page_default = {
245         /*page_code*/SMS_CONTROL_MODE_PAGE,
246         /*page_length*/sizeof(struct scsi_control_page) - 2,
247         /*rlec*/0,
248         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
249         /*eca_and_aen*/0,
250         /*flags4*/SCP_TAS,
251         /*aen_holdoff_period*/{0, 0},
252         /*busy_timeout_period*/{0, 0},
253         /*extended_selftest_completion_time*/{0, 0}
254 };
255
256 const static struct scsi_control_page control_page_changeable = {
257         /*page_code*/SMS_CONTROL_MODE_PAGE,
258         /*page_length*/sizeof(struct scsi_control_page) - 2,
259         /*rlec*/SCP_DSENSE,
260         /*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
261         /*eca_and_aen*/SCP_SWP,
262         /*flags4*/0,
263         /*aen_holdoff_period*/{0, 0},
264         /*busy_timeout_period*/{0, 0},
265         /*extended_selftest_completion_time*/{0, 0}
266 };
267
268 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
269
270 const static struct scsi_control_ext_page control_ext_page_default = {
271         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
272         /*subpage_code*/0x01,
273         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
274         /*flags*/0,
275         /*prio*/0,
276         /*max_sense*/0
277 };
278
279 const static struct scsi_control_ext_page control_ext_page_changeable = {
280         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
281         /*subpage_code*/0x01,
282         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
283         /*flags*/0,
284         /*prio*/0,
285         /*max_sense*/0xff
286 };
287
288 const static struct scsi_info_exceptions_page ie_page_default = {
289         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
290         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
291         /*info_flags*/SIEP_FLAGS_EWASC,
292         /*mrie*/SIEP_MRIE_NO,
293         /*interval_timer*/{0, 0, 0, 0},
294         /*report_count*/{0, 0, 0, 1}
295 };
296
297 const static struct scsi_info_exceptions_page ie_page_changeable = {
298         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
299         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
300         /*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
301             SIEP_FLAGS_LOGERR,
302         /*mrie*/0x0f,
303         /*interval_timer*/{0xff, 0xff, 0xff, 0xff},
304         /*report_count*/{0xff, 0xff, 0xff, 0xff}
305 };
306
307 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
308
309 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
310         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
311         /*subpage_code*/0x02,
312         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
313         /*flags*/0,
314         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
315         /*descr*/{}},
316         {{/*flags*/0,
317           /*resource*/0x01,
318           /*reserved*/{0, 0},
319           /*count*/{0, 0, 0, 0}},
320          {/*flags*/0,
321           /*resource*/0x02,
322           /*reserved*/{0, 0},
323           /*count*/{0, 0, 0, 0}},
324          {/*flags*/0,
325           /*resource*/0xf1,
326           /*reserved*/{0, 0},
327           /*count*/{0, 0, 0, 0}},
328          {/*flags*/0,
329           /*resource*/0xf2,
330           /*reserved*/{0, 0},
331           /*count*/{0, 0, 0, 0}}
332         }
333 };
334
335 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
336         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
337         /*subpage_code*/0x02,
338         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
339         /*flags*/SLBPP_SITUA,
340         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
341         /*descr*/{}},
342         {{/*flags*/0,
343           /*resource*/0,
344           /*reserved*/{0, 0},
345           /*count*/{0, 0, 0, 0}},
346          {/*flags*/0,
347           /*resource*/0,
348           /*reserved*/{0, 0},
349           /*count*/{0, 0, 0, 0}},
350          {/*flags*/0,
351           /*resource*/0,
352           /*reserved*/{0, 0},
353           /*count*/{0, 0, 0, 0}},
354          {/*flags*/0,
355           /*resource*/0,
356           /*reserved*/{0, 0},
357           /*count*/{0, 0, 0, 0}}
358         }
359 };
360
361 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
362         /*page_code*/SMS_CDDVD_CAPS_PAGE,
363         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
364         /*caps1*/0x3f,
365         /*caps2*/0x00,
366         /*caps3*/0xf0,
367         /*caps4*/0x00,
368         /*caps5*/0x29,
369         /*caps6*/0x00,
370         /*obsolete*/{0, 0},
371         /*nvol_levels*/{0, 0},
372         /*buffer_size*/{8, 0},
373         /*obsolete2*/{0, 0},
374         /*reserved*/0,
375         /*digital*/0,
376         /*obsolete3*/0,
377         /*copy_management*/0,
378         /*reserved2*/0,
379         /*rotation_control*/0,
380         /*cur_write_speed*/0,
381         /*num_speed_descr*/0,
382 };
383
384 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
385         /*page_code*/SMS_CDDVD_CAPS_PAGE,
386         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
387         /*caps1*/0,
388         /*caps2*/0,
389         /*caps3*/0,
390         /*caps4*/0,
391         /*caps5*/0,
392         /*caps6*/0,
393         /*obsolete*/{0, 0},
394         /*nvol_levels*/{0, 0},
395         /*buffer_size*/{0, 0},
396         /*obsolete2*/{0, 0},
397         /*reserved*/0,
398         /*digital*/0,
399         /*obsolete3*/0,
400         /*copy_management*/0,
401         /*reserved2*/0,
402         /*rotation_control*/0,
403         /*cur_write_speed*/0,
404         /*num_speed_descr*/0,
405 };
406
407 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
408 static int worker_threads = -1;
409 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
410     &worker_threads, 1, "Number of worker threads");
411 static int ctl_debug = CTL_DEBUG_NONE;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
413     &ctl_debug, 0, "Enabled debug flags");
414 static int ctl_lun_map_size = 1024;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
416     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
417 #ifdef  CTL_TIME_IO
418 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
419 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
420     &ctl_time_io_secs, 0, "Log requests taking more seconds");
421 #endif
422
423 /*
424  * Maximum number of LUNs we support.  MUST be a power of 2.
425  */
426 #define CTL_DEFAULT_MAX_LUNS    1024
427 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
428 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
429 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
430     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
431
432 /*
433  * Maximum number of ports registered at one time.
434  */
435 #define CTL_DEFAULT_MAX_PORTS           256
436 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
437 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
438 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
439     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
440
441 /*
442  * Maximum number of initiators we support.
443  */
444 #define CTL_MAX_INITIATORS      (CTL_MAX_INIT_PER_PORT * ctl_max_ports)
445
446 /*
447  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
448  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
449  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
450  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
451  */
452 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
453
454 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
455                                   int param);
456 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
457 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
458 static int ctl_init(void);
459 static int ctl_shutdown(void);
460 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
461 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
462 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
463 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
464                               struct ctl_ooa *ooa_hdr,
465                               struct ctl_ooa_entry *kern_entries);
466 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
467                      struct thread *td);
468 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
469                          struct ctl_be_lun *be_lun);
470 static int ctl_free_lun(struct ctl_lun *lun);
471 static void ctl_create_lun(struct ctl_be_lun *be_lun);
472
473 static int ctl_do_mode_select(union ctl_io *io);
474 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
475                            uint64_t res_key, uint64_t sa_res_key,
476                            uint8_t type, uint32_t residx,
477                            struct ctl_scsiio *ctsio,
478                            struct scsi_per_res_out *cdb,
479                            struct scsi_per_res_out_parms* param);
480 static void ctl_pro_preempt_other(struct ctl_lun *lun,
481                                   union ctl_ha_msg *msg);
482 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
483 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
484 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
485 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
486 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
489                                          int alloc_len);
490 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
491                                          int alloc_len);
492 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
493 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
495 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
496 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
497 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
498     bool seq);
499 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
500 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
501     union ctl_io *pending_io, union ctl_io *ooa_io);
502 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
503                                 union ctl_io *starting_io);
504 static int ctl_check_blocked(struct ctl_lun *lun);
505 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
506                                 const struct ctl_cmd_entry *entry,
507                                 struct ctl_scsiio *ctsio);
508 static void ctl_failover_lun(union ctl_io *io);
509 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
510                                struct ctl_scsiio *ctsio);
511 static int ctl_scsiio(struct ctl_scsiio *ctsio);
512
513 static int ctl_target_reset(union ctl_io *io);
514 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
515                          ctl_ua_type ua_type);
516 static int ctl_lun_reset(union ctl_io *io);
517 static int ctl_abort_task(union ctl_io *io);
518 static int ctl_abort_task_set(union ctl_io *io);
519 static int ctl_query_task(union ctl_io *io, int task_set);
520 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
521                               ctl_ua_type ua_type);
522 static int ctl_i_t_nexus_reset(union ctl_io *io);
523 static int ctl_query_async_event(union ctl_io *io);
524 static void ctl_run_task(union ctl_io *io);
525 #ifdef CTL_IO_DELAY
526 static void ctl_datamove_timer_wakeup(void *arg);
527 static void ctl_done_timer_wakeup(void *arg);
528 #endif /* CTL_IO_DELAY */
529
530 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
531 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
532 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
533 static void ctl_datamove_remote_write(union ctl_io *io);
534 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
535 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
536 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
537 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
538                                     ctl_ha_dt_cb callback);
539 static void ctl_datamove_remote_read(union ctl_io *io);
540 static void ctl_datamove_remote(union ctl_io *io);
541 static void ctl_process_done(union ctl_io *io);
542 static void ctl_lun_thread(void *arg);
543 static void ctl_thresh_thread(void *arg);
544 static void ctl_work_thread(void *arg);
545 static void ctl_enqueue_incoming(union ctl_io *io);
546 static void ctl_enqueue_rtr(union ctl_io *io);
547 static void ctl_enqueue_done(union ctl_io *io);
548 static void ctl_enqueue_isc(union ctl_io *io);
549 static const struct ctl_cmd_entry *
550     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
551 static const struct ctl_cmd_entry *
552     ctl_validate_command(struct ctl_scsiio *ctsio);
553 static int ctl_cmd_applicable(uint8_t lun_type,
554     const struct ctl_cmd_entry *entry);
555 static int ctl_ha_init(void);
556 static int ctl_ha_shutdown(void);
557
558 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
559 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
560 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
561 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
562
563 /*
564  * Load the serialization table.  This isn't very pretty, but is probably
565  * the easiest way to do it.
566  */
567 #include "ctl_ser_table.c"
568
569 /*
570  * We only need to define open, close and ioctl routines for this driver.
571  */
572 static struct cdevsw ctl_cdevsw = {
573         .d_version =    D_VERSION,
574         .d_flags =      0,
575         .d_open =       ctl_open,
576         .d_close =      ctl_close,
577         .d_ioctl =      ctl_ioctl,
578         .d_name =       "ctl",
579 };
580
581
582 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
583
584 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
585
586 static moduledata_t ctl_moduledata = {
587         "ctl",
588         ctl_module_event_handler,
589         NULL
590 };
591
592 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
593 MODULE_VERSION(ctl, 1);
594
595 static struct ctl_frontend ha_frontend =
596 {
597         .name = "ha",
598         .init = ctl_ha_init,
599         .shutdown = ctl_ha_shutdown,
600 };
601
602 static int
603 ctl_ha_init(void)
604 {
605         struct ctl_softc *softc = control_softc;
606
607         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
608                             &softc->othersc_pool) != 0)
609                 return (ENOMEM);
610         if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
611                 ctl_pool_free(softc->othersc_pool);
612                 return (EIO);
613         }
614         if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
615             != CTL_HA_STATUS_SUCCESS) {
616                 ctl_ha_msg_destroy(softc);
617                 ctl_pool_free(softc->othersc_pool);
618                 return (EIO);
619         }
620         return (0);
621 };
622
623 static int
624 ctl_ha_shutdown(void)
625 {
626         struct ctl_softc *softc = control_softc;
627         struct ctl_port *port;
628
629         ctl_ha_msg_shutdown(softc);
630         if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
631                 return (EIO);
632         if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
633                 return (EIO);
634         ctl_pool_free(softc->othersc_pool);
635         while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
636                 ctl_port_deregister(port);
637                 free(port->port_name, M_CTL);
638                 free(port, M_CTL);
639         }
640         return (0);
641 };
642
643 static void
644 ctl_ha_datamove(union ctl_io *io)
645 {
646         struct ctl_lun *lun = CTL_LUN(io);
647         struct ctl_sg_entry *sgl;
648         union ctl_ha_msg msg;
649         uint32_t sg_entries_sent;
650         int do_sg_copy, i, j;
651
652         memset(&msg.dt, 0, sizeof(msg.dt));
653         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
654         msg.hdr.original_sc = io->io_hdr.original_sc;
655         msg.hdr.serializing_sc = io;
656         msg.hdr.nexus = io->io_hdr.nexus;
657         msg.hdr.status = io->io_hdr.status;
658         msg.dt.flags = io->io_hdr.flags;
659
660         /*
661          * We convert everything into a S/G list here.  We can't
662          * pass by reference, only by value between controllers.
663          * So we can't pass a pointer to the S/G list, only as many
664          * S/G entries as we can fit in here.  If it's possible for
665          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
666          * then we need to break this up into multiple transfers.
667          */
668         if (io->scsiio.kern_sg_entries == 0) {
669                 msg.dt.kern_sg_entries = 1;
670 #if 0
671                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
672                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
673                 } else {
674                         /* XXX KDM use busdma here! */
675                         msg.dt.sg_list[0].addr =
676                             (void *)vtophys(io->scsiio.kern_data_ptr);
677                 }
678 #else
679                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
680                     ("HA does not support BUS_ADDR"));
681                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
682 #endif
683                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
684                 do_sg_copy = 0;
685         } else {
686                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
687                 do_sg_copy = 1;
688         }
689
690         msg.dt.kern_data_len = io->scsiio.kern_data_len;
691         msg.dt.kern_total_len = io->scsiio.kern_total_len;
692         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
693         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
694         msg.dt.sg_sequence = 0;
695
696         /*
697          * Loop until we've sent all of the S/G entries.  On the
698          * other end, we'll recompose these S/G entries into one
699          * contiguous list before processing.
700          */
701         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
702             msg.dt.sg_sequence++) {
703                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
704                     sizeof(msg.dt.sg_list[0])),
705                     msg.dt.kern_sg_entries - sg_entries_sent);
706                 if (do_sg_copy != 0) {
707                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
708                         for (i = sg_entries_sent, j = 0;
709                              i < msg.dt.cur_sg_entries; i++, j++) {
710 #if 0
711                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
712                                         msg.dt.sg_list[j].addr = sgl[i].addr;
713                                 } else {
714                                         /* XXX KDM use busdma here! */
715                                         msg.dt.sg_list[j].addr =
716                                             (void *)vtophys(sgl[i].addr);
717                                 }
718 #else
719                                 KASSERT((io->io_hdr.flags &
720                                     CTL_FLAG_BUS_ADDR) == 0,
721                                     ("HA does not support BUS_ADDR"));
722                                 msg.dt.sg_list[j].addr = sgl[i].addr;
723 #endif
724                                 msg.dt.sg_list[j].len = sgl[i].len;
725                         }
726                 }
727
728                 sg_entries_sent += msg.dt.cur_sg_entries;
729                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
730                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
731                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
732                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
733                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
734                         io->io_hdr.port_status = 31341;
735                         io->scsiio.be_move_done(io);
736                         return;
737                 }
738                 msg.dt.sent_sg_entries = sg_entries_sent;
739         }
740
741         /*
742          * Officially handover the request from us to peer.
743          * If failover has just happened, then we must return error.
744          * If failover happen just after, then it is not our problem.
745          */
746         if (lun)
747                 mtx_lock(&lun->lun_lock);
748         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
749                 if (lun)
750                         mtx_unlock(&lun->lun_lock);
751                 io->io_hdr.port_status = 31342;
752                 io->scsiio.be_move_done(io);
753                 return;
754         }
755         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
756         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
757         if (lun)
758                 mtx_unlock(&lun->lun_lock);
759 }
760
761 static void
762 ctl_ha_done(union ctl_io *io)
763 {
764         union ctl_ha_msg msg;
765
766         if (io->io_hdr.io_type == CTL_IO_SCSI) {
767                 memset(&msg, 0, sizeof(msg));
768                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
769                 msg.hdr.original_sc = io->io_hdr.original_sc;
770                 msg.hdr.nexus = io->io_hdr.nexus;
771                 msg.hdr.status = io->io_hdr.status;
772                 msg.scsi.scsi_status = io->scsiio.scsi_status;
773                 msg.scsi.tag_num = io->scsiio.tag_num;
774                 msg.scsi.tag_type = io->scsiio.tag_type;
775                 msg.scsi.sense_len = io->scsiio.sense_len;
776                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
777                     io->scsiio.sense_len);
778                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
779                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
780                     msg.scsi.sense_len, M_WAITOK);
781         }
782         ctl_free_io(io);
783 }
784
785 static void
786 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
787                             union ctl_ha_msg *msg_info)
788 {
789         struct ctl_scsiio *ctsio;
790
791         if (msg_info->hdr.original_sc == NULL) {
792                 printf("%s: original_sc == NULL!\n", __func__);
793                 /* XXX KDM now what? */
794                 return;
795         }
796
797         ctsio = &msg_info->hdr.original_sc->scsiio;
798         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
799         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
800         ctsio->io_hdr.status = msg_info->hdr.status;
801         ctsio->scsi_status = msg_info->scsi.scsi_status;
802         ctsio->sense_len = msg_info->scsi.sense_len;
803         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
804                msg_info->scsi.sense_len);
805         ctl_enqueue_isc((union ctl_io *)ctsio);
806 }
807
808 static void
809 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
810                                 union ctl_ha_msg *msg_info)
811 {
812         struct ctl_scsiio *ctsio;
813
814         if (msg_info->hdr.serializing_sc == NULL) {
815                 printf("%s: serializing_sc == NULL!\n", __func__);
816                 /* XXX KDM now what? */
817                 return;
818         }
819
820         ctsio = &msg_info->hdr.serializing_sc->scsiio;
821         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
822         ctl_enqueue_isc((union ctl_io *)ctsio);
823 }
824
825 void
826 ctl_isc_announce_lun(struct ctl_lun *lun)
827 {
828         struct ctl_softc *softc = lun->ctl_softc;
829         union ctl_ha_msg *msg;
830         struct ctl_ha_msg_lun_pr_key pr_key;
831         int i, k;
832
833         if (softc->ha_link != CTL_HA_LINK_ONLINE)
834                 return;
835         mtx_lock(&lun->lun_lock);
836         i = sizeof(msg->lun);
837         if (lun->lun_devid)
838                 i += lun->lun_devid->len;
839         i += sizeof(pr_key) * lun->pr_key_count;
840 alloc:
841         mtx_unlock(&lun->lun_lock);
842         msg = malloc(i, M_CTL, M_WAITOK);
843         mtx_lock(&lun->lun_lock);
844         k = sizeof(msg->lun);
845         if (lun->lun_devid)
846                 k += lun->lun_devid->len;
847         k += sizeof(pr_key) * lun->pr_key_count;
848         if (i < k) {
849                 free(msg, M_CTL);
850                 i = k;
851                 goto alloc;
852         }
853         bzero(&msg->lun, sizeof(msg->lun));
854         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
855         msg->hdr.nexus.targ_lun = lun->lun;
856         msg->hdr.nexus.targ_mapped_lun = lun->lun;
857         msg->lun.flags = lun->flags;
858         msg->lun.pr_generation = lun->pr_generation;
859         msg->lun.pr_res_idx = lun->pr_res_idx;
860         msg->lun.pr_res_type = lun->pr_res_type;
861         msg->lun.pr_key_count = lun->pr_key_count;
862         i = 0;
863         if (lun->lun_devid) {
864                 msg->lun.lun_devid_len = lun->lun_devid->len;
865                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
866                     msg->lun.lun_devid_len);
867                 i += msg->lun.lun_devid_len;
868         }
869         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
870                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
871                         continue;
872                 pr_key.pr_iid = k;
873                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
874                 i += sizeof(pr_key);
875         }
876         mtx_unlock(&lun->lun_lock);
877         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
878             M_WAITOK);
879         free(msg, M_CTL);
880
881         if (lun->flags & CTL_LUN_PRIMARY_SC) {
882                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
883                         ctl_isc_announce_mode(lun, -1,
884                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
885                             lun->mode_pages.index[i].subpage);
886                 }
887         }
888 }
889
890 void
891 ctl_isc_announce_port(struct ctl_port *port)
892 {
893         struct ctl_softc *softc = port->ctl_softc;
894         union ctl_ha_msg *msg;
895         int i;
896
897         if (port->targ_port < softc->port_min ||
898             port->targ_port >= softc->port_max ||
899             softc->ha_link != CTL_HA_LINK_ONLINE)
900                 return;
901         i = sizeof(msg->port) + strlen(port->port_name) + 1;
902         if (port->lun_map)
903                 i += port->lun_map_size * sizeof(uint32_t);
904         if (port->port_devid)
905                 i += port->port_devid->len;
906         if (port->target_devid)
907                 i += port->target_devid->len;
908         if (port->init_devid)
909                 i += port->init_devid->len;
910         msg = malloc(i, M_CTL, M_WAITOK);
911         bzero(&msg->port, sizeof(msg->port));
912         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
913         msg->hdr.nexus.targ_port = port->targ_port;
914         msg->port.port_type = port->port_type;
915         msg->port.physical_port = port->physical_port;
916         msg->port.virtual_port = port->virtual_port;
917         msg->port.status = port->status;
918         i = 0;
919         msg->port.name_len = sprintf(&msg->port.data[i],
920             "%d:%s", softc->ha_id, port->port_name) + 1;
921         i += msg->port.name_len;
922         if (port->lun_map) {
923                 msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
924                 memcpy(&msg->port.data[i], port->lun_map,
925                     msg->port.lun_map_len);
926                 i += msg->port.lun_map_len;
927         }
928         if (port->port_devid) {
929                 msg->port.port_devid_len = port->port_devid->len;
930                 memcpy(&msg->port.data[i], port->port_devid->data,
931                     msg->port.port_devid_len);
932                 i += msg->port.port_devid_len;
933         }
934         if (port->target_devid) {
935                 msg->port.target_devid_len = port->target_devid->len;
936                 memcpy(&msg->port.data[i], port->target_devid->data,
937                     msg->port.target_devid_len);
938                 i += msg->port.target_devid_len;
939         }
940         if (port->init_devid) {
941                 msg->port.init_devid_len = port->init_devid->len;
942                 memcpy(&msg->port.data[i], port->init_devid->data,
943                     msg->port.init_devid_len);
944                 i += msg->port.init_devid_len;
945         }
946         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
947             M_WAITOK);
948         free(msg, M_CTL);
949 }
950
951 void
952 ctl_isc_announce_iid(struct ctl_port *port, int iid)
953 {
954         struct ctl_softc *softc = port->ctl_softc;
955         union ctl_ha_msg *msg;
956         int i, l;
957
958         if (port->targ_port < softc->port_min ||
959             port->targ_port >= softc->port_max ||
960             softc->ha_link != CTL_HA_LINK_ONLINE)
961                 return;
962         mtx_lock(&softc->ctl_lock);
963         i = sizeof(msg->iid);
964         l = 0;
965         if (port->wwpn_iid[iid].name)
966                 l = strlen(port->wwpn_iid[iid].name) + 1;
967         i += l;
968         msg = malloc(i, M_CTL, M_NOWAIT);
969         if (msg == NULL) {
970                 mtx_unlock(&softc->ctl_lock);
971                 return;
972         }
973         bzero(&msg->iid, sizeof(msg->iid));
974         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
975         msg->hdr.nexus.targ_port = port->targ_port;
976         msg->hdr.nexus.initid = iid;
977         msg->iid.in_use = port->wwpn_iid[iid].in_use;
978         msg->iid.name_len = l;
979         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
980         if (port->wwpn_iid[iid].name)
981                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
982         mtx_unlock(&softc->ctl_lock);
983         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
984         free(msg, M_CTL);
985 }
986
987 void
988 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
989     uint8_t page, uint8_t subpage)
990 {
991         struct ctl_softc *softc = lun->ctl_softc;
992         union ctl_ha_msg msg;
993         u_int i;
994
995         if (softc->ha_link != CTL_HA_LINK_ONLINE)
996                 return;
997         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
998                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
999                     page && lun->mode_pages.index[i].subpage == subpage)
1000                         break;
1001         }
1002         if (i == CTL_NUM_MODE_PAGES)
1003                 return;
1004
1005         /* Don't try to replicate pages not present on this device. */
1006         if (lun->mode_pages.index[i].page_data == NULL)
1007                 return;
1008
1009         bzero(&msg.mode, sizeof(msg.mode));
1010         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1011         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1012         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1013         msg.hdr.nexus.targ_lun = lun->lun;
1014         msg.hdr.nexus.targ_mapped_lun = lun->lun;
1015         msg.mode.page_code = page;
1016         msg.mode.subpage = subpage;
1017         msg.mode.page_len = lun->mode_pages.index[i].page_len;
1018         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1019             msg.mode.page_len);
1020         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1021             M_WAITOK);
1022 }
1023
1024 static void
1025 ctl_isc_ha_link_up(struct ctl_softc *softc)
1026 {
1027         struct ctl_port *port;
1028         struct ctl_lun *lun;
1029         union ctl_ha_msg msg;
1030         int i;
1031
1032         /* Announce this node parameters to peer for validation. */
1033         msg.login.msg_type = CTL_MSG_LOGIN;
1034         msg.login.version = CTL_HA_VERSION;
1035         msg.login.ha_mode = softc->ha_mode;
1036         msg.login.ha_id = softc->ha_id;
1037         msg.login.max_luns = ctl_max_luns;
1038         msg.login.max_ports = ctl_max_ports;
1039         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1040         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1041             M_WAITOK);
1042
1043         STAILQ_FOREACH(port, &softc->port_list, links) {
1044                 ctl_isc_announce_port(port);
1045                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1046                         if (port->wwpn_iid[i].in_use)
1047                                 ctl_isc_announce_iid(port, i);
1048                 }
1049         }
1050         STAILQ_FOREACH(lun, &softc->lun_list, links)
1051                 ctl_isc_announce_lun(lun);
1052 }
1053
1054 static void
1055 ctl_isc_ha_link_down(struct ctl_softc *softc)
1056 {
1057         struct ctl_port *port;
1058         struct ctl_lun *lun;
1059         union ctl_io *io;
1060         int i;
1061
1062         mtx_lock(&softc->ctl_lock);
1063         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1064                 mtx_lock(&lun->lun_lock);
1065                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1066                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1067                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1068                 }
1069                 mtx_unlock(&lun->lun_lock);
1070
1071                 mtx_unlock(&softc->ctl_lock);
1072                 io = ctl_alloc_io(softc->othersc_pool);
1073                 mtx_lock(&softc->ctl_lock);
1074                 ctl_zero_io(io);
1075                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1076                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1077                 ctl_enqueue_isc(io);
1078         }
1079
1080         STAILQ_FOREACH(port, &softc->port_list, links) {
1081                 if (port->targ_port >= softc->port_min &&
1082                     port->targ_port < softc->port_max)
1083                         continue;
1084                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1085                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1086                         port->wwpn_iid[i].in_use = 0;
1087                         free(port->wwpn_iid[i].name, M_CTL);
1088                         port->wwpn_iid[i].name = NULL;
1089                 }
1090         }
1091         mtx_unlock(&softc->ctl_lock);
1092 }
1093
1094 static void
1095 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1096 {
1097         struct ctl_lun *lun;
1098         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1099
1100         mtx_lock(&softc->ctl_lock);
1101         if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1102             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1103                 mtx_unlock(&softc->ctl_lock);
1104                 return;
1105         }
1106         mtx_lock(&lun->lun_lock);
1107         mtx_unlock(&softc->ctl_lock);
1108         if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1109                 memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1110         if (msg->ua.ua_all) {
1111                 if (msg->ua.ua_set)
1112                         ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1113                 else
1114                         ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1115         } else {
1116                 if (msg->ua.ua_set)
1117                         ctl_est_ua(lun, iid, msg->ua.ua_type);
1118                 else
1119                         ctl_clr_ua(lun, iid, msg->ua.ua_type);
1120         }
1121         mtx_unlock(&lun->lun_lock);
1122 }
1123
1124 static void
1125 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1126 {
1127         struct ctl_lun *lun;
1128         struct ctl_ha_msg_lun_pr_key pr_key;
1129         int i, k;
1130         ctl_lun_flags oflags;
1131         uint32_t targ_lun;
1132
1133         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1134         mtx_lock(&softc->ctl_lock);
1135         if (targ_lun >= ctl_max_luns ||
1136             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1137                 mtx_unlock(&softc->ctl_lock);
1138                 return;
1139         }
1140         mtx_lock(&lun->lun_lock);
1141         mtx_unlock(&softc->ctl_lock);
1142         if (lun->flags & CTL_LUN_DISABLED) {
1143                 mtx_unlock(&lun->lun_lock);
1144                 return;
1145         }
1146         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1147         if (msg->lun.lun_devid_len != i || (i > 0 &&
1148             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1149                 mtx_unlock(&lun->lun_lock);
1150                 printf("%s: Received conflicting HA LUN %d\n",
1151                     __func__, targ_lun);
1152                 return;
1153         } else {
1154                 /* Record whether peer is primary. */
1155                 oflags = lun->flags;
1156                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1157                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1158                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1159                 else
1160                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1161                 if (oflags != lun->flags)
1162                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1163
1164                 /* If peer is primary and we are not -- use data */
1165                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1166                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1167                         lun->pr_generation = msg->lun.pr_generation;
1168                         lun->pr_res_idx = msg->lun.pr_res_idx;
1169                         lun->pr_res_type = msg->lun.pr_res_type;
1170                         lun->pr_key_count = msg->lun.pr_key_count;
1171                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1172                                 ctl_clr_prkey(lun, k);
1173                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1174                                 memcpy(&pr_key, &msg->lun.data[i],
1175                                     sizeof(pr_key));
1176                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1177                                 ctl_set_prkey(lun, pr_key.pr_iid,
1178                                     pr_key.pr_key);
1179                                 i += sizeof(pr_key);
1180                         }
1181                 }
1182
1183                 mtx_unlock(&lun->lun_lock);
1184                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1185                     __func__, targ_lun,
1186                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1187                     "primary" : "secondary"));
1188
1189                 /* If we are primary but peer doesn't know -- notify */
1190                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1191                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1192                         ctl_isc_announce_lun(lun);
1193         }
1194 }
1195
1196 static void
1197 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1198 {
1199         struct ctl_port *port;
1200         struct ctl_lun *lun;
1201         int i, new;
1202
1203         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1204         if (port == NULL) {
1205                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1206                     msg->hdr.nexus.targ_port));
1207                 new = 1;
1208                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1209                 port->frontend = &ha_frontend;
1210                 port->targ_port = msg->hdr.nexus.targ_port;
1211                 port->fe_datamove = ctl_ha_datamove;
1212                 port->fe_done = ctl_ha_done;
1213         } else if (port->frontend == &ha_frontend) {
1214                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1215                     msg->hdr.nexus.targ_port));
1216                 new = 0;
1217         } else {
1218                 printf("%s: Received conflicting HA port %d\n",
1219                     __func__, msg->hdr.nexus.targ_port);
1220                 return;
1221         }
1222         port->port_type = msg->port.port_type;
1223         port->physical_port = msg->port.physical_port;
1224         port->virtual_port = msg->port.virtual_port;
1225         port->status = msg->port.status;
1226         i = 0;
1227         free(port->port_name, M_CTL);
1228         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1229             M_CTL);
1230         i += msg->port.name_len;
1231         if (msg->port.lun_map_len != 0) {
1232                 if (port->lun_map == NULL ||
1233                     port->lun_map_size * sizeof(uint32_t) <
1234                     msg->port.lun_map_len) {
1235                         port->lun_map_size = 0;
1236                         free(port->lun_map, M_CTL);
1237                         port->lun_map = malloc(msg->port.lun_map_len,
1238                             M_CTL, M_WAITOK);
1239                 }
1240                 memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1241                 port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1242                 i += msg->port.lun_map_len;
1243         } else {
1244                 port->lun_map_size = 0;
1245                 free(port->lun_map, M_CTL);
1246                 port->lun_map = NULL;
1247         }
1248         if (msg->port.port_devid_len != 0) {
1249                 if (port->port_devid == NULL ||
1250                     port->port_devid->len < msg->port.port_devid_len) {
1251                         free(port->port_devid, M_CTL);
1252                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1253                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1254                 }
1255                 memcpy(port->port_devid->data, &msg->port.data[i],
1256                     msg->port.port_devid_len);
1257                 port->port_devid->len = msg->port.port_devid_len;
1258                 i += msg->port.port_devid_len;
1259         } else {
1260                 free(port->port_devid, M_CTL);
1261                 port->port_devid = NULL;
1262         }
1263         if (msg->port.target_devid_len != 0) {
1264                 if (port->target_devid == NULL ||
1265                     port->target_devid->len < msg->port.target_devid_len) {
1266                         free(port->target_devid, M_CTL);
1267                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1268                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1269                 }
1270                 memcpy(port->target_devid->data, &msg->port.data[i],
1271                     msg->port.target_devid_len);
1272                 port->target_devid->len = msg->port.target_devid_len;
1273                 i += msg->port.target_devid_len;
1274         } else {
1275                 free(port->target_devid, M_CTL);
1276                 port->target_devid = NULL;
1277         }
1278         if (msg->port.init_devid_len != 0) {
1279                 if (port->init_devid == NULL ||
1280                     port->init_devid->len < msg->port.init_devid_len) {
1281                         free(port->init_devid, M_CTL);
1282                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1283                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1284                 }
1285                 memcpy(port->init_devid->data, &msg->port.data[i],
1286                     msg->port.init_devid_len);
1287                 port->init_devid->len = msg->port.init_devid_len;
1288                 i += msg->port.init_devid_len;
1289         } else {
1290                 free(port->init_devid, M_CTL);
1291                 port->init_devid = NULL;
1292         }
1293         if (new) {
1294                 if (ctl_port_register(port) != 0) {
1295                         printf("%s: ctl_port_register() failed with error\n",
1296                             __func__);
1297                 }
1298         }
1299         mtx_lock(&softc->ctl_lock);
1300         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1301                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1302                         continue;
1303                 mtx_lock(&lun->lun_lock);
1304                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1305                 mtx_unlock(&lun->lun_lock);
1306         }
1307         mtx_unlock(&softc->ctl_lock);
1308 }
1309
1310 static void
1311 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1312 {
1313         struct ctl_port *port;
1314         int iid;
1315
1316         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1317         if (port == NULL) {
1318                 printf("%s: Received IID for unknown port %d\n",
1319                     __func__, msg->hdr.nexus.targ_port);
1320                 return;
1321         }
1322         iid = msg->hdr.nexus.initid;
1323         if (port->wwpn_iid[iid].in_use != 0 &&
1324             msg->iid.in_use == 0)
1325                 ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1326         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1327         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1328         free(port->wwpn_iid[iid].name, M_CTL);
1329         if (msg->iid.name_len) {
1330                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1331                     msg->iid.name_len, M_CTL);
1332         } else
1333                 port->wwpn_iid[iid].name = NULL;
1334 }
1335
1336 static void
1337 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1338 {
1339
1340         if (msg->login.version != CTL_HA_VERSION) {
1341                 printf("CTL HA peers have different versions %d != %d\n",
1342                     msg->login.version, CTL_HA_VERSION);
1343                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1344                 return;
1345         }
1346         if (msg->login.ha_mode != softc->ha_mode) {
1347                 printf("CTL HA peers have different ha_mode %d != %d\n",
1348                     msg->login.ha_mode, softc->ha_mode);
1349                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1350                 return;
1351         }
1352         if (msg->login.ha_id == softc->ha_id) {
1353                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1354                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1355                 return;
1356         }
1357         if (msg->login.max_luns != ctl_max_luns ||
1358             msg->login.max_ports != ctl_max_ports ||
1359             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1360                 printf("CTL HA peers have different limits\n");
1361                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1362                 return;
1363         }
1364 }
1365
1366 static void
1367 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1368 {
1369         struct ctl_lun *lun;
1370         u_int i;
1371         uint32_t initidx, targ_lun;
1372
1373         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1374         mtx_lock(&softc->ctl_lock);
1375         if (targ_lun >= ctl_max_luns ||
1376             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1377                 mtx_unlock(&softc->ctl_lock);
1378                 return;
1379         }
1380         mtx_lock(&lun->lun_lock);
1381         mtx_unlock(&softc->ctl_lock);
1382         if (lun->flags & CTL_LUN_DISABLED) {
1383                 mtx_unlock(&lun->lun_lock);
1384                 return;
1385         }
1386         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1387                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1388                     msg->mode.page_code &&
1389                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1390                         break;
1391         }
1392         if (i == CTL_NUM_MODE_PAGES) {
1393                 mtx_unlock(&lun->lun_lock);
1394                 return;
1395         }
1396         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1397             lun->mode_pages.index[i].page_len);
1398         initidx = ctl_get_initindex(&msg->hdr.nexus);
1399         if (initidx != -1)
1400                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1401         mtx_unlock(&lun->lun_lock);
1402 }
1403
1404 /*
1405  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1406  * subsystem come in here.
1407  */
1408 static void
1409 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1410 {
1411         struct ctl_softc *softc = control_softc;
1412         union ctl_io *io;
1413         struct ctl_prio *presio;
1414         ctl_ha_status isc_status;
1415
1416         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1417         if (event == CTL_HA_EVT_MSG_RECV) {
1418                 union ctl_ha_msg *msg, msgbuf;
1419
1420                 if (param > sizeof(msgbuf))
1421                         msg = malloc(param, M_CTL, M_WAITOK);
1422                 else
1423                         msg = &msgbuf;
1424                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1425                     M_WAITOK);
1426                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1427                         printf("%s: Error receiving message: %d\n",
1428                             __func__, isc_status);
1429                         if (msg != &msgbuf)
1430                                 free(msg, M_CTL);
1431                         return;
1432                 }
1433
1434                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1435                 switch (msg->hdr.msg_type) {
1436                 case CTL_MSG_SERIALIZE:
1437                         io = ctl_alloc_io(softc->othersc_pool);
1438                         ctl_zero_io(io);
1439                         // populate ctsio from msg
1440                         io->io_hdr.io_type = CTL_IO_SCSI;
1441                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1442                         io->io_hdr.original_sc = msg->hdr.original_sc;
1443                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1444                                             CTL_FLAG_IO_ACTIVE;
1445                         /*
1446                          * If we're in serialization-only mode, we don't
1447                          * want to go through full done processing.  Thus
1448                          * the COPY flag.
1449                          *
1450                          * XXX KDM add another flag that is more specific.
1451                          */
1452                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1453                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1454                         io->io_hdr.nexus = msg->hdr.nexus;
1455 #if 0
1456                         printf("port %u, iid %u, lun %u\n",
1457                                io->io_hdr.nexus.targ_port,
1458                                io->io_hdr.nexus.initid,
1459                                io->io_hdr.nexus.targ_lun);
1460 #endif
1461                         io->scsiio.tag_num = msg->scsi.tag_num;
1462                         io->scsiio.tag_type = msg->scsi.tag_type;
1463 #ifdef CTL_TIME_IO
1464                         io->io_hdr.start_time = time_uptime;
1465                         getbinuptime(&io->io_hdr.start_bt);
1466 #endif /* CTL_TIME_IO */
1467                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1468                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1469                                CTL_MAX_CDBLEN);
1470                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1471                                 const struct ctl_cmd_entry *entry;
1472
1473                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1474                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1475                                 io->io_hdr.flags |=
1476                                         entry->flags & CTL_FLAG_DATA_MASK;
1477                         }
1478                         ctl_enqueue_isc(io);
1479                         break;
1480
1481                 /* Performed on the Originating SC, XFER mode only */
1482                 case CTL_MSG_DATAMOVE: {
1483                         struct ctl_sg_entry *sgl;
1484                         int i, j;
1485
1486                         io = msg->hdr.original_sc;
1487                         if (io == NULL) {
1488                                 printf("%s: original_sc == NULL!\n", __func__);
1489                                 /* XXX KDM do something here */
1490                                 break;
1491                         }
1492                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1493                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1494                         /*
1495                          * Keep track of this, we need to send it back over
1496                          * when the datamove is complete.
1497                          */
1498                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1499                         if (msg->hdr.status == CTL_SUCCESS)
1500                                 io->io_hdr.status = msg->hdr.status;
1501
1502                         if (msg->dt.sg_sequence == 0) {
1503 #ifdef CTL_TIME_IO
1504                                 getbinuptime(&io->io_hdr.dma_start_bt);
1505 #endif
1506                                 i = msg->dt.kern_sg_entries +
1507                                     msg->dt.kern_data_len /
1508                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1509                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1510                                     M_WAITOK | M_ZERO);
1511                                 io->io_hdr.remote_sglist = sgl;
1512                                 io->io_hdr.local_sglist =
1513                                     &sgl[msg->dt.kern_sg_entries];
1514
1515                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1516
1517                                 io->scsiio.kern_sg_entries =
1518                                         msg->dt.kern_sg_entries;
1519                                 io->scsiio.rem_sg_entries =
1520                                         msg->dt.kern_sg_entries;
1521                                 io->scsiio.kern_data_len =
1522                                         msg->dt.kern_data_len;
1523                                 io->scsiio.kern_total_len =
1524                                         msg->dt.kern_total_len;
1525                                 io->scsiio.kern_data_resid =
1526                                         msg->dt.kern_data_resid;
1527                                 io->scsiio.kern_rel_offset =
1528                                         msg->dt.kern_rel_offset;
1529                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1530                                 io->io_hdr.flags |= msg->dt.flags &
1531                                     CTL_FLAG_BUS_ADDR;
1532                         } else
1533                                 sgl = (struct ctl_sg_entry *)
1534                                         io->scsiio.kern_data_ptr;
1535
1536                         for (i = msg->dt.sent_sg_entries, j = 0;
1537                              i < (msg->dt.sent_sg_entries +
1538                              msg->dt.cur_sg_entries); i++, j++) {
1539                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1540                                 sgl[i].len = msg->dt.sg_list[j].len;
1541
1542 #if 0
1543                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1544                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1545 #endif
1546                         }
1547
1548                         /*
1549                          * If this is the last piece of the I/O, we've got
1550                          * the full S/G list.  Queue processing in the thread.
1551                          * Otherwise wait for the next piece.
1552                          */
1553                         if (msg->dt.sg_last != 0)
1554                                 ctl_enqueue_isc(io);
1555                         break;
1556                 }
1557                 /* Performed on the Serializing (primary) SC, XFER mode only */
1558                 case CTL_MSG_DATAMOVE_DONE: {
1559                         if (msg->hdr.serializing_sc == NULL) {
1560                                 printf("%s: serializing_sc == NULL!\n",
1561                                        __func__);
1562                                 /* XXX KDM now what? */
1563                                 break;
1564                         }
1565                         /*
1566                          * We grab the sense information here in case
1567                          * there was a failure, so we can return status
1568                          * back to the initiator.
1569                          */
1570                         io = msg->hdr.serializing_sc;
1571                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1572                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1573                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1574                         io->io_hdr.port_status = msg->scsi.port_status;
1575                         io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1576                         if (msg->hdr.status != CTL_STATUS_NONE) {
1577                                 io->io_hdr.status = msg->hdr.status;
1578                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1579                                 io->scsiio.sense_len = msg->scsi.sense_len;
1580                                 memcpy(&io->scsiio.sense_data,
1581                                     &msg->scsi.sense_data,
1582                                     msg->scsi.sense_len);
1583                                 if (msg->hdr.status == CTL_SUCCESS)
1584                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1585                         }
1586                         ctl_enqueue_isc(io);
1587                         break;
1588                 }
1589
1590                 /* Preformed on Originating SC, SER_ONLY mode */
1591                 case CTL_MSG_R2R:
1592                         io = msg->hdr.original_sc;
1593                         if (io == NULL) {
1594                                 printf("%s: original_sc == NULL!\n",
1595                                     __func__);
1596                                 break;
1597                         }
1598                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1599                         io->io_hdr.msg_type = CTL_MSG_R2R;
1600                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1601                         ctl_enqueue_isc(io);
1602                         break;
1603
1604                 /*
1605                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1606                  * mode.
1607                  * Performed on the Originating (i.e. secondary) SC in XFER
1608                  * mode
1609                  */
1610                 case CTL_MSG_FINISH_IO:
1611                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1612                                 ctl_isc_handler_finish_xfer(softc, msg);
1613                         else
1614                                 ctl_isc_handler_finish_ser_only(softc, msg);
1615                         break;
1616
1617                 /* Preformed on Originating SC */
1618                 case CTL_MSG_BAD_JUJU:
1619                         io = msg->hdr.original_sc;
1620                         if (io == NULL) {
1621                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1622                                        __func__);
1623                                 break;
1624                         }
1625                         ctl_copy_sense_data(msg, io);
1626                         /*
1627                          * IO should have already been cleaned up on other
1628                          * SC so clear this flag so we won't send a message
1629                          * back to finish the IO there.
1630                          */
1631                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1632                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1633
1634                         /* io = msg->hdr.serializing_sc; */
1635                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1636                         ctl_enqueue_isc(io);
1637                         break;
1638
1639                 /* Handle resets sent from the other side */
1640                 case CTL_MSG_MANAGE_TASKS: {
1641                         struct ctl_taskio *taskio;
1642                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1643                             softc->othersc_pool);
1644                         ctl_zero_io((union ctl_io *)taskio);
1645                         taskio->io_hdr.io_type = CTL_IO_TASK;
1646                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1647                         taskio->io_hdr.nexus = msg->hdr.nexus;
1648                         taskio->task_action = msg->task.task_action;
1649                         taskio->tag_num = msg->task.tag_num;
1650                         taskio->tag_type = msg->task.tag_type;
1651 #ifdef CTL_TIME_IO
1652                         taskio->io_hdr.start_time = time_uptime;
1653                         getbinuptime(&taskio->io_hdr.start_bt);
1654 #endif /* CTL_TIME_IO */
1655                         ctl_run_task((union ctl_io *)taskio);
1656                         break;
1657                 }
1658                 /* Persistent Reserve action which needs attention */
1659                 case CTL_MSG_PERS_ACTION:
1660                         presio = (struct ctl_prio *)ctl_alloc_io(
1661                             softc->othersc_pool);
1662                         ctl_zero_io((union ctl_io *)presio);
1663                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1664                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1665                         presio->io_hdr.nexus = msg->hdr.nexus;
1666                         presio->pr_msg = msg->pr;
1667                         ctl_enqueue_isc((union ctl_io *)presio);
1668                         break;
1669                 case CTL_MSG_UA:
1670                         ctl_isc_ua(softc, msg, param);
1671                         break;
1672                 case CTL_MSG_PORT_SYNC:
1673                         ctl_isc_port_sync(softc, msg, param);
1674                         break;
1675                 case CTL_MSG_LUN_SYNC:
1676                         ctl_isc_lun_sync(softc, msg, param);
1677                         break;
1678                 case CTL_MSG_IID_SYNC:
1679                         ctl_isc_iid_sync(softc, msg, param);
1680                         break;
1681                 case CTL_MSG_LOGIN:
1682                         ctl_isc_login(softc, msg, param);
1683                         break;
1684                 case CTL_MSG_MODE_SYNC:
1685                         ctl_isc_mode_sync(softc, msg, param);
1686                         break;
1687                 default:
1688                         printf("Received HA message of unknown type %d\n",
1689                             msg->hdr.msg_type);
1690                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1691                         break;
1692                 }
1693                 if (msg != &msgbuf)
1694                         free(msg, M_CTL);
1695         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1696                 printf("CTL: HA link status changed from %d to %d\n",
1697                     softc->ha_link, param);
1698                 if (param == softc->ha_link)
1699                         return;
1700                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1701                         softc->ha_link = param;
1702                         ctl_isc_ha_link_down(softc);
1703                 } else {
1704                         softc->ha_link = param;
1705                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1706                                 ctl_isc_ha_link_up(softc);
1707                 }
1708                 return;
1709         } else {
1710                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1711                 return;
1712         }
1713 }
1714
1715 static void
1716 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1717 {
1718
1719         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1720             src->scsi.sense_len);
1721         dest->scsiio.scsi_status = src->scsi.scsi_status;
1722         dest->scsiio.sense_len = src->scsi.sense_len;
1723         dest->io_hdr.status = src->hdr.status;
1724 }
1725
1726 static void
1727 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1728 {
1729
1730         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1731             src->scsiio.sense_len);
1732         dest->scsi.scsi_status = src->scsiio.scsi_status;
1733         dest->scsi.sense_len = src->scsiio.sense_len;
1734         dest->hdr.status = src->io_hdr.status;
1735 }
1736
1737 void
1738 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1739 {
1740         struct ctl_softc *softc = lun->ctl_softc;
1741         ctl_ua_type *pu;
1742
1743         if (initidx < softc->init_min || initidx >= softc->init_max)
1744                 return;
1745         mtx_assert(&lun->lun_lock, MA_OWNED);
1746         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1747         if (pu == NULL)
1748                 return;
1749         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1750 }
1751
1752 void
1753 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1754 {
1755         int i;
1756
1757         mtx_assert(&lun->lun_lock, MA_OWNED);
1758         if (lun->pending_ua[port] == NULL)
1759                 return;
1760         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1761                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1762                         continue;
1763                 lun->pending_ua[port][i] |= ua;
1764         }
1765 }
1766
1767 void
1768 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1769 {
1770         struct ctl_softc *softc = lun->ctl_softc;
1771         int i;
1772
1773         mtx_assert(&lun->lun_lock, MA_OWNED);
1774         for (i = softc->port_min; i < softc->port_max; i++)
1775                 ctl_est_ua_port(lun, i, except, ua);
1776 }
1777
1778 void
1779 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1780 {
1781         struct ctl_softc *softc = lun->ctl_softc;
1782         ctl_ua_type *pu;
1783
1784         if (initidx < softc->init_min || initidx >= softc->init_max)
1785                 return;
1786         mtx_assert(&lun->lun_lock, MA_OWNED);
1787         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1788         if (pu == NULL)
1789                 return;
1790         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1791 }
1792
1793 void
1794 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1795 {
1796         struct ctl_softc *softc = lun->ctl_softc;
1797         int i, j;
1798
1799         mtx_assert(&lun->lun_lock, MA_OWNED);
1800         for (i = softc->port_min; i < softc->port_max; i++) {
1801                 if (lun->pending_ua[i] == NULL)
1802                         continue;
1803                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1804                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1805                                 continue;
1806                         lun->pending_ua[i][j] &= ~ua;
1807                 }
1808         }
1809 }
1810
1811 void
1812 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1813     ctl_ua_type ua_type)
1814 {
1815         struct ctl_lun *lun;
1816
1817         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1818         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1819                 mtx_lock(&lun->lun_lock);
1820                 ctl_clr_ua(lun, initidx, ua_type);
1821                 mtx_unlock(&lun->lun_lock);
1822         }
1823 }
1824
1825 static int
1826 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1827 {
1828         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1829         struct ctl_lun *lun;
1830         struct ctl_lun_req ireq;
1831         int error, value;
1832
1833         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1834         error = sysctl_handle_int(oidp, &value, 0, req);
1835         if ((error != 0) || (req->newptr == NULL))
1836                 return (error);
1837
1838         mtx_lock(&softc->ctl_lock);
1839         if (value == 0)
1840                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1841         else
1842                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1843         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1844                 mtx_unlock(&softc->ctl_lock);
1845                 bzero(&ireq, sizeof(ireq));
1846                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1847                 ireq.reqdata.modify.lun_id = lun->lun;
1848                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1849                     curthread);
1850                 if (ireq.status != CTL_LUN_OK) {
1851                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1852                             __func__, ireq.status, ireq.error_str);
1853                 }
1854                 mtx_lock(&softc->ctl_lock);
1855         }
1856         mtx_unlock(&softc->ctl_lock);
1857         return (0);
1858 }
1859
1860 static int
1861 ctl_init(void)
1862 {
1863         struct make_dev_args args;
1864         struct ctl_softc *softc;
1865         int i, error;
1866
1867         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1868                                M_WAITOK | M_ZERO);
1869
1870         make_dev_args_init(&args);
1871         args.mda_devsw = &ctl_cdevsw;
1872         args.mda_uid = UID_ROOT;
1873         args.mda_gid = GID_OPERATOR;
1874         args.mda_mode = 0600;
1875         args.mda_si_drv1 = softc;
1876         args.mda_si_drv2 = NULL;
1877         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1878         if (error != 0) {
1879                 free(softc, M_DEVBUF);
1880                 control_softc = NULL;
1881                 return (error);
1882         }
1883
1884         sysctl_ctx_init(&softc->sysctl_ctx);
1885         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1886                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1887                 CTLFLAG_RD, 0, "CAM Target Layer");
1888
1889         if (softc->sysctl_tree == NULL) {
1890                 printf("%s: unable to allocate sysctl tree\n", __func__);
1891                 destroy_dev(softc->dev);
1892                 free(softc, M_DEVBUF);
1893                 control_softc = NULL;
1894                 return (ENOMEM);
1895         }
1896
1897         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1898         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1899             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1900         softc->flags = 0;
1901
1902         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1903             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1904             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1905
1906         if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1907                 printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1908                     ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1909                 ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1910         }
1911         softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1912             M_DEVBUF, M_WAITOK | M_ZERO);
1913         softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1914             ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1915         if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1916                 printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1917                     ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1918                 ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1919         }
1920         softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1921           ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1922         softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1923              M_DEVBUF, M_WAITOK | M_ZERO);
1924
1925
1926         /*
1927          * In Copan's HA scheme, the "master" and "slave" roles are
1928          * figured out through the slot the controller is in.  Although it
1929          * is an active/active system, someone has to be in charge.
1930          */
1931         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1932             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1933             "HA head ID (0 - no HA)");
1934         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1935                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1936                 softc->is_single = 1;
1937                 softc->port_cnt = ctl_max_ports;
1938                 softc->port_min = 0;
1939         } else {
1940                 softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1941                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1942         }
1943         softc->port_max = softc->port_min + softc->port_cnt;
1944         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1945         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1946
1947         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1948             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1949             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1950
1951         STAILQ_INIT(&softc->lun_list);
1952         STAILQ_INIT(&softc->pending_lun_queue);
1953         STAILQ_INIT(&softc->fe_list);
1954         STAILQ_INIT(&softc->port_list);
1955         STAILQ_INIT(&softc->be_list);
1956         ctl_tpc_init(softc);
1957
1958         if (worker_threads <= 0)
1959                 worker_threads = max(1, mp_ncpus / 4);
1960         if (worker_threads > CTL_MAX_THREADS)
1961                 worker_threads = CTL_MAX_THREADS;
1962
1963         for (i = 0; i < worker_threads; i++) {
1964                 struct ctl_thread *thr = &softc->threads[i];
1965
1966                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1967                 thr->ctl_softc = softc;
1968                 STAILQ_INIT(&thr->incoming_queue);
1969                 STAILQ_INIT(&thr->rtr_queue);
1970                 STAILQ_INIT(&thr->done_queue);
1971                 STAILQ_INIT(&thr->isc_queue);
1972
1973                 error = kproc_kthread_add(ctl_work_thread, thr,
1974                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1975                 if (error != 0) {
1976                         printf("error creating CTL work thread!\n");
1977                         return (error);
1978                 }
1979         }
1980         error = kproc_kthread_add(ctl_lun_thread, softc,
1981             &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1982         if (error != 0) {
1983                 printf("error creating CTL lun thread!\n");
1984                 return (error);
1985         }
1986         error = kproc_kthread_add(ctl_thresh_thread, softc,
1987             &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1988         if (error != 0) {
1989                 printf("error creating CTL threshold thread!\n");
1990                 return (error);
1991         }
1992
1993         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1994             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1995             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1996
1997         if (softc->is_single == 0) {
1998                 if (ctl_frontend_register(&ha_frontend) != 0)
1999                         softc->is_single = 1;
2000         }
2001         return (0);
2002 }
2003
2004 static int
2005 ctl_shutdown(void)
2006 {
2007         struct ctl_softc *softc = control_softc;
2008         int i;
2009
2010         if (softc->is_single == 0)
2011                 ctl_frontend_deregister(&ha_frontend);
2012
2013         destroy_dev(softc->dev);
2014
2015         /* Shutdown CTL threads. */
2016         softc->shutdown = 1;
2017         for (i = 0; i < worker_threads; i++) {
2018                 struct ctl_thread *thr = &softc->threads[i];
2019                 while (thr->thread != NULL) {
2020                         wakeup(thr);
2021                         if (thr->thread != NULL)
2022                                 pause("CTL thr shutdown", 1);
2023                 }
2024                 mtx_destroy(&thr->queue_lock);
2025         }
2026         while (softc->lun_thread != NULL) {
2027                 wakeup(&softc->pending_lun_queue);
2028                 if (softc->lun_thread != NULL)
2029                         pause("CTL thr shutdown", 1);
2030         }
2031         while (softc->thresh_thread != NULL) {
2032                 wakeup(softc->thresh_thread);
2033                 if (softc->thresh_thread != NULL)
2034                         pause("CTL thr shutdown", 1);
2035         }
2036
2037         ctl_tpc_shutdown(softc);
2038         uma_zdestroy(softc->io_zone);
2039         mtx_destroy(&softc->ctl_lock);
2040
2041         free(softc->ctl_luns, M_DEVBUF);
2042         free(softc->ctl_lun_mask, M_DEVBUF);
2043         free(softc->ctl_port_mask, M_DEVBUF);
2044         free(softc->ctl_ports, M_DEVBUF);
2045
2046         sysctl_ctx_free(&softc->sysctl_ctx);
2047
2048         free(softc, M_DEVBUF);
2049         control_softc = NULL;
2050         return (0);
2051 }
2052
2053 static int
2054 ctl_module_event_handler(module_t mod, int what, void *arg)
2055 {
2056
2057         switch (what) {
2058         case MOD_LOAD:
2059                 return (ctl_init());
2060         case MOD_UNLOAD:
2061                 return (ctl_shutdown());
2062         default:
2063                 return (EOPNOTSUPP);
2064         }
2065 }
2066
2067 /*
2068  * XXX KDM should we do some access checks here?  Bump a reference count to
2069  * prevent a CTL module from being unloaded while someone has it open?
2070  */
2071 static int
2072 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2073 {
2074         return (0);
2075 }
2076
2077 static int
2078 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2079 {
2080         return (0);
2081 }
2082
2083 /*
2084  * Remove an initiator by port number and initiator ID.
2085  * Returns 0 for success, -1 for failure.
2086  */
2087 int
2088 ctl_remove_initiator(struct ctl_port *port, int iid)
2089 {
2090         struct ctl_softc *softc = port->ctl_softc;
2091         int last;
2092
2093         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2094
2095         if (iid > CTL_MAX_INIT_PER_PORT) {
2096                 printf("%s: initiator ID %u > maximun %u!\n",
2097                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2098                 return (-1);
2099         }
2100
2101         mtx_lock(&softc->ctl_lock);
2102         last = (--port->wwpn_iid[iid].in_use == 0);
2103         port->wwpn_iid[iid].last_use = time_uptime;
2104         mtx_unlock(&softc->ctl_lock);
2105         if (last)
2106                 ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2107         ctl_isc_announce_iid(port, iid);
2108
2109         return (0);
2110 }
2111
2112 /*
2113  * Add an initiator to the initiator map.
2114  * Returns iid for success, < 0 for failure.
2115  */
2116 int
2117 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2118 {
2119         struct ctl_softc *softc = port->ctl_softc;
2120         time_t best_time;
2121         int i, best;
2122
2123         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2124
2125         if (iid >= CTL_MAX_INIT_PER_PORT) {
2126                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2127                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2128                 free(name, M_CTL);
2129                 return (-1);
2130         }
2131
2132         mtx_lock(&softc->ctl_lock);
2133
2134         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2135                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2136                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2137                                 iid = i;
2138                                 break;
2139                         }
2140                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2141                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2142                                 iid = i;
2143                                 break;
2144                         }
2145                 }
2146         }
2147
2148         if (iid < 0) {
2149                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2150                         if (port->wwpn_iid[i].in_use == 0 &&
2151                             port->wwpn_iid[i].wwpn == 0 &&
2152                             port->wwpn_iid[i].name == NULL) {
2153                                 iid = i;
2154                                 break;
2155                         }
2156                 }
2157         }
2158
2159         if (iid < 0) {
2160                 best = -1;
2161                 best_time = INT32_MAX;
2162                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2163                         if (port->wwpn_iid[i].in_use == 0) {
2164                                 if (port->wwpn_iid[i].last_use < best_time) {
2165                                         best = i;
2166                                         best_time = port->wwpn_iid[i].last_use;
2167                                 }
2168                         }
2169                 }
2170                 iid = best;
2171         }
2172
2173         if (iid < 0) {
2174                 mtx_unlock(&softc->ctl_lock);
2175                 free(name, M_CTL);
2176                 return (-2);
2177         }
2178
2179         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2180                 /*
2181                  * This is not an error yet.
2182                  */
2183                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2184 #if 0
2185                         printf("%s: port %d iid %u WWPN %#jx arrived"
2186                             " again\n", __func__, port->targ_port,
2187                             iid, (uintmax_t)wwpn);
2188 #endif
2189                         goto take;
2190                 }
2191                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2192                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2193 #if 0
2194                         printf("%s: port %d iid %u name '%s' arrived"
2195                             " again\n", __func__, port->targ_port,
2196                             iid, name);
2197 #endif
2198                         goto take;
2199                 }
2200
2201                 /*
2202                  * This is an error, but what do we do about it?  The
2203                  * driver is telling us we have a new WWPN for this
2204                  * initiator ID, so we pretty much need to use it.
2205                  */
2206                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2207                     " but WWPN %#jx '%s' is still at that address\n",
2208                     __func__, port->targ_port, iid, wwpn, name,
2209                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2210                     port->wwpn_iid[iid].name);
2211         }
2212 take:
2213         free(port->wwpn_iid[iid].name, M_CTL);
2214         port->wwpn_iid[iid].name = name;
2215         port->wwpn_iid[iid].wwpn = wwpn;
2216         port->wwpn_iid[iid].in_use++;
2217         mtx_unlock(&softc->ctl_lock);
2218         ctl_isc_announce_iid(port, iid);
2219
2220         return (iid);
2221 }
2222
2223 static int
2224 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2225 {
2226         int len;
2227
2228         switch (port->port_type) {
2229         case CTL_PORT_FC:
2230         {
2231                 struct scsi_transportid_fcp *id =
2232                     (struct scsi_transportid_fcp *)buf;
2233                 if (port->wwpn_iid[iid].wwpn == 0)
2234                         return (0);
2235                 memset(id, 0, sizeof(*id));
2236                 id->format_protocol = SCSI_PROTO_FC;
2237                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2238                 return (sizeof(*id));
2239         }
2240         case CTL_PORT_ISCSI:
2241         {
2242                 struct scsi_transportid_iscsi_port *id =
2243                     (struct scsi_transportid_iscsi_port *)buf;
2244                 if (port->wwpn_iid[iid].name == NULL)
2245                         return (0);
2246                 memset(id, 0, 256);
2247                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2248                     SCSI_PROTO_ISCSI;
2249                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2250                 len = roundup2(min(len, 252), 4);
2251                 scsi_ulto2b(len, id->additional_length);
2252                 return (sizeof(*id) + len);
2253         }
2254         case CTL_PORT_SAS:
2255         {
2256                 struct scsi_transportid_sas *id =
2257                     (struct scsi_transportid_sas *)buf;
2258                 if (port->wwpn_iid[iid].wwpn == 0)
2259                         return (0);
2260                 memset(id, 0, sizeof(*id));
2261                 id->format_protocol = SCSI_PROTO_SAS;
2262                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2263                 return (sizeof(*id));
2264         }
2265         default:
2266         {
2267                 struct scsi_transportid_spi *id =
2268                     (struct scsi_transportid_spi *)buf;
2269                 memset(id, 0, sizeof(*id));
2270                 id->format_protocol = SCSI_PROTO_SPI;
2271                 scsi_ulto2b(iid, id->scsi_addr);
2272                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2273                 return (sizeof(*id));
2274         }
2275         }
2276 }
2277
2278 /*
2279  * Serialize a command that went down the "wrong" side, and so was sent to
2280  * this controller for execution.  The logic is a little different than the
2281  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2282  * sent back to the other side, but in the success case, we execute the
2283  * command on this side (XFER mode) or tell the other side to execute it
2284  * (SER_ONLY mode).
2285  */
2286 static void
2287 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2288 {
2289         struct ctl_softc *softc = CTL_SOFTC(ctsio);
2290         struct ctl_port *port = CTL_PORT(ctsio);
2291         union ctl_ha_msg msg_info;
2292         struct ctl_lun *lun;
2293         const struct ctl_cmd_entry *entry;
2294         uint32_t targ_lun;
2295
2296         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2297
2298         /* Make sure that we know about this port. */
2299         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2300                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2301                                          /*retry_count*/ 1);
2302                 goto badjuju;
2303         }
2304
2305         /* Make sure that we know about this LUN. */
2306         mtx_lock(&softc->ctl_lock);
2307         if (targ_lun >= ctl_max_luns ||
2308             (lun = softc->ctl_luns[targ_lun]) == NULL) {
2309                 mtx_unlock(&softc->ctl_lock);
2310
2311                 /*
2312                  * The other node would not send this request to us unless
2313                  * received announce that we are primary node for this LUN.
2314                  * If this LUN does not exist now, it is probably result of
2315                  * a race, so respond to initiator in the most opaque way.
2316                  */
2317                 ctl_set_busy(ctsio);
2318                 goto badjuju;
2319         }
2320         mtx_lock(&lun->lun_lock);
2321         mtx_unlock(&softc->ctl_lock);
2322
2323         /*
2324          * If the LUN is invalid, pretend that it doesn't exist.
2325          * It will go away as soon as all pending I/Os completed.
2326          */
2327         if (lun->flags & CTL_LUN_DISABLED) {
2328                 mtx_unlock(&lun->lun_lock);
2329                 ctl_set_busy(ctsio);
2330                 goto badjuju;
2331         }
2332
2333         entry = ctl_get_cmd_entry(ctsio, NULL);
2334         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2335                 mtx_unlock(&lun->lun_lock);
2336                 goto badjuju;
2337         }
2338
2339         CTL_LUN(ctsio) = lun;
2340         CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2341
2342         /*
2343          * Every I/O goes into the OOA queue for a
2344          * particular LUN, and stays there until completion.
2345          */
2346 #ifdef CTL_TIME_IO
2347         if (TAILQ_EMPTY(&lun->ooa_queue))
2348                 lun->idle_time += getsbinuptime() - lun->last_busy;
2349 #endif
2350         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2351
2352         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2353                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2354                  ooa_links))) {
2355         case CTL_ACTION_BLOCK:
2356                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2357                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2358                                   blocked_links);
2359                 mtx_unlock(&lun->lun_lock);
2360                 break;
2361         case CTL_ACTION_PASS:
2362         case CTL_ACTION_SKIP:
2363                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2364                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2365                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2366                         mtx_unlock(&lun->lun_lock);
2367                 } else {
2368                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2369                         mtx_unlock(&lun->lun_lock);
2370
2371                         /* send msg back to other side */
2372                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2373                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2374                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2375                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2376                             sizeof(msg_info.hdr), M_WAITOK);
2377                 }
2378                 break;
2379         case CTL_ACTION_OVERLAP:
2380                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2381                 mtx_unlock(&lun->lun_lock);
2382                 ctl_set_overlapped_cmd(ctsio);
2383                 goto badjuju;
2384         case CTL_ACTION_OVERLAP_TAG:
2385                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2386                 mtx_unlock(&lun->lun_lock);
2387                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2388                 goto badjuju;
2389         case CTL_ACTION_ERROR:
2390         default:
2391                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2392                 mtx_unlock(&lun->lun_lock);
2393
2394                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2395                                          /*retry_count*/ 0);
2396 badjuju:
2397                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2398                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2399                 msg_info.hdr.serializing_sc = NULL;
2400                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2401                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2402                     sizeof(msg_info.scsi), M_WAITOK);
2403                 ctl_free_io((union ctl_io *)ctsio);
2404                 break;
2405         }
2406 }
2407
2408 /*
2409  * Returns 0 for success, errno for failure.
2410  */
2411 static void
2412 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2413                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2414 {
2415         union ctl_io *io;
2416
2417         mtx_lock(&lun->lun_lock);
2418         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2419              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2420              ooa_links)) {
2421                 struct ctl_ooa_entry *entry;
2422
2423                 /*
2424                  * If we've got more than we can fit, just count the
2425                  * remaining entries.
2426                  */
2427                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2428                         continue;
2429
2430                 entry = &kern_entries[*cur_fill_num];
2431
2432                 entry->tag_num = io->scsiio.tag_num;
2433                 entry->lun_num = lun->lun;
2434 #ifdef CTL_TIME_IO
2435                 entry->start_bt = io->io_hdr.start_bt;
2436 #endif
2437                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2438                 entry->cdb_len = io->scsiio.cdb_len;
2439                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2440                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2441
2442                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2443                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2444
2445                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2446                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2447
2448                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2449                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2450
2451                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2452                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2453         }
2454         mtx_unlock(&lun->lun_lock);
2455 }
2456
2457 /*
2458  * Escape characters that are illegal or not recommended in XML.
2459  */
2460 int
2461 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2462 {
2463         char *end = str + size;
2464         int retval;
2465
2466         retval = 0;
2467
2468         for (; *str && str < end; str++) {
2469                 switch (*str) {
2470                 case '&':
2471                         retval = sbuf_printf(sb, "&amp;");
2472                         break;
2473                 case '>':
2474                         retval = sbuf_printf(sb, "&gt;");
2475                         break;
2476                 case '<':
2477                         retval = sbuf_printf(sb, "&lt;");
2478                         break;
2479                 default:
2480                         retval = sbuf_putc(sb, *str);
2481                         break;
2482                 }
2483
2484                 if (retval != 0)
2485                         break;
2486
2487         }
2488
2489         return (retval);
2490 }
2491
2492 static void
2493 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2494 {
2495         struct scsi_vpd_id_descriptor *desc;
2496         int i;
2497
2498         if (id == NULL || id->len < 4)
2499                 return;
2500         desc = (struct scsi_vpd_id_descriptor *)id->data;
2501         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2502         case SVPD_ID_TYPE_T10:
2503                 sbuf_printf(sb, "t10.");
2504                 break;
2505         case SVPD_ID_TYPE_EUI64:
2506                 sbuf_printf(sb, "eui.");
2507                 break;
2508         case SVPD_ID_TYPE_NAA:
2509                 sbuf_printf(sb, "naa.");
2510                 break;
2511         case SVPD_ID_TYPE_SCSI_NAME:
2512                 break;
2513         }
2514         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2515         case SVPD_ID_CODESET_BINARY:
2516                 for (i = 0; i < desc->length; i++)
2517                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2518                 break;
2519         case SVPD_ID_CODESET_ASCII:
2520                 sbuf_printf(sb, "%.*s", (int)desc->length,
2521                     (char *)desc->identifier);
2522                 break;
2523         case SVPD_ID_CODESET_UTF8:
2524                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2525                 break;
2526         }
2527 }
2528
2529 static int
2530 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2531           struct thread *td)
2532 {
2533         struct ctl_softc *softc = dev->si_drv1;
2534         struct ctl_port *port;
2535         struct ctl_lun *lun;
2536         int retval;
2537
2538         retval = 0;
2539
2540         switch (cmd) {
2541         case CTL_IO:
2542                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2543                 break;
2544         case CTL_ENABLE_PORT:
2545         case CTL_DISABLE_PORT:
2546         case CTL_SET_PORT_WWNS: {
2547                 struct ctl_port *port;
2548                 struct ctl_port_entry *entry;
2549
2550                 entry = (struct ctl_port_entry *)addr;
2551                 
2552                 mtx_lock(&softc->ctl_lock);
2553                 STAILQ_FOREACH(port, &softc->port_list, links) {
2554                         int action, done;
2555
2556                         if (port->targ_port < softc->port_min ||
2557                             port->targ_port >= softc->port_max)
2558                                 continue;
2559
2560                         action = 0;
2561                         done = 0;
2562                         if ((entry->port_type == CTL_PORT_NONE)
2563                          && (entry->targ_port == port->targ_port)) {
2564                                 /*
2565                                  * If the user only wants to enable or
2566                                  * disable or set WWNs on a specific port,
2567                                  * do the operation and we're done.
2568                                  */
2569                                 action = 1;
2570                                 done = 1;
2571                         } else if (entry->port_type & port->port_type) {
2572                                 /*
2573                                  * Compare the user's type mask with the
2574                                  * particular frontend type to see if we
2575                                  * have a match.
2576                                  */
2577                                 action = 1;
2578                                 done = 0;
2579
2580                                 /*
2581                                  * Make sure the user isn't trying to set
2582                                  * WWNs on multiple ports at the same time.
2583                                  */
2584                                 if (cmd == CTL_SET_PORT_WWNS) {
2585                                         printf("%s: Can't set WWNs on "
2586                                                "multiple ports\n", __func__);
2587                                         retval = EINVAL;
2588                                         break;
2589                                 }
2590                         }
2591                         if (action == 0)
2592                                 continue;
2593
2594                         /*
2595                          * XXX KDM we have to drop the lock here, because
2596                          * the online/offline operations can potentially
2597                          * block.  We need to reference count the frontends
2598                          * so they can't go away,
2599                          */
2600                         if (cmd == CTL_ENABLE_PORT) {
2601                                 mtx_unlock(&softc->ctl_lock);
2602                                 ctl_port_online(port);
2603                                 mtx_lock(&softc->ctl_lock);
2604                         } else if (cmd == CTL_DISABLE_PORT) {
2605                                 mtx_unlock(&softc->ctl_lock);
2606                                 ctl_port_offline(port);
2607                                 mtx_lock(&softc->ctl_lock);
2608                         } else if (cmd == CTL_SET_PORT_WWNS) {
2609                                 ctl_port_set_wwns(port,
2610                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2611                                     1 : 0, entry->wwnn,
2612                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2613                                     1 : 0, entry->wwpn);
2614                         }
2615                         if (done != 0)
2616                                 break;
2617                 }
2618                 mtx_unlock(&softc->ctl_lock);
2619                 break;
2620         }
2621         case CTL_GET_OOA: {
2622                 struct ctl_ooa *ooa_hdr;
2623                 struct ctl_ooa_entry *entries;
2624                 uint32_t cur_fill_num;
2625
2626                 ooa_hdr = (struct ctl_ooa *)addr;
2627
2628                 if ((ooa_hdr->alloc_len == 0)
2629                  || (ooa_hdr->alloc_num == 0)) {
2630                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2631                                "must be non-zero\n", __func__,
2632                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2633                         retval = EINVAL;
2634                         break;
2635                 }
2636
2637                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2638                     sizeof(struct ctl_ooa_entry))) {
2639                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2640                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2641                                __func__, ooa_hdr->alloc_len,
2642                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2643                         retval = EINVAL;
2644                         break;
2645                 }
2646
2647                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2648                 if (entries == NULL) {
2649                         printf("%s: could not allocate %d bytes for OOA "
2650                                "dump\n", __func__, ooa_hdr->alloc_len);
2651                         retval = ENOMEM;
2652                         break;
2653                 }
2654
2655                 mtx_lock(&softc->ctl_lock);
2656                 if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2657                     (ooa_hdr->lun_num >= ctl_max_luns ||
2658                      softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2659                         mtx_unlock(&softc->ctl_lock);
2660                         free(entries, M_CTL);
2661                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2662                                __func__, (uintmax_t)ooa_hdr->lun_num);
2663                         retval = EINVAL;
2664                         break;
2665                 }
2666
2667                 cur_fill_num = 0;
2668
2669                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2670                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2671                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2672                                     ooa_hdr, entries);
2673                         }
2674                 } else {
2675                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2676                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2677                             entries);
2678                 }
2679                 mtx_unlock(&softc->ctl_lock);
2680
2681                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2682                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2683                         sizeof(struct ctl_ooa_entry);
2684                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2685                 if (retval != 0) {
2686                         printf("%s: error copying out %d bytes for OOA dump\n", 
2687                                __func__, ooa_hdr->fill_len);
2688                 }
2689
2690                 getbinuptime(&ooa_hdr->cur_bt);
2691
2692                 if (cur_fill_num > ooa_hdr->alloc_num) {
2693                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2694                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2695                 } else {
2696                         ooa_hdr->dropped_num = 0;
2697                         ooa_hdr->status = CTL_OOA_OK;
2698                 }
2699
2700                 free(entries, M_CTL);
2701                 break;
2702         }
2703         case CTL_DELAY_IO: {
2704                 struct ctl_io_delay_info *delay_info;
2705
2706                 delay_info = (struct ctl_io_delay_info *)addr;
2707
2708 #ifdef CTL_IO_DELAY
2709                 mtx_lock(&softc->ctl_lock);
2710                 if (delay_info->lun_id >= ctl_max_luns ||
2711                     (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2712                         mtx_unlock(&softc->ctl_lock);
2713                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2714                         break;
2715                 }
2716                 mtx_lock(&lun->lun_lock);
2717                 mtx_unlock(&softc->ctl_lock);
2718                 delay_info->status = CTL_DELAY_STATUS_OK;
2719                 switch (delay_info->delay_type) {
2720                 case CTL_DELAY_TYPE_CONT:
2721                 case CTL_DELAY_TYPE_ONESHOT:
2722                         break;
2723                 default:
2724                         delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2725                         break;
2726                 }
2727                 switch (delay_info->delay_loc) {
2728                 case CTL_DELAY_LOC_DATAMOVE:
2729                         lun->delay_info.datamove_type = delay_info->delay_type;
2730                         lun->delay_info.datamove_delay = delay_info->delay_secs;
2731                         break;
2732                 case CTL_DELAY_LOC_DONE:
2733                         lun->delay_info.done_type = delay_info->delay_type;
2734                         lun->delay_info.done_delay = delay_info->delay_secs;
2735                         break;
2736                 default:
2737                         delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2738                         break;
2739                 }
2740                 mtx_unlock(&lun->lun_lock);
2741 #else
2742                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2743 #endif /* CTL_IO_DELAY */
2744                 break;
2745         }
2746 #ifdef CTL_LEGACY_STATS
2747         case CTL_GETSTATS: {
2748                 struct ctl_stats *stats = (struct ctl_stats *)addr;
2749                 int i;
2750
2751                 /*
2752                  * XXX KDM no locking here.  If the LUN list changes,
2753                  * things can blow up.
2754                  */
2755                 i = 0;
2756                 stats->status = CTL_SS_OK;
2757                 stats->fill_len = 0;
2758                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2759                         if (stats->fill_len + sizeof(lun->legacy_stats) >
2760                             stats->alloc_len) {
2761                                 stats->status = CTL_SS_NEED_MORE_SPACE;
2762                                 break;
2763                         }
2764                         retval = copyout(&lun->legacy_stats, &stats->lun_stats[i++],
2765                                          sizeof(lun->legacy_stats));
2766                         if (retval != 0)
2767                                 break;
2768                         stats->fill_len += sizeof(lun->legacy_stats);
2769                 }
2770                 stats->num_luns = softc->num_luns;
2771                 stats->flags = CTL_STATS_FLAG_NONE;
2772 #ifdef CTL_TIME_IO
2773                 stats->flags |= CTL_STATS_FLAG_TIME_VALID;
2774 #endif
2775                 getnanouptime(&stats->timestamp);
2776                 break;
2777         }
2778 #endif /* CTL_LEGACY_STATS */
2779         case CTL_ERROR_INJECT: {
2780                 struct ctl_error_desc *err_desc, *new_err_desc;
2781
2782                 err_desc = (struct ctl_error_desc *)addr;
2783
2784                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2785                                       M_WAITOK | M_ZERO);
2786                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2787
2788                 mtx_lock(&softc->ctl_lock);
2789                 if (err_desc->lun_id >= ctl_max_luns ||
2790                     (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2791                         mtx_unlock(&softc->ctl_lock);
2792                         free(new_err_desc, M_CTL);
2793                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2794                                __func__, (uintmax_t)err_desc->lun_id);
2795                         retval = EINVAL;
2796                         break;
2797                 }
2798                 mtx_lock(&lun->lun_lock);
2799                 mtx_unlock(&softc->ctl_lock);
2800
2801                 /*
2802                  * We could do some checking here to verify the validity
2803                  * of the request, but given the complexity of error
2804                  * injection requests, the checking logic would be fairly
2805                  * complex.
2806                  *
2807                  * For now, if the request is invalid, it just won't get
2808                  * executed and might get deleted.
2809                  */
2810                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2811
2812                 /*
2813                  * XXX KDM check to make sure the serial number is unique,
2814                  * in case we somehow manage to wrap.  That shouldn't
2815                  * happen for a very long time, but it's the right thing to
2816                  * do.
2817                  */
2818                 new_err_desc->serial = lun->error_serial;
2819                 err_desc->serial = lun->error_serial;
2820                 lun->error_serial++;
2821
2822                 mtx_unlock(&lun->lun_lock);
2823                 break;
2824         }
2825         case CTL_ERROR_INJECT_DELETE: {
2826                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2827                 int delete_done;
2828
2829                 delete_desc = (struct ctl_error_desc *)addr;
2830                 delete_done = 0;
2831
2832                 mtx_lock(&softc->ctl_lock);
2833                 if (delete_desc->lun_id >= ctl_max_luns ||
2834                     (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2835                         mtx_unlock(&softc->ctl_lock);
2836                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2837                                __func__, (uintmax_t)delete_desc->lun_id);
2838                         retval = EINVAL;
2839                         break;
2840                 }
2841                 mtx_lock(&lun->lun_lock);
2842                 mtx_unlock(&softc->ctl_lock);
2843                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2844                         if (desc->serial != delete_desc->serial)
2845                                 continue;
2846
2847                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2848                                       links);
2849                         free(desc, M_CTL);
2850                         delete_done = 1;
2851                 }
2852                 mtx_unlock(&lun->lun_lock);
2853                 if (delete_done == 0) {
2854                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2855                                "error serial %ju on LUN %u\n", __func__, 
2856                                delete_desc->serial, delete_desc->lun_id);
2857                         retval = EINVAL;
2858                         break;
2859                 }
2860                 break;
2861         }
2862         case CTL_DUMP_STRUCTS: {
2863                 int j, k;
2864                 struct ctl_port *port;
2865                 struct ctl_frontend *fe;
2866
2867                 mtx_lock(&softc->ctl_lock);
2868                 printf("CTL Persistent Reservation information start:\n");
2869                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2870                         mtx_lock(&lun->lun_lock);
2871                         if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2872                                 mtx_unlock(&lun->lun_lock);
2873                                 continue;
2874                         }
2875
2876                         for (j = 0; j < ctl_max_ports; j++) {
2877                                 if (lun->pr_keys[j] == NULL)
2878                                         continue;
2879                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2880                                         if (lun->pr_keys[j][k] == 0)
2881                                                 continue;
2882                                         printf("  LUN %ju port %d iid %d key "
2883                                                "%#jx\n", lun->lun, j, k,
2884                                                (uintmax_t)lun->pr_keys[j][k]);
2885                                 }
2886                         }
2887                         mtx_unlock(&lun->lun_lock);
2888                 }
2889                 printf("CTL Persistent Reservation information end\n");
2890                 printf("CTL Ports:\n");
2891                 STAILQ_FOREACH(port, &softc->port_list, links) {
2892                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2893                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2894                                port->frontend->name, port->port_type,
2895                                port->physical_port, port->virtual_port,
2896                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2897                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2898                                 if (port->wwpn_iid[j].in_use == 0 &&
2899                                     port->wwpn_iid[j].wwpn == 0 &&
2900                                     port->wwpn_iid[j].name == NULL)
2901                                         continue;
2902
2903                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2904                                     j, port->wwpn_iid[j].in_use,
2905                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2906                                     port->wwpn_iid[j].name);
2907                         }
2908                 }
2909                 printf("CTL Port information end\n");
2910                 mtx_unlock(&softc->ctl_lock);
2911                 /*
2912                  * XXX KDM calling this without a lock.  We'd likely want
2913                  * to drop the lock before calling the frontend's dump
2914                  * routine anyway.
2915                  */
2916                 printf("CTL Frontends:\n");
2917                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2918                         printf("  Frontend '%s'\n", fe->name);
2919                         if (fe->fe_dump != NULL)
2920                                 fe->fe_dump();
2921                 }
2922                 printf("CTL Frontend information end\n");
2923                 break;
2924         }
2925         case CTL_LUN_REQ: {
2926                 struct ctl_lun_req *lun_req;
2927                 struct ctl_backend_driver *backend;
2928                 void *packed;
2929                 nvlist_t *tmp_args_nvl;
2930                 size_t packed_len;
2931
2932                 lun_req = (struct ctl_lun_req *)addr;
2933                 tmp_args_nvl = lun_req->args_nvl;
2934
2935                 backend = ctl_backend_find(lun_req->backend);
2936                 if (backend == NULL) {
2937                         lun_req->status = CTL_LUN_ERROR;
2938                         snprintf(lun_req->error_str,
2939                                  sizeof(lun_req->error_str),
2940                                  "Backend \"%s\" not found.",
2941                                  lun_req->backend);
2942                         break;
2943                 }
2944
2945                 if (lun_req->args != NULL) {
2946                         lun_req->args_nvl = nvlist_unpack(lun_req->args,
2947                             lun_req->args_len, 0);
2948
2949                         if (lun_req->args_nvl == NULL) {
2950                                 lun_req->status = CTL_LUN_ERROR;
2951                                 snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2952                                     "Cannot unpack args nvlist.");
2953                                 break;
2954                         }
2955                 } else
2956                         lun_req->args_nvl = nvlist_create(0);
2957
2958                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2959                 nvlist_destroy(lun_req->args_nvl);
2960                 lun_req->args_nvl = tmp_args_nvl;
2961
2962                 if (lun_req->result_nvl != NULL) {
2963                         if (lun_req->result != NULL) {
2964                                 packed = nvlist_pack(lun_req->result_nvl,
2965                                     &packed_len);
2966                                 if (packed == NULL) {
2967                                         lun_req->status = CTL_LUN_ERROR;
2968                                         snprintf(lun_req->error_str,
2969                                             sizeof(lun_req->error_str),
2970                                             "Cannot pack result nvlist.");
2971                                         break;
2972                                 }
2973
2974                                 if (packed_len > lun_req->result_len) {
2975                                         lun_req->status = CTL_LUN_ERROR;
2976                                         snprintf(lun_req->error_str,
2977                                             sizeof(lun_req->error_str),
2978                                             "Result nvlist too large.");
2979                                         free(packed, M_NVLIST);
2980                                         break;
2981                                 }
2982
2983                                 if (copyout(packed, lun_req->result, packed_len)) {
2984                                         lun_req->status = CTL_LUN_ERROR;
2985                                         snprintf(lun_req->error_str,
2986                                             sizeof(lun_req->error_str),
2987                                             "Cannot copyout() the result.");
2988                                         free(packed, M_NVLIST);
2989                                         break;
2990                                 }
2991
2992                                 lun_req->result_len = packed_len;
2993                                 free(packed, M_NVLIST);
2994                         }
2995
2996                         nvlist_destroy(lun_req->result_nvl);
2997                 }
2998                 break;
2999         }
3000         case CTL_LUN_LIST: {
3001                 struct sbuf *sb;
3002                 struct ctl_lun_list *list;
3003                 const char *name, *value;
3004                 void *cookie;
3005                 int type;
3006
3007                 list = (struct ctl_lun_list *)addr;
3008
3009                 /*
3010                  * Allocate a fixed length sbuf here, based on the length
3011                  * of the user's buffer.  We could allocate an auto-extending
3012                  * buffer, and then tell the user how much larger our
3013                  * amount of data is than his buffer, but that presents
3014                  * some problems:
3015                  *
3016                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3017                  *     we can't hold a lock while calling them with an
3018                  *     auto-extending buffer.
3019                  *
3020                  * 2.  There is not currently a LUN reference counting
3021                  *     mechanism, outside of outstanding transactions on
3022                  *     the LUN's OOA queue.  So a LUN could go away on us
3023                  *     while we're getting the LUN number, backend-specific
3024                  *     information, etc.  Thus, given the way things
3025                  *     currently work, we need to hold the CTL lock while
3026                  *     grabbing LUN information.
3027                  *
3028                  * So, from the user's standpoint, the best thing to do is
3029                  * allocate what he thinks is a reasonable buffer length,
3030                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3031                  * double the buffer length and try again.  (And repeat
3032                  * that until he succeeds.)
3033                  */
3034                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3035                 if (sb == NULL) {
3036                         list->status = CTL_LUN_LIST_ERROR;
3037                         snprintf(list->error_str, sizeof(list->error_str),
3038                                  "Unable to allocate %d bytes for LUN list",
3039                                  list->alloc_len);
3040                         break;
3041                 }
3042
3043                 sbuf_printf(sb, "<ctllunlist>\n");
3044
3045                 mtx_lock(&softc->ctl_lock);
3046                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3047                         mtx_lock(&lun->lun_lock);
3048                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3049                                              (uintmax_t)lun->lun);
3050
3051                         /*
3052                          * Bail out as soon as we see that we've overfilled
3053                          * the buffer.
3054                          */
3055                         if (retval != 0)
3056                                 break;
3057
3058                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3059                                              "</backend_type>\n",
3060                                              (lun->backend == NULL) ?  "none" :
3061                                              lun->backend->name);
3062
3063                         if (retval != 0)
3064                                 break;
3065
3066                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3067                                              lun->be_lun->lun_type);
3068
3069                         if (retval != 0)
3070                                 break;
3071
3072                         if (lun->backend == NULL) {
3073                                 retval = sbuf_printf(sb, "</lun>\n");
3074                                 if (retval != 0)
3075                                         break;
3076                                 continue;
3077                         }
3078
3079                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3080                                              (lun->be_lun->maxlba > 0) ?
3081                                              lun->be_lun->maxlba + 1 : 0);
3082
3083                         if (retval != 0)
3084                                 break;
3085
3086                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3087                                              lun->be_lun->blocksize);
3088
3089                         if (retval != 0)
3090                                 break;
3091
3092                         retval = sbuf_printf(sb, "\t<serial_number>");
3093
3094                         if (retval != 0)
3095                                 break;
3096
3097                         retval = ctl_sbuf_printf_esc(sb,
3098                             lun->be_lun->serial_num,
3099                             sizeof(lun->be_lun->serial_num));
3100
3101                         if (retval != 0)
3102                                 break;
3103
3104                         retval = sbuf_printf(sb, "</serial_number>\n");
3105                 
3106                         if (retval != 0)
3107                                 break;
3108
3109                         retval = sbuf_printf(sb, "\t<device_id>");
3110
3111                         if (retval != 0)
3112                                 break;
3113
3114                         retval = ctl_sbuf_printf_esc(sb,
3115                             lun->be_lun->device_id,
3116                             sizeof(lun->be_lun->device_id));
3117
3118                         if (retval != 0)
3119                                 break;
3120
3121                         retval = sbuf_printf(sb, "</device_id>\n");
3122
3123                         if (retval != 0)
3124                                 break;
3125
3126                         if (lun->backend->lun_info != NULL) {
3127                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3128                                 if (retval != 0)
3129                                         break;
3130                         }
3131
3132                         cookie = NULL;
3133                         while ((name = nvlist_next(lun->be_lun->options, &type,
3134                             &cookie)) != NULL) {
3135                                 sbuf_printf(sb, "\t<%s>", name);
3136
3137                                 if (type == NV_TYPE_STRING) {
3138                                         value = dnvlist_get_string(
3139                                             lun->be_lun->options, name, NULL);
3140                                         if (value != NULL)
3141                                                 sbuf_printf(sb, "%s", value);
3142                                 }
3143
3144                                 sbuf_printf(sb, "</%s>\n", name);
3145                         }
3146
3147                         retval = sbuf_printf(sb, "</lun>\n");
3148
3149                         if (retval != 0)
3150                                 break;
3151                         mtx_unlock(&lun->lun_lock);
3152                 }
3153                 if (lun != NULL)
3154                         mtx_unlock(&lun->lun_lock);
3155                 mtx_unlock(&softc->ctl_lock);
3156
3157                 if ((retval != 0)
3158                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3159                         retval = 0;
3160                         sbuf_delete(sb);
3161                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3162                         snprintf(list->error_str, sizeof(list->error_str),
3163                                  "Out of space, %d bytes is too small",
3164                                  list->alloc_len);
3165                         break;
3166                 }
3167
3168                 sbuf_finish(sb);
3169
3170                 retval = copyout(sbuf_data(sb), list->lun_xml,
3171                                  sbuf_len(sb) + 1);
3172
3173                 list->fill_len = sbuf_len(sb) + 1;
3174                 list->status = CTL_LUN_LIST_OK;
3175                 sbuf_delete(sb);
3176                 break;
3177         }
3178         case CTL_ISCSI: {
3179                 struct ctl_iscsi *ci;
3180                 struct ctl_frontend *fe;
3181
3182                 ci = (struct ctl_iscsi *)addr;
3183
3184                 fe = ctl_frontend_find("iscsi");
3185                 if (fe == NULL) {
3186                         ci->status = CTL_ISCSI_ERROR;
3187                         snprintf(ci->error_str, sizeof(ci->error_str),
3188                             "Frontend \"iscsi\" not found.");
3189                         break;
3190                 }
3191
3192                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3193                 break;
3194         }
3195         case CTL_PORT_REQ: {
3196                 struct ctl_req *req;
3197                 struct ctl_frontend *fe;
3198                 void *packed;
3199                 nvlist_t *tmp_args_nvl;
3200                 size_t packed_len;
3201
3202                 req = (struct ctl_req *)addr;
3203                 tmp_args_nvl = req->args_nvl;
3204
3205                 fe = ctl_frontend_find(req->driver);
3206                 if (fe == NULL) {
3207                         req->status = CTL_LUN_ERROR;
3208                         snprintf(req->error_str, sizeof(req->error_str),
3209                             "Frontend \"%s\" not found.", req->driver);
3210                         break;
3211                 }
3212
3213                 if (req->args != NULL) {
3214                         req->args_nvl = nvlist_unpack(req->args,
3215                             req->args_len, 0);
3216
3217                         if (req->args_nvl == NULL) {
3218                                 req->status = CTL_LUN_ERROR;
3219                                 snprintf(req->error_str, sizeof(req->error_str),
3220                                     "Cannot unpack args nvlist.");
3221                                 break;
3222                         }
3223                 } else
3224                         req->args_nvl = nvlist_create(0);
3225
3226                 if (fe->ioctl)
3227                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3228                 else
3229                         retval = ENODEV;
3230
3231                 nvlist_destroy(req->args_nvl);
3232                 req->args_nvl = tmp_args_nvl;
3233
3234                 if (req->result_nvl != NULL) {
3235                         if (req->result != NULL) {
3236                                 packed = nvlist_pack(req->result_nvl,
3237                                     &packed_len);
3238                                 if (packed == NULL) {
3239                                         req->status = CTL_LUN_ERROR;
3240                                         snprintf(req->error_str,
3241                                             sizeof(req->error_str),
3242                                             "Cannot pack result nvlist.");
3243                                         break;
3244                                 }
3245
3246                                 if (packed_len > req->result_len) {
3247                                         req->status = CTL_LUN_ERROR;
3248                                         snprintf(req->error_str,
3249                                             sizeof(req->error_str),
3250                                             "Result nvlist too large.");
3251                                         free(packed, M_NVLIST);
3252                                         break;
3253                                 }
3254
3255                                 if (copyout(packed, req->result, packed_len)) {
3256                                         req->status = CTL_LUN_ERROR;
3257                                         snprintf(req->error_str,
3258                                             sizeof(req->error_str),
3259                                             "Cannot copyout() the result.");
3260                                         free(packed, M_NVLIST);
3261                                         break;
3262                                 }
3263
3264                                 req->result_len = packed_len;
3265                                 free(packed, M_NVLIST);
3266                         }
3267
3268                         nvlist_destroy(req->result_nvl);
3269                 }
3270                 break;
3271         }
3272         case CTL_PORT_LIST: {
3273                 struct sbuf *sb;
3274                 struct ctl_port *port;
3275                 struct ctl_lun_list *list;
3276                 const char *name, *value;
3277                 void *cookie;
3278                 int j, type;
3279                 uint32_t plun;
3280
3281                 list = (struct ctl_lun_list *)addr;
3282
3283                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3284                 if (sb == NULL) {
3285                         list->status = CTL_LUN_LIST_ERROR;
3286                         snprintf(list->error_str, sizeof(list->error_str),
3287                                  "Unable to allocate %d bytes for LUN list",
3288                                  list->alloc_len);
3289                         break;
3290                 }
3291
3292                 sbuf_printf(sb, "<ctlportlist>\n");
3293
3294                 mtx_lock(&softc->ctl_lock);
3295                 STAILQ_FOREACH(port, &softc->port_list, links) {
3296                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3297                                              (uintmax_t)port->targ_port);
3298
3299                         /*
3300                          * Bail out as soon as we see that we've overfilled
3301                          * the buffer.
3302                          */
3303                         if (retval != 0)
3304                                 break;
3305
3306                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3307                             "</frontend_type>\n", port->frontend->name);
3308                         if (retval != 0)
3309                                 break;
3310
3311                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3312                                              port->port_type);
3313                         if (retval != 0)
3314                                 break;
3315
3316                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3317                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3318                         if (retval != 0)
3319                                 break;
3320
3321                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3322                             port->port_name);
3323                         if (retval != 0)
3324                                 break;
3325
3326                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3327                             port->physical_port);
3328                         if (retval != 0)
3329                                 break;
3330
3331                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3332                             port->virtual_port);
3333                         if (retval != 0)
3334                                 break;
3335
3336                         if (port->target_devid != NULL) {
3337                                 sbuf_printf(sb, "\t<target>");
3338                                 ctl_id_sbuf(port->target_devid, sb);
3339                                 sbuf_printf(sb, "</target>\n");
3340                         }
3341
3342                         if (port->port_devid != NULL) {
3343                                 sbuf_printf(sb, "\t<port>");
3344                                 ctl_id_sbuf(port->port_devid, sb);
3345                                 sbuf_printf(sb, "</port>\n");
3346                         }
3347
3348                         if (port->port_info != NULL) {
3349                                 retval = port->port_info(port->onoff_arg, sb);
3350                                 if (retval != 0)
3351                                         break;
3352                         }
3353
3354                         cookie = NULL;
3355                         while ((name = nvlist_next(port->options, &type,
3356                             &cookie)) != NULL) {
3357                                 sbuf_printf(sb, "\t<%s>", name);
3358
3359                                 if (type == NV_TYPE_STRING) {
3360                                         value = dnvlist_get_string(port->options,
3361                                             name, NULL);
3362                                         if (value != NULL)
3363                                                 sbuf_printf(sb, "%s", value);
3364                                 }
3365
3366                                 sbuf_printf(sb, "</%s>\n", name);
3367                         }
3368
3369                         if (port->lun_map != NULL) {
3370                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3371                                 for (j = 0; j < port->lun_map_size; j++) {
3372                                         plun = ctl_lun_map_from_port(port, j);
3373                                         if (plun == UINT32_MAX)
3374                                                 continue;
3375                                         sbuf_printf(sb,
3376                                             "\t<lun id=\"%u\">%u</lun>\n",
3377                                             j, plun);
3378                                 }
3379                         }
3380
3381                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3382                                 if (port->wwpn_iid[j].in_use == 0 ||
3383                                     (port->wwpn_iid[j].wwpn == 0 &&
3384                                      port->wwpn_iid[j].name == NULL))
3385                                         continue;
3386
3387                                 if (port->wwpn_iid[j].name != NULL)
3388                                         retval = sbuf_printf(sb,
3389                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3390                                             j, port->wwpn_iid[j].name);
3391                                 else
3392                                         retval = sbuf_printf(sb,
3393                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3394                                             j, port->wwpn_iid[j].wwpn);
3395                                 if (retval != 0)
3396                                         break;
3397                         }
3398                         if (retval != 0)
3399                                 break;
3400
3401                         retval = sbuf_printf(sb, "</targ_port>\n");
3402                         if (retval != 0)
3403                                 break;
3404                 }
3405                 mtx_unlock(&softc->ctl_lock);
3406
3407                 if ((retval != 0)
3408                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3409                         retval = 0;
3410                         sbuf_delete(sb);
3411                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3412                         snprintf(list->error_str, sizeof(list->error_str),
3413                                  "Out of space, %d bytes is too small",
3414                                  list->alloc_len);
3415                         break;
3416                 }
3417
3418                 sbuf_finish(sb);
3419
3420                 retval = copyout(sbuf_data(sb), list->lun_xml,
3421                                  sbuf_len(sb) + 1);
3422
3423                 list->fill_len = sbuf_len(sb) + 1;
3424                 list->status = CTL_LUN_LIST_OK;
3425                 sbuf_delete(sb);
3426                 break;
3427         }
3428         case CTL_LUN_MAP: {
3429                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3430                 struct ctl_port *port;
3431
3432                 mtx_lock(&softc->ctl_lock);
3433                 if (lm->port < softc->port_min ||
3434                     lm->port >= softc->port_max ||
3435                     (port = softc->ctl_ports[lm->port]) == NULL) {
3436                         mtx_unlock(&softc->ctl_lock);
3437                         return (ENXIO);
3438                 }
3439                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3440                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3441                                 if (ctl_lun_map_to_port(port, lun->lun) ==
3442                                     UINT32_MAX)
3443                                         continue;
3444                                 mtx_lock(&lun->lun_lock);
3445                                 ctl_est_ua_port(lun, lm->port, -1,
3446                                     CTL_UA_LUN_CHANGE);
3447                                 mtx_unlock(&lun->lun_lock);
3448                         }
3449                 }
3450                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3451                 if (lm->plun != UINT32_MAX) {
3452                         if (lm->lun == UINT32_MAX)
3453                                 retval = ctl_lun_map_unset(port, lm->plun);
3454                         else if (lm->lun < ctl_max_luns &&
3455                             softc->ctl_luns[lm->lun] != NULL)
3456                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3457                         else
3458                                 return (ENXIO);
3459                 } else {
3460                         if (lm->lun == UINT32_MAX)
3461                                 retval = ctl_lun_map_deinit(port);
3462                         else
3463                                 retval = ctl_lun_map_init(port);
3464                 }
3465                 if (port->status & CTL_PORT_STATUS_ONLINE)
3466                         ctl_isc_announce_port(port);
3467                 break;
3468         }
3469         case CTL_GET_LUN_STATS: {
3470                 struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3471                 int i;
3472
3473                 /*
3474                  * XXX KDM no locking here.  If the LUN list changes,
3475                  * things can blow up.
3476                  */
3477                 i = 0;
3478                 stats->status = CTL_SS_OK;
3479                 stats->fill_len = 0;
3480                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3481                         if (lun->lun < stats->first_item)
3482                                 continue;
3483                         if (stats->fill_len + sizeof(lun->stats) >
3484                             stats->alloc_len) {
3485                                 stats->status = CTL_SS_NEED_MORE_SPACE;
3486                                 break;
3487                         }
3488                         retval = copyout(&lun->stats, &stats->stats[i++],
3489                                          sizeof(lun->stats));
3490                         if (retval != 0)
3491                                 break;
3492                         stats->fill_len += sizeof(lun->stats);
3493                 }
3494                 stats->num_items = softc->num_luns;
3495                 stats->flags = CTL_STATS_FLAG_NONE;
3496 #ifdef CTL_TIME_IO
3497                 stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3498 #endif
3499                 getnanouptime(&stats->timestamp);
3500                 break;
3501         }
3502         case CTL_GET_PORT_STATS: {
3503                 struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3504                 int i;
3505
3506                 /*
3507                  * XXX KDM no locking here.  If the LUN list changes,
3508                  * things can blow up.
3509                  */
3510                 i = 0;
3511                 stats->status = CTL_SS_OK;
3512                 stats->fill_len = 0;
3513                 STAILQ_FOREACH(port, &softc->port_list, links) {
3514                         if (port->targ_port < stats->first_item)
3515                                 continue;
3516                         if (stats->fill_len + sizeof(port->stats) >
3517                             stats->alloc_len) {
3518                                 stats->status = CTL_SS_NEED_MORE_SPACE;
3519                                 break;
3520                         }
3521                         retval = copyout(&port->stats, &stats->stats[i++],
3522                                          sizeof(port->stats));
3523                         if (retval != 0)
3524                                 break;
3525                         stats->fill_len += sizeof(port->stats);
3526                 }
3527                 stats->num_items = softc->num_ports;
3528                 stats->flags = CTL_STATS_FLAG_NONE;
3529 #ifdef CTL_TIME_IO
3530                 stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3531 #endif
3532                 getnanouptime(&stats->timestamp);
3533                 break;
3534         }
3535         default: {
3536                 /* XXX KDM should we fix this? */
3537 #if 0
3538                 struct ctl_backend_driver *backend;
3539                 unsigned int type;
3540                 int found;
3541
3542                 found = 0;
3543
3544                 /*
3545                  * We encode the backend type as the ioctl type for backend
3546                  * ioctls.  So parse it out here, and then search for a
3547                  * backend of this type.
3548                  */
3549                 type = _IOC_TYPE(cmd);
3550
3551                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3552                         if (backend->type == type) {
3553                                 found = 1;
3554                                 break;
3555                         }
3556                 }
3557                 if (found == 0) {
3558                         printf("ctl: unknown ioctl command %#lx or backend "
3559                                "%d\n", cmd, type);
3560                         retval = EINVAL;
3561                         break;
3562                 }
3563                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3564 #endif
3565                 retval = ENOTTY;
3566                 break;
3567         }
3568         }
3569         return (retval);
3570 }
3571
3572 uint32_t
3573 ctl_get_initindex(struct ctl_nexus *nexus)
3574 {
3575         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3576 }
3577
3578 int
3579 ctl_lun_map_init(struct ctl_port *port)
3580 {
3581         struct ctl_softc *softc = port->ctl_softc;
3582         struct ctl_lun *lun;
3583         int size = ctl_lun_map_size;
3584         uint32_t i;
3585
3586         if (port->lun_map == NULL || port->lun_map_size < size) {
3587                 port->lun_map_size = 0;
3588                 free(port->lun_map, M_CTL);
3589                 port->lun_map = malloc(size * sizeof(uint32_t),
3590                     M_CTL, M_NOWAIT);
3591         }
3592         if (port->lun_map == NULL)
3593                 return (ENOMEM);
3594         for (i = 0; i < size; i++)
3595                 port->lun_map[i] = UINT32_MAX;
3596         port->lun_map_size = size;
3597         if (port->status & CTL_PORT_STATUS_ONLINE) {
3598                 if (port->lun_disable != NULL) {
3599                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3600                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3601                 }
3602                 ctl_isc_announce_port(port);
3603         }
3604         return (0);
3605 }
3606
3607 int
3608 ctl_lun_map_deinit(struct ctl_port *port)
3609 {
3610         struct ctl_softc *softc = port->ctl_softc;
3611         struct ctl_lun *lun;
3612
3613         if (port->lun_map == NULL)
3614                 return (0);
3615         port->lun_map_size = 0;
3616         free(port->lun_map, M_CTL);
3617         port->lun_map = NULL;
3618         if (port->status & CTL_PORT_STATUS_ONLINE) {
3619                 if (port->lun_enable != NULL) {
3620                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3621                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3622                 }
3623                 ctl_isc_announce_port(port);
3624         }
3625         return (0);
3626 }
3627
3628 int
3629 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3630 {
3631         int status;
3632         uint32_t old;
3633
3634         if (port->lun_map == NULL) {
3635                 status = ctl_lun_map_init(port);
3636                 if (status != 0)
3637                         return (status);
3638         }
3639         if (plun >= port->lun_map_size)
3640                 return (EINVAL);
3641         old = port->lun_map[plun];
3642         port->lun_map[plun] = glun;
3643         if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3644                 if (port->lun_enable != NULL)
3645                         port->lun_enable(port->targ_lun_arg, plun);
3646                 ctl_isc_announce_port(port);
3647         }
3648         return (0);
3649 }
3650
3651 int
3652 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3653 {
3654         uint32_t old;
3655
3656         if (port->lun_map == NULL || plun >= port->lun_map_size)
3657                 return (0);
3658         old = port->lun_map[plun];
3659         port->lun_map[plun] = UINT32_MAX;
3660         if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3661                 if (port->lun_disable != NULL)
3662                         port->lun_disable(port->targ_lun_arg, plun);
3663                 ctl_isc_announce_port(port);
3664         }
3665         return (0);
3666 }
3667
3668 uint32_t
3669 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3670 {
3671
3672         if (port == NULL)
3673                 return (UINT32_MAX);
3674         if (port->lun_map == NULL)
3675                 return (lun_id);
3676         if (lun_id > port->lun_map_size)
3677                 return (UINT32_MAX);
3678         return (port->lun_map[lun_id]);
3679 }
3680
3681 uint32_t
3682 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3683 {
3684         uint32_t i;
3685
3686         if (port == NULL)
3687                 return (UINT32_MAX);
3688         if (port->lun_map == NULL)
3689                 return (lun_id);
3690         for (i = 0; i < port->lun_map_size; i++) {
3691                 if (port->lun_map[i] == lun_id)
3692                         return (i);
3693         }
3694         return (UINT32_MAX);
3695 }
3696
3697 uint32_t
3698 ctl_decode_lun(uint64_t encoded)
3699 {
3700         uint8_t lun[8];
3701         uint32_t result = 0xffffffff;
3702
3703         be64enc(lun, encoded);
3704         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3705         case RPL_LUNDATA_ATYP_PERIPH:
3706                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3707                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3708                         result = lun[1];
3709                 break;
3710         case RPL_LUNDATA_ATYP_FLAT:
3711                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3712                     lun[6] == 0 && lun[7] == 0)
3713                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3714                 break;
3715         case RPL_LUNDATA_ATYP_EXTLUN:
3716                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3717                 case 0x02:
3718                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3719                         case 0x00:
3720                                 result = lun[1];
3721                                 break;
3722                         case 0x10:
3723                                 result = (lun[1] << 16) + (lun[2] << 8) +
3724                                     lun[3];
3725                                 break;
3726                         case 0x20:
3727                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3728                                         result = (lun[2] << 24) +
3729                                             (lun[3] << 16) + (lun[4] << 8) +
3730                                             lun[5];
3731                                 break;
3732                         }
3733                         break;
3734                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3735                         result = 0xffffffff;
3736                         break;
3737                 }
3738                 break;
3739         }
3740         return (result);
3741 }
3742
3743 uint64_t
3744 ctl_encode_lun(uint32_t decoded)
3745 {
3746         uint64_t l = decoded;
3747
3748         if (l <= 0xff)
3749                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3750         if (l <= 0x3fff)
3751                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3752         if (l <= 0xffffff)
3753                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3754                     (l << 32));
3755         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3756 }
3757
3758 int
3759 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3760 {
3761         int i;
3762
3763         for (i = first; i < last; i++) {
3764                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3765                         return (i);
3766         }
3767         return (-1);
3768 }
3769
3770 int
3771 ctl_set_mask(uint32_t *mask, uint32_t bit)
3772 {
3773         uint32_t chunk, piece;
3774
3775         chunk = bit >> 5;
3776         piece = bit % (sizeof(uint32_t) * 8);
3777
3778         if ((mask[chunk] & (1 << piece)) != 0)
3779                 return (-1);
3780         else
3781                 mask[chunk] |= (1 << piece);
3782
3783         return (0);
3784 }
3785
3786 int
3787 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3788 {
3789         uint32_t chunk, piece;
3790
3791         chunk = bit >> 5;
3792         piece = bit % (sizeof(uint32_t) * 8);
3793
3794         if ((mask[chunk] & (1 << piece)) == 0)
3795                 return (-1);
3796         else
3797                 mask[chunk] &= ~(1 << piece);
3798
3799         return (0);
3800 }
3801
3802 int
3803 ctl_is_set(uint32_t *mask, uint32_t bit)
3804 {
3805         uint32_t chunk, piece;
3806
3807         chunk = bit >> 5;
3808         piece = bit % (sizeof(uint32_t) * 8);
3809
3810         if ((mask[chunk] & (1 << piece)) == 0)
3811                 return (0);
3812         else
3813                 return (1);
3814 }
3815
3816 static uint64_t
3817 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3818 {
3819         uint64_t *t;
3820
3821         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3822         if (t == NULL)
3823                 return (0);
3824         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3825 }
3826
3827 static void
3828 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3829 {
3830         uint64_t *t;
3831
3832         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3833         if (t == NULL)
3834                 return;
3835         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3836 }
3837
3838 static void
3839 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3840 {
3841         uint64_t *p;
3842         u_int i;
3843
3844         i = residx/CTL_MAX_INIT_PER_PORT;
3845         if (lun->pr_keys[i] != NULL)
3846                 return;
3847         mtx_unlock(&lun->lun_lock);
3848         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3849             M_WAITOK | M_ZERO);
3850         mtx_lock(&lun->lun_lock);
3851         if (lun->pr_keys[i] == NULL)
3852                 lun->pr_keys[i] = p;
3853         else
3854                 free(p, M_CTL);
3855 }
3856
3857 static void
3858 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3859 {
3860         uint64_t *t;
3861
3862         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3863         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3864         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3865 }
3866
3867 /*
3868  * ctl_softc, pool_name, total_ctl_io are passed in.
3869  * npool is passed out.
3870  */
3871 int
3872 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3873                 uint32_t total_ctl_io, void **npool)
3874 {
3875         struct ctl_io_pool *pool;
3876
3877         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3878                                             M_NOWAIT | M_ZERO);
3879         if (pool == NULL)
3880                 return (ENOMEM);
3881
3882         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3883         pool->ctl_softc = ctl_softc;
3884 #ifdef IO_POOLS
3885         pool->zone = uma_zsecond_create(pool->name, NULL,
3886             NULL, NULL, NULL, ctl_softc->io_zone);
3887         /* uma_prealloc(pool->zone, total_ctl_io); */
3888 #else
3889         pool->zone = ctl_softc->io_zone;
3890 #endif
3891
3892         *npool = pool;
3893         return (0);
3894 }
3895
3896 void
3897 ctl_pool_free(struct ctl_io_pool *pool)
3898 {
3899
3900         if (pool == NULL)
3901                 return;
3902
3903 #ifdef IO_POOLS
3904         uma_zdestroy(pool->zone);
3905 #endif
3906         free(pool, M_CTL);
3907 }
3908
3909 union ctl_io *
3910 ctl_alloc_io(void *pool_ref)
3911 {
3912         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3913         union ctl_io *io;
3914
3915         io = uma_zalloc(pool->zone, M_WAITOK);
3916         if (io != NULL) {
3917                 io->io_hdr.pool = pool_ref;
3918                 CTL_SOFTC(io) = pool->ctl_softc;
3919         }
3920         return (io);
3921 }
3922
3923 union ctl_io *
3924 ctl_alloc_io_nowait(void *pool_ref)
3925 {
3926         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3927         union ctl_io *io;
3928
3929         io = uma_zalloc(pool->zone, M_NOWAIT);
3930         if (io != NULL) {
3931                 io->io_hdr.pool = pool_ref;
3932                 CTL_SOFTC(io) = pool->ctl_softc;
3933         }
3934         return (io);
3935 }
3936
3937 void
3938 ctl_free_io(union ctl_io *io)
3939 {
3940         struct ctl_io_pool *pool;
3941
3942         if (io == NULL)
3943                 return;
3944
3945         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3946         uma_zfree(pool->zone, io);
3947 }
3948
3949 void
3950 ctl_zero_io(union ctl_io *io)
3951 {
3952         struct ctl_io_pool *pool;
3953
3954         if (io == NULL)
3955                 return;
3956
3957         /*
3958          * May need to preserve linked list pointers at some point too.
3959          */
3960         pool = io->io_hdr.pool;
3961         memset(io, 0, sizeof(*io));
3962         io->io_hdr.pool = pool;
3963         CTL_SOFTC(io) = pool->ctl_softc;
3964 }
3965
3966 int
3967 ctl_expand_number(const char *buf, uint64_t *num)
3968 {
3969         char *endptr;
3970         uint64_t number;
3971         unsigned shift;
3972
3973         number = strtoq(buf, &endptr, 0);
3974
3975         switch (tolower((unsigned char)*endptr)) {
3976         case 'e':
3977                 shift = 60;
3978                 break;
3979         case 'p':
3980                 shift = 50;
3981                 break;
3982         case 't':
3983                 shift = 40;
3984                 break;
3985         case 'g':
3986                 shift = 30;
3987                 break;
3988         case 'm':
3989                 shift = 20;
3990                 break;
3991         case 'k':
3992                 shift = 10;
3993                 break;
3994         case 'b':
3995         case '\0': /* No unit. */
3996                 *num = number;
3997                 return (0);
3998         default:
3999                 /* Unrecognized unit. */
4000                 return (-1);
4001         }
4002
4003         if ((number << shift) >> shift != number) {
4004                 /* Overflow */
4005                 return (-1);
4006         }
4007         *num = number << shift;
4008         return (0);
4009 }
4010
4011
4012 /*
4013  * This routine could be used in the future to load default and/or saved
4014  * mode page parameters for a particuar lun.
4015  */
4016 static int
4017 ctl_init_page_index(struct ctl_lun *lun)
4018 {
4019         int i, page_code;
4020         struct ctl_page_index *page_index;
4021         const char *value;
4022         uint64_t ival;
4023
4024         memcpy(&lun->mode_pages.index, page_index_template,
4025                sizeof(page_index_template));
4026
4027         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4028
4029                 page_index = &lun->mode_pages.index[i];
4030                 if (lun->be_lun->lun_type == T_DIRECT &&
4031                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4032                         continue;
4033                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4034                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4035                         continue;
4036                 if (lun->be_lun->lun_type == T_CDROM &&
4037                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4038                         continue;
4039
4040                 page_code = page_index->page_code & SMPH_PC_MASK;
4041                 switch (page_code) {
4042                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4043                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4044                             ("subpage %#x for page %#x is incorrect!",
4045                             page_index->subpage, page_code));
4046                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4047                                &rw_er_page_default,
4048                                sizeof(rw_er_page_default));
4049                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4050                                &rw_er_page_changeable,
4051                                sizeof(rw_er_page_changeable));
4052                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4053                                &rw_er_page_default,
4054                                sizeof(rw_er_page_default));
4055                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4056                                &rw_er_page_default,
4057                                sizeof(rw_er_page_default));
4058                         page_index->page_data =
4059                                 (uint8_t *)lun->mode_pages.rw_er_page;
4060                         break;
4061                 }
4062                 case SMS_FORMAT_DEVICE_PAGE: {
4063                         struct scsi_format_page *format_page;
4064
4065                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4066                             ("subpage %#x for page %#x is incorrect!",
4067                             page_index->subpage, page_code));
4068
4069                         /*
4070                          * Sectors per track are set above.  Bytes per
4071                          * sector need to be set here on a per-LUN basis.
4072                          */
4073                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4074                                &format_page_default,
4075                                sizeof(format_page_default));
4076                         memcpy(&lun->mode_pages.format_page[
4077                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4078                                sizeof(format_page_changeable));
4079                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4080                                &format_page_default,
4081                                sizeof(format_page_default));
4082                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4083                                &format_page_default,
4084                                sizeof(format_page_default));
4085
4086                         format_page = &lun->mode_pages.format_page[
4087                                 CTL_PAGE_CURRENT];
4088                         scsi_ulto2b(lun->be_lun->blocksize,
4089                                     format_page->bytes_per_sector);
4090
4091                         format_page = &lun->mode_pages.format_page[
4092                                 CTL_PAGE_DEFAULT];
4093                         scsi_ulto2b(lun->be_lun->blocksize,
4094                                     format_page->bytes_per_sector);
4095
4096                         format_page = &lun->mode_pages.format_page[
4097                                 CTL_PAGE_SAVED];
4098                         scsi_ulto2b(lun->be_lun->blocksize,
4099                                     format_page->bytes_per_sector);
4100
4101                         page_index->page_data =
4102                                 (uint8_t *)lun->mode_pages.format_page;
4103                         break;
4104                 }
4105                 case SMS_RIGID_DISK_PAGE: {
4106                         struct scsi_rigid_disk_page *rigid_disk_page;
4107                         uint32_t sectors_per_cylinder;
4108                         uint64_t cylinders;
4109 #ifndef __XSCALE__
4110                         int shift;
4111 #endif /* !__XSCALE__ */
4112
4113                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4114                             ("subpage %#x for page %#x is incorrect!",
4115                             page_index->subpage, page_code));
4116
4117                         /*
4118                          * Rotation rate and sectors per track are set
4119                          * above.  We calculate the cylinders here based on
4120                          * capacity.  Due to the number of heads and
4121                          * sectors per track we're using, smaller arrays
4122                          * may turn out to have 0 cylinders.  Linux and
4123                          * FreeBSD don't pay attention to these mode pages
4124                          * to figure out capacity, but Solaris does.  It
4125                          * seems to deal with 0 cylinders just fine, and
4126                          * works out a fake geometry based on the capacity.
4127                          */
4128                         memcpy(&lun->mode_pages.rigid_disk_page[
4129                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4130                                sizeof(rigid_disk_page_default));
4131                         memcpy(&lun->mode_pages.rigid_disk_page[
4132                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4133                                sizeof(rigid_disk_page_changeable));
4134
4135                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4136                                 CTL_DEFAULT_HEADS;
4137
4138                         /*
4139                          * The divide method here will be more accurate,
4140                          * probably, but results in floating point being
4141                          * used in the kernel on i386 (__udivdi3()).  On the
4142                          * XScale, though, __udivdi3() is implemented in
4143                          * software.
4144                          *
4145                          * The shift method for cylinder calculation is
4146                          * accurate if sectors_per_cylinder is a power of
4147                          * 2.  Otherwise it might be slightly off -- you
4148                          * might have a bit of a truncation problem.
4149                          */
4150 #ifdef  __XSCALE__
4151                         cylinders = (lun->be_lun->maxlba + 1) /
4152                                 sectors_per_cylinder;
4153 #else
4154                         for (shift = 31; shift > 0; shift--) {
4155                                 if (sectors_per_cylinder & (1 << shift))
4156                                         break;
4157                         }
4158                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4159 #endif
4160
4161                         /*
4162                          * We've basically got 3 bytes, or 24 bits for the
4163                          * cylinder size in the mode page.  If we're over,
4164                          * just round down to 2^24.
4165                          */
4166                         if (cylinders > 0xffffff)
4167                                 cylinders = 0xffffff;
4168
4169                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4170                                 CTL_PAGE_DEFAULT];
4171                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4172
4173                         if ((value = dnvlist_get_string(lun->be_lun->options,
4174                             "rpm", NULL)) != NULL) {
4175                                 scsi_ulto2b(strtol(value, NULL, 0),
4176                                      rigid_disk_page->rotation_rate);
4177                         }
4178
4179                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4180                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4181                                sizeof(rigid_disk_page_default));
4182                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4183                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4184                                sizeof(rigid_disk_page_default));
4185
4186                         page_index->page_data =
4187                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4188                         break;
4189                 }
4190                 case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4191                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4192                             ("subpage %#x for page %#x is incorrect!",
4193                             page_index->subpage, page_code));
4194                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4195                                &verify_er_page_default,
4196                                sizeof(verify_er_page_default));
4197                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4198                                &verify_er_page_changeable,
4199                                sizeof(verify_er_page_changeable));
4200                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4201                                &verify_er_page_default,
4202                                sizeof(verify_er_page_default));
4203                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4204                                &verify_er_page_default,
4205                                sizeof(verify_er_page_default));
4206                         page_index->page_data =
4207                                 (uint8_t *)lun->mode_pages.verify_er_page;
4208                         break;
4209                 }
4210                 case SMS_CACHING_PAGE: {
4211                         struct scsi_caching_page *caching_page;
4212
4213                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4214                             ("subpage %#x for page %#x is incorrect!",
4215                             page_index->subpage, page_code));
4216                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4217                                &caching_page_default,
4218                                sizeof(caching_page_default));
4219                         memcpy(&lun->mode_pages.caching_page[
4220                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4221                                sizeof(caching_page_changeable));
4222                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4223                                &caching_page_default,
4224                                sizeof(caching_page_default));
4225                         caching_page = &lun->mode_pages.caching_page[
4226                             CTL_PAGE_SAVED];
4227                         value = dnvlist_get_string(lun->be_lun->options,
4228                             "writecache", NULL);
4229                         if (value != NULL && strcmp(value, "off") == 0)
4230                                 caching_page->flags1 &= ~SCP_WCE;
4231                         value = dnvlist_get_string(lun->be_lun->options,
4232                             "readcache", NULL);
4233                         if (value != NULL && strcmp(value, "off") == 0)
4234                                 caching_page->flags1 |= SCP_RCD;
4235                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4236                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4237                                sizeof(caching_page_default));
4238                         page_index->page_data =
4239                                 (uint8_t *)lun->mode_pages.caching_page;
4240                         break;
4241                 }
4242                 case SMS_CONTROL_MODE_PAGE: {
4243                         switch (page_index->subpage) {
4244                         case SMS_SUBPAGE_PAGE_0: {
4245                                 struct scsi_control_page *control_page;
4246
4247                                 memcpy(&lun->mode_pages.control_page[
4248                                     CTL_PAGE_DEFAULT],
4249                                        &control_page_default,
4250                                        sizeof(control_page_default));
4251                                 memcpy(&lun->mode_pages.control_page[
4252                                     CTL_PAGE_CHANGEABLE],
4253                                        &control_page_changeable,
4254                                        sizeof(control_page_changeable));
4255                                 memcpy(&lun->mode_pages.control_page[
4256                                     CTL_PAGE_SAVED],
4257                                        &control_page_default,
4258                                        sizeof(control_page_default));
4259                                 control_page = &lun->mode_pages.control_page[
4260                                     CTL_PAGE_SAVED];
4261                                 value = dnvlist_get_string(lun->be_lun->options,
4262                                     "reordering", NULL);
4263                                 if (value != NULL &&
4264                                     strcmp(value, "unrestricted") == 0) {
4265                                         control_page->queue_flags &=
4266                                             ~SCP_QUEUE_ALG_MASK;
4267                                         control_page->queue_flags |=
4268                                             SCP_QUEUE_ALG_UNRESTRICTED;
4269                                 }
4270                                 memcpy(&lun->mode_pages.control_page[
4271                                     CTL_PAGE_CURRENT],
4272                                        &lun->mode_pages.control_page[
4273                                     CTL_PAGE_SAVED],
4274                                        sizeof(control_page_default));
4275                                 page_index->page_data =
4276                                     (uint8_t *)lun->mode_pages.control_page;
4277                                 break;
4278                         }
4279                         case 0x01:
4280                                 memcpy(&lun->mode_pages.control_ext_page[
4281                                     CTL_PAGE_DEFAULT],
4282                                        &control_ext_page_default,
4283                                        sizeof(control_ext_page_default));
4284                                 memcpy(&lun->mode_pages.control_ext_page[
4285                                     CTL_PAGE_CHANGEABLE],
4286                                        &control_ext_page_changeable,
4287                                        sizeof(control_ext_page_changeable));
4288                                 memcpy(&lun->mode_pages.control_ext_page[
4289                                     CTL_PAGE_SAVED],
4290                                        &control_ext_page_default,
4291                                        sizeof(control_ext_page_default));
4292                                 memcpy(&lun->mode_pages.control_ext_page[
4293                                     CTL_PAGE_CURRENT],
4294                                        &lun->mode_pages.control_ext_page[
4295                                     CTL_PAGE_SAVED],
4296                                        sizeof(control_ext_page_default));
4297                                 page_index->page_data =
4298                                     (uint8_t *)lun->mode_pages.control_ext_page;
4299                                 break;
4300                         default:
4301                                 panic("subpage %#x for page %#x is incorrect!",
4302                                       page_index->subpage, page_code);
4303                         }
4304                         break;
4305                 }
4306                 case SMS_INFO_EXCEPTIONS_PAGE: {
4307                         switch (page_index->subpage) {
4308                         case SMS_SUBPAGE_PAGE_0:
4309                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4310                                        &ie_page_default,
4311                                        sizeof(ie_page_default));
4312                                 memcpy(&lun->mode_pages.ie_page[
4313                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4314                                        sizeof(ie_page_changeable));
4315                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4316                                        &ie_page_default,
4317                                        sizeof(ie_page_default));
4318                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4319                                        &ie_page_default,
4320                                        sizeof(ie_page_default));
4321                                 page_index->page_data =
4322                                         (uint8_t *)lun->mode_pages.ie_page;
4323                                 break;
4324                         case 0x02: {
4325                                 struct ctl_logical_block_provisioning_page *page;
4326
4327                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4328                                        &lbp_page_default,
4329                                        sizeof(lbp_page_default));
4330                                 memcpy(&lun->mode_pages.lbp_page[
4331                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4332                                        sizeof(lbp_page_changeable));
4333                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4334                                        &lbp_page_default,
4335                                        sizeof(lbp_page_default));
4336                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4337                                 value = dnvlist_get_string(lun->be_lun->options,
4338                                     "avail-threshold", NULL);
4339                                 if (value != NULL &&
4340                                     ctl_expand_number(value, &ival) == 0) {
4341                                         page->descr[0].flags |= SLBPPD_ENABLED |
4342                                             SLBPPD_ARMING_DEC;
4343                                         if (lun->be_lun->blocksize)
4344                                                 ival /= lun->be_lun->blocksize;
4345                                         else
4346                                                 ival /= 512;
4347                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4348                                             page->descr[0].count);
4349                                 }
4350                                 value = dnvlist_get_string(lun->be_lun->options,
4351                                     "used-threshold", NULL);
4352                                 if (value != NULL &&
4353                                     ctl_expand_number(value, &ival) == 0) {
4354                                         page->descr[1].flags |= SLBPPD_ENABLED |
4355                                             SLBPPD_ARMING_INC;
4356                                         if (lun->be_lun->blocksize)
4357                                                 ival /= lun->be_lun->blocksize;
4358                                         else
4359                                                 ival /= 512;
4360                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4361                                             page->descr[1].count);
4362                                 }
4363                                 value = dnvlist_get_string(lun->be_lun->options,
4364                                     "pool-avail-threshold", NULL);
4365                                 if (value != NULL &&
4366                                     ctl_expand_number(value, &ival) == 0) {
4367                                         page->descr[2].flags |= SLBPPD_ENABLED |
4368                                             SLBPPD_ARMING_DEC;
4369                                         if (lun->be_lun->blocksize)
4370                                                 ival /= lun->be_lun->blocksize;
4371                                         else
4372                                                 ival /= 512;
4373                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4374                                             page->descr[2].count);
4375                                 }
4376                                 value = dnvlist_get_string(lun->be_lun->options,
4377                                     "pool-used-threshold", NULL);
4378                                 if (value != NULL &&
4379                                     ctl_expand_number(value, &ival) == 0) {
4380                                         page->descr[3].flags |= SLBPPD_ENABLED |
4381                                             SLBPPD_ARMING_INC;
4382                                         if (lun->be_lun->blocksize)
4383                                                 ival /= lun->be_lun->blocksize;
4384                                         else
4385                                                 ival /= 512;
4386                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4387                                             page->descr[3].count);
4388                                 }
4389                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4390                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4391                                        sizeof(lbp_page_default));
4392                                 page_index->page_data =
4393                                         (uint8_t *)lun->mode_pages.lbp_page;
4394                                 break;
4395                         }
4396                         default:
4397                                 panic("subpage %#x for page %#x is incorrect!",
4398                                       page_index->subpage, page_code);
4399                         }
4400                         break;
4401                 }
4402                 case SMS_CDDVD_CAPS_PAGE:{
4403                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4404                             ("subpage %#x for page %#x is incorrect!",
4405                             page_index->subpage, page_code));
4406                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4407                                &cddvd_page_default,
4408                                sizeof(cddvd_page_default));
4409                         memcpy(&lun->mode_pages.cddvd_page[
4410                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4411                                sizeof(cddvd_page_changeable));
4412                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4413                                &cddvd_page_default,
4414                                sizeof(cddvd_page_default));
4415                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4416                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4417                                sizeof(cddvd_page_default));
4418                         page_index->page_data =
4419                                 (uint8_t *)lun->mode_pages.cddvd_page;
4420                         break;
4421                 }
4422                 default:
4423                         panic("invalid page code value %#x", page_code);
4424                 }
4425         }
4426
4427         return (CTL_RETVAL_COMPLETE);
4428 }
4429
4430 static int
4431 ctl_init_log_page_index(struct ctl_lun *lun)
4432 {
4433         struct ctl_page_index *page_index;
4434         int i, j, k, prev;
4435
4436         memcpy(&lun->log_pages.index, log_page_index_template,
4437                sizeof(log_page_index_template));
4438
4439         prev = -1;
4440         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4441
4442                 page_index = &lun->log_pages.index[i];
4443                 if (lun->be_lun->lun_type == T_DIRECT &&
4444                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4445                         continue;
4446                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4447                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4448                         continue;
4449                 if (lun->be_lun->lun_type == T_CDROM &&
4450                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4451                         continue;
4452
4453                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4454                     lun->backend->lun_attr == NULL)
4455                         continue;
4456
4457                 if (page_index->page_code != prev) {
4458                         lun->log_pages.pages_page[j] = page_index->page_code;
4459                         prev = page_index->page_code;
4460                         j++;
4461                 }
4462                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4463                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4464                 k++;
4465         }
4466         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4467         lun->log_pages.index[0].page_len = j;
4468         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4469         lun->log_pages.index[1].page_len = k * 2;
4470         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4471         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4472         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4473         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4474         lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4475         lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4476
4477         return (CTL_RETVAL_COMPLETE);
4478 }
4479
4480 static int
4481 hex2bin(const char *str, uint8_t *buf, int buf_size)
4482 {
4483         int i;
4484         u_char c;
4485
4486         memset(buf, 0, buf_size);
4487         while (isspace(str[0]))
4488                 str++;
4489         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4490                 str += 2;
4491         buf_size *= 2;
4492         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4493                 while (str[i] == '-')   /* Skip dashes in UUIDs. */
4494                         str++;
4495                 c = str[i];
4496                 if (isdigit(c))
4497                         c -= '0';
4498                 else if (isalpha(c))
4499                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4500                 else
4501                         break;
4502                 if (c >= 16)
4503                         break;
4504                 if ((i & 1) == 0)
4505                         buf[i / 2] |= (c << 4);
4506                 else
4507                         buf[i / 2] |= c;
4508         }
4509         return ((i + 1) / 2);
4510 }
4511
4512 /*
4513  * LUN allocation.
4514  *
4515  * Requirements:
4516  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4517  *   wants us to allocate the LUN and he can block.
4518  * - ctl_softc is always set
4519  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4520  *
4521  * Returns 0 for success, non-zero (errno) for failure.
4522  */
4523 static int
4524 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4525               struct ctl_be_lun *const be_lun)
4526 {
4527         struct ctl_lun *nlun, *lun;
4528         struct scsi_vpd_id_descriptor *desc;
4529         struct scsi_vpd_id_t10 *t10id;
4530         const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4531         int lun_number, lun_malloced;
4532         int devidlen, idlen1, idlen2 = 0, len;
4533
4534         if (be_lun == NULL)
4535                 return (EINVAL);
4536
4537         /*
4538          * We currently only support Direct Access or Processor LUN types.
4539          */
4540         switch (be_lun->lun_type) {
4541         case T_DIRECT:
4542         case T_PROCESSOR:
4543         case T_CDROM:
4544                 break;
4545         case T_SEQUENTIAL:
4546         case T_CHANGER:
4547         default:
4548                 be_lun->lun_config_status(be_lun->be_lun,
4549                                           CTL_LUN_CONFIG_FAILURE);
4550                 break;
4551         }
4552         if (ctl_lun == NULL) {
4553                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4554                 lun_malloced = 1;
4555         } else {
4556                 lun_malloced = 0;
4557                 lun = ctl_lun;
4558         }
4559
4560         memset(lun, 0, sizeof(*lun));
4561         if (lun_malloced)
4562                 lun->flags = CTL_LUN_MALLOCED;
4563
4564         lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4565             ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4566         lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4567             M_DEVBUF, M_WAITOK | M_ZERO);
4568         lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4569             M_DEVBUF, M_WAITOK | M_ZERO);
4570
4571         /* Generate LUN ID. */
4572         devidlen = max(CTL_DEVID_MIN_LEN,
4573             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4574         idlen1 = sizeof(*t10id) + devidlen;
4575         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4576         scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4577         if (scsiname != NULL) {
4578                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4579                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4580         }
4581         eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4582         if (eui != NULL) {
4583                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4584         }
4585         naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4586         if (naa != NULL) {
4587                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4588         }
4589         uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4590         if (uuid != NULL) {
4591                 len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4592         }
4593         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4594             M_CTL, M_WAITOK | M_ZERO);
4595         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4596         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4597         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4598         desc->length = idlen1;
4599         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4600         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4601         if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4602                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4603         } else {
4604                 strncpy(t10id->vendor, vendor,
4605                     min(sizeof(t10id->vendor), strlen(vendor)));
4606         }
4607         strncpy((char *)t10id->vendor_spec_id,
4608             (char *)be_lun->device_id, devidlen);
4609         if (scsiname != NULL) {
4610                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4611                     desc->length);
4612                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4613                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4614                     SVPD_ID_TYPE_SCSI_NAME;
4615                 desc->length = idlen2;
4616                 strlcpy(desc->identifier, scsiname, idlen2);
4617         }
4618         if (eui != NULL) {
4619                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4620                     desc->length);
4621                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4622                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4623                     SVPD_ID_TYPE_EUI64;
4624                 desc->length = hex2bin(eui, desc->identifier, 16);
4625                 desc->length = desc->length > 12 ? 16 :
4626                     (desc->length > 8 ? 12 : 8);
4627                 len -= 16 - desc->length;
4628         }
4629         if (naa != NULL) {
4630                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4631                     desc->length);
4632                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4633                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4634                     SVPD_ID_TYPE_NAA;
4635                 desc->length = hex2bin(naa, desc->identifier, 16);
4636                 desc->length = desc->length > 8 ? 16 : 8;
4637                 len -= 16 - desc->length;
4638         }
4639         if (uuid != NULL) {
4640                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4641                     desc->length);
4642                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4643                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4644                     SVPD_ID_TYPE_UUID;
4645                 desc->identifier[0] = 0x10;
4646                 hex2bin(uuid, &desc->identifier[2], 16);
4647                 desc->length = 18;
4648         }
4649         lun->lun_devid->len = len;
4650
4651         mtx_lock(&ctl_softc->ctl_lock);
4652         /*
4653          * See if the caller requested a particular LUN number.  If so, see
4654          * if it is available.  Otherwise, allocate the first available LUN.
4655          */
4656         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4657                 if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4658                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4659                         mtx_unlock(&ctl_softc->ctl_lock);
4660                         if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4661                                 printf("ctl: requested LUN ID %d is higher "
4662                                        "than ctl_max_luns - 1 (%d)\n",
4663                                        be_lun->req_lun_id, ctl_max_luns - 1);
4664                         } else {
4665                                 /*
4666                                  * XXX KDM return an error, or just assign
4667                                  * another LUN ID in this case??
4668                                  */
4669                                 printf("ctl: requested LUN ID %d is already "
4670                                        "in use\n", be_lun->req_lun_id);
4671                         }
4672 fail:
4673                         free(lun->lun_devid, M_CTL);
4674                         if (lun->flags & CTL_LUN_MALLOCED)
4675                                 free(lun, M_CTL);
4676                         be_lun->lun_config_status(be_lun->be_lun,
4677                                                   CTL_LUN_CONFIG_FAILURE);
4678                         return (ENOSPC);
4679                 }
4680                 lun_number = be_lun->req_lun_id;
4681         } else {
4682                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4683                 if (lun_number == -1) {
4684                         mtx_unlock(&ctl_softc->ctl_lock);
4685                         printf("ctl: can't allocate LUN, out of LUNs\n");
4686                         goto fail;
4687                 }
4688         }
4689         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4690         mtx_unlock(&ctl_softc->ctl_lock);
4691
4692         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4693         lun->lun = lun_number;
4694         lun->be_lun = be_lun;
4695         /*
4696          * The processor LUN is always enabled.  Disk LUNs come on line
4697          * disabled, and must be enabled by the backend.
4698          */
4699         lun->flags |= CTL_LUN_DISABLED;
4700         lun->backend = be_lun->be;
4701         be_lun->ctl_lun = lun;
4702         be_lun->lun_id = lun_number;
4703         atomic_add_int(&be_lun->be->num_luns, 1);
4704         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4705                 lun->flags |= CTL_LUN_EJECTED;
4706         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4707                 lun->flags |= CTL_LUN_NO_MEDIA;
4708         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4709                 lun->flags |= CTL_LUN_STOPPED;
4710
4711         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4712                 lun->flags |= CTL_LUN_PRIMARY_SC;
4713
4714         value = dnvlist_get_string(be_lun->options, "removable", NULL);
4715         if (value != NULL) {
4716                 if (strcmp(value, "on") == 0)
4717                         lun->flags |= CTL_LUN_REMOVABLE;
4718         } else if (be_lun->lun_type == T_CDROM)
4719                 lun->flags |= CTL_LUN_REMOVABLE;
4720
4721         lun->ctl_softc = ctl_softc;
4722 #ifdef CTL_TIME_IO
4723         lun->last_busy = getsbinuptime();
4724 #endif
4725         TAILQ_INIT(&lun->ooa_queue);
4726         TAILQ_INIT(&lun->blocked_queue);
4727         STAILQ_INIT(&lun->error_list);
4728         lun->ie_reported = 1;
4729         callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4730         ctl_tpc_lun_init(lun);
4731         if (lun->flags & CTL_LUN_REMOVABLE) {
4732                 lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4733                     M_CTL, M_WAITOK);
4734         }
4735
4736         /*
4737          * Initialize the mode and log page index.
4738          */
4739         ctl_init_page_index(lun);
4740         ctl_init_log_page_index(lun);
4741
4742         /* Setup statistics gathering */
4743 #ifdef CTL_LEGACY_STATS
4744         lun->legacy_stats.device_type = be_lun->lun_type;
4745         lun->legacy_stats.lun_number = lun_number;
4746         lun->legacy_stats.blocksize = be_lun->blocksize;
4747         if (be_lun->blocksize == 0)
4748                 lun->legacy_stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4749         lun->legacy_stats.ports = malloc(sizeof(struct ctl_lun_io_port_stats) *
4750             ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4751         for (len = 0; len < ctl_max_ports; len++)
4752                 lun->legacy_stats.ports[len].targ_port = len;
4753 #endif /* CTL_LEGACY_STATS */
4754         lun->stats.item = lun_number;
4755
4756         /*
4757          * Now, before we insert this lun on the lun list, set the lun
4758          * inventory changed UA for all other luns.
4759          */
4760         mtx_lock(&ctl_softc->ctl_lock);
4761         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4762                 mtx_lock(&nlun->lun_lock);
4763                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4764                 mtx_unlock(&nlun->lun_lock);
4765         }
4766         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4767         ctl_softc->ctl_luns[lun_number] = lun;
4768         ctl_softc->num_luns++;
4769         mtx_unlock(&ctl_softc->ctl_lock);
4770
4771         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4772         return (0);
4773 }
4774
4775 /*
4776  * Delete a LUN.
4777  * Assumptions:
4778  * - LUN has already been marked invalid and any pending I/O has been taken
4779  *   care of.
4780  */
4781 static int
4782 ctl_free_lun(struct ctl_lun *lun)
4783 {
4784         struct ctl_softc *softc = lun->ctl_softc;
4785         struct ctl_lun *nlun;
4786         int i;
4787
4788         KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4789             ("Freeing a LUN %p with outstanding I/O!\n", lun));
4790
4791         mtx_lock(&softc->ctl_lock);
4792         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4793         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4794         softc->ctl_luns[lun->lun] = NULL;
4795         softc->num_luns--;
4796         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4797                 mtx_lock(&nlun->lun_lock);
4798                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4799                 mtx_unlock(&nlun->lun_lock);
4800         }
4801         mtx_unlock(&softc->ctl_lock);
4802
4803         /*
4804          * Tell the backend to free resources, if this LUN has a backend.
4805          */
4806         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4807         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4808
4809         lun->ie_reportcnt = UINT32_MAX;
4810         callout_drain(&lun->ie_callout);
4811         ctl_tpc_lun_shutdown(lun);
4812         mtx_destroy(&lun->lun_lock);
4813         free(lun->lun_devid, M_CTL);
4814         for (i = 0; i < ctl_max_ports; i++)
4815                 free(lun->pending_ua[i], M_CTL);
4816         free(lun->pending_ua, M_DEVBUF);
4817         for (i = 0; i < ctl_max_ports; i++)
4818                 free(lun->pr_keys[i], M_CTL);
4819         free(lun->pr_keys, M_DEVBUF);
4820         free(lun->write_buffer, M_CTL);
4821         free(lun->prevent, M_CTL);
4822         if (lun->flags & CTL_LUN_MALLOCED)
4823                 free(lun, M_CTL);
4824
4825         return (0);
4826 }
4827
4828 static void
4829 ctl_create_lun(struct ctl_be_lun *be_lun)
4830 {
4831
4832         /*
4833          * ctl_alloc_lun() should handle all potential failure cases.
4834          */
4835         ctl_alloc_lun(control_softc, NULL, be_lun);
4836 }
4837
4838 int
4839 ctl_add_lun(struct ctl_be_lun *be_lun)
4840 {
4841         struct ctl_softc *softc = control_softc;
4842
4843         mtx_lock(&softc->ctl_lock);
4844         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4845         mtx_unlock(&softc->ctl_lock);
4846         wakeup(&softc->pending_lun_queue);
4847
4848         return (0);
4849 }
4850
4851 int
4852 ctl_enable_lun(struct ctl_be_lun *be_lun)
4853 {
4854         struct ctl_softc *softc;
4855         struct ctl_port *port, *nport;
4856         struct ctl_lun *lun;
4857         int retval;
4858
4859         lun = (struct ctl_lun *)be_lun->ctl_lun;
4860         softc = lun->ctl_softc;
4861
4862         mtx_lock(&softc->ctl_lock);
4863         mtx_lock(&lun->lun_lock);
4864         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4865                 /*
4866                  * eh?  Why did we get called if the LUN is already
4867                  * enabled?
4868                  */
4869                 mtx_unlock(&lun->lun_lock);
4870                 mtx_unlock(&softc->ctl_lock);
4871                 return (0);
4872         }
4873         lun->flags &= ~CTL_LUN_DISABLED;
4874         mtx_unlock(&lun->lun_lock);
4875
4876         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4877                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4878                     port->lun_map != NULL || port->lun_enable == NULL)
4879                         continue;
4880
4881                 /*
4882                  * Drop the lock while we call the FETD's enable routine.
4883                  * This can lead to a callback into CTL (at least in the
4884                  * case of the internal initiator frontend.
4885                  */
4886                 mtx_unlock(&softc->ctl_lock);
4887                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4888                 mtx_lock(&softc->ctl_lock);
4889                 if (retval != 0) {
4890                         printf("%s: FETD %s port %d returned error "
4891                                "%d for lun_enable on lun %jd\n",
4892                                __func__, port->port_name, port->targ_port,
4893                                retval, (intmax_t)lun->lun);
4894                 }
4895         }
4896
4897         mtx_unlock(&softc->ctl_lock);
4898         ctl_isc_announce_lun(lun);
4899
4900         return (0);
4901 }
4902
4903 int
4904 ctl_disable_lun(struct ctl_be_lun *be_lun)
4905 {
4906         struct ctl_softc *softc;
4907         struct ctl_port *port;
4908         struct ctl_lun *lun;
4909         int retval;
4910
4911         lun = (struct ctl_lun *)be_lun->ctl_lun;
4912         softc = lun->ctl_softc;
4913
4914         mtx_lock(&softc->ctl_lock);
4915         mtx_lock(&lun->lun_lock);
4916         if (lun->flags & CTL_LUN_DISABLED) {
4917                 mtx_unlock(&lun->lun_lock);
4918                 mtx_unlock(&softc->ctl_lock);
4919                 return (0);
4920         }
4921         lun->flags |= CTL_LUN_DISABLED;
4922         mtx_unlock(&lun->lun_lock);
4923
4924         STAILQ_FOREACH(port, &softc->port_list, links) {
4925                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4926                     port->lun_map != NULL || port->lun_disable == NULL)
4927                         continue;
4928
4929                 /*
4930                  * Drop the lock before we call the frontend's disable
4931                  * routine, to avoid lock order reversals.
4932                  *
4933                  * XXX KDM what happens if the frontend list changes while
4934                  * we're traversing it?  It's unlikely, but should be handled.
4935                  */
4936                 mtx_unlock(&softc->ctl_lock);
4937                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4938                 mtx_lock(&softc->ctl_lock);
4939                 if (retval != 0) {
4940                         printf("%s: FETD %s port %d returned error "
4941                                "%d for lun_disable on lun %jd\n",
4942                                __func__, port->port_name, port->targ_port,
4943                                retval, (intmax_t)lun->lun);
4944                 }
4945         }
4946
4947         mtx_unlock(&softc->ctl_lock);
4948         ctl_isc_announce_lun(lun);
4949
4950         return (0);
4951 }
4952
4953 int
4954 ctl_start_lun(struct ctl_be_lun *be_lun)
4955 {
4956         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4957
4958         mtx_lock(&lun->lun_lock);
4959         lun->flags &= ~CTL_LUN_STOPPED;
4960         mtx_unlock(&lun->lun_lock);
4961         return (0);
4962 }
4963
4964 int
4965 ctl_stop_lun(struct ctl_be_lun *be_lun)
4966 {
4967         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4968
4969         mtx_lock(&lun->lun_lock);
4970         lun->flags |= CTL_LUN_STOPPED;
4971         mtx_unlock(&lun->lun_lock);
4972         return (0);
4973 }
4974
4975 int
4976 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4977 {
4978         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4979
4980         mtx_lock(&lun->lun_lock);
4981         lun->flags |= CTL_LUN_NO_MEDIA;
4982         mtx_unlock(&lun->lun_lock);
4983         return (0);
4984 }
4985
4986 int
4987 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4988 {
4989         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4990         union ctl_ha_msg msg;
4991
4992         mtx_lock(&lun->lun_lock);
4993         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4994         if (lun->flags & CTL_LUN_REMOVABLE)
4995                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4996         mtx_unlock(&lun->lun_lock);
4997         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4998             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4999                 bzero(&msg.ua, sizeof(msg.ua));
5000                 msg.hdr.msg_type = CTL_MSG_UA;
5001                 msg.hdr.nexus.initid = -1;
5002                 msg.hdr.nexus.targ_port = -1;
5003                 msg.hdr.nexus.targ_lun = lun->lun;
5004                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
5005                 msg.ua.ua_all = 1;
5006                 msg.ua.ua_set = 1;
5007                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
5008                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5009                     M_WAITOK);
5010         }
5011         return (0);
5012 }
5013
5014 int
5015 ctl_lun_ejected(struct ctl_be_lun *be_lun)
5016 {
5017         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5018
5019         mtx_lock(&lun->lun_lock);
5020         lun->flags |= CTL_LUN_EJECTED;
5021         mtx_unlock(&lun->lun_lock);
5022         return (0);
5023 }
5024
5025 int
5026 ctl_lun_primary(struct ctl_be_lun *be_lun)
5027 {
5028         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5029
5030         mtx_lock(&lun->lun_lock);
5031         lun->flags |= CTL_LUN_PRIMARY_SC;
5032         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5033         mtx_unlock(&lun->lun_lock);
5034         ctl_isc_announce_lun(lun);
5035         return (0);
5036 }
5037
5038 int
5039 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5040 {
5041         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5042
5043         mtx_lock(&lun->lun_lock);
5044         lun->flags &= ~CTL_LUN_PRIMARY_SC;
5045         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5046         mtx_unlock(&lun->lun_lock);
5047         ctl_isc_announce_lun(lun);
5048         return (0);
5049 }
5050
5051 int
5052 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5053 {
5054         struct ctl_lun *lun;
5055
5056         lun = (struct ctl_lun *)be_lun->ctl_lun;
5057
5058         mtx_lock(&lun->lun_lock);
5059
5060         /*
5061          * The LUN needs to be disabled before it can be marked invalid.
5062          */
5063         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5064                 mtx_unlock(&lun->lun_lock);
5065                 return (-1);
5066         }
5067         /*
5068          * Mark the LUN invalid.
5069          */
5070         lun->flags |= CTL_LUN_INVALID;
5071
5072         /*
5073          * If there is nothing in the OOA queue, go ahead and free the LUN.
5074          * If we have something in the OOA queue, we'll free it when the
5075          * last I/O completes.
5076          */
5077         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5078                 mtx_unlock(&lun->lun_lock);
5079                 ctl_free_lun(lun);
5080         } else
5081                 mtx_unlock(&lun->lun_lock);
5082
5083         return (0);
5084 }
5085
5086 void
5087 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5088 {
5089         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5090         union ctl_ha_msg msg;
5091
5092         mtx_lock(&lun->lun_lock);
5093         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5094         mtx_unlock(&lun->lun_lock);
5095         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5096                 /* Send msg to other side. */
5097                 bzero(&msg.ua, sizeof(msg.ua));
5098                 msg.hdr.msg_type = CTL_MSG_UA;
5099                 msg.hdr.nexus.initid = -1;
5100                 msg.hdr.nexus.targ_port = -1;
5101                 msg.hdr.nexus.targ_lun = lun->lun;
5102                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
5103                 msg.ua.ua_all = 1;
5104                 msg.ua.ua_set = 1;
5105                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5106                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5107                     M_WAITOK);
5108         }
5109 }
5110
5111 /*
5112  * Backend "memory move is complete" callback for requests that never
5113  * make it down to say RAIDCore's configuration code.
5114  */
5115 int
5116 ctl_config_move_done(union ctl_io *io)
5117 {
5118         int retval;
5119
5120         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5121         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5122             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5123
5124         if ((io->io_hdr.port_status != 0) &&
5125             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5126              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5127                 ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5128                     /*retry_count*/ io->io_hdr.port_status);
5129         } else if (io->scsiio.kern_data_resid != 0 &&
5130             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5131             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5132              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5133                 ctl_set_invalid_field_ciu(&io->scsiio);
5134         }
5135
5136         if (ctl_debug & CTL_DEBUG_CDB_DATA)
5137                 ctl_data_print(io);
5138         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5139             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5140              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5141             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5142                 /*
5143                  * XXX KDM just assuming a single pointer here, and not a
5144                  * S/G list.  If we start using S/G lists for config data,
5145                  * we'll need to know how to clean them up here as well.
5146                  */
5147                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5148                         free(io->scsiio.kern_data_ptr, M_CTL);
5149                 ctl_done(io);
5150                 retval = CTL_RETVAL_COMPLETE;
5151         } else {
5152                 /*
5153                  * XXX KDM now we need to continue data movement.  Some
5154                  * options:
5155                  * - call ctl_scsiio() again?  We don't do this for data
5156                  *   writes, because for those at least we know ahead of
5157                  *   time where the write will go and how long it is.  For
5158                  *   config writes, though, that information is largely
5159                  *   contained within the write itself, thus we need to
5160                  *   parse out the data again.
5161                  *
5162                  * - Call some other function once the data is in?
5163                  */
5164
5165                 /*
5166                  * XXX KDM call ctl_scsiio() again for now, and check flag
5167                  * bits to see whether we're allocated or not.
5168                  */
5169                 retval = ctl_scsiio(&io->scsiio);
5170         }
5171         return (retval);
5172 }
5173
5174 /*
5175  * This gets called by a backend driver when it is done with a
5176  * data_submit method.
5177  */
5178 void
5179 ctl_data_submit_done(union ctl_io *io)
5180 {
5181         /*
5182          * If the IO_CONT flag is set, we need to call the supplied
5183          * function to continue processing the I/O, instead of completing
5184          * the I/O just yet.
5185          *
5186          * If there is an error, though, we don't want to keep processing.
5187          * Instead, just send status back to the initiator.
5188          */
5189         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5190             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5191             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5192              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5193                 io->scsiio.io_cont(io);
5194                 return;
5195         }
5196         ctl_done(io);
5197 }
5198
5199 /*
5200  * This gets called by a backend driver when it is done with a
5201  * configuration write.
5202  */
5203 void
5204 ctl_config_write_done(union ctl_io *io)
5205 {
5206         uint8_t *buf;
5207
5208         /*
5209          * If the IO_CONT flag is set, we need to call the supplied
5210          * function to continue processing the I/O, instead of completing
5211          * the I/O just yet.
5212          *
5213          * If there is an error, though, we don't want to keep processing.
5214          * Instead, just send status back to the initiator.
5215          */
5216         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5217             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5218             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5219              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5220                 io->scsiio.io_cont(io);
5221                 return;
5222         }
5223         /*
5224          * Since a configuration write can be done for commands that actually
5225          * have data allocated, like write buffer, and commands that have
5226          * no data, like start/stop unit, we need to check here.
5227          */
5228         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5229                 buf = io->scsiio.kern_data_ptr;
5230         else
5231                 buf = NULL;
5232         ctl_done(io);
5233         if (buf)
5234                 free(buf, M_CTL);
5235 }
5236
5237 void
5238 ctl_config_read_done(union ctl_io *io)
5239 {
5240         uint8_t *buf;
5241
5242         /*
5243          * If there is some error -- we are done, skip data transfer.
5244          */
5245         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5246             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5247              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5248                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5249                         buf = io->scsiio.kern_data_ptr;
5250                 else
5251                         buf = NULL;
5252                 ctl_done(io);
5253                 if (buf)
5254                         free(buf, M_CTL);
5255                 return;
5256         }
5257
5258         /*
5259          * If the IO_CONT flag is set, we need to call the supplied
5260          * function to continue processing the I/O, instead of completing
5261          * the I/O just yet.
5262          */
5263         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5264                 io->scsiio.io_cont(io);
5265                 return;
5266         }
5267
5268         ctl_datamove(io);
5269 }
5270
5271 /*
5272  * SCSI release command.
5273  */
5274 int
5275 ctl_scsi_release(struct ctl_scsiio *ctsio)
5276 {
5277         struct ctl_lun *lun = CTL_LUN(ctsio);
5278         uint32_t residx;
5279
5280         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5281
5282         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5283
5284         /*
5285          * XXX KDM right now, we only support LUN reservation.  We don't
5286          * support 3rd party reservations, or extent reservations, which
5287          * might actually need the parameter list.  If we've gotten this
5288          * far, we've got a LUN reservation.  Anything else got kicked out
5289          * above.  So, according to SPC, ignore the length.
5290          */
5291
5292         mtx_lock(&lun->lun_lock);
5293
5294         /*
5295          * According to SPC, it is not an error for an intiator to attempt
5296          * to release a reservation on a LUN that isn't reserved, or that
5297          * is reserved by another initiator.  The reservation can only be
5298          * released, though, by the initiator who made it or by one of
5299          * several reset type events.
5300          */
5301         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5302                         lun->flags &= ~CTL_LUN_RESERVED;
5303
5304         mtx_unlock(&lun->lun_lock);
5305
5306         ctl_set_success(ctsio);
5307         ctl_done((union ctl_io *)ctsio);
5308         return (CTL_RETVAL_COMPLETE);
5309 }
5310
5311 int
5312 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5313 {
5314         struct ctl_lun *lun = CTL_LUN(ctsio);
5315         uint32_t residx;
5316
5317         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5318
5319         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5320
5321         /*
5322          * XXX KDM right now, we only support LUN reservation.  We don't
5323          * support 3rd party reservations, or extent reservations, which
5324          * might actually need the parameter list.  If we've gotten this
5325          * far, we've got a LUN reservation.  Anything else got kicked out
5326          * above.  So, according to SPC, ignore the length.
5327          */
5328
5329         mtx_lock(&lun->lun_lock);
5330         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5331                 ctl_set_reservation_conflict(ctsio);
5332                 goto bailout;
5333         }
5334
5335         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5336         if (lun->flags & CTL_LUN_PR_RESERVED) {
5337                 ctl_set_success(ctsio);
5338                 goto bailout;
5339         }
5340
5341         lun->flags |= CTL_LUN_RESERVED;
5342         lun->res_idx = residx;
5343         ctl_set_success(ctsio);
5344
5345 bailout:
5346         mtx_unlock(&lun->lun_lock);
5347         ctl_done((union ctl_io *)ctsio);
5348         return (CTL_RETVAL_COMPLETE);
5349 }
5350
5351 int
5352 ctl_start_stop(struct ctl_scsiio *ctsio)
5353 {
5354         struct ctl_lun *lun = CTL_LUN(ctsio);
5355         struct scsi_start_stop_unit *cdb;
5356         int retval;
5357
5358         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5359
5360         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5361
5362         if ((cdb->how & SSS_PC_MASK) == 0) {
5363                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5364                     (cdb->how & SSS_START) == 0) {
5365                         uint32_t residx;
5366
5367                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5368                         if (ctl_get_prkey(lun, residx) == 0 ||
5369                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5370
5371                                 ctl_set_reservation_conflict(ctsio);
5372                                 ctl_done((union ctl_io *)ctsio);
5373                                 return (CTL_RETVAL_COMPLETE);
5374                         }
5375                 }
5376
5377                 if ((cdb->how & SSS_LOEJ) &&
5378                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5379                         ctl_set_invalid_field(ctsio,
5380                                               /*sks_valid*/ 1,
5381                                               /*command*/ 1,
5382                                               /*field*/ 4,
5383                                               /*bit_valid*/ 1,
5384                                               /*bit*/ 1);
5385                         ctl_done((union ctl_io *)ctsio);
5386                         return (CTL_RETVAL_COMPLETE);
5387                 }
5388
5389                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5390                     lun->prevent_count > 0) {
5391                         /* "Medium removal prevented" */
5392                         ctl_set_sense(ctsio, /*current_error*/ 1,
5393                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5394                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5395                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5396                         ctl_done((union ctl_io *)ctsio);
5397                         return (CTL_RETVAL_COMPLETE);
5398                 }
5399         }
5400
5401         retval = lun->backend->config_write((union ctl_io *)ctsio);
5402         return (retval);
5403 }
5404
5405 int
5406 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5407 {
5408         struct ctl_lun *lun = CTL_LUN(ctsio);
5409         struct scsi_prevent *cdb;
5410         int retval;
5411         uint32_t initidx;
5412
5413         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5414
5415         cdb = (struct scsi_prevent *)ctsio->cdb;
5416
5417         if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5418                 ctl_set_invalid_opcode(ctsio);
5419                 ctl_done((union ctl_io *)ctsio);
5420                 return (CTL_RETVAL_COMPLETE);
5421         }
5422
5423         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5424         mtx_lock(&lun->lun_lock);
5425         if ((cdb->how & PR_PREVENT) &&
5426             ctl_is_set(lun->prevent, initidx) == 0) {
5427                 ctl_set_mask(lun->prevent, initidx);
5428                 lun->prevent_count++;
5429         } else if ((cdb->how & PR_PREVENT) == 0 &&
5430             ctl_is_set(lun->prevent, initidx)) {
5431                 ctl_clear_mask(lun->prevent, initidx);
5432                 lun->prevent_count--;
5433         }
5434         mtx_unlock(&lun->lun_lock);
5435         retval = lun->backend->config_write((union ctl_io *)ctsio);
5436         return (retval);
5437 }
5438
5439 /*
5440  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5441  * we don't really do anything with the LBA and length fields if the user
5442  * passes them in.  Instead we'll just flush out the cache for the entire
5443  * LUN.
5444  */
5445 int
5446 ctl_sync_cache(struct ctl_scsiio *ctsio)
5447 {
5448         struct ctl_lun *lun = CTL_LUN(ctsio);
5449         struct ctl_lba_len_flags *lbalen;
5450         uint64_t starting_lba;
5451         uint32_t block_count;
5452         int retval;
5453         uint8_t byte2;
5454
5455         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5456
5457         retval = 0;
5458
5459         switch (ctsio->cdb[0]) {
5460         case SYNCHRONIZE_CACHE: {
5461                 struct scsi_sync_cache *cdb;
5462                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5463
5464                 starting_lba = scsi_4btoul(cdb->begin_lba);
5465                 block_count = scsi_2btoul(cdb->lb_count);
5466                 byte2 = cdb->byte2;
5467                 break;
5468         }
5469         case SYNCHRONIZE_CACHE_16: {
5470                 struct scsi_sync_cache_16 *cdb;
5471                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5472
5473                 starting_lba = scsi_8btou64(cdb->begin_lba);
5474                 block_count = scsi_4btoul(cdb->lb_count);
5475                 byte2 = cdb->byte2;
5476                 break;
5477         }
5478         default:
5479                 ctl_set_invalid_opcode(ctsio);
5480                 ctl_done((union ctl_io *)ctsio);
5481                 goto bailout;
5482                 break; /* NOTREACHED */
5483         }
5484
5485         /*
5486          * We check the LBA and length, but don't do anything with them.
5487          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5488          * get flushed.  This check will just help satisfy anyone who wants
5489          * to see an error for an out of range LBA.
5490          */
5491         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5492                 ctl_set_lba_out_of_range(ctsio,
5493                     MAX(starting_lba, lun->be_lun->maxlba + 1));
5494                 ctl_done((union ctl_io *)ctsio);
5495                 goto bailout;
5496         }
5497
5498         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5499         lbalen->lba = starting_lba;
5500         lbalen->len = block_count;
5501         lbalen->flags = byte2;
5502         retval = lun->backend->config_write((union ctl_io *)ctsio);
5503
5504 bailout:
5505         return (retval);
5506 }
5507
5508 int
5509 ctl_format(struct ctl_scsiio *ctsio)
5510 {
5511         struct scsi_format *cdb;
5512         int length, defect_list_len;
5513
5514         CTL_DEBUG_PRINT(("ctl_format\n"));
5515
5516         cdb = (struct scsi_format *)ctsio->cdb;
5517
5518         length = 0;
5519         if (cdb->byte2 & SF_FMTDATA) {
5520                 if (cdb->byte2 & SF_LONGLIST)
5521                         length = sizeof(struct scsi_format_header_long);
5522                 else
5523                         length = sizeof(struct scsi_format_header_short);
5524         }
5525
5526         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5527          && (length > 0)) {
5528                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5529                 ctsio->kern_data_len = length;
5530                 ctsio->kern_total_len = length;
5531                 ctsio->kern_rel_offset = 0;
5532                 ctsio->kern_sg_entries = 0;
5533                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5534                 ctsio->be_move_done = ctl_config_move_done;
5535                 ctl_datamove((union ctl_io *)ctsio);
5536
5537                 return (CTL_RETVAL_COMPLETE);
5538         }
5539
5540         defect_list_len = 0;
5541
5542         if (cdb->byte2 & SF_FMTDATA) {
5543                 if (cdb->byte2 & SF_LONGLIST) {
5544                         struct scsi_format_header_long *header;
5545
5546                         header = (struct scsi_format_header_long *)
5547                                 ctsio->kern_data_ptr;
5548
5549                         defect_list_len = scsi_4btoul(header->defect_list_len);
5550                         if (defect_list_len != 0) {
5551                                 ctl_set_invalid_field(ctsio,
5552                                                       /*sks_valid*/ 1,
5553                                                       /*command*/ 0,
5554                                                       /*field*/ 2,
5555                                                       /*bit_valid*/ 0,
5556                                                       /*bit*/ 0);
5557                                 goto bailout;
5558                         }
5559                 } else {
5560                         struct scsi_format_header_short *header;
5561
5562                         header = (struct scsi_format_header_short *)
5563                                 ctsio->kern_data_ptr;
5564
5565                         defect_list_len = scsi_2btoul(header->defect_list_len);
5566                         if (defect_list_len != 0) {
5567                                 ctl_set_invalid_field(ctsio,
5568                                                       /*sks_valid*/ 1,
5569                                                       /*command*/ 0,
5570                                                       /*field*/ 2,
5571                                                       /*bit_valid*/ 0,
5572                                                       /*bit*/ 0);
5573                                 goto bailout;
5574                         }
5575                 }
5576         }
5577
5578         ctl_set_success(ctsio);
5579 bailout:
5580
5581         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5582                 free(ctsio->kern_data_ptr, M_CTL);
5583                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5584         }
5585
5586         ctl_done((union ctl_io *)ctsio);
5587         return (CTL_RETVAL_COMPLETE);
5588 }
5589
5590 int
5591 ctl_read_buffer(struct ctl_scsiio *ctsio)
5592 {
5593         struct ctl_lun *lun = CTL_LUN(ctsio);
5594         uint64_t buffer_offset;
5595         uint32_t len;
5596         uint8_t byte2;
5597         static uint8_t descr[4];
5598         static uint8_t echo_descr[4] = { 0 };
5599
5600         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5601
5602         switch (ctsio->cdb[0]) {
5603         case READ_BUFFER: {
5604                 struct scsi_read_buffer *cdb;
5605
5606                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5607                 buffer_offset = scsi_3btoul(cdb->offset);
5608                 len = scsi_3btoul(cdb->length);
5609                 byte2 = cdb->byte2;
5610                 break;
5611         }
5612         case READ_BUFFER_16: {
5613                 struct scsi_read_buffer_16 *cdb;
5614
5615                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5616                 buffer_offset = scsi_8btou64(cdb->offset);
5617                 len = scsi_4btoul(cdb->length);
5618                 byte2 = cdb->byte2;
5619                 break;
5620         }
5621         default: /* This shouldn't happen. */
5622                 ctl_set_invalid_opcode(ctsio);
5623                 ctl_done((union ctl_io *)ctsio);
5624                 return (CTL_RETVAL_COMPLETE);
5625         }
5626
5627         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5628             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5629                 ctl_set_invalid_field(ctsio,
5630                                       /*sks_valid*/ 1,
5631                                       /*command*/ 1,
5632                                       /*field*/ 6,
5633                                       /*bit_valid*/ 0,
5634                                       /*bit*/ 0);
5635                 ctl_done((union ctl_io *)ctsio);
5636                 return (CTL_RETVAL_COMPLETE);
5637         }
5638
5639         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5640                 descr[0] = 0;
5641                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5642                 ctsio->kern_data_ptr = descr;
5643                 len = min(len, sizeof(descr));
5644         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5645                 ctsio->kern_data_ptr = echo_descr;
5646                 len = min(len, sizeof(echo_descr));
5647         } else {
5648                 if (lun->write_buffer == NULL) {
5649                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5650                             M_CTL, M_WAITOK);
5651                 }
5652                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5653         }
5654         ctsio->kern_data_len = len;
5655         ctsio->kern_total_len = len;
5656         ctsio->kern_rel_offset = 0;
5657         ctsio->kern_sg_entries = 0;
5658         ctl_set_success(ctsio);
5659         ctsio->be_move_done = ctl_config_move_done;
5660         ctl_datamove((union ctl_io *)ctsio);
5661         return (CTL_RETVAL_COMPLETE);
5662 }
5663
5664 int
5665 ctl_write_buffer(struct ctl_scsiio *ctsio)
5666 {
5667         struct ctl_lun *lun = CTL_LUN(ctsio);
5668         struct scsi_write_buffer *cdb;
5669         int buffer_offset, len;
5670
5671         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5672
5673         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5674
5675         len = scsi_3btoul(cdb->length);
5676         buffer_offset = scsi_3btoul(cdb->offset);
5677
5678         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5679                 ctl_set_invalid_field(ctsio,
5680                                       /*sks_valid*/ 1,
5681                                       /*command*/ 1,
5682                                       /*field*/ 6,
5683                                       /*bit_valid*/ 0,
5684                                       /*bit*/ 0);
5685                 ctl_done((union ctl_io *)ctsio);
5686                 return (CTL_RETVAL_COMPLETE);
5687         }
5688
5689         /*
5690          * If we've got a kernel request that hasn't been malloced yet,
5691          * malloc it and tell the caller the data buffer is here.
5692          */
5693         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5694                 if (lun->write_buffer == NULL) {
5695                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5696                             M_CTL, M_WAITOK);
5697                 }
5698                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5699                 ctsio->kern_data_len = len;
5700                 ctsio->kern_total_len = len;
5701                 ctsio->kern_rel_offset = 0;
5702                 ctsio->kern_sg_entries = 0;
5703                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5704                 ctsio->be_move_done = ctl_config_move_done;
5705                 ctl_datamove((union ctl_io *)ctsio);
5706
5707                 return (CTL_RETVAL_COMPLETE);
5708         }
5709
5710         ctl_set_success(ctsio);
5711         ctl_done((union ctl_io *)ctsio);
5712         return (CTL_RETVAL_COMPLETE);
5713 }
5714
5715 int
5716 ctl_write_same(struct ctl_scsiio *ctsio)
5717 {
5718         struct ctl_lun *lun = CTL_LUN(ctsio);
5719         struct ctl_lba_len_flags *lbalen;
5720         uint64_t lba;
5721         uint32_t num_blocks;
5722         int len, retval;
5723         uint8_t byte2;
5724
5725         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5726
5727         switch (ctsio->cdb[0]) {
5728         case WRITE_SAME_10: {
5729                 struct scsi_write_same_10 *cdb;
5730
5731                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5732
5733                 lba = scsi_4btoul(cdb->addr);
5734                 num_blocks = scsi_2btoul(cdb->length);
5735                 byte2 = cdb->byte2;
5736                 break;
5737         }
5738         case WRITE_SAME_16: {
5739                 struct scsi_write_same_16 *cdb;
5740
5741                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5742
5743                 lba = scsi_8btou64(cdb->addr);
5744                 num_blocks = scsi_4btoul(cdb->length);
5745                 byte2 = cdb->byte2;
5746                 break;
5747         }
5748         default:
5749                 /*
5750                  * We got a command we don't support.  This shouldn't
5751                  * happen, commands should be filtered out above us.
5752                  */
5753                 ctl_set_invalid_opcode(ctsio);
5754                 ctl_done((union ctl_io *)ctsio);
5755
5756                 return (CTL_RETVAL_COMPLETE);
5757                 break; /* NOTREACHED */
5758         }
5759
5760         /* ANCHOR flag can be used only together with UNMAP */
5761         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5762                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5763                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5764                 ctl_done((union ctl_io *)ctsio);
5765                 return (CTL_RETVAL_COMPLETE);
5766         }
5767
5768         /*
5769          * The first check is to make sure we're in bounds, the second
5770          * check is to catch wrap-around problems.  If the lba + num blocks
5771          * is less than the lba, then we've wrapped around and the block
5772          * range is invalid anyway.
5773          */
5774         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5775          || ((lba + num_blocks) < lba)) {
5776                 ctl_set_lba_out_of_range(ctsio,
5777                     MAX(lba, lun->be_lun->maxlba + 1));
5778                 ctl_done((union ctl_io *)ctsio);
5779                 return (CTL_RETVAL_COMPLETE);
5780         }
5781
5782         /* Zero number of blocks means "to the last logical block" */
5783         if (num_blocks == 0) {
5784                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5785                         ctl_set_invalid_field(ctsio,
5786                                               /*sks_valid*/ 0,
5787                                               /*command*/ 1,
5788                                               /*field*/ 0,
5789                                               /*bit_valid*/ 0,
5790                                               /*bit*/ 0);
5791                         ctl_done((union ctl_io *)ctsio);
5792                         return (CTL_RETVAL_COMPLETE);
5793                 }
5794                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5795         }
5796
5797         len = lun->be_lun->blocksize;
5798
5799         /*
5800          * If we've got a kernel request that hasn't been malloced yet,
5801          * malloc it and tell the caller the data buffer is here.
5802          */
5803         if ((byte2 & SWS_NDOB) == 0 &&
5804             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5805                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5806                 ctsio->kern_data_len = len;
5807                 ctsio->kern_total_len = len;
5808                 ctsio->kern_rel_offset = 0;
5809                 ctsio->kern_sg_entries = 0;
5810                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5811                 ctsio->be_move_done = ctl_config_move_done;
5812                 ctl_datamove((union ctl_io *)ctsio);
5813
5814                 return (CTL_RETVAL_COMPLETE);
5815         }
5816
5817         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5818         lbalen->lba = lba;
5819         lbalen->len = num_blocks;
5820         lbalen->flags = byte2;
5821         retval = lun->backend->config_write((union ctl_io *)ctsio);
5822
5823         return (retval);
5824 }
5825
5826 int
5827 ctl_unmap(struct ctl_scsiio *ctsio)
5828 {
5829         struct ctl_lun *lun = CTL_LUN(ctsio);
5830         struct scsi_unmap *cdb;
5831         struct ctl_ptr_len_flags *ptrlen;
5832         struct scsi_unmap_header *hdr;
5833         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5834         uint64_t lba;
5835         uint32_t num_blocks;
5836         int len, retval;
5837         uint8_t byte2;
5838
5839         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5840
5841         cdb = (struct scsi_unmap *)ctsio->cdb;
5842         len = scsi_2btoul(cdb->length);
5843         byte2 = cdb->byte2;
5844
5845         /*
5846          * If we've got a kernel request that hasn't been malloced yet,
5847          * malloc it and tell the caller the data buffer is here.
5848          */
5849         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5850                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5851                 ctsio->kern_data_len = len;
5852                 ctsio->kern_total_len = len;
5853                 ctsio->kern_rel_offset = 0;
5854                 ctsio->kern_sg_entries = 0;
5855                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5856                 ctsio->be_move_done = ctl_config_move_done;
5857                 ctl_datamove((union ctl_io *)ctsio);
5858
5859                 return (CTL_RETVAL_COMPLETE);
5860         }
5861
5862         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5863         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5864         if (len < sizeof (*hdr) ||
5865             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5866             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5867             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5868                 ctl_set_invalid_field(ctsio,
5869                                       /*sks_valid*/ 0,
5870                                       /*command*/ 0,
5871                                       /*field*/ 0,
5872                                       /*bit_valid*/ 0,
5873                                       /*bit*/ 0);
5874                 goto done;
5875         }
5876         len = scsi_2btoul(hdr->desc_length);
5877         buf = (struct scsi_unmap_desc *)(hdr + 1);
5878         end = buf + len / sizeof(*buf);
5879
5880         endnz = buf;
5881         for (range = buf; range < end; range++) {
5882                 lba = scsi_8btou64(range->lba);
5883                 num_blocks = scsi_4btoul(range->length);
5884                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5885                  || ((lba + num_blocks) < lba)) {
5886                         ctl_set_lba_out_of_range(ctsio,
5887                             MAX(lba, lun->be_lun->maxlba + 1));
5888                         ctl_done((union ctl_io *)ctsio);
5889                         return (CTL_RETVAL_COMPLETE);
5890                 }
5891                 if (num_blocks != 0)
5892                         endnz = range + 1;
5893         }
5894
5895         /*
5896          * Block backend can not handle zero last range.
5897          * Filter it out and return if there is nothing left.
5898          */
5899         len = (uint8_t *)endnz - (uint8_t *)buf;
5900         if (len == 0) {
5901                 ctl_set_success(ctsio);
5902                 goto done;
5903         }
5904
5905         mtx_lock(&lun->lun_lock);
5906         ptrlen = (struct ctl_ptr_len_flags *)
5907             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5908         ptrlen->ptr = (void *)buf;
5909         ptrlen->len = len;
5910         ptrlen->flags = byte2;
5911         ctl_check_blocked(lun);
5912         mtx_unlock(&lun->lun_lock);
5913
5914         retval = lun->backend->config_write((union ctl_io *)ctsio);
5915         return (retval);
5916
5917 done:
5918         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5919                 free(ctsio->kern_data_ptr, M_CTL);
5920                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5921         }
5922         ctl_done((union ctl_io *)ctsio);
5923         return (CTL_RETVAL_COMPLETE);
5924 }
5925
5926 int
5927 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5928                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5929 {
5930         struct ctl_lun *lun = CTL_LUN(ctsio);
5931         uint8_t *current_cp;
5932         int set_ua;
5933         uint32_t initidx;
5934
5935         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5936         set_ua = 0;
5937
5938         current_cp = (page_index->page_data + (page_index->page_len *
5939             CTL_PAGE_CURRENT));
5940
5941         mtx_lock(&lun->lun_lock);
5942         if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5943                 memcpy(current_cp, page_ptr, page_index->page_len);
5944                 set_ua = 1;
5945         }
5946         if (set_ua != 0)
5947                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5948         mtx_unlock(&lun->lun_lock);
5949         if (set_ua) {
5950                 ctl_isc_announce_mode(lun,
5951                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5952                     page_index->page_code, page_index->subpage);
5953         }
5954         return (CTL_RETVAL_COMPLETE);
5955 }
5956
5957 static void
5958 ctl_ie_timer(void *arg)
5959 {
5960         struct ctl_lun *lun = arg;
5961         uint64_t t;
5962
5963         if (lun->ie_asc == 0)
5964                 return;
5965
5966         if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5967                 ctl_est_ua_all(lun, -1, CTL_UA_IE);
5968         else
5969                 lun->ie_reported = 0;
5970
5971         if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5972                 lun->ie_reportcnt++;
5973                 t = scsi_4btoul(lun->MODE_IE.interval_timer);
5974                 if (t == 0 || t == UINT32_MAX)
5975                         t = 3000;  /* 5 min */
5976                 callout_schedule(&lun->ie_callout, t * hz / 10);
5977         }
5978 }
5979
5980 int
5981 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5982                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5983 {
5984         struct ctl_lun *lun = CTL_LUN(ctsio);
5985         struct scsi_info_exceptions_page *pg;
5986         uint64_t t;
5987
5988         (void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5989
5990         pg = (struct scsi_info_exceptions_page *)page_ptr;
5991         mtx_lock(&lun->lun_lock);
5992         if (pg->info_flags & SIEP_FLAGS_TEST) {
5993                 lun->ie_asc = 0x5d;
5994                 lun->ie_ascq = 0xff;
5995                 if (pg->mrie == SIEP_MRIE_UA) {
5996                         ctl_est_ua_all(lun, -1, CTL_UA_IE);
5997                         lun->ie_reported = 1;
5998                 } else {
5999                         ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6000                         lun->ie_reported = -1;
6001                 }
6002                 lun->ie_reportcnt = 1;
6003                 if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
6004                         lun->ie_reportcnt++;
6005                         t = scsi_4btoul(pg->interval_timer);
6006                         if (t == 0 || t == UINT32_MAX)
6007                                 t = 3000;  /* 5 min */
6008                         callout_reset(&lun->ie_callout, t * hz / 10,
6009                             ctl_ie_timer, lun);
6010                 }
6011         } else {
6012                 lun->ie_asc = 0;
6013                 lun->ie_ascq = 0;
6014                 lun->ie_reported = 1;
6015                 ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6016                 lun->ie_reportcnt = UINT32_MAX;
6017                 callout_stop(&lun->ie_callout);
6018         }
6019         mtx_unlock(&lun->lun_lock);
6020         return (CTL_RETVAL_COMPLETE);
6021 }
6022
6023 static int
6024 ctl_do_mode_select(union ctl_io *io)
6025 {
6026         struct ctl_lun *lun = CTL_LUN(io);
6027         struct scsi_mode_page_header *page_header;
6028         struct ctl_page_index *page_index;
6029         struct ctl_scsiio *ctsio;
6030         int page_len, page_len_offset, page_len_size;
6031         union ctl_modepage_info *modepage_info;
6032         uint16_t *len_left, *len_used;
6033         int retval, i;
6034
6035         ctsio = &io->scsiio;
6036         page_index = NULL;
6037         page_len = 0;
6038
6039         modepage_info = (union ctl_modepage_info *)
6040                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6041         len_left = &modepage_info->header.len_left;
6042         len_used = &modepage_info->header.len_used;
6043
6044 do_next_page:
6045
6046         page_header = (struct scsi_mode_page_header *)
6047                 (ctsio->kern_data_ptr + *len_used);
6048
6049         if (*len_left == 0) {
6050                 free(ctsio->kern_data_ptr, M_CTL);
6051                 ctl_set_success(ctsio);
6052                 ctl_done((union ctl_io *)ctsio);
6053                 return (CTL_RETVAL_COMPLETE);
6054         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6055
6056                 free(ctsio->kern_data_ptr, M_CTL);
6057                 ctl_set_param_len_error(ctsio);
6058                 ctl_done((union ctl_io *)ctsio);
6059                 return (CTL_RETVAL_COMPLETE);
6060
6061         } else if ((page_header->page_code & SMPH_SPF)
6062                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6063
6064                 free(ctsio->kern_data_ptr, M_CTL);
6065                 ctl_set_param_len_error(ctsio);
6066                 ctl_done((union ctl_io *)ctsio);
6067                 return (CTL_RETVAL_COMPLETE);
6068         }
6069
6070
6071         /*
6072          * XXX KDM should we do something with the block descriptor?
6073          */
6074         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6075                 page_index = &lun->mode_pages.index[i];
6076                 if (lun->be_lun->lun_type == T_DIRECT &&
6077                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6078                         continue;
6079                 if (lun->be_lun->lun_type == T_PROCESSOR &&
6080                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6081                         continue;
6082                 if (lun->be_lun->lun_type == T_CDROM &&
6083                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6084                         continue;
6085
6086                 if ((page_index->page_code & SMPH_PC_MASK) !=
6087                     (page_header->page_code & SMPH_PC_MASK))
6088                         continue;
6089
6090                 /*
6091                  * If neither page has a subpage code, then we've got a
6092                  * match.
6093                  */
6094                 if (((page_index->page_code & SMPH_SPF) == 0)
6095                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6096                         page_len = page_header->page_length;
6097                         break;
6098                 }
6099
6100                 /*
6101                  * If both pages have subpages, then the subpage numbers
6102                  * have to match.
6103                  */
6104                 if ((page_index->page_code & SMPH_SPF)
6105                   && (page_header->page_code & SMPH_SPF)) {
6106                         struct scsi_mode_page_header_sp *sph;
6107
6108                         sph = (struct scsi_mode_page_header_sp *)page_header;
6109                         if (page_index->subpage == sph->subpage) {
6110                                 page_len = scsi_2btoul(sph->page_length);
6111                                 break;
6112                         }
6113                 }
6114         }
6115
6116         /*
6117          * If we couldn't find the page, or if we don't have a mode select
6118          * handler for it, send back an error to the user.
6119          */
6120         if ((i >= CTL_NUM_MODE_PAGES)
6121          || (page_index->select_handler == NULL)) {
6122                 ctl_set_invalid_field(ctsio,
6123                                       /*sks_valid*/ 1,
6124                                       /*command*/ 0,
6125                                       /*field*/ *len_used,
6126                                       /*bit_valid*/ 0,
6127                                       /*bit*/ 0);
6128                 free(ctsio->kern_data_ptr, M_CTL);
6129                 ctl_done((union ctl_io *)ctsio);
6130                 return (CTL_RETVAL_COMPLETE);
6131         }
6132
6133         if (page_index->page_code & SMPH_SPF) {
6134                 page_len_offset = 2;
6135                 page_len_size = 2;
6136         } else {
6137                 page_len_size = 1;
6138                 page_len_offset = 1;
6139         }
6140
6141         /*
6142          * If the length the initiator gives us isn't the one we specify in
6143          * the mode page header, or if they didn't specify enough data in
6144          * the CDB to avoid truncating this page, kick out the request.
6145          */
6146         if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6147                 ctl_set_invalid_field(ctsio,
6148                                       /*sks_valid*/ 1,
6149                                       /*command*/ 0,
6150                                       /*field*/ *len_used + page_len_offset,
6151                                       /*bit_valid*/ 0,
6152                                       /*bit*/ 0);
6153                 free(ctsio->kern_data_ptr, M_CTL);
6154                 ctl_done((union ctl_io *)ctsio);
6155                 return (CTL_RETVAL_COMPLETE);
6156         }
6157         if (*len_left < page_index->page_len) {
6158                 free(ctsio->kern_data_ptr, M_CTL);
6159                 ctl_set_param_len_error(ctsio);
6160                 ctl_done((union ctl_io *)ctsio);
6161                 return (CTL_RETVAL_COMPLETE);
6162         }
6163
6164         /*
6165          * Run through the mode page, checking to make sure that the bits
6166          * the user changed are actually legal for him to change.
6167          */
6168         for (i = 0; i < page_index->page_len; i++) {
6169                 uint8_t *user_byte, *change_mask, *current_byte;
6170                 int bad_bit;
6171                 int j;
6172
6173                 user_byte = (uint8_t *)page_header + i;
6174                 change_mask = page_index->page_data +
6175                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6176                 current_byte = page_index->page_data +
6177                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6178
6179                 /*
6180                  * Check to see whether the user set any bits in this byte
6181                  * that he is not allowed to set.
6182                  */
6183                 if ((*user_byte & ~(*change_mask)) ==
6184                     (*current_byte & ~(*change_mask)))
6185                         continue;
6186
6187                 /*
6188                  * Go through bit by bit to determine which one is illegal.
6189                  */
6190                 bad_bit = 0;
6191                 for (j = 7; j >= 0; j--) {
6192                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6193                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6194                                 bad_bit = i;
6195                                 break;
6196                         }
6197                 }
6198                 ctl_set_invalid_field(ctsio,
6199                                       /*sks_valid*/ 1,
6200                                       /*command*/ 0,
6201                                       /*field*/ *len_used + i,
6202                                       /*bit_valid*/ 1,
6203                                       /*bit*/ bad_bit);
6204                 free(ctsio->kern_data_ptr, M_CTL);
6205                 ctl_done((union ctl_io *)ctsio);
6206                 return (CTL_RETVAL_COMPLETE);
6207         }
6208
6209         /*
6210          * Decrement these before we call the page handler, since we may
6211          * end up getting called back one way or another before the handler
6212          * returns to this context.
6213          */
6214         *len_left -= page_index->page_len;
6215         *len_used += page_index->page_len;
6216
6217         retval = page_index->select_handler(ctsio, page_index,
6218                                             (uint8_t *)page_header);
6219
6220         /*
6221          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6222          * wait until this queued command completes to finish processing
6223          * the mode page.  If it returns anything other than
6224          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6225          * already set the sense information, freed the data pointer, and
6226          * completed the io for us.
6227          */
6228         if (retval != CTL_RETVAL_COMPLETE)
6229                 goto bailout_no_done;
6230
6231         /*
6232          * If the initiator sent us more than one page, parse the next one.
6233          */
6234         if (*len_left > 0)
6235                 goto do_next_page;
6236
6237         ctl_set_success(ctsio);
6238         free(ctsio->kern_data_ptr, M_CTL);
6239         ctl_done((union ctl_io *)ctsio);
6240
6241 bailout_no_done:
6242
6243         return (CTL_RETVAL_COMPLETE);
6244
6245 }
6246
6247 int
6248 ctl_mode_select(struct ctl_scsiio *ctsio)
6249 {
6250         struct ctl_lun *lun = CTL_LUN(ctsio);
6251         union ctl_modepage_info *modepage_info;
6252         int bd_len, i, header_size, param_len, rtd;
6253         uint32_t initidx;
6254
6255         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6256         switch (ctsio->cdb[0]) {
6257         case MODE_SELECT_6: {
6258                 struct scsi_mode_select_6 *cdb;
6259
6260                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6261
6262                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6263                 param_len = cdb->length;
6264                 header_size = sizeof(struct scsi_mode_header_6);
6265                 break;
6266         }
6267         case MODE_SELECT_10: {
6268                 struct scsi_mode_select_10 *cdb;
6269
6270                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6271
6272                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6273                 param_len = scsi_2btoul(cdb->length);
6274                 header_size = sizeof(struct scsi_mode_header_10);
6275                 break;
6276         }
6277         default:
6278                 ctl_set_invalid_opcode(ctsio);
6279                 ctl_done((union ctl_io *)ctsio);
6280                 return (CTL_RETVAL_COMPLETE);
6281         }
6282
6283         if (rtd) {
6284                 if (param_len != 0) {
6285                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6286                             /*command*/ 1, /*field*/ 0,
6287                             /*bit_valid*/ 0, /*bit*/ 0);
6288                         ctl_done((union ctl_io *)ctsio);
6289                         return (CTL_RETVAL_COMPLETE);
6290                 }
6291
6292                 /* Revert to defaults. */
6293                 ctl_init_page_index(lun);
6294                 mtx_lock(&lun->lun_lock);
6295                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6296                 mtx_unlock(&lun->lun_lock);
6297                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6298                         ctl_isc_announce_mode(lun, -1,
6299                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6300                             lun->mode_pages.index[i].subpage);
6301                 }
6302                 ctl_set_success(ctsio);
6303                 ctl_done((union ctl_io *)ctsio);
6304                 return (CTL_RETVAL_COMPLETE);
6305         }
6306
6307         /*
6308          * From SPC-3:
6309          * "A parameter list length of zero indicates that the Data-Out Buffer
6310          * shall be empty. This condition shall not be considered as an error."
6311          */
6312         if (param_len == 0) {
6313                 ctl_set_success(ctsio);
6314                 ctl_done((union ctl_io *)ctsio);
6315                 return (CTL_RETVAL_COMPLETE);
6316         }
6317
6318         /*
6319          * Since we'll hit this the first time through, prior to
6320          * allocation, we don't need to free a data buffer here.
6321          */
6322         if (param_len < header_size) {
6323                 ctl_set_param_len_error(ctsio);
6324                 ctl_done((union ctl_io *)ctsio);
6325                 return (CTL_RETVAL_COMPLETE);
6326         }
6327
6328         /*
6329          * Allocate the data buffer and grab the user's data.  In theory,
6330          * we shouldn't have to sanity check the parameter list length here
6331          * because the maximum size is 64K.  We should be able to malloc
6332          * that much without too many problems.
6333          */
6334         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6335                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6336                 ctsio->kern_data_len = param_len;
6337                 ctsio->kern_total_len = param_len;
6338                 ctsio->kern_rel_offset = 0;
6339                 ctsio->kern_sg_entries = 0;
6340                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6341                 ctsio->be_move_done = ctl_config_move_done;
6342                 ctl_datamove((union ctl_io *)ctsio);
6343
6344                 return (CTL_RETVAL_COMPLETE);
6345         }
6346
6347         switch (ctsio->cdb[0]) {
6348         case MODE_SELECT_6: {
6349                 struct scsi_mode_header_6 *mh6;
6350
6351                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6352                 bd_len = mh6->blk_desc_len;
6353                 break;
6354         }
6355         case MODE_SELECT_10: {
6356                 struct scsi_mode_header_10 *mh10;
6357
6358                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6359                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6360                 break;
6361         }
6362         default:
6363                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6364         }
6365
6366         if (param_len < (header_size + bd_len)) {
6367                 free(ctsio->kern_data_ptr, M_CTL);
6368                 ctl_set_param_len_error(ctsio);
6369                 ctl_done((union ctl_io *)ctsio);
6370                 return (CTL_RETVAL_COMPLETE);
6371         }
6372
6373         /*
6374          * Set the IO_CONT flag, so that if this I/O gets passed to
6375          * ctl_config_write_done(), it'll get passed back to
6376          * ctl_do_mode_select() for further processing, or completion if
6377          * we're all done.
6378          */
6379         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6380         ctsio->io_cont = ctl_do_mode_select;
6381
6382         modepage_info = (union ctl_modepage_info *)
6383                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6384         memset(modepage_info, 0, sizeof(*modepage_info));
6385         modepage_info->header.len_left = param_len - header_size - bd_len;
6386         modepage_info->header.len_used = header_size + bd_len;
6387
6388         return (ctl_do_mode_select((union ctl_io *)ctsio));
6389 }
6390
6391 int
6392 ctl_mode_sense(struct ctl_scsiio *ctsio)
6393 {
6394         struct ctl_lun *lun = CTL_LUN(ctsio);
6395         int pc, page_code, dbd, subpage;
6396         int alloc_len, page_len, header_len, total_len;
6397         struct scsi_mode_block_descr *block_desc;
6398         struct ctl_page_index *page_index;
6399
6400         dbd = 0;
6401         block_desc = NULL;
6402
6403         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6404
6405         switch (ctsio->cdb[0]) {
6406         case MODE_SENSE_6: {
6407                 struct scsi_mode_sense_6 *cdb;
6408
6409                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6410
6411                 header_len = sizeof(struct scsi_mode_hdr_6);
6412                 if (cdb->byte2 & SMS_DBD)
6413                         dbd = 1;
6414                 else
6415                         header_len += sizeof(struct scsi_mode_block_descr);
6416
6417                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6418                 page_code = cdb->page & SMS_PAGE_CODE;
6419                 subpage = cdb->subpage;
6420                 alloc_len = cdb->length;
6421                 break;
6422         }
6423         case MODE_SENSE_10: {
6424                 struct scsi_mode_sense_10 *cdb;
6425
6426                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6427
6428                 header_len = sizeof(struct scsi_mode_hdr_10);
6429
6430                 if (cdb->byte2 & SMS_DBD)
6431                         dbd = 1;
6432                 else
6433                         header_len += sizeof(struct scsi_mode_block_descr);
6434                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6435                 page_code = cdb->page & SMS_PAGE_CODE;
6436                 subpage = cdb->subpage;
6437                 alloc_len = scsi_2btoul(cdb->length);
6438                 break;
6439         }
6440         default:
6441                 ctl_set_invalid_opcode(ctsio);
6442                 ctl_done((union ctl_io *)ctsio);
6443                 return (CTL_RETVAL_COMPLETE);
6444                 break; /* NOTREACHED */
6445         }
6446
6447         /*
6448          * We have to make a first pass through to calculate the size of
6449          * the pages that match the user's query.  Then we allocate enough
6450          * memory to hold it, and actually copy the data into the buffer.
6451          */
6452         switch (page_code) {
6453         case SMS_ALL_PAGES_PAGE: {
6454                 u_int i;
6455
6456                 page_len = 0;
6457
6458                 /*
6459                  * At the moment, values other than 0 and 0xff here are
6460                  * reserved according to SPC-3.
6461                  */
6462                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6463                  && (subpage != SMS_SUBPAGE_ALL)) {
6464                         ctl_set_invalid_field(ctsio,
6465                                               /*sks_valid*/ 1,
6466                                               /*command*/ 1,
6467                                               /*field*/ 3,
6468                                               /*bit_valid*/ 0,
6469                                               /*bit*/ 0);
6470                         ctl_done((union ctl_io *)ctsio);
6471                         return (CTL_RETVAL_COMPLETE);
6472                 }
6473
6474                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6475                         page_index = &lun->mode_pages.index[i];
6476
6477                         /* Make sure the page is supported for this dev type */
6478                         if (lun->be_lun->lun_type == T_DIRECT &&
6479                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6480                                 continue;
6481                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6482                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6483                                 continue;
6484                         if (lun->be_lun->lun_type == T_CDROM &&
6485                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6486                                 continue;
6487
6488                         /*
6489                          * We don't use this subpage if the user didn't
6490                          * request all subpages.
6491                          */
6492                         if ((page_index->subpage != 0)
6493                          && (subpage == SMS_SUBPAGE_PAGE_0))
6494                                 continue;
6495
6496 #if 0
6497                         printf("found page %#x len %d\n",
6498                                page_index->page_code & SMPH_PC_MASK,
6499                                page_index->page_len);
6500 #endif
6501                         page_len += page_index->page_len;
6502                 }
6503                 break;
6504         }
6505         default: {
6506                 u_int i;
6507
6508                 page_len = 0;
6509
6510                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6511                         page_index = &lun->mode_pages.index[i];
6512
6513                         /* Make sure the page is supported for this dev type */
6514                         if (lun->be_lun->lun_type == T_DIRECT &&
6515                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6516                                 continue;
6517                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6518                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6519                                 continue;
6520                         if (lun->be_lun->lun_type == T_CDROM &&
6521                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6522                                 continue;
6523
6524                         /* Look for the right page code */
6525                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6526                                 continue;
6527
6528                         /* Look for the right subpage or the subpage wildcard*/
6529                         if ((page_index->subpage != subpage)
6530                          && (subpage != SMS_SUBPAGE_ALL))
6531                                 continue;
6532
6533 #if 0
6534                         printf("found page %#x len %d\n",
6535                                page_index->page_code & SMPH_PC_MASK,
6536                                page_index->page_len);
6537 #endif
6538
6539                         page_len += page_index->page_len;
6540                 }
6541
6542                 if (page_len == 0) {
6543                         ctl_set_invalid_field(ctsio,
6544                                               /*sks_valid*/ 1,
6545                                               /*command*/ 1,
6546                                               /*field*/ 2,
6547                                               /*bit_valid*/ 1,
6548                                               /*bit*/ 5);
6549                         ctl_done((union ctl_io *)ctsio);
6550                         return (CTL_RETVAL_COMPLETE);
6551                 }
6552                 break;
6553         }
6554         }
6555
6556         total_len = header_len + page_len;
6557 #if 0
6558         printf("header_len = %d, page_len = %d, total_len = %d\n",
6559                header_len, page_len, total_len);
6560 #endif
6561
6562         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6563         ctsio->kern_sg_entries = 0;
6564         ctsio->kern_rel_offset = 0;
6565         ctsio->kern_data_len = min(total_len, alloc_len);
6566         ctsio->kern_total_len = ctsio->kern_data_len;
6567
6568         switch (ctsio->cdb[0]) {
6569         case MODE_SENSE_6: {
6570                 struct scsi_mode_hdr_6 *header;
6571
6572                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6573
6574                 header->datalen = MIN(total_len - 1, 254);
6575                 if (lun->be_lun->lun_type == T_DIRECT) {
6576                         header->dev_specific = 0x10; /* DPOFUA */
6577                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6578                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6579                                 header->dev_specific |= 0x80; /* WP */
6580                 }
6581                 if (dbd)
6582                         header->block_descr_len = 0;
6583                 else
6584                         header->block_descr_len =
6585                                 sizeof(struct scsi_mode_block_descr);
6586                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6587                 break;
6588         }
6589         case MODE_SENSE_10: {
6590                 struct scsi_mode_hdr_10 *header;
6591                 int datalen;
6592
6593                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6594
6595                 datalen = MIN(total_len - 2, 65533);
6596                 scsi_ulto2b(datalen, header->datalen);
6597                 if (lun->be_lun->lun_type == T_DIRECT) {
6598                         header->dev_specific = 0x10; /* DPOFUA */
6599                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6600                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6601                                 header->dev_specific |= 0x80; /* WP */
6602                 }
6603                 if (dbd)
6604                         scsi_ulto2b(0, header->block_descr_len);
6605                 else
6606                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6607                                     header->block_descr_len);
6608                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6609                 break;
6610         }
6611         default:
6612                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6613         }
6614
6615         /*
6616          * If we've got a disk, use its blocksize in the block
6617          * descriptor.  Otherwise, just set it to 0.
6618          */
6619         if (dbd == 0) {
6620                 if (lun->be_lun->lun_type == T_DIRECT)
6621                         scsi_ulto3b(lun->be_lun->blocksize,
6622                                     block_desc->block_len);
6623                 else
6624                         scsi_ulto3b(0, block_desc->block_len);
6625         }
6626
6627         switch (page_code) {
6628         case SMS_ALL_PAGES_PAGE: {
6629                 int i, data_used;
6630
6631                 data_used = header_len;
6632                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6633                         struct ctl_page_index *page_index;
6634
6635                         page_index = &lun->mode_pages.index[i];
6636                         if (lun->be_lun->lun_type == T_DIRECT &&
6637                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6638                                 continue;
6639                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6640                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6641                                 continue;
6642                         if (lun->be_lun->lun_type == T_CDROM &&
6643                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6644                                 continue;
6645
6646                         /*
6647                          * We don't use this subpage if the user didn't
6648                          * request all subpages.  We already checked (above)
6649                          * to make sure the user only specified a subpage
6650                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6651                          */
6652                         if ((page_index->subpage != 0)
6653                          && (subpage == SMS_SUBPAGE_PAGE_0))
6654                                 continue;
6655
6656                         /*
6657                          * Call the handler, if it exists, to update the
6658                          * page to the latest values.
6659                          */
6660                         if (page_index->sense_handler != NULL)
6661                                 page_index->sense_handler(ctsio, page_index,pc);
6662
6663                         memcpy(ctsio->kern_data_ptr + data_used,
6664                                page_index->page_data +
6665                                (page_index->page_len * pc),
6666                                page_index->page_len);
6667                         data_used += page_index->page_len;
6668                 }
6669                 break;
6670         }
6671         default: {
6672                 int i, data_used;
6673
6674                 data_used = header_len;
6675
6676                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6677                         struct ctl_page_index *page_index;
6678
6679                         page_index = &lun->mode_pages.index[i];
6680
6681                         /* Look for the right page code */
6682                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6683                                 continue;
6684
6685                         /* Look for the right subpage or the subpage wildcard*/
6686                         if ((page_index->subpage != subpage)
6687                          && (subpage != SMS_SUBPAGE_ALL))
6688                                 continue;
6689
6690                         /* Make sure the page is supported for this dev type */
6691                         if (lun->be_lun->lun_type == T_DIRECT &&
6692                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6693                                 continue;
6694                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6695                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6696                                 continue;
6697                         if (lun->be_lun->lun_type == T_CDROM &&
6698                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6699                                 continue;
6700
6701                         /*
6702                          * Call the handler, if it exists, to update the
6703                          * page to the latest values.
6704                          */
6705                         if (page_index->sense_handler != NULL)
6706                                 page_index->sense_handler(ctsio, page_index,pc);
6707
6708                         memcpy(ctsio->kern_data_ptr + data_used,
6709                                page_index->page_data +
6710                                (page_index->page_len * pc),
6711                                page_index->page_len);
6712                         data_used += page_index->page_len;
6713                 }
6714                 break;
6715         }
6716         }
6717
6718         ctl_set_success(ctsio);
6719         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6720         ctsio->be_move_done = ctl_config_move_done;
6721         ctl_datamove((union ctl_io *)ctsio);
6722         return (CTL_RETVAL_COMPLETE);
6723 }
6724
6725 int
6726 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6727                                struct ctl_page_index *page_index,
6728                                int pc)
6729 {
6730         struct ctl_lun *lun = CTL_LUN(ctsio);
6731         struct scsi_log_param_header *phdr;
6732         uint8_t *data;
6733         uint64_t val;
6734
6735         data = page_index->page_data;
6736
6737         if (lun->backend->lun_attr != NULL &&
6738             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6739              != UINT64_MAX) {
6740                 phdr = (struct scsi_log_param_header *)data;
6741                 scsi_ulto2b(0x0001, phdr->param_code);
6742                 phdr->param_control = SLP_LBIN | SLP_LP;
6743                 phdr->param_len = 8;
6744                 data = (uint8_t *)(phdr + 1);
6745                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6746                 data[4] = 0x02; /* per-pool */
6747                 data += phdr->param_len;
6748         }
6749
6750         if (lun->backend->lun_attr != NULL &&
6751             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6752              != UINT64_MAX) {
6753                 phdr = (struct scsi_log_param_header *)data;
6754                 scsi_ulto2b(0x0002, phdr->param_code);
6755                 phdr->param_control = SLP_LBIN | SLP_LP;
6756                 phdr->param_len = 8;
6757                 data = (uint8_t *)(phdr + 1);
6758                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6759                 data[4] = 0x01; /* per-LUN */
6760                 data += phdr->param_len;
6761         }
6762
6763         if (lun->backend->lun_attr != NULL &&
6764             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6765              != UINT64_MAX) {
6766                 phdr = (struct scsi_log_param_header *)data;
6767                 scsi_ulto2b(0x00f1, phdr->param_code);
6768                 phdr->param_control = SLP_LBIN | SLP_LP;
6769                 phdr->param_len = 8;
6770                 data = (uint8_t *)(phdr + 1);
6771                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6772                 data[4] = 0x02; /* per-pool */
6773                 data += phdr->param_len;
6774         }
6775
6776         if (lun->backend->lun_attr != NULL &&
6777             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6778              != UINT64_MAX) {
6779                 phdr = (struct scsi_log_param_header *)data;
6780                 scsi_ulto2b(0x00f2, phdr->param_code);
6781                 phdr->param_control = SLP_LBIN | SLP_LP;
6782                 phdr->param_len = 8;
6783                 data = (uint8_t *)(phdr + 1);
6784                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6785                 data[4] = 0x02; /* per-pool */
6786                 data += phdr->param_len;
6787         }
6788
6789         page_index->page_len = data - page_index->page_data;
6790         return (0);
6791 }
6792
6793 int
6794 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6795                                struct ctl_page_index *page_index,
6796                                int pc)
6797 {
6798         struct ctl_lun *lun = CTL_LUN(ctsio);
6799         struct stat_page *data;
6800         struct bintime *t;
6801
6802         data = (struct stat_page *)page_index->page_data;
6803
6804         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6805         data->sap.hdr.param_control = SLP_LBIN;
6806         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6807             sizeof(struct scsi_log_param_header);
6808         scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6809             data->sap.read_num);
6810         scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6811             data->sap.write_num);
6812         if (lun->be_lun->blocksize > 0) {
6813                 scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6814                     lun->be_lun->blocksize, data->sap.recvieved_lba);
6815                 scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6816                     lun->be_lun->blocksize, data->sap.transmitted_lba);
6817         }
6818         t = &lun->stats.time[CTL_STATS_READ];
6819         scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6820             data->sap.read_int);
6821         t = &lun->stats.time[CTL_STATS_WRITE];
6822         scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6823             data->sap.write_int);
6824         scsi_u64to8b(0, data->sap.weighted_num);
6825         scsi_u64to8b(0, data->sap.weighted_int);
6826         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6827         data->it.hdr.param_control = SLP_LBIN;
6828         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6829             sizeof(struct scsi_log_param_header);
6830 #ifdef CTL_TIME_IO
6831         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6832 #endif
6833         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6834         data->it.hdr.param_control = SLP_LBIN;
6835         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6836             sizeof(struct scsi_log_param_header);
6837         scsi_ulto4b(3, data->ti.exponent);
6838         scsi_ulto4b(1, data->ti.integer);
6839         return (0);
6840 }
6841
6842 int
6843 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6844                                struct ctl_page_index *page_index,
6845                                int pc)
6846 {
6847         struct ctl_lun *lun = CTL_LUN(ctsio);
6848         struct scsi_log_informational_exceptions *data;
6849
6850         data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6851
6852         scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6853         data->hdr.param_control = SLP_LBIN;
6854         data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6855             sizeof(struct scsi_log_param_header);
6856         data->ie_asc = lun->ie_asc;
6857         data->ie_ascq = lun->ie_ascq;
6858         data->temperature = 0xff;
6859         return (0);
6860 }
6861
6862 int
6863 ctl_log_sense(struct ctl_scsiio *ctsio)
6864 {
6865         struct ctl_lun *lun = CTL_LUN(ctsio);
6866         int i, pc, page_code, subpage;
6867         int alloc_len, total_len;
6868         struct ctl_page_index *page_index;
6869         struct scsi_log_sense *cdb;
6870         struct scsi_log_header *header;
6871
6872         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6873
6874         cdb = (struct scsi_log_sense *)ctsio->cdb;
6875         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6876         page_code = cdb->page & SLS_PAGE_CODE;
6877         subpage = cdb->subpage;
6878         alloc_len = scsi_2btoul(cdb->length);
6879
6880         page_index = NULL;
6881         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6882                 page_index = &lun->log_pages.index[i];
6883
6884                 /* Look for the right page code */
6885                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6886                         continue;
6887
6888                 /* Look for the right subpage or the subpage wildcard*/
6889                 if (page_index->subpage != subpage)
6890                         continue;
6891
6892                 break;
6893         }
6894         if (i >= CTL_NUM_LOG_PAGES) {
6895                 ctl_set_invalid_field(ctsio,
6896                                       /*sks_valid*/ 1,
6897                                       /*command*/ 1,
6898                                       /*field*/ 2,
6899                                       /*bit_valid*/ 0,
6900                                       /*bit*/ 0);
6901                 ctl_done((union ctl_io *)ctsio);
6902                 return (CTL_RETVAL_COMPLETE);
6903         }
6904
6905         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6906
6907         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6908         ctsio->kern_sg_entries = 0;
6909         ctsio->kern_rel_offset = 0;
6910         ctsio->kern_data_len = min(total_len, alloc_len);
6911         ctsio->kern_total_len = ctsio->kern_data_len;
6912
6913         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6914         header->page = page_index->page_code;
6915         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6916                 header->page |= SL_DS;
6917         if (page_index->subpage) {
6918                 header->page |= SL_SPF;
6919                 header->subpage = page_index->subpage;
6920         }
6921         scsi_ulto2b(page_index->page_len, header->datalen);
6922
6923         /*
6924          * Call the handler, if it exists, to update the
6925          * page to the latest values.
6926          */
6927         if (page_index->sense_handler != NULL)
6928                 page_index->sense_handler(ctsio, page_index, pc);
6929
6930         memcpy(header + 1, page_index->page_data, page_index->page_len);
6931
6932         ctl_set_success(ctsio);
6933         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6934         ctsio->be_move_done = ctl_config_move_done;
6935         ctl_datamove((union ctl_io *)ctsio);
6936         return (CTL_RETVAL_COMPLETE);
6937 }
6938
6939 int
6940 ctl_read_capacity(struct ctl_scsiio *ctsio)
6941 {
6942         struct ctl_lun *lun = CTL_LUN(ctsio);
6943         struct scsi_read_capacity *cdb;
6944         struct scsi_read_capacity_data *data;
6945         uint32_t lba;
6946
6947         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6948
6949         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6950
6951         lba = scsi_4btoul(cdb->addr);
6952         if (((cdb->pmi & SRC_PMI) == 0)
6953          && (lba != 0)) {
6954                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6955                                       /*sks_valid*/ 1,
6956                                       /*command*/ 1,
6957                                       /*field*/ 2,
6958                                       /*bit_valid*/ 0,
6959                                       /*bit*/ 0);
6960                 ctl_done((union ctl_io *)ctsio);
6961                 return (CTL_RETVAL_COMPLETE);
6962         }
6963
6964         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6965         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6966         ctsio->kern_data_len = sizeof(*data);
6967         ctsio->kern_total_len = sizeof(*data);
6968         ctsio->kern_rel_offset = 0;
6969         ctsio->kern_sg_entries = 0;
6970
6971         /*
6972          * If the maximum LBA is greater than 0xfffffffe, the user must
6973          * issue a SERVICE ACTION IN (16) command, with the read capacity
6974          * serivce action set.
6975          */
6976         if (lun->be_lun->maxlba > 0xfffffffe)
6977                 scsi_ulto4b(0xffffffff, data->addr);
6978         else
6979                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6980
6981         /*
6982          * XXX KDM this may not be 512 bytes...
6983          */
6984         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6985
6986         ctl_set_success(ctsio);
6987         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6988         ctsio->be_move_done = ctl_config_move_done;
6989         ctl_datamove((union ctl_io *)ctsio);
6990         return (CTL_RETVAL_COMPLETE);
6991 }
6992
6993 int
6994 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6995 {
6996         struct ctl_lun *lun = CTL_LUN(ctsio);
6997         struct scsi_read_capacity_16 *cdb;
6998         struct scsi_read_capacity_data_long *data;
6999         uint64_t lba;
7000         uint32_t alloc_len;
7001
7002         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7003
7004         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7005
7006         alloc_len = scsi_4btoul(cdb->alloc_len);
7007         lba = scsi_8btou64(cdb->addr);
7008
7009         if ((cdb->reladr & SRC16_PMI)
7010          && (lba != 0)) {
7011                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7012                                       /*sks_valid*/ 1,
7013                                       /*command*/ 1,
7014                                       /*field*/ 2,
7015                                       /*bit_valid*/ 0,
7016                                       /*bit*/ 0);
7017                 ctl_done((union ctl_io *)ctsio);
7018                 return (CTL_RETVAL_COMPLETE);
7019         }
7020
7021         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7022         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7023         ctsio->kern_rel_offset = 0;
7024         ctsio->kern_sg_entries = 0;
7025         ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7026         ctsio->kern_total_len = ctsio->kern_data_len;
7027
7028         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7029         /* XXX KDM this may not be 512 bytes... */
7030         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7031         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7032         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7033         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7034                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7035
7036         ctl_set_success(ctsio);
7037         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7038         ctsio->be_move_done = ctl_config_move_done;
7039         ctl_datamove((union ctl_io *)ctsio);
7040         return (CTL_RETVAL_COMPLETE);
7041 }
7042
7043 int
7044 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7045 {
7046         struct ctl_lun *lun = CTL_LUN(ctsio);
7047         struct scsi_get_lba_status *cdb;
7048         struct scsi_get_lba_status_data *data;
7049         struct ctl_lba_len_flags *lbalen;
7050         uint64_t lba;
7051         uint32_t alloc_len, total_len;
7052         int retval;
7053
7054         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7055
7056         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7057         lba = scsi_8btou64(cdb->addr);
7058         alloc_len = scsi_4btoul(cdb->alloc_len);
7059
7060         if (lba > lun->be_lun->maxlba) {
7061                 ctl_set_lba_out_of_range(ctsio, lba);
7062                 ctl_done((union ctl_io *)ctsio);
7063                 return (CTL_RETVAL_COMPLETE);
7064         }
7065
7066         total_len = sizeof(*data) + sizeof(data->descr[0]);
7067         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7068         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7069         ctsio->kern_rel_offset = 0;
7070         ctsio->kern_sg_entries = 0;
7071         ctsio->kern_data_len = min(total_len, alloc_len);
7072         ctsio->kern_total_len = ctsio->kern_data_len;
7073
7074         /* Fill dummy data in case backend can't tell anything. */
7075         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7076         scsi_u64to8b(lba, data->descr[0].addr);
7077         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7078             data->descr[0].length);
7079         data->descr[0].status = 0; /* Mapped or unknown. */
7080
7081         ctl_set_success(ctsio);
7082         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7083         ctsio->be_move_done = ctl_config_move_done;
7084
7085         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7086         lbalen->lba = lba;
7087         lbalen->len = total_len;
7088         lbalen->flags = 0;
7089         retval = lun->backend->config_read((union ctl_io *)ctsio);
7090         return (retval);
7091 }
7092
7093 int
7094 ctl_read_defect(struct ctl_scsiio *ctsio)
7095 {
7096         struct scsi_read_defect_data_10 *ccb10;
7097         struct scsi_read_defect_data_12 *ccb12;
7098         struct scsi_read_defect_data_hdr_10 *data10;
7099         struct scsi_read_defect_data_hdr_12 *data12;
7100         uint32_t alloc_len, data_len;
7101         uint8_t format;
7102
7103         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7104
7105         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7106                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7107                 format = ccb10->format;
7108                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7109                 data_len = sizeof(*data10);
7110         } else {
7111                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7112                 format = ccb12->format;
7113                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7114                 data_len = sizeof(*data12);
7115         }
7116         if (alloc_len == 0) {
7117                 ctl_set_success(ctsio);
7118                 ctl_done((union ctl_io *)ctsio);
7119                 return (CTL_RETVAL_COMPLETE);
7120         }
7121
7122         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7123         ctsio->kern_rel_offset = 0;
7124         ctsio->kern_sg_entries = 0;
7125         ctsio->kern_data_len = min(data_len, alloc_len);
7126         ctsio->kern_total_len = ctsio->kern_data_len;
7127
7128         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7129                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7130                     ctsio->kern_data_ptr;
7131                 data10->format = format;
7132                 scsi_ulto2b(0, data10->length);
7133         } else {
7134                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7135                     ctsio->kern_data_ptr;
7136                 data12->format = format;
7137                 scsi_ulto2b(0, data12->generation);
7138                 scsi_ulto4b(0, data12->length);
7139         }
7140
7141         ctl_set_success(ctsio);
7142         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7143         ctsio->be_move_done = ctl_config_move_done;
7144         ctl_datamove((union ctl_io *)ctsio);
7145         return (CTL_RETVAL_COMPLETE);
7146 }
7147
7148 int
7149 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7150 {
7151         struct ctl_softc *softc = CTL_SOFTC(ctsio);
7152         struct ctl_lun *lun = CTL_LUN(ctsio);
7153         struct scsi_maintenance_in *cdb;
7154         int retval;
7155         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7156         int num_ha_groups, num_target_ports, shared_group;
7157         struct ctl_port *port;
7158         struct scsi_target_group_data *rtg_ptr;
7159         struct scsi_target_group_data_extended *rtg_ext_ptr;
7160         struct scsi_target_port_group_descriptor *tpg_desc;
7161
7162         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7163
7164         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7165         retval = CTL_RETVAL_COMPLETE;
7166
7167         switch (cdb->byte2 & STG_PDF_MASK) {
7168         case STG_PDF_LENGTH:
7169                 ext = 0;
7170                 break;
7171         case STG_PDF_EXTENDED:
7172                 ext = 1;
7173                 break;
7174         default:
7175                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7176                                       /*sks_valid*/ 1,
7177                                       /*command*/ 1,
7178                                       /*field*/ 2,
7179                                       /*bit_valid*/ 1,
7180                                       /*bit*/ 5);
7181                 ctl_done((union ctl_io *)ctsio);
7182                 return(retval);
7183         }
7184
7185         num_target_ports = 0;
7186         shared_group = (softc->is_single != 0);
7187         mtx_lock(&softc->ctl_lock);
7188         STAILQ_FOREACH(port, &softc->port_list, links) {
7189                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7190                         continue;
7191                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7192                         continue;
7193                 num_target_ports++;
7194                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7195                         shared_group = 1;
7196         }
7197         mtx_unlock(&softc->ctl_lock);
7198         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7199
7200         if (ext)
7201                 total_len = sizeof(struct scsi_target_group_data_extended);
7202         else
7203                 total_len = sizeof(struct scsi_target_group_data);
7204         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7205                 (shared_group + num_ha_groups) +
7206             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7207
7208         alloc_len = scsi_4btoul(cdb->length);
7209
7210         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7211         ctsio->kern_sg_entries = 0;
7212         ctsio->kern_rel_offset = 0;
7213         ctsio->kern_data_len = min(total_len, alloc_len);
7214         ctsio->kern_total_len = ctsio->kern_data_len;
7215
7216         if (ext) {
7217                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7218                     ctsio->kern_data_ptr;
7219                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7220                 rtg_ext_ptr->format_type = 0x10;
7221                 rtg_ext_ptr->implicit_transition_time = 0;
7222                 tpg_desc = &rtg_ext_ptr->groups[0];
7223         } else {
7224                 rtg_ptr = (struct scsi_target_group_data *)
7225                     ctsio->kern_data_ptr;
7226                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7227                 tpg_desc = &rtg_ptr->groups[0];
7228         }
7229
7230         mtx_lock(&softc->ctl_lock);
7231         pg = softc->port_min / softc->port_cnt;
7232         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7233                 /* Some shelf is known to be primary. */
7234                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7235                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7236                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7237                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7238                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7239                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7240                 else
7241                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7242                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7243                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7244                 } else {
7245                         ts = os;
7246                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7247                 }
7248         } else {
7249                 /* No known primary shelf. */
7250                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7251                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7252                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7253                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7254                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7255                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7256                 } else {
7257                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7258                 }
7259         }
7260         if (shared_group) {
7261                 tpg_desc->pref_state = ts;
7262                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7263                     TPG_U_SUP | TPG_T_SUP;
7264                 scsi_ulto2b(1, tpg_desc->target_port_group);
7265                 tpg_desc->status = TPG_IMPLICIT;
7266                 pc = 0;
7267                 STAILQ_FOREACH(port, &softc->port_list, links) {
7268                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7269                                 continue;
7270                         if (!softc->is_single &&
7271                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7272                                 continue;
7273                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7274                                 continue;
7275                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7276                             relative_target_port_identifier);
7277                         pc++;
7278                 }
7279                 tpg_desc->target_port_count = pc;
7280                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7281                     &tpg_desc->descriptors[pc];
7282         }
7283         for (g = 0; g < num_ha_groups; g++) {
7284                 tpg_desc->pref_state = (g == pg) ? ts : os;
7285                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7286                     TPG_U_SUP | TPG_T_SUP;
7287                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7288                 tpg_desc->status = TPG_IMPLICIT;
7289                 pc = 0;
7290                 STAILQ_FOREACH(port, &softc->port_list, links) {
7291                         if (port->targ_port < g * softc->port_cnt ||
7292                             port->targ_port >= (g + 1) * softc->port_cnt)
7293                                 continue;
7294                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7295                                 continue;
7296                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7297                                 continue;
7298                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7299                                 continue;
7300                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7301                             relative_target_port_identifier);
7302                         pc++;
7303                 }
7304                 tpg_desc->target_port_count = pc;
7305                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7306                     &tpg_desc->descriptors[pc];
7307         }
7308         mtx_unlock(&softc->ctl_lock);
7309
7310         ctl_set_success(ctsio);
7311         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7312         ctsio->be_move_done = ctl_config_move_done;
7313         ctl_datamove((union ctl_io *)ctsio);
7314         return(retval);
7315 }
7316
7317 int
7318 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7319 {
7320         struct ctl_lun *lun = CTL_LUN(ctsio);
7321         struct scsi_report_supported_opcodes *cdb;
7322         const struct ctl_cmd_entry *entry, *sentry;
7323         struct scsi_report_supported_opcodes_all *all;
7324         struct scsi_report_supported_opcodes_descr *descr;
7325         struct scsi_report_supported_opcodes_one *one;
7326         int retval;
7327         int alloc_len, total_len;
7328         int opcode, service_action, i, j, num;
7329
7330         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7331
7332         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7333         retval = CTL_RETVAL_COMPLETE;
7334
7335         opcode = cdb->requested_opcode;
7336         service_action = scsi_2btoul(cdb->requested_service_action);
7337         switch (cdb->options & RSO_OPTIONS_MASK) {
7338         case RSO_OPTIONS_ALL:
7339                 num = 0;
7340                 for (i = 0; i < 256; i++) {
7341                         entry = &ctl_cmd_table[i];
7342                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7343                                 for (j = 0; j < 32; j++) {
7344                                         sentry = &((const struct ctl_cmd_entry *)
7345                                             entry->execute)[j];
7346                                         if (ctl_cmd_applicable(
7347                                             lun->be_lun->lun_type, sentry))
7348                                                 num++;
7349                                 }
7350                         } else {
7351                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7352                                     entry))
7353                                         num++;
7354                         }
7355                 }
7356                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7357                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7358                 break;
7359         case RSO_OPTIONS_OC:
7360                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7361                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7362                                               /*sks_valid*/ 1,
7363                                               /*command*/ 1,
7364                                               /*field*/ 2,
7365                                               /*bit_valid*/ 1,
7366                                               /*bit*/ 2);
7367                         ctl_done((union ctl_io *)ctsio);
7368                         return (CTL_RETVAL_COMPLETE);
7369                 }
7370                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7371                 break;
7372         case RSO_OPTIONS_OC_SA:
7373                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7374                     service_action >= 32) {
7375                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7376                                               /*sks_valid*/ 1,
7377                                               /*command*/ 1,
7378                                               /*field*/ 2,
7379                                               /*bit_valid*/ 1,
7380                                               /*bit*/ 2);
7381                         ctl_done((union ctl_io *)ctsio);
7382                         return (CTL_RETVAL_COMPLETE);
7383                 }
7384                 /* FALLTHROUGH */
7385         case RSO_OPTIONS_OC_ASA:
7386                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7387                 break;
7388         default:
7389                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7390                                       /*sks_valid*/ 1,
7391                                       /*command*/ 1,
7392                                       /*field*/ 2,
7393                                       /*bit_valid*/ 1,
7394                                       /*bit*/ 2);
7395                 ctl_done((union ctl_io *)ctsio);
7396                 return (CTL_RETVAL_COMPLETE);
7397         }
7398
7399         alloc_len = scsi_4btoul(cdb->length);
7400
7401         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7402         ctsio->kern_sg_entries = 0;
7403         ctsio->kern_rel_offset = 0;
7404         ctsio->kern_data_len = min(total_len, alloc_len);
7405         ctsio->kern_total_len = ctsio->kern_data_len;
7406
7407         switch (cdb->options & RSO_OPTIONS_MASK) {
7408         case RSO_OPTIONS_ALL:
7409                 all = (struct scsi_report_supported_opcodes_all *)
7410                     ctsio->kern_data_ptr;
7411                 num = 0;
7412                 for (i = 0; i < 256; i++) {
7413                         entry = &ctl_cmd_table[i];
7414                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7415                                 for (j = 0; j < 32; j++) {
7416                                         sentry = &((const struct ctl_cmd_entry *)
7417                                             entry->execute)[j];
7418                                         if (!ctl_cmd_applicable(
7419                                             lun->be_lun->lun_type, sentry))
7420                                                 continue;
7421                                         descr = &all->descr[num++];
7422                                         descr->opcode = i;
7423                                         scsi_ulto2b(j, descr->service_action);
7424                                         descr->flags = RSO_SERVACTV;
7425                                         scsi_ulto2b(sentry->length,
7426                                             descr->cdb_length);
7427                                 }
7428                         } else {
7429                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7430                                     entry))
7431                                         continue;
7432                                 descr = &all->descr[num++];
7433                                 descr->opcode = i;
7434                                 scsi_ulto2b(0, descr->service_action);
7435                                 descr->flags = 0;
7436                                 scsi_ulto2b(entry->length, descr->cdb_length);
7437                         }
7438                 }
7439                 scsi_ulto4b(
7440                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7441                     all->length);
7442                 break;
7443         case RSO_OPTIONS_OC:
7444                 one = (struct scsi_report_supported_opcodes_one *)
7445                     ctsio->kern_data_ptr;
7446                 entry = &ctl_cmd_table[opcode];
7447                 goto fill_one;
7448         case RSO_OPTIONS_OC_SA:
7449                 one = (struct scsi_report_supported_opcodes_one *)
7450                     ctsio->kern_data_ptr;
7451                 entry = &ctl_cmd_table[opcode];
7452                 entry = &((const struct ctl_cmd_entry *)
7453                     entry->execute)[service_action];
7454 fill_one:
7455                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7456                         one->support = 3;
7457                         scsi_ulto2b(entry->length, one->cdb_length);
7458                         one->cdb_usage[0] = opcode;
7459                         memcpy(&one->cdb_usage[1], entry->usage,
7460                             entry->length - 1);
7461                 } else
7462                         one->support = 1;
7463                 break;
7464         case RSO_OPTIONS_OC_ASA:
7465                 one = (struct scsi_report_supported_opcodes_one *)
7466                     ctsio->kern_data_ptr;
7467                 entry = &ctl_cmd_table[opcode];
7468                 if (entry->flags & CTL_CMD_FLAG_SA5) {
7469                         entry = &((const struct ctl_cmd_entry *)
7470                             entry->execute)[service_action];
7471                 } else if (service_action != 0) {
7472                         one->support = 1;
7473                         break;
7474                 }
7475                 goto fill_one;
7476         }
7477
7478         ctl_set_success(ctsio);
7479         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7480         ctsio->be_move_done = ctl_config_move_done;
7481         ctl_datamove((union ctl_io *)ctsio);
7482         return(retval);
7483 }
7484
7485 int
7486 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7487 {
7488         struct scsi_report_supported_tmf *cdb;
7489         struct scsi_report_supported_tmf_ext_data *data;
7490         int retval;
7491         int alloc_len, total_len;
7492
7493         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7494
7495         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7496
7497         retval = CTL_RETVAL_COMPLETE;
7498
7499         if (cdb->options & RST_REPD)
7500                 total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7501         else
7502                 total_len = sizeof(struct scsi_report_supported_tmf_data);
7503         alloc_len = scsi_4btoul(cdb->length);
7504
7505         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7506         ctsio->kern_sg_entries = 0;
7507         ctsio->kern_rel_offset = 0;
7508         ctsio->kern_data_len = min(total_len, alloc_len);
7509         ctsio->kern_total_len = ctsio->kern_data_len;
7510
7511         data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7512         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7513             RST_TRS;
7514         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7515         data->length = total_len - 4;
7516
7517         ctl_set_success(ctsio);
7518         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7519         ctsio->be_move_done = ctl_config_move_done;
7520         ctl_datamove((union ctl_io *)ctsio);
7521         return (retval);
7522 }
7523
7524 int
7525 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7526 {
7527         struct scsi_report_timestamp *cdb;
7528         struct scsi_report_timestamp_data *data;
7529         struct timeval tv;
7530         int64_t timestamp;
7531         int retval;
7532         int alloc_len, total_len;
7533
7534         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7535
7536         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7537
7538         retval = CTL_RETVAL_COMPLETE;
7539
7540         total_len = sizeof(struct scsi_report_timestamp_data);
7541         alloc_len = scsi_4btoul(cdb->length);
7542
7543         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7544         ctsio->kern_sg_entries = 0;
7545         ctsio->kern_rel_offset = 0;
7546         ctsio->kern_data_len = min(total_len, alloc_len);
7547         ctsio->kern_total_len = ctsio->kern_data_len;
7548
7549         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7550         scsi_ulto2b(sizeof(*data) - 2, data->length);
7551         data->origin = RTS_ORIG_OUTSIDE;
7552         getmicrotime(&tv);
7553         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7554         scsi_ulto4b(timestamp >> 16, data->timestamp);
7555         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7556
7557         ctl_set_success(ctsio);
7558         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7559         ctsio->be_move_done = ctl_config_move_done;
7560         ctl_datamove((union ctl_io *)ctsio);
7561         return (retval);
7562 }
7563
7564 int
7565 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7566 {
7567         struct ctl_softc *softc = CTL_SOFTC(ctsio);
7568         struct ctl_lun *lun = CTL_LUN(ctsio);
7569         struct scsi_per_res_in *cdb;
7570         int alloc_len, total_len = 0;
7571         /* struct scsi_per_res_in_rsrv in_data; */
7572         uint64_t key;
7573
7574         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7575
7576         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7577
7578         alloc_len = scsi_2btoul(cdb->length);
7579
7580 retry:
7581         mtx_lock(&lun->lun_lock);
7582         switch (cdb->action) {
7583         case SPRI_RK: /* read keys */
7584                 total_len = sizeof(struct scsi_per_res_in_keys) +
7585                         lun->pr_key_count *
7586                         sizeof(struct scsi_per_res_key);
7587                 break;
7588         case SPRI_RR: /* read reservation */
7589                 if (lun->flags & CTL_LUN_PR_RESERVED)
7590                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7591                 else
7592                         total_len = sizeof(struct scsi_per_res_in_header);
7593                 break;
7594         case SPRI_RC: /* report capabilities */
7595                 total_len = sizeof(struct scsi_per_res_cap);
7596                 break;
7597         case SPRI_RS: /* read full status */
7598                 total_len = sizeof(struct scsi_per_res_in_header) +
7599                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7600                     lun->pr_key_count;
7601                 break;
7602         default:
7603                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7604         }
7605         mtx_unlock(&lun->lun_lock);
7606
7607         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7608         ctsio->kern_rel_offset = 0;
7609         ctsio->kern_sg_entries = 0;
7610         ctsio->kern_data_len = min(total_len, alloc_len);
7611         ctsio->kern_total_len = ctsio->kern_data_len;
7612
7613         mtx_lock(&lun->lun_lock);
7614         switch (cdb->action) {
7615         case SPRI_RK: { // read keys
7616         struct scsi_per_res_in_keys *res_keys;
7617                 int i, key_count;
7618
7619                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7620
7621                 /*
7622                  * We had to drop the lock to allocate our buffer, which
7623                  * leaves time for someone to come in with another
7624                  * persistent reservation.  (That is unlikely, though,
7625                  * since this should be the only persistent reservation
7626                  * command active right now.)
7627                  */
7628                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7629                     (lun->pr_key_count *
7630                      sizeof(struct scsi_per_res_key)))){
7631                         mtx_unlock(&lun->lun_lock);
7632                         free(ctsio->kern_data_ptr, M_CTL);
7633                         printf("%s: reservation length changed, retrying\n",
7634                                __func__);
7635                         goto retry;
7636                 }
7637
7638                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7639
7640                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7641                              lun->pr_key_count, res_keys->header.length);
7642
7643                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7644                         if ((key = ctl_get_prkey(lun, i)) == 0)
7645                                 continue;
7646
7647                         /*
7648                          * We used lun->pr_key_count to calculate the
7649                          * size to allocate.  If it turns out the number of
7650                          * initiators with the registered flag set is
7651                          * larger than that (i.e. they haven't been kept in
7652                          * sync), we've got a problem.
7653                          */
7654                         if (key_count >= lun->pr_key_count) {
7655                                 key_count++;
7656                                 continue;
7657                         }
7658                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7659                         key_count++;
7660                 }
7661                 break;
7662         }
7663         case SPRI_RR: { // read reservation
7664                 struct scsi_per_res_in_rsrv *res;
7665                 int tmp_len, header_only;
7666
7667                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7668
7669                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7670
7671                 if (lun->flags & CTL_LUN_PR_RESERVED)
7672                 {
7673                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7674                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7675                                     res->header.length);
7676                         header_only = 0;
7677                 } else {
7678                         tmp_len = sizeof(struct scsi_per_res_in_header);
7679                         scsi_ulto4b(0, res->header.length);
7680                         header_only = 1;
7681                 }
7682
7683                 /*
7684                  * We had to drop the lock to allocate our buffer, which
7685                  * leaves time for someone to come in with another
7686                  * persistent reservation.  (That is unlikely, though,
7687                  * since this should be the only persistent reservation
7688                  * command active right now.)
7689                  */
7690                 if (tmp_len != total_len) {
7691                         mtx_unlock(&lun->lun_lock);
7692                         free(ctsio->kern_data_ptr, M_CTL);
7693                         printf("%s: reservation status changed, retrying\n",
7694                                __func__);
7695                         goto retry;
7696                 }
7697
7698                 /*
7699                  * No reservation held, so we're done.
7700                  */
7701                 if (header_only != 0)
7702                         break;
7703
7704                 /*
7705                  * If the registration is an All Registrants type, the key
7706                  * is 0, since it doesn't really matter.
7707                  */
7708                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7709                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7710                             res->data.reservation);
7711                 }
7712                 res->data.scopetype = lun->pr_res_type;
7713                 break;
7714         }
7715         case SPRI_RC:     //report capabilities
7716         {
7717                 struct scsi_per_res_cap *res_cap;
7718                 uint16_t type_mask;
7719
7720                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7721                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7722                 res_cap->flags1 = SPRI_CRH;
7723                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7724                 type_mask = SPRI_TM_WR_EX_AR |
7725                             SPRI_TM_EX_AC_RO |
7726                             SPRI_TM_WR_EX_RO |
7727                             SPRI_TM_EX_AC |
7728                             SPRI_TM_WR_EX |
7729                             SPRI_TM_EX_AC_AR;
7730                 scsi_ulto2b(type_mask, res_cap->type_mask);
7731                 break;
7732         }
7733         case SPRI_RS: { // read full status
7734                 struct scsi_per_res_in_full *res_status;
7735                 struct scsi_per_res_in_full_desc *res_desc;
7736                 struct ctl_port *port;
7737                 int i, len;
7738
7739                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7740
7741                 /*
7742                  * We had to drop the lock to allocate our buffer, which
7743                  * leaves time for someone to come in with another
7744                  * persistent reservation.  (That is unlikely, though,
7745                  * since this should be the only persistent reservation
7746                  * command active right now.)
7747                  */
7748                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7749                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7750                      lun->pr_key_count)){
7751                         mtx_unlock(&lun->lun_lock);
7752                         free(ctsio->kern_data_ptr, M_CTL);
7753                         printf("%s: reservation length changed, retrying\n",
7754                                __func__);
7755                         goto retry;
7756                 }
7757
7758                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7759
7760                 res_desc = &res_status->desc[0];
7761                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7762                         if ((key = ctl_get_prkey(lun, i)) == 0)
7763                                 continue;
7764
7765                         scsi_u64to8b(key, res_desc->res_key.key);
7766                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7767                             (lun->pr_res_idx == i ||
7768                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7769                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7770                                 res_desc->scopetype = lun->pr_res_type;
7771                         }
7772                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7773                             res_desc->rel_trgt_port_id);
7774                         len = 0;
7775                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7776                         if (port != NULL)
7777                                 len = ctl_create_iid(port,
7778                                     i % CTL_MAX_INIT_PER_PORT,
7779                                     res_desc->transport_id);
7780                         scsi_ulto4b(len, res_desc->additional_length);
7781                         res_desc = (struct scsi_per_res_in_full_desc *)
7782                             &res_desc->transport_id[len];
7783                 }
7784                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7785                     res_status->header.length);
7786                 break;
7787         }
7788         default:
7789                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7790         }
7791         mtx_unlock(&lun->lun_lock);
7792
7793         ctl_set_success(ctsio);
7794         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7795         ctsio->be_move_done = ctl_config_move_done;
7796         ctl_datamove((union ctl_io *)ctsio);
7797         return (CTL_RETVAL_COMPLETE);
7798 }
7799
7800 /*
7801  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7802  * it should return.
7803  */
7804 static int
7805 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7806                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7807                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7808                 struct scsi_per_res_out_parms* param)
7809 {
7810         union ctl_ha_msg persis_io;
7811         int i;
7812
7813         mtx_lock(&lun->lun_lock);
7814         if (sa_res_key == 0) {
7815                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7816                         /* validate scope and type */
7817                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7818                              SPR_LU_SCOPE) {
7819                                 mtx_unlock(&lun->lun_lock);
7820                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7821                                                       /*sks_valid*/ 1,
7822                                                       /*command*/ 1,
7823                                                       /*field*/ 2,
7824                                                       /*bit_valid*/ 1,
7825                                                       /*bit*/ 4);
7826                                 ctl_done((union ctl_io *)ctsio);
7827                                 return (1);
7828                         }
7829
7830                         if (type>8 || type==2 || type==4 || type==0) {
7831                                 mtx_unlock(&lun->lun_lock);
7832                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7833                                                       /*sks_valid*/ 1,
7834                                                       /*command*/ 1,
7835                                                       /*field*/ 2,
7836                                                       /*bit_valid*/ 1,
7837                                                       /*bit*/ 0);
7838                                 ctl_done((union ctl_io *)ctsio);
7839                                 return (1);
7840                         }
7841
7842                         /*
7843                          * Unregister everybody else and build UA for
7844                          * them
7845                          */
7846                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7847                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7848                                         continue;
7849
7850                                 ctl_clr_prkey(lun, i);
7851                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7852                         }
7853                         lun->pr_key_count = 1;
7854                         lun->pr_res_type = type;
7855                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7856                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7857                                 lun->pr_res_idx = residx;
7858                         lun->pr_generation++;
7859                         mtx_unlock(&lun->lun_lock);
7860
7861                         /* send msg to other side */
7862                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7863                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7864                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7865                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7866                         persis_io.pr.pr_info.res_type = type;
7867                         memcpy(persis_io.pr.pr_info.sa_res_key,
7868                                param->serv_act_res_key,
7869                                sizeof(param->serv_act_res_key));
7870                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7871                             sizeof(persis_io.pr), M_WAITOK);
7872                 } else {
7873                         /* not all registrants */
7874                         mtx_unlock(&lun->lun_lock);
7875                         free(ctsio->kern_data_ptr, M_CTL);
7876                         ctl_set_invalid_field(ctsio,
7877                                               /*sks_valid*/ 1,
7878                                               /*command*/ 0,
7879                                               /*field*/ 8,
7880                                               /*bit_valid*/ 0,
7881                                               /*bit*/ 0);
7882                         ctl_done((union ctl_io *)ctsio);
7883                         return (1);
7884                 }
7885         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7886                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7887                 int found = 0;
7888
7889                 if (res_key == sa_res_key) {
7890                         /* special case */
7891                         /*
7892                          * The spec implies this is not good but doesn't
7893                          * say what to do. There are two choices either
7894                          * generate a res conflict or check condition
7895                          * with illegal field in parameter data. Since
7896                          * that is what is done when the sa_res_key is
7897                          * zero I'll take that approach since this has
7898                          * to do with the sa_res_key.
7899                          */
7900                         mtx_unlock(&lun->lun_lock);
7901                         free(ctsio->kern_data_ptr, M_CTL);
7902                         ctl_set_invalid_field(ctsio,
7903                                               /*sks_valid*/ 1,
7904                                               /*command*/ 0,
7905                                               /*field*/ 8,
7906                                               /*bit_valid*/ 0,
7907                                               /*bit*/ 0);
7908                         ctl_done((union ctl_io *)ctsio);
7909                         return (1);
7910                 }
7911
7912                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7913                         if (ctl_get_prkey(lun, i) != sa_res_key)
7914                                 continue;
7915
7916                         found = 1;
7917                         ctl_clr_prkey(lun, i);
7918                         lun->pr_key_count--;
7919                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7920                 }
7921                 if (!found) {
7922                         mtx_unlock(&lun->lun_lock);
7923                         free(ctsio->kern_data_ptr, M_CTL);
7924                         ctl_set_reservation_conflict(ctsio);
7925                         ctl_done((union ctl_io *)ctsio);
7926                         return (CTL_RETVAL_COMPLETE);
7927                 }
7928                 lun->pr_generation++;
7929                 mtx_unlock(&lun->lun_lock);
7930
7931                 /* send msg to other side */
7932                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7933                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7934                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7935                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7936                 persis_io.pr.pr_info.res_type = type;
7937                 memcpy(persis_io.pr.pr_info.sa_res_key,
7938                        param->serv_act_res_key,
7939                        sizeof(param->serv_act_res_key));
7940                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7941                     sizeof(persis_io.pr), M_WAITOK);
7942         } else {
7943                 /* Reserved but not all registrants */
7944                 /* sa_res_key is res holder */
7945                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7946                         /* validate scope and type */
7947                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7948                              SPR_LU_SCOPE) {
7949                                 mtx_unlock(&lun->lun_lock);
7950                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7951                                                       /*sks_valid*/ 1,
7952                                                       /*command*/ 1,
7953                                                       /*field*/ 2,
7954                                                       /*bit_valid*/ 1,
7955                                                       /*bit*/ 4);
7956                                 ctl_done((union ctl_io *)ctsio);
7957                                 return (1);
7958                         }
7959
7960                         if (type>8 || type==2 || type==4 || type==0) {
7961                                 mtx_unlock(&lun->lun_lock);
7962                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7963                                                       /*sks_valid*/ 1,
7964                                                       /*command*/ 1,
7965                                                       /*field*/ 2,
7966                                                       /*bit_valid*/ 1,
7967                                                       /*bit*/ 0);
7968                                 ctl_done((union ctl_io *)ctsio);
7969                                 return (1);
7970                         }
7971
7972                         /*
7973                          * Do the following:
7974                          * if sa_res_key != res_key remove all
7975                          * registrants w/sa_res_key and generate UA
7976                          * for these registrants(Registrations
7977                          * Preempted) if it wasn't an exclusive
7978                          * reservation generate UA(Reservations
7979                          * Preempted) for all other registered nexuses
7980                          * if the type has changed. Establish the new
7981                          * reservation and holder. If res_key and
7982                          * sa_res_key are the same do the above
7983                          * except don't unregister the res holder.
7984                          */
7985
7986                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7987                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7988                                         continue;
7989
7990                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7991                                         ctl_clr_prkey(lun, i);
7992                                         lun->pr_key_count--;
7993                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7994                                 } else if (type != lun->pr_res_type &&
7995                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7996                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7997                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7998                                 }
7999                         }
8000                         lun->pr_res_type = type;
8001                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8002                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8003                                 lun->pr_res_idx = residx;
8004                         else
8005                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8006                         lun->pr_generation++;
8007                         mtx_unlock(&lun->lun_lock);
8008
8009                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8010                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8011                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8012                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8013                         persis_io.pr.pr_info.res_type = type;
8014                         memcpy(persis_io.pr.pr_info.sa_res_key,
8015                                param->serv_act_res_key,
8016                                sizeof(param->serv_act_res_key));
8017                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8018                             sizeof(persis_io.pr), M_WAITOK);
8019                 } else {
8020                         /*
8021                          * sa_res_key is not the res holder just
8022                          * remove registrants
8023                          */
8024                         int found=0;
8025
8026                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8027                                 if (sa_res_key != ctl_get_prkey(lun, i))
8028                                         continue;
8029
8030                                 found = 1;
8031                                 ctl_clr_prkey(lun, i);
8032                                 lun->pr_key_count--;
8033                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8034                         }
8035
8036                         if (!found) {
8037                                 mtx_unlock(&lun->lun_lock);
8038                                 free(ctsio->kern_data_ptr, M_CTL);
8039                                 ctl_set_reservation_conflict(ctsio);
8040                                 ctl_done((union ctl_io *)ctsio);
8041                                 return (1);
8042                         }
8043                         lun->pr_generation++;
8044                         mtx_unlock(&lun->lun_lock);
8045
8046                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8047                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8048                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8049                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8050                         persis_io.pr.pr_info.res_type = type;
8051                         memcpy(persis_io.pr.pr_info.sa_res_key,
8052                                param->serv_act_res_key,
8053                                sizeof(param->serv_act_res_key));
8054                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8055                             sizeof(persis_io.pr), M_WAITOK);
8056                 }
8057         }
8058         return (0);
8059 }
8060
8061 static void
8062 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8063 {
8064         uint64_t sa_res_key;
8065         int i;
8066
8067         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8068
8069         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8070          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8071          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8072                 if (sa_res_key == 0) {
8073                         /*
8074                          * Unregister everybody else and build UA for
8075                          * them
8076                          */
8077                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8078                                 if (i == msg->pr.pr_info.residx ||
8079                                     ctl_get_prkey(lun, i) == 0)
8080                                         continue;
8081
8082                                 ctl_clr_prkey(lun, i);
8083                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8084                         }
8085
8086                         lun->pr_key_count = 1;
8087                         lun->pr_res_type = msg->pr.pr_info.res_type;
8088                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8089                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8090                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8091                 } else {
8092                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8093                                 if (sa_res_key == ctl_get_prkey(lun, i))
8094                                         continue;
8095
8096                                 ctl_clr_prkey(lun, i);
8097                                 lun->pr_key_count--;
8098                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8099                         }
8100                 }
8101         } else {
8102                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8103                         if (i == msg->pr.pr_info.residx ||
8104                             ctl_get_prkey(lun, i) == 0)
8105                                 continue;
8106
8107                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8108                                 ctl_clr_prkey(lun, i);
8109                                 lun->pr_key_count--;
8110                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8111                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8112                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8113                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8114                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8115                         }
8116                 }
8117                 lun->pr_res_type = msg->pr.pr_info.res_type;
8118                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8119                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8120                         lun->pr_res_idx = msg->pr.pr_info.residx;
8121                 else
8122                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8123         }
8124         lun->pr_generation++;
8125
8126 }
8127
8128
8129 int
8130 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8131 {
8132         struct ctl_softc *softc = CTL_SOFTC(ctsio);
8133         struct ctl_lun *lun = CTL_LUN(ctsio);
8134         int retval;
8135         u_int32_t param_len;
8136         struct scsi_per_res_out *cdb;
8137         struct scsi_per_res_out_parms* param;
8138         uint32_t residx;
8139         uint64_t res_key, sa_res_key, key;
8140         uint8_t type;
8141         union ctl_ha_msg persis_io;
8142         int    i;
8143
8144         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8145
8146         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8147         retval = CTL_RETVAL_COMPLETE;
8148
8149         /*
8150          * We only support whole-LUN scope.  The scope & type are ignored for
8151          * register, register and ignore existing key and clear.
8152          * We sometimes ignore scope and type on preempts too!!
8153          * Verify reservation type here as well.
8154          */
8155         type = cdb->scope_type & SPR_TYPE_MASK;
8156         if ((cdb->action == SPRO_RESERVE)
8157          || (cdb->action == SPRO_RELEASE)) {
8158                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8159                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8160                                               /*sks_valid*/ 1,
8161                                               /*command*/ 1,
8162                                               /*field*/ 2,
8163                                               /*bit_valid*/ 1,
8164                                               /*bit*/ 4);
8165                         ctl_done((union ctl_io *)ctsio);
8166                         return (CTL_RETVAL_COMPLETE);
8167                 }
8168
8169                 if (type>8 || type==2 || type==4 || type==0) {
8170                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8171                                               /*sks_valid*/ 1,
8172                                               /*command*/ 1,
8173                                               /*field*/ 2,
8174                                               /*bit_valid*/ 1,
8175                                               /*bit*/ 0);
8176                         ctl_done((union ctl_io *)ctsio);
8177                         return (CTL_RETVAL_COMPLETE);
8178                 }
8179         }
8180
8181         param_len = scsi_4btoul(cdb->length);
8182
8183         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8184                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8185                 ctsio->kern_data_len = param_len;
8186                 ctsio->kern_total_len = param_len;
8187                 ctsio->kern_rel_offset = 0;
8188                 ctsio->kern_sg_entries = 0;
8189                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8190                 ctsio->be_move_done = ctl_config_move_done;
8191                 ctl_datamove((union ctl_io *)ctsio);
8192
8193                 return (CTL_RETVAL_COMPLETE);
8194         }
8195
8196         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8197
8198         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8199         res_key = scsi_8btou64(param->res_key.key);
8200         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8201
8202         /*
8203          * Validate the reservation key here except for SPRO_REG_IGNO
8204          * This must be done for all other service actions
8205          */
8206         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8207                 mtx_lock(&lun->lun_lock);
8208                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8209                         if (res_key != key) {
8210                                 /*
8211                                  * The current key passed in doesn't match
8212                                  * the one the initiator previously
8213                                  * registered.
8214                                  */
8215                                 mtx_unlock(&lun->lun_lock);
8216                                 free(ctsio->kern_data_ptr, M_CTL);
8217                                 ctl_set_reservation_conflict(ctsio);
8218                                 ctl_done((union ctl_io *)ctsio);
8219                                 return (CTL_RETVAL_COMPLETE);
8220                         }
8221                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8222                         /*
8223                          * We are not registered
8224                          */
8225                         mtx_unlock(&lun->lun_lock);
8226                         free(ctsio->kern_data_ptr, M_CTL);
8227                         ctl_set_reservation_conflict(ctsio);
8228                         ctl_done((union ctl_io *)ctsio);
8229                         return (CTL_RETVAL_COMPLETE);
8230                 } else if (res_key != 0) {
8231                         /*
8232                          * We are not registered and trying to register but
8233                          * the register key isn't zero.
8234                          */
8235                         mtx_unlock(&lun->lun_lock);
8236                         free(ctsio->kern_data_ptr, M_CTL);
8237                         ctl_set_reservation_conflict(ctsio);
8238                         ctl_done((union ctl_io *)ctsio);
8239                         return (CTL_RETVAL_COMPLETE);
8240                 }
8241                 mtx_unlock(&lun->lun_lock);
8242         }
8243
8244         switch (cdb->action & SPRO_ACTION_MASK) {
8245         case SPRO_REGISTER:
8246         case SPRO_REG_IGNO: {
8247
8248 #if 0
8249                 printf("Registration received\n");
8250 #endif
8251
8252                 /*
8253                  * We don't support any of these options, as we report in
8254                  * the read capabilities request (see
8255                  * ctl_persistent_reserve_in(), above).
8256                  */
8257                 if ((param->flags & SPR_SPEC_I_PT)
8258                  || (param->flags & SPR_ALL_TG_PT)
8259                  || (param->flags & SPR_APTPL)) {
8260                         int bit_ptr;
8261
8262                         if (param->flags & SPR_APTPL)
8263                                 bit_ptr = 0;
8264                         else if (param->flags & SPR_ALL_TG_PT)
8265                                 bit_ptr = 2;
8266                         else /* SPR_SPEC_I_PT */
8267                                 bit_ptr = 3;
8268
8269                         free(ctsio->kern_data_ptr, M_CTL);
8270                         ctl_set_invalid_field(ctsio,
8271                                               /*sks_valid*/ 1,
8272                                               /*command*/ 0,
8273                                               /*field*/ 20,
8274                                               /*bit_valid*/ 1,
8275                                               /*bit*/ bit_ptr);
8276                         ctl_done((union ctl_io *)ctsio);
8277                         return (CTL_RETVAL_COMPLETE);
8278                 }
8279
8280                 mtx_lock(&lun->lun_lock);
8281
8282                 /*
8283                  * The initiator wants to clear the
8284                  * key/unregister.
8285                  */
8286                 if (sa_res_key == 0) {
8287                         if ((res_key == 0
8288                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8289                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8290                           && ctl_get_prkey(lun, residx) == 0)) {
8291                                 mtx_unlock(&lun->lun_lock);
8292                                 goto done;
8293                         }
8294
8295                         ctl_clr_prkey(lun, residx);
8296                         lun->pr_key_count--;
8297
8298                         if (residx == lun->pr_res_idx) {
8299                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8300                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8301
8302                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8303                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8304                                     lun->pr_key_count) {
8305                                         /*
8306                                          * If the reservation is a registrants
8307                                          * only type we need to generate a UA
8308                                          * for other registered inits.  The
8309                                          * sense code should be RESERVATIONS
8310                                          * RELEASED
8311                                          */
8312
8313                                         for (i = softc->init_min; i < softc->init_max; i++){
8314                                                 if (ctl_get_prkey(lun, i) == 0)
8315                                                         continue;
8316                                                 ctl_est_ua(lun, i,
8317                                                     CTL_UA_RES_RELEASE);
8318                                         }
8319                                 }
8320                                 lun->pr_res_type = 0;
8321                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8322                                 if (lun->pr_key_count==0) {
8323                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8324                                         lun->pr_res_type = 0;
8325                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8326                                 }
8327                         }
8328                         lun->pr_generation++;
8329                         mtx_unlock(&lun->lun_lock);
8330
8331                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8332                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8333                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8334                         persis_io.pr.pr_info.residx = residx;
8335                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8336                             sizeof(persis_io.pr), M_WAITOK);
8337                 } else /* sa_res_key != 0 */ {
8338
8339                         /*
8340                          * If we aren't registered currently then increment
8341                          * the key count and set the registered flag.
8342                          */
8343                         ctl_alloc_prkey(lun, residx);
8344                         if (ctl_get_prkey(lun, residx) == 0)
8345                                 lun->pr_key_count++;
8346                         ctl_set_prkey(lun, residx, sa_res_key);
8347                         lun->pr_generation++;
8348                         mtx_unlock(&lun->lun_lock);
8349
8350                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8351                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8352                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8353                         persis_io.pr.pr_info.residx = residx;
8354                         memcpy(persis_io.pr.pr_info.sa_res_key,
8355                                param->serv_act_res_key,
8356                                sizeof(param->serv_act_res_key));
8357                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8358                             sizeof(persis_io.pr), M_WAITOK);
8359                 }
8360
8361                 break;
8362         }
8363         case SPRO_RESERVE:
8364 #if 0
8365                 printf("Reserve executed type %d\n", type);
8366 #endif
8367                 mtx_lock(&lun->lun_lock);
8368                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8369                         /*
8370                          * if this isn't the reservation holder and it's
8371                          * not a "all registrants" type or if the type is
8372                          * different then we have a conflict
8373                          */
8374                         if ((lun->pr_res_idx != residx
8375                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8376                          || lun->pr_res_type != type) {
8377                                 mtx_unlock(&lun->lun_lock);
8378                                 free(ctsio->kern_data_ptr, M_CTL);
8379                                 ctl_set_reservation_conflict(ctsio);
8380                                 ctl_done((union ctl_io *)ctsio);
8381                                 return (CTL_RETVAL_COMPLETE);
8382                         }
8383                         mtx_unlock(&lun->lun_lock);
8384                 } else /* create a reservation */ {
8385                         /*
8386                          * If it's not an "all registrants" type record
8387                          * reservation holder
8388                          */
8389                         if (type != SPR_TYPE_WR_EX_AR
8390                          && type != SPR_TYPE_EX_AC_AR)
8391                                 lun->pr_res_idx = residx; /* Res holder */
8392                         else
8393                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8394
8395                         lun->flags |= CTL_LUN_PR_RESERVED;
8396                         lun->pr_res_type = type;
8397
8398                         mtx_unlock(&lun->lun_lock);
8399
8400                         /* send msg to other side */
8401                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8402                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8403                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8404                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8405                         persis_io.pr.pr_info.res_type = type;
8406                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8407                             sizeof(persis_io.pr), M_WAITOK);
8408                 }
8409                 break;
8410
8411         case SPRO_RELEASE:
8412                 mtx_lock(&lun->lun_lock);
8413                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8414                         /* No reservation exists return good status */
8415                         mtx_unlock(&lun->lun_lock);
8416                         goto done;
8417                 }
8418                 /*
8419                  * Is this nexus a reservation holder?
8420                  */
8421                 if (lun->pr_res_idx != residx
8422                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8423                         /*
8424                          * not a res holder return good status but
8425                          * do nothing
8426                          */
8427                         mtx_unlock(&lun->lun_lock);
8428                         goto done;
8429                 }
8430
8431                 if (lun->pr_res_type != type) {
8432                         mtx_unlock(&lun->lun_lock);
8433                         free(ctsio->kern_data_ptr, M_CTL);
8434                         ctl_set_illegal_pr_release(ctsio);
8435                         ctl_done((union ctl_io *)ctsio);
8436                         return (CTL_RETVAL_COMPLETE);
8437                 }
8438
8439                 /* okay to release */
8440                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8441                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8442                 lun->pr_res_type = 0;
8443
8444                 /*
8445                  * If this isn't an exclusive access reservation and NUAR
8446                  * is not set, generate UA for all other registrants.
8447                  */
8448                 if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8449                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8450                         for (i = softc->init_min; i < softc->init_max; i++) {
8451                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8452                                         continue;
8453                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8454                         }
8455                 }
8456                 mtx_unlock(&lun->lun_lock);
8457
8458                 /* Send msg to other side */
8459                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8460                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8461                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8462                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8463                      sizeof(persis_io.pr), M_WAITOK);
8464                 break;
8465
8466         case SPRO_CLEAR:
8467                 /* send msg to other side */
8468
8469                 mtx_lock(&lun->lun_lock);
8470                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8471                 lun->pr_res_type = 0;
8472                 lun->pr_key_count = 0;
8473                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8474
8475                 ctl_clr_prkey(lun, residx);
8476                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8477                         if (ctl_get_prkey(lun, i) != 0) {
8478                                 ctl_clr_prkey(lun, i);
8479                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8480                         }
8481                 lun->pr_generation++;
8482                 mtx_unlock(&lun->lun_lock);
8483
8484                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8485                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8486                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8487                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8488                      sizeof(persis_io.pr), M_WAITOK);
8489                 break;
8490
8491         case SPRO_PREEMPT:
8492         case SPRO_PRE_ABO: {
8493                 int nretval;
8494
8495                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8496                                           residx, ctsio, cdb, param);
8497                 if (nretval != 0)
8498                         return (CTL_RETVAL_COMPLETE);
8499                 break;
8500         }
8501         default:
8502                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8503         }
8504
8505 done:
8506         free(ctsio->kern_data_ptr, M_CTL);
8507         ctl_set_success(ctsio);
8508         ctl_done((union ctl_io *)ctsio);
8509
8510         return (retval);
8511 }
8512
8513 /*
8514  * This routine is for handling a message from the other SC pertaining to
8515  * persistent reserve out. All the error checking will have been done
8516  * so only perorming the action need be done here to keep the two
8517  * in sync.
8518  */
8519 static void
8520 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8521 {
8522         struct ctl_softc *softc = CTL_SOFTC(io);
8523         union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8524         struct ctl_lun *lun;
8525         int i;
8526         uint32_t residx, targ_lun;
8527
8528         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8529         mtx_lock(&softc->ctl_lock);
8530         if (targ_lun >= ctl_max_luns ||
8531             (lun = softc->ctl_luns[targ_lun]) == NULL) {
8532                 mtx_unlock(&softc->ctl_lock);
8533                 return;
8534         }
8535         mtx_lock(&lun->lun_lock);
8536         mtx_unlock(&softc->ctl_lock);
8537         if (lun->flags & CTL_LUN_DISABLED) {
8538                 mtx_unlock(&lun->lun_lock);
8539                 return;
8540         }
8541         residx = ctl_get_initindex(&msg->hdr.nexus);
8542         switch(msg->pr.pr_info.action) {
8543         case CTL_PR_REG_KEY:
8544                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8545                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8546                         lun->pr_key_count++;
8547                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8548                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8549                 lun->pr_generation++;
8550                 break;
8551
8552         case CTL_PR_UNREG_KEY:
8553                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8554                 lun->pr_key_count--;
8555
8556                 /* XXX Need to see if the reservation has been released */
8557                 /* if so do we need to generate UA? */
8558                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8559                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8560                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8561
8562                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8563                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8564                             lun->pr_key_count) {
8565                                 /*
8566                                  * If the reservation is a registrants
8567                                  * only type we need to generate a UA
8568                                  * for other registered inits.  The
8569                                  * sense code should be RESERVATIONS
8570                                  * RELEASED
8571                                  */
8572
8573                                 for (i = softc->init_min; i < softc->init_max; i++) {
8574                                         if (ctl_get_prkey(lun, i) == 0)
8575                                                 continue;
8576
8577                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8578                                 }
8579                         }
8580                         lun->pr_res_type = 0;
8581                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8582                         if (lun->pr_key_count==0) {
8583                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8584                                 lun->pr_res_type = 0;
8585                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8586                         }
8587                 }
8588                 lun->pr_generation++;
8589                 break;
8590
8591         case CTL_PR_RESERVE:
8592                 lun->flags |= CTL_LUN_PR_RESERVED;
8593                 lun->pr_res_type = msg->pr.pr_info.res_type;
8594                 lun->pr_res_idx = msg->pr.pr_info.residx;
8595
8596                 break;
8597
8598         case CTL_PR_RELEASE:
8599                 /*
8600                  * If this isn't an exclusive access reservation and NUAR
8601                  * is not set, generate UA for all other registrants.
8602                  */
8603                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8604                     lun->pr_res_type != SPR_TYPE_WR_EX &&
8605                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8606                         for (i = softc->init_min; i < softc->init_max; i++) {
8607                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8608                                         continue;
8609                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8610                         }
8611                 }
8612
8613                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8614                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8615                 lun->pr_res_type = 0;
8616                 break;
8617
8618         case CTL_PR_PREEMPT:
8619                 ctl_pro_preempt_other(lun, msg);
8620                 break;
8621         case CTL_PR_CLEAR:
8622                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8623                 lun->pr_res_type = 0;
8624                 lun->pr_key_count = 0;
8625                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8626
8627                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8628                         if (ctl_get_prkey(lun, i) == 0)
8629                                 continue;
8630                         ctl_clr_prkey(lun, i);
8631                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8632                 }
8633                 lun->pr_generation++;
8634                 break;
8635         }
8636
8637         mtx_unlock(&lun->lun_lock);
8638 }
8639
8640 int
8641 ctl_read_write(struct ctl_scsiio *ctsio)
8642 {
8643         struct ctl_lun *lun = CTL_LUN(ctsio);
8644         struct ctl_lba_len_flags *lbalen;
8645         uint64_t lba;
8646         uint32_t num_blocks;
8647         int flags, retval;
8648         int isread;
8649
8650         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8651
8652         flags = 0;
8653         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8654               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8655         switch (ctsio->cdb[0]) {
8656         case READ_6:
8657         case WRITE_6: {
8658                 struct scsi_rw_6 *cdb;
8659
8660                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8661
8662                 lba = scsi_3btoul(cdb->addr);
8663                 /* only 5 bits are valid in the most significant address byte */
8664                 lba &= 0x1fffff;
8665                 num_blocks = cdb->length;
8666                 /*
8667                  * This is correct according to SBC-2.
8668                  */
8669                 if (num_blocks == 0)
8670                         num_blocks = 256;
8671                 break;
8672         }
8673         case READ_10:
8674         case WRITE_10: {
8675                 struct scsi_rw_10 *cdb;
8676
8677                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8678                 if (cdb->byte2 & SRW10_FUA)
8679                         flags |= CTL_LLF_FUA;
8680                 if (cdb->byte2 & SRW10_DPO)
8681                         flags |= CTL_LLF_DPO;
8682                 lba = scsi_4btoul(cdb->addr);
8683                 num_blocks = scsi_2btoul(cdb->length);
8684                 break;
8685         }
8686         case WRITE_VERIFY_10: {
8687                 struct scsi_write_verify_10 *cdb;
8688
8689                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8690                 flags |= CTL_LLF_FUA;
8691                 if (cdb->byte2 & SWV_DPO)
8692                         flags |= CTL_LLF_DPO;
8693                 lba = scsi_4btoul(cdb->addr);
8694                 num_blocks = scsi_2btoul(cdb->length);
8695                 break;
8696         }
8697         case READ_12:
8698         case WRITE_12: {
8699                 struct scsi_rw_12 *cdb;
8700
8701                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8702                 if (cdb->byte2 & SRW12_FUA)
8703                         flags |= CTL_LLF_FUA;
8704                 if (cdb->byte2 & SRW12_DPO)
8705                         flags |= CTL_LLF_DPO;
8706                 lba = scsi_4btoul(cdb->addr);
8707                 num_blocks = scsi_4btoul(cdb->length);
8708                 break;
8709         }
8710         case WRITE_VERIFY_12: {
8711                 struct scsi_write_verify_12 *cdb;
8712
8713                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8714                 flags |= CTL_LLF_FUA;
8715                 if (cdb->byte2 & SWV_DPO)
8716                         flags |= CTL_LLF_DPO;
8717                 lba = scsi_4btoul(cdb->addr);
8718                 num_blocks = scsi_4btoul(cdb->length);
8719                 break;
8720         }
8721         case READ_16:
8722         case WRITE_16: {
8723                 struct scsi_rw_16 *cdb;
8724
8725                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8726                 if (cdb->byte2 & SRW12_FUA)
8727                         flags |= CTL_LLF_FUA;
8728                 if (cdb->byte2 & SRW12_DPO)
8729                         flags |= CTL_LLF_DPO;
8730                 lba = scsi_8btou64(cdb->addr);
8731                 num_blocks = scsi_4btoul(cdb->length);
8732                 break;
8733         }
8734         case WRITE_ATOMIC_16: {
8735                 struct scsi_write_atomic_16 *cdb;
8736
8737                 if (lun->be_lun->atomicblock == 0) {
8738                         ctl_set_invalid_opcode(ctsio);
8739                         ctl_done((union ctl_io *)ctsio);
8740                         return (CTL_RETVAL_COMPLETE);
8741                 }
8742
8743                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8744                 if (cdb->byte2 & SRW12_FUA)
8745                         flags |= CTL_LLF_FUA;
8746                 if (cdb->byte2 & SRW12_DPO)
8747                         flags |= CTL_LLF_DPO;
8748                 lba = scsi_8btou64(cdb->addr);
8749                 num_blocks = scsi_2btoul(cdb->length);
8750                 if (num_blocks > lun->be_lun->atomicblock) {
8751                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8752                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8753                             /*bit*/ 0);
8754                         ctl_done((union ctl_io *)ctsio);
8755                         return (CTL_RETVAL_COMPLETE);
8756                 }
8757                 break;
8758         }
8759         case WRITE_VERIFY_16: {
8760                 struct scsi_write_verify_16 *cdb;
8761
8762                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8763                 flags |= CTL_LLF_FUA;
8764                 if (cdb->byte2 & SWV_DPO)
8765                         flags |= CTL_LLF_DPO;
8766                 lba = scsi_8btou64(cdb->addr);
8767                 num_blocks = scsi_4btoul(cdb->length);
8768                 break;
8769         }
8770         default:
8771                 /*
8772                  * We got a command we don't support.  This shouldn't
8773                  * happen, commands should be filtered out above us.
8774                  */
8775                 ctl_set_invalid_opcode(ctsio);
8776                 ctl_done((union ctl_io *)ctsio);
8777
8778                 return (CTL_RETVAL_COMPLETE);
8779                 break; /* NOTREACHED */
8780         }
8781
8782         /*
8783          * The first check is to make sure we're in bounds, the second
8784          * check is to catch wrap-around problems.  If the lba + num blocks
8785          * is less than the lba, then we've wrapped around and the block
8786          * range is invalid anyway.
8787          */
8788         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8789          || ((lba + num_blocks) < lba)) {
8790                 ctl_set_lba_out_of_range(ctsio,
8791                     MAX(lba, lun->be_lun->maxlba + 1));
8792                 ctl_done((union ctl_io *)ctsio);
8793                 return (CTL_RETVAL_COMPLETE);
8794         }
8795
8796         /*
8797          * According to SBC-3, a transfer length of 0 is not an error.
8798          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8799          * translates to 256 blocks for those commands.
8800          */
8801         if (num_blocks == 0) {
8802                 ctl_set_success(ctsio);
8803                 ctl_done((union ctl_io *)ctsio);
8804                 return (CTL_RETVAL_COMPLETE);
8805         }
8806
8807         /* Set FUA and/or DPO if caches are disabled. */
8808         if (isread) {
8809                 if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8810                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8811         } else {
8812                 if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8813                         flags |= CTL_LLF_FUA;
8814         }
8815
8816         lbalen = (struct ctl_lba_len_flags *)
8817             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8818         lbalen->lba = lba;
8819         lbalen->len = num_blocks;
8820         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8821
8822         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8823         ctsio->kern_rel_offset = 0;
8824
8825         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8826
8827         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8828         return (retval);
8829 }
8830
8831 static int
8832 ctl_cnw_cont(union ctl_io *io)
8833 {
8834         struct ctl_lun *lun = CTL_LUN(io);
8835         struct ctl_scsiio *ctsio;
8836         struct ctl_lba_len_flags *lbalen;
8837         int retval;
8838
8839         ctsio = &io->scsiio;
8840         ctsio->io_hdr.status = CTL_STATUS_NONE;
8841         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8842         lbalen = (struct ctl_lba_len_flags *)
8843             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8844         lbalen->flags &= ~CTL_LLF_COMPARE;
8845         lbalen->flags |= CTL_LLF_WRITE;
8846
8847         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8848         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8849         return (retval);
8850 }
8851
8852 int
8853 ctl_cnw(struct ctl_scsiio *ctsio)
8854 {
8855         struct ctl_lun *lun = CTL_LUN(ctsio);
8856         struct ctl_lba_len_flags *lbalen;
8857         uint64_t lba;
8858         uint32_t num_blocks;
8859         int flags, retval;
8860
8861         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8862
8863         flags = 0;
8864         switch (ctsio->cdb[0]) {
8865         case COMPARE_AND_WRITE: {
8866                 struct scsi_compare_and_write *cdb;
8867
8868                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8869                 if (cdb->byte2 & SRW10_FUA)
8870                         flags |= CTL_LLF_FUA;
8871                 if (cdb->byte2 & SRW10_DPO)
8872                         flags |= CTL_LLF_DPO;
8873                 lba = scsi_8btou64(cdb->addr);
8874                 num_blocks = cdb->length;
8875                 break;
8876         }
8877         default:
8878                 /*
8879                  * We got a command we don't support.  This shouldn't
8880                  * happen, commands should be filtered out above us.
8881                  */
8882                 ctl_set_invalid_opcode(ctsio);
8883                 ctl_done((union ctl_io *)ctsio);
8884
8885                 return (CTL_RETVAL_COMPLETE);
8886                 break; /* NOTREACHED */
8887         }
8888
8889         /*
8890          * The first check is to make sure we're in bounds, the second
8891          * check is to catch wrap-around problems.  If the lba + num blocks
8892          * is less than the lba, then we've wrapped around and the block
8893          * range is invalid anyway.
8894          */
8895         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8896          || ((lba + num_blocks) < lba)) {
8897                 ctl_set_lba_out_of_range(ctsio,
8898                     MAX(lba, lun->be_lun->maxlba + 1));
8899                 ctl_done((union ctl_io *)ctsio);
8900                 return (CTL_RETVAL_COMPLETE);
8901         }
8902
8903         /*
8904          * According to SBC-3, a transfer length of 0 is not an error.
8905          */
8906         if (num_blocks == 0) {
8907                 ctl_set_success(ctsio);
8908                 ctl_done((union ctl_io *)ctsio);
8909                 return (CTL_RETVAL_COMPLETE);
8910         }
8911
8912         /* Set FUA if write cache is disabled. */
8913         if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8914                 flags |= CTL_LLF_FUA;
8915
8916         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8917         ctsio->kern_rel_offset = 0;
8918
8919         /*
8920          * Set the IO_CONT flag, so that if this I/O gets passed to
8921          * ctl_data_submit_done(), it'll get passed back to
8922          * ctl_ctl_cnw_cont() for further processing.
8923          */
8924         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8925         ctsio->io_cont = ctl_cnw_cont;
8926
8927         lbalen = (struct ctl_lba_len_flags *)
8928             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8929         lbalen->lba = lba;
8930         lbalen->len = num_blocks;
8931         lbalen->flags = CTL_LLF_COMPARE | flags;
8932
8933         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8934         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8935         return (retval);
8936 }
8937
8938 int
8939 ctl_verify(struct ctl_scsiio *ctsio)
8940 {
8941         struct ctl_lun *lun = CTL_LUN(ctsio);
8942         struct ctl_lba_len_flags *lbalen;
8943         uint64_t lba;
8944         uint32_t num_blocks;
8945         int bytchk, flags;
8946         int retval;
8947
8948         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8949
8950         bytchk = 0;
8951         flags = CTL_LLF_FUA;
8952         switch (ctsio->cdb[0]) {
8953         case VERIFY_10: {
8954                 struct scsi_verify_10 *cdb;
8955
8956                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8957                 if (cdb->byte2 & SVFY_BYTCHK)
8958                         bytchk = 1;
8959                 if (cdb->byte2 & SVFY_DPO)
8960                         flags |= CTL_LLF_DPO;
8961                 lba = scsi_4btoul(cdb->addr);
8962                 num_blocks = scsi_2btoul(cdb->length);
8963                 break;
8964         }
8965         case VERIFY_12: {
8966                 struct scsi_verify_12 *cdb;
8967
8968                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8969                 if (cdb->byte2 & SVFY_BYTCHK)
8970                         bytchk = 1;
8971                 if (cdb->byte2 & SVFY_DPO)
8972                         flags |= CTL_LLF_DPO;
8973                 lba = scsi_4btoul(cdb->addr);
8974                 num_blocks = scsi_4btoul(cdb->length);
8975                 break;
8976         }
8977         case VERIFY_16: {
8978                 struct scsi_rw_16 *cdb;
8979
8980                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8981                 if (cdb->byte2 & SVFY_BYTCHK)
8982                         bytchk = 1;
8983                 if (cdb->byte2 & SVFY_DPO)
8984                         flags |= CTL_LLF_DPO;
8985                 lba = scsi_8btou64(cdb->addr);
8986                 num_blocks = scsi_4btoul(cdb->length);
8987                 break;
8988         }
8989         default:
8990                 /*
8991                  * We got a command we don't support.  This shouldn't
8992                  * happen, commands should be filtered out above us.
8993                  */
8994                 ctl_set_invalid_opcode(ctsio);
8995                 ctl_done((union ctl_io *)ctsio);
8996                 return (CTL_RETVAL_COMPLETE);
8997         }
8998
8999         /*
9000          * The first check is to make sure we're in bounds, the second
9001          * check is to catch wrap-around problems.  If the lba + num blocks
9002          * is less than the lba, then we've wrapped around and the block
9003          * range is invalid anyway.
9004          */
9005         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9006          || ((lba + num_blocks) < lba)) {
9007                 ctl_set_lba_out_of_range(ctsio,
9008                     MAX(lba, lun->be_lun->maxlba + 1));
9009                 ctl_done((union ctl_io *)ctsio);
9010                 return (CTL_RETVAL_COMPLETE);
9011         }
9012
9013         /*
9014          * According to SBC-3, a transfer length of 0 is not an error.
9015          */
9016         if (num_blocks == 0) {
9017                 ctl_set_success(ctsio);
9018                 ctl_done((union ctl_io *)ctsio);
9019                 return (CTL_RETVAL_COMPLETE);
9020         }
9021
9022         lbalen = (struct ctl_lba_len_flags *)
9023             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9024         lbalen->lba = lba;
9025         lbalen->len = num_blocks;
9026         if (bytchk) {
9027                 lbalen->flags = CTL_LLF_COMPARE | flags;
9028                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9029         } else {
9030                 lbalen->flags = CTL_LLF_VERIFY | flags;
9031                 ctsio->kern_total_len = 0;
9032         }
9033         ctsio->kern_rel_offset = 0;
9034
9035         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9036         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9037         return (retval);
9038 }
9039
9040 int
9041 ctl_report_luns(struct ctl_scsiio *ctsio)
9042 {
9043         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9044         struct ctl_port *port = CTL_PORT(ctsio);
9045         struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9046         struct scsi_report_luns *cdb;
9047         struct scsi_report_luns_data *lun_data;
9048         int num_filled, num_luns, num_port_luns, retval;
9049         uint32_t alloc_len, lun_datalen;
9050         uint32_t initidx, targ_lun_id, lun_id;
9051
9052         retval = CTL_RETVAL_COMPLETE;
9053         cdb = (struct scsi_report_luns *)ctsio->cdb;
9054
9055         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9056
9057         num_luns = 0;
9058         num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9059         mtx_lock(&softc->ctl_lock);
9060         for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9061                 if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9062                         num_luns++;
9063         }
9064         mtx_unlock(&softc->ctl_lock);
9065
9066         switch (cdb->select_report) {
9067         case RPL_REPORT_DEFAULT:
9068         case RPL_REPORT_ALL:
9069         case RPL_REPORT_NONSUBSID:
9070                 break;
9071         case RPL_REPORT_WELLKNOWN:
9072         case RPL_REPORT_ADMIN:
9073         case RPL_REPORT_CONGLOM:
9074                 num_luns = 0;
9075                 break;
9076         default:
9077                 ctl_set_invalid_field(ctsio,
9078                                       /*sks_valid*/ 1,
9079                                       /*command*/ 1,
9080                                       /*field*/ 2,
9081                                       /*bit_valid*/ 0,
9082                                       /*bit*/ 0);
9083                 ctl_done((union ctl_io *)ctsio);
9084                 return (retval);
9085                 break; /* NOTREACHED */
9086         }
9087
9088         alloc_len = scsi_4btoul(cdb->length);
9089         /*
9090          * The initiator has to allocate at least 16 bytes for this request,
9091          * so he can at least get the header and the first LUN.  Otherwise
9092          * we reject the request (per SPC-3 rev 14, section 6.21).
9093          */
9094         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9095             sizeof(struct scsi_report_luns_lundata))) {
9096                 ctl_set_invalid_field(ctsio,
9097                                       /*sks_valid*/ 1,
9098                                       /*command*/ 1,
9099                                       /*field*/ 6,
9100                                       /*bit_valid*/ 0,
9101                                       /*bit*/ 0);
9102                 ctl_done((union ctl_io *)ctsio);
9103                 return (retval);
9104         }
9105
9106         lun_datalen = sizeof(*lun_data) +
9107                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9108
9109         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9110         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9111         ctsio->kern_sg_entries = 0;
9112
9113         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9114
9115         mtx_lock(&softc->ctl_lock);
9116         for (targ_lun_id = 0, num_filled = 0;
9117             targ_lun_id < num_port_luns && num_filled < num_luns;
9118             targ_lun_id++) {
9119                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9120                 if (lun_id == UINT32_MAX)
9121                         continue;
9122                 lun = softc->ctl_luns[lun_id];
9123                 if (lun == NULL)
9124                         continue;
9125
9126                 be64enc(lun_data->luns[num_filled++].lundata,
9127                     ctl_encode_lun(targ_lun_id));
9128
9129                 /*
9130                  * According to SPC-3, rev 14 section 6.21:
9131                  *
9132                  * "The execution of a REPORT LUNS command to any valid and
9133                  * installed logical unit shall clear the REPORTED LUNS DATA
9134                  * HAS CHANGED unit attention condition for all logical
9135                  * units of that target with respect to the requesting
9136                  * initiator. A valid and installed logical unit is one
9137                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9138                  * INQUIRY data (see 6.4.2)."
9139                  *
9140                  * If request_lun is NULL, the LUN this report luns command
9141                  * was issued to is either disabled or doesn't exist. In that
9142                  * case, we shouldn't clear any pending lun change unit
9143                  * attention.
9144                  */
9145                 if (request_lun != NULL) {
9146                         mtx_lock(&lun->lun_lock);
9147                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9148                         mtx_unlock(&lun->lun_lock);
9149                 }
9150         }
9151         mtx_unlock(&softc->ctl_lock);
9152
9153         /*
9154          * It's quite possible that we've returned fewer LUNs than we allocated
9155          * space for.  Trim it.
9156          */
9157         lun_datalen = sizeof(*lun_data) +
9158                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9159         ctsio->kern_rel_offset = 0;
9160         ctsio->kern_sg_entries = 0;
9161         ctsio->kern_data_len = min(lun_datalen, alloc_len);
9162         ctsio->kern_total_len = ctsio->kern_data_len;
9163
9164         /*
9165          * We set this to the actual data length, regardless of how much
9166          * space we actually have to return results.  If the user looks at
9167          * this value, he'll know whether or not he allocated enough space
9168          * and reissue the command if necessary.  We don't support well
9169          * known logical units, so if the user asks for that, return none.
9170          */
9171         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9172
9173         /*
9174          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9175          * this request.
9176          */
9177         ctl_set_success(ctsio);
9178         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9179         ctsio->be_move_done = ctl_config_move_done;
9180         ctl_datamove((union ctl_io *)ctsio);
9181         return (retval);
9182 }
9183
9184 int
9185 ctl_request_sense(struct ctl_scsiio *ctsio)
9186 {
9187         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9188         struct ctl_lun *lun = CTL_LUN(ctsio);
9189         struct scsi_request_sense *cdb;
9190         struct scsi_sense_data *sense_ptr, *ps;
9191         uint32_t initidx;
9192         int have_error;
9193         u_int sense_len = SSD_FULL_SIZE;
9194         scsi_sense_data_type sense_format;
9195         ctl_ua_type ua_type;
9196         uint8_t asc = 0, ascq = 0;
9197
9198         cdb = (struct scsi_request_sense *)ctsio->cdb;
9199
9200         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9201
9202         /*
9203          * Determine which sense format the user wants.
9204          */
9205         if (cdb->byte2 & SRS_DESC)
9206                 sense_format = SSD_TYPE_DESC;
9207         else
9208                 sense_format = SSD_TYPE_FIXED;
9209
9210         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9211         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9212         ctsio->kern_sg_entries = 0;
9213         ctsio->kern_rel_offset = 0;
9214
9215         /*
9216          * struct scsi_sense_data, which is currently set to 256 bytes, is
9217          * larger than the largest allowed value for the length field in the
9218          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9219          */
9220         ctsio->kern_data_len = cdb->length;
9221         ctsio->kern_total_len = cdb->length;
9222
9223         /*
9224          * If we don't have a LUN, we don't have any pending sense.
9225          */
9226         if (lun == NULL ||
9227             ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9228              softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9229                 /* "Logical unit not supported" */
9230                 ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9231                     /*current_error*/ 1,
9232                     /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9233                     /*asc*/ 0x25,
9234                     /*ascq*/ 0x00,
9235                     SSD_ELEM_NONE);
9236                 goto send;
9237         }
9238
9239         have_error = 0;
9240         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9241         /*
9242          * Check for pending sense, and then for pending unit attentions.
9243          * Pending sense gets returned first, then pending unit attentions.
9244          */
9245         mtx_lock(&lun->lun_lock);
9246         ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9247         if (ps != NULL)
9248                 ps += initidx % CTL_MAX_INIT_PER_PORT;
9249         if (ps != NULL && ps->error_code != 0) {
9250                 scsi_sense_data_type stored_format;
9251
9252                 /*
9253                  * Check to see which sense format was used for the stored
9254                  * sense data.
9255                  */
9256                 stored_format = scsi_sense_type(ps);
9257
9258                 /*
9259                  * If the user requested a different sense format than the
9260                  * one we stored, then we need to convert it to the other
9261                  * format.  If we're going from descriptor to fixed format
9262                  * sense data, we may lose things in translation, depending
9263                  * on what options were used.
9264                  *
9265                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9266                  * for some reason we'll just copy it out as-is.
9267                  */
9268                 if ((stored_format == SSD_TYPE_FIXED)
9269                  && (sense_format == SSD_TYPE_DESC))
9270                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9271                             ps, (struct scsi_sense_data_desc *)sense_ptr);
9272                 else if ((stored_format == SSD_TYPE_DESC)
9273                       && (sense_format == SSD_TYPE_FIXED))
9274                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9275                             ps, (struct scsi_sense_data_fixed *)sense_ptr);
9276                 else
9277                         memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9278
9279                 ps->error_code = 0;
9280                 have_error = 1;
9281         } else {
9282                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9283                     sense_format);
9284                 if (ua_type != CTL_UA_NONE)
9285                         have_error = 1;
9286         }
9287         if (have_error == 0) {
9288                 /*
9289                  * Report informational exception if have one and allowed.
9290                  */
9291                 if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9292                         asc = lun->ie_asc;
9293                         ascq = lun->ie_ascq;
9294                 }
9295                 ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9296                     /*current_error*/ 1,
9297                     /*sense_key*/ SSD_KEY_NO_SENSE,
9298                     /*asc*/ asc,
9299                     /*ascq*/ ascq,
9300                     SSD_ELEM_NONE);
9301         }
9302         mtx_unlock(&lun->lun_lock);
9303
9304 send:
9305         /*
9306          * We report the SCSI status as OK, since the status of the command
9307          * itself is OK.  We're reporting sense as parameter data.
9308          */
9309         ctl_set_success(ctsio);
9310         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9311         ctsio->be_move_done = ctl_config_move_done;
9312         ctl_datamove((union ctl_io *)ctsio);
9313         return (CTL_RETVAL_COMPLETE);
9314 }
9315
9316 int
9317 ctl_tur(struct ctl_scsiio *ctsio)
9318 {
9319
9320         CTL_DEBUG_PRINT(("ctl_tur\n"));
9321
9322         ctl_set_success(ctsio);
9323         ctl_done((union ctl_io *)ctsio);
9324
9325         return (CTL_RETVAL_COMPLETE);
9326 }
9327
9328 /*
9329  * SCSI VPD page 0x00, the Supported VPD Pages page.
9330  */
9331 static int
9332 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9333 {
9334         struct ctl_lun *lun = CTL_LUN(ctsio);
9335         struct scsi_vpd_supported_pages *pages;
9336         int sup_page_size;
9337         int p;
9338
9339         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9340             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9341         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9342         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9343         ctsio->kern_rel_offset = 0;
9344         ctsio->kern_sg_entries = 0;
9345         ctsio->kern_data_len = min(sup_page_size, alloc_len);
9346         ctsio->kern_total_len = ctsio->kern_data_len;
9347
9348         /*
9349          * The control device is always connected.  The disk device, on the
9350          * other hand, may not be online all the time.  Need to change this
9351          * to figure out whether the disk device is actually online or not.
9352          */
9353         if (lun != NULL)
9354                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9355                                 lun->be_lun->lun_type;
9356         else
9357                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9358
9359         p = 0;
9360         /* Supported VPD pages */
9361         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9362         /* Serial Number */
9363         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9364         /* Device Identification */
9365         pages->page_list[p++] = SVPD_DEVICE_ID;
9366         /* Extended INQUIRY Data */
9367         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9368         /* Mode Page Policy */
9369         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9370         /* SCSI Ports */
9371         pages->page_list[p++] = SVPD_SCSI_PORTS;
9372         /* Third-party Copy */
9373         pages->page_list[p++] = SVPD_SCSI_TPC;
9374         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9375                 /* Block limits */
9376                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9377                 /* Block Device Characteristics */
9378                 pages->page_list[p++] = SVPD_BDC;
9379                 /* Logical Block Provisioning */
9380                 pages->page_list[p++] = SVPD_LBP;
9381         }
9382         pages->length = p;
9383
9384         ctl_set_success(ctsio);
9385         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9386         ctsio->be_move_done = ctl_config_move_done;
9387         ctl_datamove((union ctl_io *)ctsio);
9388         return (CTL_RETVAL_COMPLETE);
9389 }
9390
9391 /*
9392  * SCSI VPD page 0x80, the Unit Serial Number page.
9393  */
9394 static int
9395 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9396 {
9397         struct ctl_lun *lun = CTL_LUN(ctsio);
9398         struct scsi_vpd_unit_serial_number *sn_ptr;
9399         int data_len;
9400
9401         data_len = 4 + CTL_SN_LEN;
9402         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9403         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9404         ctsio->kern_rel_offset = 0;
9405         ctsio->kern_sg_entries = 0;
9406         ctsio->kern_data_len = min(data_len, alloc_len);
9407         ctsio->kern_total_len = ctsio->kern_data_len;
9408
9409         /*
9410          * The control device is always connected.  The disk device, on the
9411          * other hand, may not be online all the time.  Need to change this
9412          * to figure out whether the disk device is actually online or not.
9413          */
9414         if (lun != NULL)
9415                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9416                                   lun->be_lun->lun_type;
9417         else
9418                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9419
9420         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9421         sn_ptr->length = CTL_SN_LEN;
9422         /*
9423          * If we don't have a LUN, we just leave the serial number as
9424          * all spaces.
9425          */
9426         if (lun != NULL) {
9427                 strncpy((char *)sn_ptr->serial_num,
9428                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9429         } else
9430                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9431
9432         ctl_set_success(ctsio);
9433         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9434         ctsio->be_move_done = ctl_config_move_done;
9435         ctl_datamove((union ctl_io *)ctsio);
9436         return (CTL_RETVAL_COMPLETE);
9437 }
9438
9439
9440 /*
9441  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9442  */
9443 static int
9444 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9445 {
9446         struct ctl_lun *lun = CTL_LUN(ctsio);
9447         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9448         int data_len;
9449
9450         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9451         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9452         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9453         ctsio->kern_sg_entries = 0;
9454         ctsio->kern_rel_offset = 0;
9455         ctsio->kern_data_len = min(data_len, alloc_len);
9456         ctsio->kern_total_len = ctsio->kern_data_len;
9457
9458         /*
9459          * The control device is always connected.  The disk device, on the
9460          * other hand, may not be online all the time.
9461          */
9462         if (lun != NULL)
9463                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9464                                      lun->be_lun->lun_type;
9465         else
9466                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9467         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9468         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9469         /*
9470          * We support head of queue, ordered and simple tags.
9471          */
9472         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9473         /*
9474          * Volatile cache supported.
9475          */
9476         eid_ptr->flags3 = SVPD_EID_V_SUP;
9477
9478         /*
9479          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9480          * attention for a particular IT nexus on all LUNs once we report
9481          * it to that nexus once.  This bit is required as of SPC-4.
9482          */
9483         eid_ptr->flags4 = SVPD_EID_LUICLR;
9484
9485         /*
9486          * We support revert to defaults (RTD) bit in MODE SELECT.
9487          */
9488         eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9489
9490         /*
9491          * XXX KDM in order to correctly answer this, we would need
9492          * information from the SIM to determine how much sense data it
9493          * can send.  So this would really be a path inquiry field, most
9494          * likely.  This can be set to a maximum of 252 according to SPC-4,
9495          * but the hardware may or may not be able to support that much.
9496          * 0 just means that the maximum sense data length is not reported.
9497          */
9498         eid_ptr->max_sense_length = 0;
9499
9500         ctl_set_success(ctsio);
9501         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9502         ctsio->be_move_done = ctl_config_move_done;
9503         ctl_datamove((union ctl_io *)ctsio);
9504         return (CTL_RETVAL_COMPLETE);
9505 }
9506
9507 static int
9508 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9509 {
9510         struct ctl_lun *lun = CTL_LUN(ctsio);
9511         struct scsi_vpd_mode_page_policy *mpp_ptr;
9512         int data_len;
9513
9514         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9515             sizeof(struct scsi_vpd_mode_page_policy_descr);
9516
9517         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9518         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9519         ctsio->kern_rel_offset = 0;
9520         ctsio->kern_sg_entries = 0;
9521         ctsio->kern_data_len = min(data_len, alloc_len);
9522         ctsio->kern_total_len = ctsio->kern_data_len;
9523
9524         /*
9525          * The control device is always connected.  The disk device, on the
9526          * other hand, may not be online all the time.
9527          */
9528         if (lun != NULL)
9529                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9530                                      lun->be_lun->lun_type;
9531         else
9532                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9533         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9534         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9535         mpp_ptr->descr[0].page_code = 0x3f;
9536         mpp_ptr->descr[0].subpage_code = 0xff;
9537         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9538
9539         ctl_set_success(ctsio);
9540         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9541         ctsio->be_move_done = ctl_config_move_done;
9542         ctl_datamove((union ctl_io *)ctsio);
9543         return (CTL_RETVAL_COMPLETE);
9544 }
9545
9546 /*
9547  * SCSI VPD page 0x83, the Device Identification page.
9548  */
9549 static int
9550 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9551 {
9552         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9553         struct ctl_port *port = CTL_PORT(ctsio);
9554         struct ctl_lun *lun = CTL_LUN(ctsio);
9555         struct scsi_vpd_device_id *devid_ptr;
9556         struct scsi_vpd_id_descriptor *desc;
9557         int data_len, g;
9558         uint8_t proto;
9559
9560         data_len = sizeof(struct scsi_vpd_device_id) +
9561             sizeof(struct scsi_vpd_id_descriptor) +
9562                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9563             sizeof(struct scsi_vpd_id_descriptor) +
9564                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9565         if (lun && lun->lun_devid)
9566                 data_len += lun->lun_devid->len;
9567         if (port && port->port_devid)
9568                 data_len += port->port_devid->len;
9569         if (port && port->target_devid)
9570                 data_len += port->target_devid->len;
9571
9572         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9573         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9574         ctsio->kern_sg_entries = 0;
9575         ctsio->kern_rel_offset = 0;
9576         ctsio->kern_sg_entries = 0;
9577         ctsio->kern_data_len = min(data_len, alloc_len);
9578         ctsio->kern_total_len = ctsio->kern_data_len;
9579
9580         /*
9581          * The control device is always connected.  The disk device, on the
9582          * other hand, may not be online all the time.
9583          */
9584         if (lun != NULL)
9585                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9586                                      lun->be_lun->lun_type;
9587         else
9588                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9589         devid_ptr->page_code = SVPD_DEVICE_ID;
9590         scsi_ulto2b(data_len - 4, devid_ptr->length);
9591
9592         if (port && port->port_type == CTL_PORT_FC)
9593                 proto = SCSI_PROTO_FC << 4;
9594         else if (port && port->port_type == CTL_PORT_SAS)
9595                 proto = SCSI_PROTO_SAS << 4;
9596         else if (port && port->port_type == CTL_PORT_ISCSI)
9597                 proto = SCSI_PROTO_ISCSI << 4;
9598         else
9599                 proto = SCSI_PROTO_SPI << 4;
9600         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9601
9602         /*
9603          * We're using a LUN association here.  i.e., this device ID is a
9604          * per-LUN identifier.
9605          */
9606         if (lun && lun->lun_devid) {
9607                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9608                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9609                     lun->lun_devid->len);
9610         }
9611
9612         /*
9613          * This is for the WWPN which is a port association.
9614          */
9615         if (port && port->port_devid) {
9616                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9617                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9618                     port->port_devid->len);
9619         }
9620
9621         /*
9622          * This is for the Relative Target Port(type 4h) identifier
9623          */
9624         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9625         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9626             SVPD_ID_TYPE_RELTARG;
9627         desc->length = 4;
9628         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9629         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9630             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9631
9632         /*
9633          * This is for the Target Port Group(type 5h) identifier
9634          */
9635         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9636         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9637             SVPD_ID_TYPE_TPORTGRP;
9638         desc->length = 4;
9639         if (softc->is_single ||
9640             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9641                 g = 1;
9642         else
9643                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9644         scsi_ulto2b(g, &desc->identifier[2]);
9645         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9646             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9647
9648         /*
9649          * This is for the Target identifier
9650          */
9651         if (port && port->target_devid) {
9652                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9653         }
9654
9655         ctl_set_success(ctsio);
9656         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9657         ctsio->be_move_done = ctl_config_move_done;
9658         ctl_datamove((union ctl_io *)ctsio);
9659         return (CTL_RETVAL_COMPLETE);
9660 }
9661
9662 static int
9663 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9664 {
9665         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9666         struct ctl_lun *lun = CTL_LUN(ctsio);
9667         struct scsi_vpd_scsi_ports *sp;
9668         struct scsi_vpd_port_designation *pd;
9669         struct scsi_vpd_port_designation_cont *pdc;
9670         struct ctl_port *port;
9671         int data_len, num_target_ports, iid_len, id_len;
9672
9673         num_target_ports = 0;
9674         iid_len = 0;
9675         id_len = 0;
9676         mtx_lock(&softc->ctl_lock);
9677         STAILQ_FOREACH(port, &softc->port_list, links) {
9678                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9679                         continue;
9680                 if (lun != NULL &&
9681                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9682                         continue;
9683                 num_target_ports++;
9684                 if (port->init_devid)
9685                         iid_len += port->init_devid->len;
9686                 if (port->port_devid)
9687                         id_len += port->port_devid->len;
9688         }
9689         mtx_unlock(&softc->ctl_lock);
9690
9691         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9692             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9693              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9694         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9695         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9696         ctsio->kern_sg_entries = 0;
9697         ctsio->kern_rel_offset = 0;
9698         ctsio->kern_sg_entries = 0;
9699         ctsio->kern_data_len = min(data_len, alloc_len);
9700         ctsio->kern_total_len = ctsio->kern_data_len;
9701
9702         /*
9703          * The control device is always connected.  The disk device, on the
9704          * other hand, may not be online all the time.  Need to change this
9705          * to figure out whether the disk device is actually online or not.
9706          */
9707         if (lun != NULL)
9708                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9709                                   lun->be_lun->lun_type;
9710         else
9711                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9712
9713         sp->page_code = SVPD_SCSI_PORTS;
9714         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9715             sp->page_length);
9716         pd = &sp->design[0];
9717
9718         mtx_lock(&softc->ctl_lock);
9719         STAILQ_FOREACH(port, &softc->port_list, links) {
9720                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9721                         continue;
9722                 if (lun != NULL &&
9723                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9724                         continue;
9725                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9726                 if (port->init_devid) {
9727                         iid_len = port->init_devid->len;
9728                         memcpy(pd->initiator_transportid,
9729                             port->init_devid->data, port->init_devid->len);
9730                 } else
9731                         iid_len = 0;
9732                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9733                 pdc = (struct scsi_vpd_port_designation_cont *)
9734                     (&pd->initiator_transportid[iid_len]);
9735                 if (port->port_devid) {
9736                         id_len = port->port_devid->len;
9737                         memcpy(pdc->target_port_descriptors,
9738                             port->port_devid->data, port->port_devid->len);
9739                 } else
9740                         id_len = 0;
9741                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9742                 pd = (struct scsi_vpd_port_designation *)
9743                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9744         }
9745         mtx_unlock(&softc->ctl_lock);
9746
9747         ctl_set_success(ctsio);
9748         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9749         ctsio->be_move_done = ctl_config_move_done;
9750         ctl_datamove((union ctl_io *)ctsio);
9751         return (CTL_RETVAL_COMPLETE);
9752 }
9753
9754 static int
9755 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9756 {
9757         struct ctl_lun *lun = CTL_LUN(ctsio);
9758         struct scsi_vpd_block_limits *bl_ptr;
9759         const char *val;
9760         uint64_t ival;
9761
9762         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9763         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9764         ctsio->kern_sg_entries = 0;
9765         ctsio->kern_rel_offset = 0;
9766         ctsio->kern_sg_entries = 0;
9767         ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9768         ctsio->kern_total_len = ctsio->kern_data_len;
9769
9770         /*
9771          * The control device is always connected.  The disk device, on the
9772          * other hand, may not be online all the time.  Need to change this
9773          * to figure out whether the disk device is actually online or not.
9774          */
9775         if (lun != NULL)
9776                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9777                                   lun->be_lun->lun_type;
9778         else
9779                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9780
9781         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9782         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9783         bl_ptr->max_cmp_write_len = 0xff;
9784         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9785         if (lun != NULL) {
9786                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9787                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9788                         ival = 0xffffffff;
9789                         val = dnvlist_get_string(lun->be_lun->options,
9790                             "unmap_max_lba", NULL);
9791                         if (val != NULL)
9792                                 ctl_expand_number(val, &ival);
9793                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9794                         ival = 0xffffffff;
9795                         val = dnvlist_get_string(lun->be_lun->options,
9796                             "unmap_max_descr", NULL);
9797                         if (val != NULL)
9798                                 ctl_expand_number(val, &ival);
9799                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9800                         if (lun->be_lun->ublockexp != 0) {
9801                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9802                                     bl_ptr->opt_unmap_grain);
9803                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9804                                     bl_ptr->unmap_grain_align);
9805                         }
9806                 }
9807                 scsi_ulto4b(lun->be_lun->atomicblock,
9808                     bl_ptr->max_atomic_transfer_length);
9809                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9810                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9811                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9812                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9813                 ival = UINT64_MAX;
9814                 val = dnvlist_get_string(lun->be_lun->options,
9815                     "write_same_max_lba", NULL);
9816                 if (val != NULL)
9817                         ctl_expand_number(val, &ival);
9818                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9819         }
9820
9821         ctl_set_success(ctsio);
9822         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9823         ctsio->be_move_done = ctl_config_move_done;
9824         ctl_datamove((union ctl_io *)ctsio);
9825         return (CTL_RETVAL_COMPLETE);
9826 }
9827
9828 static int
9829 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9830 {
9831         struct ctl_lun *lun = CTL_LUN(ctsio);
9832         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9833         const char *value;
9834         u_int i;
9835
9836         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9837         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9838         ctsio->kern_sg_entries = 0;
9839         ctsio->kern_rel_offset = 0;
9840         ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9841         ctsio->kern_total_len = ctsio->kern_data_len;
9842
9843         /*
9844          * The control device is always connected.  The disk device, on the
9845          * other hand, may not be online all the time.  Need to change this
9846          * to figure out whether the disk device is actually online or not.
9847          */
9848         if (lun != NULL)
9849                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9850                                   lun->be_lun->lun_type;
9851         else
9852                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9853         bdc_ptr->page_code = SVPD_BDC;
9854         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9855         if (lun != NULL &&
9856             (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9857                 i = strtol(value, NULL, 0);
9858         else
9859                 i = CTL_DEFAULT_ROTATION_RATE;
9860         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9861         if (lun != NULL &&
9862             (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9863                 i = strtol(value, NULL, 0);
9864         else
9865                 i = 0;
9866         bdc_ptr->wab_wac_ff = (i & 0x0f);
9867         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9868
9869         ctl_set_success(ctsio);
9870         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9871         ctsio->be_move_done = ctl_config_move_done;
9872         ctl_datamove((union ctl_io *)ctsio);
9873         return (CTL_RETVAL_COMPLETE);
9874 }
9875
9876 static int
9877 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9878 {
9879         struct ctl_lun *lun = CTL_LUN(ctsio);
9880         struct scsi_vpd_logical_block_prov *lbp_ptr;
9881         const char *value;
9882
9883         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9884         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9885         ctsio->kern_sg_entries = 0;
9886         ctsio->kern_rel_offset = 0;
9887         ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9888         ctsio->kern_total_len = ctsio->kern_data_len;
9889
9890         /*
9891          * The control device is always connected.  The disk device, on the
9892          * other hand, may not be online all the time.  Need to change this
9893          * to figure out whether the disk device is actually online or not.
9894          */
9895         if (lun != NULL)
9896                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9897                                   lun->be_lun->lun_type;
9898         else
9899                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9900
9901         lbp_ptr->page_code = SVPD_LBP;
9902         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9903         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9904         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9905                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9906                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9907                 value = dnvlist_get_string(lun->be_lun->options,
9908                     "provisioning_type", NULL);
9909                 if (value != NULL) {
9910                         if (strcmp(value, "resource") == 0)
9911                                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9912                         else if (strcmp(value, "thin") == 0)
9913                                 lbp_ptr->prov_type = SVPD_LBP_THIN;
9914                 } else
9915                         lbp_ptr->prov_type = SVPD_LBP_THIN;
9916         }
9917
9918         ctl_set_success(ctsio);
9919         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9920         ctsio->be_move_done = ctl_config_move_done;
9921         ctl_datamove((union ctl_io *)ctsio);
9922         return (CTL_RETVAL_COMPLETE);
9923 }
9924
9925 /*
9926  * INQUIRY with the EVPD bit set.
9927  */
9928 static int
9929 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9930 {
9931         struct ctl_lun *lun = CTL_LUN(ctsio);
9932         struct scsi_inquiry *cdb;
9933         int alloc_len, retval;
9934
9935         cdb = (struct scsi_inquiry *)ctsio->cdb;
9936         alloc_len = scsi_2btoul(cdb->length);
9937
9938         switch (cdb->page_code) {
9939         case SVPD_SUPPORTED_PAGES:
9940                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9941                 break;
9942         case SVPD_UNIT_SERIAL_NUMBER:
9943                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9944                 break;
9945         case SVPD_DEVICE_ID:
9946                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9947                 break;
9948         case SVPD_EXTENDED_INQUIRY_DATA:
9949                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9950                 break;
9951         case SVPD_MODE_PAGE_POLICY:
9952                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9953                 break;
9954         case SVPD_SCSI_PORTS:
9955                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9956                 break;
9957         case SVPD_SCSI_TPC:
9958                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9959                 break;
9960         case SVPD_BLOCK_LIMITS:
9961                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9962                         goto err;
9963                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9964                 break;
9965         case SVPD_BDC:
9966                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9967                         goto err;
9968                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9969                 break;
9970         case SVPD_LBP:
9971                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9972                         goto err;
9973                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9974                 break;
9975         default:
9976 err:
9977                 ctl_set_invalid_field(ctsio,
9978                                       /*sks_valid*/ 1,
9979                                       /*command*/ 1,
9980                                       /*field*/ 2,
9981                                       /*bit_valid*/ 0,
9982                                       /*bit*/ 0);
9983                 ctl_done((union ctl_io *)ctsio);
9984                 retval = CTL_RETVAL_COMPLETE;
9985                 break;
9986         }
9987
9988         return (retval);
9989 }
9990
9991 /*
9992  * Standard INQUIRY data.
9993  */
9994 static int
9995 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9996 {
9997         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9998         struct ctl_port *port = CTL_PORT(ctsio);
9999         struct ctl_lun *lun = CTL_LUN(ctsio);
10000         struct scsi_inquiry_data *inq_ptr;
10001         struct scsi_inquiry *cdb;
10002         const char *val;
10003         uint32_t alloc_len, data_len;
10004         ctl_port_type port_type;
10005
10006         port_type = port->port_type;
10007         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10008                 port_type = CTL_PORT_SCSI;
10009
10010         cdb = (struct scsi_inquiry *)ctsio->cdb;
10011         alloc_len = scsi_2btoul(cdb->length);
10012
10013         /*
10014          * We malloc the full inquiry data size here and fill it
10015          * in.  If the user only asks for less, we'll give him
10016          * that much.
10017          */
10018         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10019         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10020         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10021         ctsio->kern_sg_entries = 0;
10022         ctsio->kern_rel_offset = 0;
10023         ctsio->kern_data_len = min(data_len, alloc_len);
10024         ctsio->kern_total_len = ctsio->kern_data_len;
10025
10026         if (lun != NULL) {
10027                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10028                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10029                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10030                             lun->be_lun->lun_type;
10031                 } else {
10032                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10033                             lun->be_lun->lun_type;
10034                 }
10035                 if (lun->flags & CTL_LUN_REMOVABLE)
10036                         inq_ptr->dev_qual2 |= SID_RMB;
10037         } else
10038                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10039
10040         /* RMB in byte 2 is 0 */
10041         inq_ptr->version = SCSI_REV_SPC5;
10042
10043         /*
10044          * According to SAM-3, even if a device only supports a single
10045          * level of LUN addressing, it should still set the HISUP bit:
10046          *
10047          * 4.9.1 Logical unit numbers overview
10048          *
10049          * All logical unit number formats described in this standard are
10050          * hierarchical in structure even when only a single level in that
10051          * hierarchy is used. The HISUP bit shall be set to one in the
10052          * standard INQUIRY data (see SPC-2) when any logical unit number
10053          * format described in this standard is used.  Non-hierarchical
10054          * formats are outside the scope of this standard.
10055          *
10056          * Therefore we set the HiSup bit here.
10057          *
10058          * The response format is 2, per SPC-3.
10059          */
10060         inq_ptr->response_format = SID_HiSup | 2;
10061
10062         inq_ptr->additional_length = data_len -
10063             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10064         CTL_DEBUG_PRINT(("additional_length = %d\n",
10065                          inq_ptr->additional_length));
10066
10067         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10068         if (port_type == CTL_PORT_SCSI)
10069                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10070         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10071         inq_ptr->flags = SID_CmdQue;
10072         if (port_type == CTL_PORT_SCSI)
10073                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10074
10075         /*
10076          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10077          * We have 8 bytes for the vendor name, and 16 bytes for the device
10078          * name and 4 bytes for the revision.
10079          */
10080         if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10081             "vendor", NULL)) == NULL) {
10082                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10083         } else {
10084                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10085                 strncpy(inq_ptr->vendor, val,
10086                     min(sizeof(inq_ptr->vendor), strlen(val)));
10087         }
10088         if (lun == NULL) {
10089                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10090                     sizeof(inq_ptr->product));
10091         } else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10092             NULL)) == NULL) {
10093                 switch (lun->be_lun->lun_type) {
10094                 case T_DIRECT:
10095                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10096                             sizeof(inq_ptr->product));
10097                         break;
10098                 case T_PROCESSOR:
10099                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10100                             sizeof(inq_ptr->product));
10101                         break;
10102                 case T_CDROM:
10103                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10104                             sizeof(inq_ptr->product));
10105                         break;
10106                 default:
10107                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10108                             sizeof(inq_ptr->product));
10109                         break;
10110                 }
10111         } else {
10112                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10113                 strncpy(inq_ptr->product, val,
10114                     min(sizeof(inq_ptr->product), strlen(val)));
10115         }
10116
10117         /*
10118          * XXX make this a macro somewhere so it automatically gets
10119          * incremented when we make changes.
10120          */
10121         if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10122             "revision", NULL)) == NULL) {
10123                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10124         } else {
10125                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10126                 strncpy(inq_ptr->revision, val,
10127                     min(sizeof(inq_ptr->revision), strlen(val)));
10128         }
10129
10130         /*
10131          * For parallel SCSI, we support double transition and single
10132          * transition clocking.  We also support QAS (Quick Arbitration
10133          * and Selection) and Information Unit transfers on both the
10134          * control and array devices.
10135          */
10136         if (port_type == CTL_PORT_SCSI)
10137                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10138                                     SID_SPI_IUS;
10139
10140         /* SAM-6 (no version claimed) */
10141         scsi_ulto2b(0x00C0, inq_ptr->version1);
10142         /* SPC-5 (no version claimed) */
10143         scsi_ulto2b(0x05C0, inq_ptr->version2);
10144         if (port_type == CTL_PORT_FC) {
10145                 /* FCP-2 ANSI INCITS.350:2003 */
10146                 scsi_ulto2b(0x0917, inq_ptr->version3);
10147         } else if (port_type == CTL_PORT_SCSI) {
10148                 /* SPI-4 ANSI INCITS.362:200x */
10149                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10150         } else if (port_type == CTL_PORT_ISCSI) {
10151                 /* iSCSI (no version claimed) */
10152                 scsi_ulto2b(0x0960, inq_ptr->version3);
10153         } else if (port_type == CTL_PORT_SAS) {
10154                 /* SAS (no version claimed) */
10155                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10156         } else if (port_type == CTL_PORT_UMASS) {
10157                 /* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10158                 scsi_ulto2b(0x1730, inq_ptr->version3);
10159         }
10160
10161         if (lun == NULL) {
10162                 /* SBC-4 (no version claimed) */
10163                 scsi_ulto2b(0x0600, inq_ptr->version4);
10164         } else {
10165                 switch (lun->be_lun->lun_type) {
10166                 case T_DIRECT:
10167                         /* SBC-4 (no version claimed) */
10168                         scsi_ulto2b(0x0600, inq_ptr->version4);
10169                         break;
10170                 case T_PROCESSOR:
10171                         break;
10172                 case T_CDROM:
10173                         /* MMC-6 (no version claimed) */
10174                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10175                         break;
10176                 default:
10177                         break;
10178                 }
10179         }
10180
10181         ctl_set_success(ctsio);
10182         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10183         ctsio->be_move_done = ctl_config_move_done;
10184         ctl_datamove((union ctl_io *)ctsio);
10185         return (CTL_RETVAL_COMPLETE);
10186 }
10187
10188 int
10189 ctl_inquiry(struct ctl_scsiio *ctsio)
10190 {
10191         struct scsi_inquiry *cdb;
10192         int retval;
10193
10194         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10195
10196         cdb = (struct scsi_inquiry *)ctsio->cdb;
10197         if (cdb->byte2 & SI_EVPD)
10198                 retval = ctl_inquiry_evpd(ctsio);
10199         else if (cdb->page_code == 0)
10200                 retval = ctl_inquiry_std(ctsio);
10201         else {
10202                 ctl_set_invalid_field(ctsio,
10203                                       /*sks_valid*/ 1,
10204                                       /*command*/ 1,
10205                                       /*field*/ 2,
10206                                       /*bit_valid*/ 0,
10207                                       /*bit*/ 0);
10208                 ctl_done((union ctl_io *)ctsio);
10209                 return (CTL_RETVAL_COMPLETE);
10210         }
10211
10212         return (retval);
10213 }
10214
10215 int
10216 ctl_get_config(struct ctl_scsiio *ctsio)
10217 {
10218         struct ctl_lun *lun = CTL_LUN(ctsio);
10219         struct scsi_get_config_header *hdr;
10220         struct scsi_get_config_feature *feature;
10221         struct scsi_get_config *cdb;
10222         uint32_t alloc_len, data_len;
10223         int rt, starting;
10224
10225         cdb = (struct scsi_get_config *)ctsio->cdb;
10226         rt = (cdb->rt & SGC_RT_MASK);
10227         starting = scsi_2btoul(cdb->starting_feature);
10228         alloc_len = scsi_2btoul(cdb->length);
10229
10230         data_len = sizeof(struct scsi_get_config_header) +
10231             sizeof(struct scsi_get_config_feature) + 8 +
10232             sizeof(struct scsi_get_config_feature) + 8 +
10233             sizeof(struct scsi_get_config_feature) + 4 +
10234             sizeof(struct scsi_get_config_feature) + 4 +
10235             sizeof(struct scsi_get_config_feature) + 8 +
10236             sizeof(struct scsi_get_config_feature) +
10237             sizeof(struct scsi_get_config_feature) + 4 +
10238             sizeof(struct scsi_get_config_feature) + 4 +
10239             sizeof(struct scsi_get_config_feature) + 4 +
10240             sizeof(struct scsi_get_config_feature) + 4 +
10241             sizeof(struct scsi_get_config_feature) + 4 +
10242             sizeof(struct scsi_get_config_feature) + 4;
10243         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10244         ctsio->kern_sg_entries = 0;
10245         ctsio->kern_rel_offset = 0;
10246
10247         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10248         if (lun->flags & CTL_LUN_NO_MEDIA)
10249                 scsi_ulto2b(0x0000, hdr->current_profile);
10250         else
10251                 scsi_ulto2b(0x0010, hdr->current_profile);
10252         feature = (struct scsi_get_config_feature *)(hdr + 1);
10253
10254         if (starting > 0x003b)
10255                 goto done;
10256         if (starting > 0x003a)
10257                 goto f3b;
10258         if (starting > 0x002b)
10259                 goto f3a;
10260         if (starting > 0x002a)
10261                 goto f2b;
10262         if (starting > 0x001f)
10263                 goto f2a;
10264         if (starting > 0x001e)
10265                 goto f1f;
10266         if (starting > 0x001d)
10267                 goto f1e;
10268         if (starting > 0x0010)
10269                 goto f1d;
10270         if (starting > 0x0003)
10271                 goto f10;
10272         if (starting > 0x0002)
10273                 goto f3;
10274         if (starting > 0x0001)
10275                 goto f2;
10276         if (starting > 0x0000)
10277                 goto f1;
10278
10279         /* Profile List */
10280         scsi_ulto2b(0x0000, feature->feature_code);
10281         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10282         feature->add_length = 8;
10283         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10284         feature->feature_data[2] = 0x00;
10285         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10286         feature->feature_data[6] = 0x01;
10287         feature = (struct scsi_get_config_feature *)
10288             &feature->feature_data[feature->add_length];
10289
10290 f1:     /* Core */
10291         scsi_ulto2b(0x0001, feature->feature_code);
10292         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10293         feature->add_length = 8;
10294         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10295         feature->feature_data[4] = 0x03;
10296         feature = (struct scsi_get_config_feature *)
10297             &feature->feature_data[feature->add_length];
10298
10299 f2:     /* Morphing */
10300         scsi_ulto2b(0x0002, feature->feature_code);
10301         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10302         feature->add_length = 4;
10303         feature->feature_data[0] = 0x02;
10304         feature = (struct scsi_get_config_feature *)
10305             &feature->feature_data[feature->add_length];
10306
10307 f3:     /* Removable Medium */
10308         scsi_ulto2b(0x0003, feature->feature_code);
10309         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10310         feature->add_length = 4;
10311         feature->feature_data[0] = 0x39;
10312         feature = (struct scsi_get_config_feature *)
10313             &feature->feature_data[feature->add_length];
10314
10315         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10316                 goto done;
10317
10318 f10:    /* Random Read */
10319         scsi_ulto2b(0x0010, feature->feature_code);
10320         feature->flags = 0x00;
10321         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10322                 feature->flags |= SGC_F_CURRENT;
10323         feature->add_length = 8;
10324         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10325         scsi_ulto2b(1, &feature->feature_data[4]);
10326         feature->feature_data[6] = 0x00;
10327         feature = (struct scsi_get_config_feature *)
10328             &feature->feature_data[feature->add_length];
10329
10330 f1d:    /* Multi-Read */
10331         scsi_ulto2b(0x001D, feature->feature_code);
10332         feature->flags = 0x00;
10333         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10334                 feature->flags |= SGC_F_CURRENT;
10335         feature->add_length = 0;
10336         feature = (struct scsi_get_config_feature *)
10337             &feature->feature_data[feature->add_length];
10338
10339 f1e:    /* CD Read */
10340         scsi_ulto2b(0x001E, feature->feature_code);
10341         feature->flags = 0x00;
10342         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10343                 feature->flags |= SGC_F_CURRENT;
10344         feature->add_length = 4;
10345         feature->feature_data[0] = 0x00;
10346         feature = (struct scsi_get_config_feature *)
10347             &feature->feature_data[feature->add_length];
10348
10349 f1f:    /* DVD Read */
10350         scsi_ulto2b(0x001F, feature->feature_code);
10351         feature->flags = 0x08;
10352         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10353                 feature->flags |= SGC_F_CURRENT;
10354         feature->add_length = 4;
10355         feature->feature_data[0] = 0x01;
10356         feature->feature_data[2] = 0x03;
10357         feature = (struct scsi_get_config_feature *)
10358             &feature->feature_data[feature->add_length];
10359
10360 f2a:    /* DVD+RW */
10361         scsi_ulto2b(0x002A, feature->feature_code);
10362         feature->flags = 0x04;
10363         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10364                 feature->flags |= SGC_F_CURRENT;
10365         feature->add_length = 4;
10366         feature->feature_data[0] = 0x00;
10367         feature->feature_data[1] = 0x00;
10368         feature = (struct scsi_get_config_feature *)
10369             &feature->feature_data[feature->add_length];
10370
10371 f2b:    /* DVD+R */
10372         scsi_ulto2b(0x002B, feature->feature_code);
10373         feature->flags = 0x00;
10374         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10375                 feature->flags |= SGC_F_CURRENT;
10376         feature->add_length = 4;
10377         feature->feature_data[0] = 0x00;
10378         feature = (struct scsi_get_config_feature *)
10379             &feature->feature_data[feature->add_length];
10380
10381 f3a:    /* DVD+RW Dual Layer */
10382         scsi_ulto2b(0x003A, feature->feature_code);
10383         feature->flags = 0x00;
10384         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10385                 feature->flags |= SGC_F_CURRENT;
10386         feature->add_length = 4;
10387         feature->feature_data[0] = 0x00;
10388         feature->feature_data[1] = 0x00;
10389         feature = (struct scsi_get_config_feature *)
10390             &feature->feature_data[feature->add_length];
10391
10392 f3b:    /* DVD+R Dual Layer */
10393         scsi_ulto2b(0x003B, feature->feature_code);
10394         feature->flags = 0x00;
10395         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10396                 feature->flags |= SGC_F_CURRENT;
10397         feature->add_length = 4;
10398         feature->feature_data[0] = 0x00;
10399         feature = (struct scsi_get_config_feature *)
10400             &feature->feature_data[feature->add_length];
10401
10402 done:
10403         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10404         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10405                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10406                 if (scsi_2btoul(feature->feature_code) == starting)
10407                         feature = (struct scsi_get_config_feature *)
10408                             &feature->feature_data[feature->add_length];
10409                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10410         }
10411         scsi_ulto4b(data_len - 4, hdr->data_length);
10412         ctsio->kern_data_len = min(data_len, alloc_len);
10413         ctsio->kern_total_len = ctsio->kern_data_len;
10414
10415         ctl_set_success(ctsio);
10416         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10417         ctsio->be_move_done = ctl_config_move_done;
10418         ctl_datamove((union ctl_io *)ctsio);
10419         return (CTL_RETVAL_COMPLETE);
10420 }
10421
10422 int
10423 ctl_get_event_status(struct ctl_scsiio *ctsio)
10424 {
10425         struct scsi_get_event_status_header *hdr;
10426         struct scsi_get_event_status *cdb;
10427         uint32_t alloc_len, data_len;
10428
10429         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10430         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10431                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10432                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10433                 ctl_done((union ctl_io *)ctsio);
10434                 return (CTL_RETVAL_COMPLETE);
10435         }
10436         alloc_len = scsi_2btoul(cdb->length);
10437
10438         data_len = sizeof(struct scsi_get_event_status_header);
10439         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10440         ctsio->kern_sg_entries = 0;
10441         ctsio->kern_rel_offset = 0;
10442         ctsio->kern_data_len = min(data_len, alloc_len);
10443         ctsio->kern_total_len = ctsio->kern_data_len;
10444
10445         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10446         scsi_ulto2b(0, hdr->descr_length);
10447         hdr->nea_class = SGESN_NEA;
10448         hdr->supported_class = 0;
10449
10450         ctl_set_success(ctsio);
10451         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10452         ctsio->be_move_done = ctl_config_move_done;
10453         ctl_datamove((union ctl_io *)ctsio);
10454         return (CTL_RETVAL_COMPLETE);
10455 }
10456
10457 int
10458 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10459 {
10460         struct scsi_mechanism_status_header *hdr;
10461         struct scsi_mechanism_status *cdb;
10462         uint32_t alloc_len, data_len;
10463
10464         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10465         alloc_len = scsi_2btoul(cdb->length);
10466
10467         data_len = sizeof(struct scsi_mechanism_status_header);
10468         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10469         ctsio->kern_sg_entries = 0;
10470         ctsio->kern_rel_offset = 0;
10471         ctsio->kern_data_len = min(data_len, alloc_len);
10472         ctsio->kern_total_len = ctsio->kern_data_len;
10473
10474         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10475         hdr->state1 = 0x00;
10476         hdr->state2 = 0xe0;
10477         scsi_ulto3b(0, hdr->lba);
10478         hdr->slots_num = 0;
10479         scsi_ulto2b(0, hdr->slots_length);
10480
10481         ctl_set_success(ctsio);
10482         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10483         ctsio->be_move_done = ctl_config_move_done;
10484         ctl_datamove((union ctl_io *)ctsio);
10485         return (CTL_RETVAL_COMPLETE);
10486 }
10487
10488 static void
10489 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10490 {
10491
10492         lba += 150;
10493         buf[0] = 0;
10494         buf[1] = bin2bcd((lba / 75) / 60);
10495         buf[2] = bin2bcd((lba / 75) % 60);
10496         buf[3] = bin2bcd(lba % 75);
10497 }
10498
10499 int
10500 ctl_read_toc(struct ctl_scsiio *ctsio)
10501 {
10502         struct ctl_lun *lun = CTL_LUN(ctsio);
10503         struct scsi_read_toc_hdr *hdr;
10504         struct scsi_read_toc_type01_descr *descr;
10505         struct scsi_read_toc *cdb;
10506         uint32_t alloc_len, data_len;
10507         int format, msf;
10508
10509         cdb = (struct scsi_read_toc *)ctsio->cdb;
10510         msf = (cdb->byte2 & CD_MSF) != 0;
10511         format = cdb->format;
10512         alloc_len = scsi_2btoul(cdb->data_len);
10513
10514         data_len = sizeof(struct scsi_read_toc_hdr);
10515         if (format == 0)
10516                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10517         else
10518                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10519         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10520         ctsio->kern_sg_entries = 0;
10521         ctsio->kern_rel_offset = 0;
10522         ctsio->kern_data_len = min(data_len, alloc_len);
10523         ctsio->kern_total_len = ctsio->kern_data_len;
10524
10525         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10526         if (format == 0) {
10527                 scsi_ulto2b(0x12, hdr->data_length);
10528                 hdr->first = 1;
10529                 hdr->last = 1;
10530                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10531                 descr->addr_ctl = 0x14;
10532                 descr->track_number = 1;
10533                 if (msf)
10534                         ctl_ultomsf(0, descr->track_start);
10535                 else
10536                         scsi_ulto4b(0, descr->track_start);
10537                 descr++;
10538                 descr->addr_ctl = 0x14;
10539                 descr->track_number = 0xaa;
10540                 if (msf)
10541                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10542                 else
10543                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10544         } else {
10545                 scsi_ulto2b(0x0a, hdr->data_length);
10546                 hdr->first = 1;
10547                 hdr->last = 1;
10548                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10549                 descr->addr_ctl = 0x14;
10550                 descr->track_number = 1;
10551                 if (msf)
10552                         ctl_ultomsf(0, descr->track_start);
10553                 else
10554                         scsi_ulto4b(0, descr->track_start);
10555         }
10556
10557         ctl_set_success(ctsio);
10558         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10559         ctsio->be_move_done = ctl_config_move_done;
10560         ctl_datamove((union ctl_io *)ctsio);
10561         return (CTL_RETVAL_COMPLETE);
10562 }
10563
10564 /*
10565  * For known CDB types, parse the LBA and length.
10566  */
10567 static int
10568 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10569 {
10570         if (io->io_hdr.io_type != CTL_IO_SCSI)
10571                 return (1);
10572
10573         switch (io->scsiio.cdb[0]) {
10574         case COMPARE_AND_WRITE: {
10575                 struct scsi_compare_and_write *cdb;
10576
10577                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10578
10579                 *lba = scsi_8btou64(cdb->addr);
10580                 *len = cdb->length;
10581                 break;
10582         }
10583         case READ_6:
10584         case WRITE_6: {
10585                 struct scsi_rw_6 *cdb;
10586
10587                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10588
10589                 *lba = scsi_3btoul(cdb->addr);
10590                 /* only 5 bits are valid in the most significant address byte */
10591                 *lba &= 0x1fffff;
10592                 *len = cdb->length;
10593                 break;
10594         }
10595         case READ_10:
10596         case WRITE_10: {
10597                 struct scsi_rw_10 *cdb;
10598
10599                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10600
10601                 *lba = scsi_4btoul(cdb->addr);
10602                 *len = scsi_2btoul(cdb->length);
10603                 break;
10604         }
10605         case WRITE_VERIFY_10: {
10606                 struct scsi_write_verify_10 *cdb;
10607
10608                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10609
10610                 *lba = scsi_4btoul(cdb->addr);
10611                 *len = scsi_2btoul(cdb->length);
10612                 break;
10613         }
10614         case READ_12:
10615         case WRITE_12: {
10616                 struct scsi_rw_12 *cdb;
10617
10618                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10619
10620                 *lba = scsi_4btoul(cdb->addr);
10621                 *len = scsi_4btoul(cdb->length);
10622                 break;
10623         }
10624         case WRITE_VERIFY_12: {
10625                 struct scsi_write_verify_12 *cdb;
10626
10627                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10628
10629                 *lba = scsi_4btoul(cdb->addr);
10630                 *len = scsi_4btoul(cdb->length);
10631                 break;
10632         }
10633         case READ_16:
10634         case WRITE_16: {
10635                 struct scsi_rw_16 *cdb;
10636
10637                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10638
10639                 *lba = scsi_8btou64(cdb->addr);
10640                 *len = scsi_4btoul(cdb->length);
10641                 break;
10642         }
10643         case WRITE_ATOMIC_16: {
10644                 struct scsi_write_atomic_16 *cdb;
10645
10646                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10647
10648                 *lba = scsi_8btou64(cdb->addr);
10649                 *len = scsi_2btoul(cdb->length);
10650                 break;
10651         }
10652         case WRITE_VERIFY_16: {
10653                 struct scsi_write_verify_16 *cdb;
10654
10655                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10656
10657                 *lba = scsi_8btou64(cdb->addr);
10658                 *len = scsi_4btoul(cdb->length);
10659                 break;
10660         }
10661         case WRITE_SAME_10: {
10662                 struct scsi_write_same_10 *cdb;
10663
10664                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10665
10666                 *lba = scsi_4btoul(cdb->addr);
10667                 *len = scsi_2btoul(cdb->length);
10668                 break;
10669         }
10670         case WRITE_SAME_16: {
10671                 struct scsi_write_same_16 *cdb;
10672
10673                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10674
10675                 *lba = scsi_8btou64(cdb->addr);
10676                 *len = scsi_4btoul(cdb->length);
10677                 break;
10678         }
10679         case VERIFY_10: {
10680                 struct scsi_verify_10 *cdb;
10681
10682                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10683
10684                 *lba = scsi_4btoul(cdb->addr);
10685                 *len = scsi_2btoul(cdb->length);
10686                 break;
10687         }
10688         case VERIFY_12: {
10689                 struct scsi_verify_12 *cdb;
10690
10691                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10692
10693                 *lba = scsi_4btoul(cdb->addr);
10694                 *len = scsi_4btoul(cdb->length);
10695                 break;
10696         }
10697         case VERIFY_16: {
10698                 struct scsi_verify_16 *cdb;
10699
10700                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10701
10702                 *lba = scsi_8btou64(cdb->addr);
10703                 *len = scsi_4btoul(cdb->length);
10704                 break;
10705         }
10706         case UNMAP: {
10707                 *lba = 0;
10708                 *len = UINT64_MAX;
10709                 break;
10710         }
10711         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10712                 struct scsi_get_lba_status *cdb;
10713
10714                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10715                 *lba = scsi_8btou64(cdb->addr);
10716                 *len = UINT32_MAX;
10717                 break;
10718         }
10719         default:
10720                 return (1);
10721                 break; /* NOTREACHED */
10722         }
10723
10724         return (0);
10725 }
10726
10727 static ctl_action
10728 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10729     bool seq)
10730 {
10731         uint64_t endlba1, endlba2;
10732
10733         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10734         endlba2 = lba2 + len2 - 1;
10735
10736         if ((endlba1 < lba2) || (endlba2 < lba1))
10737                 return (CTL_ACTION_PASS);
10738         else
10739                 return (CTL_ACTION_BLOCK);
10740 }
10741
10742 static int
10743 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10744 {
10745         struct ctl_ptr_len_flags *ptrlen;
10746         struct scsi_unmap_desc *buf, *end, *range;
10747         uint64_t lba;
10748         uint32_t len;
10749
10750         /* If not UNMAP -- go other way. */
10751         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10752             io->scsiio.cdb[0] != UNMAP)
10753                 return (CTL_ACTION_ERROR);
10754
10755         /* If UNMAP without data -- block and wait for data. */
10756         ptrlen = (struct ctl_ptr_len_flags *)
10757             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10758         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10759             ptrlen->ptr == NULL)
10760                 return (CTL_ACTION_BLOCK);
10761
10762         /* UNMAP with data -- check for collision. */
10763         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10764         end = buf + ptrlen->len / sizeof(*buf);
10765         for (range = buf; range < end; range++) {
10766                 lba = scsi_8btou64(range->lba);
10767                 len = scsi_4btoul(range->length);
10768                 if ((lba < lba2 + len2) && (lba + len > lba2))
10769                         return (CTL_ACTION_BLOCK);
10770         }
10771         return (CTL_ACTION_PASS);
10772 }
10773
10774 static ctl_action
10775 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10776 {
10777         uint64_t lba1, lba2;
10778         uint64_t len1, len2;
10779         int retval;
10780
10781         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10782                 return (CTL_ACTION_ERROR);
10783
10784         retval = ctl_extent_check_unmap(io1, lba2, len2);
10785         if (retval != CTL_ACTION_ERROR)
10786                 return (retval);
10787
10788         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10789                 return (CTL_ACTION_ERROR);
10790
10791         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10792                 seq = FALSE;
10793         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10794 }
10795
10796 static ctl_action
10797 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10798 {
10799         uint64_t lba1, lba2;
10800         uint64_t len1, len2;
10801
10802         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10803                 return (CTL_ACTION_PASS);
10804         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10805                 return (CTL_ACTION_ERROR);
10806         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10807                 return (CTL_ACTION_ERROR);
10808
10809         if (lba1 + len1 == lba2)
10810                 return (CTL_ACTION_BLOCK);
10811         return (CTL_ACTION_PASS);
10812 }
10813
10814 static ctl_action
10815 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10816     union ctl_io *ooa_io)
10817 {
10818         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10819         const ctl_serialize_action *serialize_row;
10820
10821         /*
10822          * The initiator attempted multiple untagged commands at the same
10823          * time.  Can't do that.
10824          */
10825         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10826          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10827          && ((pending_io->io_hdr.nexus.targ_port ==
10828               ooa_io->io_hdr.nexus.targ_port)
10829           && (pending_io->io_hdr.nexus.initid ==
10830               ooa_io->io_hdr.nexus.initid))
10831          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10832               CTL_FLAG_STATUS_SENT)) == 0))
10833                 return (CTL_ACTION_OVERLAP);
10834
10835         /*
10836          * The initiator attempted to send multiple tagged commands with
10837          * the same ID.  (It's fine if different initiators have the same
10838          * tag ID.)
10839          *
10840          * Even if all of those conditions are true, we don't kill the I/O
10841          * if the command ahead of us has been aborted.  We won't end up
10842          * sending it to the FETD, and it's perfectly legal to resend a
10843          * command with the same tag number as long as the previous
10844          * instance of this tag number has been aborted somehow.
10845          */
10846         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10847          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10848          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10849          && ((pending_io->io_hdr.nexus.targ_port ==
10850               ooa_io->io_hdr.nexus.targ_port)
10851           && (pending_io->io_hdr.nexus.initid ==
10852               ooa_io->io_hdr.nexus.initid))
10853          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10854               CTL_FLAG_STATUS_SENT)) == 0))
10855                 return (CTL_ACTION_OVERLAP_TAG);
10856
10857         /*
10858          * If we get a head of queue tag, SAM-3 says that we should
10859          * immediately execute it.
10860          *
10861          * What happens if this command would normally block for some other
10862          * reason?  e.g. a request sense with a head of queue tag
10863          * immediately after a write.  Normally that would block, but this
10864          * will result in its getting executed immediately...
10865          *
10866          * We currently return "pass" instead of "skip", so we'll end up
10867          * going through the rest of the queue to check for overlapped tags.
10868          *
10869          * XXX KDM check for other types of blockage first??
10870          */
10871         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10872                 return (CTL_ACTION_PASS);
10873
10874         /*
10875          * Ordered tags have to block until all items ahead of them
10876          * have completed.  If we get called with an ordered tag, we always
10877          * block, if something else is ahead of us in the queue.
10878          */
10879         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10880                 return (CTL_ACTION_BLOCK);
10881
10882         /*
10883          * Simple tags get blocked until all head of queue and ordered tags
10884          * ahead of them have completed.  I'm lumping untagged commands in
10885          * with simple tags here.  XXX KDM is that the right thing to do?
10886          */
10887         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10888           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10889          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10890           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10891                 return (CTL_ACTION_BLOCK);
10892
10893         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10894         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10895             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10896              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10897              pending_io->scsiio.cdb[1], pending_io));
10898         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10899         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
10900                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
10901         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
10902             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
10903              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
10904              ooa_io->scsiio.cdb[1], ooa_io));
10905
10906         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10907
10908         switch (serialize_row[pending_entry->seridx]) {
10909         case CTL_SER_BLOCK:
10910                 return (CTL_ACTION_BLOCK);
10911         case CTL_SER_EXTENT:
10912                 return (ctl_extent_check(ooa_io, pending_io,
10913                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10914         case CTL_SER_EXTENTOPT:
10915                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10916                     SCP_QUEUE_ALG_UNRESTRICTED)
10917                         return (ctl_extent_check(ooa_io, pending_io,
10918                             (lun->be_lun &&
10919                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10920                 return (CTL_ACTION_PASS);
10921         case CTL_SER_EXTENTSEQ:
10922                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10923                         return (ctl_extent_check_seq(ooa_io, pending_io));
10924                 return (CTL_ACTION_PASS);
10925         case CTL_SER_PASS:
10926                 return (CTL_ACTION_PASS);
10927         case CTL_SER_BLOCKOPT:
10928                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10929                     SCP_QUEUE_ALG_UNRESTRICTED)
10930                         return (CTL_ACTION_BLOCK);
10931                 return (CTL_ACTION_PASS);
10932         case CTL_SER_SKIP:
10933                 return (CTL_ACTION_SKIP);
10934         default:
10935                 panic("%s: Invalid serialization value %d for %d => %d",
10936                     __func__, serialize_row[pending_entry->seridx],
10937                     pending_entry->seridx, ooa_entry->seridx);
10938         }
10939
10940         return (CTL_ACTION_ERROR);
10941 }
10942
10943 /*
10944  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10945  * Assumptions:
10946  * - pending_io is generally either incoming, or on the blocked queue
10947  * - starting I/O is the I/O we want to start the check with.
10948  */
10949 static ctl_action
10950 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10951               union ctl_io *starting_io)
10952 {
10953         union ctl_io *ooa_io;
10954         ctl_action action;
10955
10956         mtx_assert(&lun->lun_lock, MA_OWNED);
10957
10958         /*
10959          * Run back along the OOA queue, starting with the current
10960          * blocked I/O and going through every I/O before it on the
10961          * queue.  If starting_io is NULL, we'll just end up returning
10962          * CTL_ACTION_PASS.
10963          */
10964         for (ooa_io = starting_io; ooa_io != NULL;
10965              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10966              ooa_links)){
10967
10968                 /*
10969                  * This routine just checks to see whether
10970                  * cur_blocked is blocked by ooa_io, which is ahead
10971                  * of it in the queue.  It doesn't queue/dequeue
10972                  * cur_blocked.
10973                  */
10974                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10975                 switch (action) {
10976                 case CTL_ACTION_BLOCK:
10977                 case CTL_ACTION_OVERLAP:
10978                 case CTL_ACTION_OVERLAP_TAG:
10979                 case CTL_ACTION_SKIP:
10980                 case CTL_ACTION_ERROR:
10981                         return (action);
10982                         break; /* NOTREACHED */
10983                 case CTL_ACTION_PASS:
10984                         break;
10985                 default:
10986                         panic("%s: Invalid action %d\n", __func__, action);
10987                 }
10988         }
10989
10990         return (CTL_ACTION_PASS);
10991 }
10992
10993 /*
10994  * Assumptions:
10995  * - An I/O has just completed, and has been removed from the per-LUN OOA
10996  *   queue, so some items on the blocked queue may now be unblocked.
10997  */
10998 static int
10999 ctl_check_blocked(struct ctl_lun *lun)
11000 {
11001         struct ctl_softc *softc = lun->ctl_softc;
11002         union ctl_io *cur_blocked, *next_blocked;
11003
11004         mtx_assert(&lun->lun_lock, MA_OWNED);
11005
11006         /*
11007          * Run forward from the head of the blocked queue, checking each
11008          * entry against the I/Os prior to it on the OOA queue to see if
11009          * there is still any blockage.
11010          *
11011          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11012          * with our removing a variable on it while it is traversing the
11013          * list.
11014          */
11015         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11016              cur_blocked != NULL; cur_blocked = next_blocked) {
11017                 union ctl_io *prev_ooa;
11018                 ctl_action action;
11019
11020                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11021                                                           blocked_links);
11022
11023                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11024                                                       ctl_ooaq, ooa_links);
11025
11026                 /*
11027                  * If cur_blocked happens to be the first item in the OOA
11028                  * queue now, prev_ooa will be NULL, and the action
11029                  * returned will just be CTL_ACTION_PASS.
11030                  */
11031                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11032
11033                 switch (action) {
11034                 case CTL_ACTION_BLOCK:
11035                         /* Nothing to do here, still blocked */
11036                         break;
11037                 case CTL_ACTION_OVERLAP:
11038                 case CTL_ACTION_OVERLAP_TAG:
11039                         /*
11040                          * This shouldn't happen!  In theory we've already
11041                          * checked this command for overlap...
11042                          */
11043                         break;
11044                 case CTL_ACTION_PASS:
11045                 case CTL_ACTION_SKIP: {
11046                         const struct ctl_cmd_entry *entry;
11047
11048                         /*
11049                          * The skip case shouldn't happen, this transaction
11050                          * should have never made it onto the blocked queue.
11051                          */
11052                         /*
11053                          * This I/O is no longer blocked, we can remove it
11054                          * from the blocked queue.  Since this is a TAILQ
11055                          * (doubly linked list), we can do O(1) removals
11056                          * from any place on the list.
11057                          */
11058                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11059                                      blocked_links);
11060                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11061
11062                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11063                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11064                                 /*
11065                                  * Need to send IO back to original side to
11066                                  * run
11067                                  */
11068                                 union ctl_ha_msg msg_info;
11069
11070                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11071                                 msg_info.hdr.original_sc =
11072                                         cur_blocked->io_hdr.original_sc;
11073                                 msg_info.hdr.serializing_sc = cur_blocked;
11074                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11075                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11076                                     sizeof(msg_info.hdr), M_NOWAIT);
11077                                 break;
11078                         }
11079                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11080
11081                         /*
11082                          * Check this I/O for LUN state changes that may
11083                          * have happened while this command was blocked.
11084                          * The LUN state may have been changed by a command
11085                          * ahead of us in the queue, so we need to re-check
11086                          * for any states that can be caused by SCSI
11087                          * commands.
11088                          */
11089                         if (ctl_scsiio_lun_check(lun, entry,
11090                                                  &cur_blocked->scsiio) == 0) {
11091                                 cur_blocked->io_hdr.flags |=
11092                                                       CTL_FLAG_IS_WAS_ON_RTR;
11093                                 ctl_enqueue_rtr(cur_blocked);
11094                         } else
11095                                 ctl_done(cur_blocked);
11096                         break;
11097                 }
11098                 default:
11099                         /*
11100                          * This probably shouldn't happen -- we shouldn't
11101                          * get CTL_ACTION_ERROR, or anything else.
11102                          */
11103                         break;
11104                 }
11105         }
11106
11107         return (CTL_RETVAL_COMPLETE);
11108 }
11109
11110 /*
11111  * This routine (with one exception) checks LUN flags that can be set by
11112  * commands ahead of us in the OOA queue.  These flags have to be checked
11113  * when a command initially comes in, and when we pull a command off the
11114  * blocked queue and are preparing to execute it.  The reason we have to
11115  * check these flags for commands on the blocked queue is that the LUN
11116  * state may have been changed by a command ahead of us while we're on the
11117  * blocked queue.
11118  *
11119  * Ordering is somewhat important with these checks, so please pay
11120  * careful attention to the placement of any new checks.
11121  */
11122 static int
11123 ctl_scsiio_lun_check(struct ctl_lun *lun,
11124     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11125 {
11126         struct ctl_softc *softc = lun->ctl_softc;
11127         int retval;
11128         uint32_t residx;
11129
11130         retval = 0;
11131
11132         mtx_assert(&lun->lun_lock, MA_OWNED);
11133
11134         /*
11135          * If this shelf is a secondary shelf controller, we may have to
11136          * reject some commands disallowed by HA mode and link state.
11137          */
11138         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11139                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11140                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11141                         ctl_set_lun_unavail(ctsio);
11142                         retval = 1;
11143                         goto bailout;
11144                 }
11145                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11146                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11147                         ctl_set_lun_transit(ctsio);
11148                         retval = 1;
11149                         goto bailout;
11150                 }
11151                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11152                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11153                         ctl_set_lun_standby(ctsio);
11154                         retval = 1;
11155                         goto bailout;
11156                 }
11157
11158                 /* The rest of checks are only done on executing side */
11159                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11160                         goto bailout;
11161         }
11162
11163         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11164                 if (lun->be_lun &&
11165                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11166                         ctl_set_hw_write_protected(ctsio);
11167                         retval = 1;
11168                         goto bailout;
11169                 }
11170                 if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11171                         ctl_set_sense(ctsio, /*current_error*/ 1,
11172                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11173                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11174                         retval = 1;
11175                         goto bailout;
11176                 }
11177         }
11178
11179         /*
11180          * Check for a reservation conflict.  If this command isn't allowed
11181          * even on reserved LUNs, and if this initiator isn't the one who
11182          * reserved us, reject the command with a reservation conflict.
11183          */
11184         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11185         if ((lun->flags & CTL_LUN_RESERVED)
11186          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11187                 if (lun->res_idx != residx) {
11188                         ctl_set_reservation_conflict(ctsio);
11189                         retval = 1;
11190                         goto bailout;
11191                 }
11192         }
11193
11194         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11195             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11196                 /* No reservation or command is allowed. */;
11197         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11198             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11199              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11200              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11201                 /* The command is allowed for Write Exclusive resv. */;
11202         } else {
11203                 /*
11204                  * if we aren't registered or it's a res holder type
11205                  * reservation and this isn't the res holder then set a
11206                  * conflict.
11207                  */
11208                 if (ctl_get_prkey(lun, residx) == 0 ||
11209                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11210                         ctl_set_reservation_conflict(ctsio);
11211                         retval = 1;
11212                         goto bailout;
11213                 }
11214         }
11215
11216         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11217                 if (lun->flags & CTL_LUN_EJECTED)
11218                         ctl_set_lun_ejected(ctsio);
11219                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11220                         if (lun->flags & CTL_LUN_REMOVABLE)
11221                                 ctl_set_lun_no_media(ctsio);
11222                         else
11223                                 ctl_set_lun_int_reqd(ctsio);
11224                 } else if (lun->flags & CTL_LUN_STOPPED)
11225                         ctl_set_lun_stopped(ctsio);
11226                 else
11227                         goto bailout;
11228                 retval = 1;
11229                 goto bailout;
11230         }
11231
11232 bailout:
11233         return (retval);
11234 }
11235
11236 static void
11237 ctl_failover_io(union ctl_io *io, int have_lock)
11238 {
11239         ctl_set_busy(&io->scsiio);
11240         ctl_done(io);
11241 }
11242
11243 static void
11244 ctl_failover_lun(union ctl_io *rio)
11245 {
11246         struct ctl_softc *softc = CTL_SOFTC(rio);
11247         struct ctl_lun *lun;
11248         struct ctl_io_hdr *io, *next_io;
11249         uint32_t targ_lun;
11250
11251         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11252         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11253
11254         /* Find and lock the LUN. */
11255         mtx_lock(&softc->ctl_lock);
11256         if (targ_lun > ctl_max_luns ||
11257             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11258                 mtx_unlock(&softc->ctl_lock);
11259                 return;
11260         }
11261         mtx_lock(&lun->lun_lock);
11262         mtx_unlock(&softc->ctl_lock);
11263         if (lun->flags & CTL_LUN_DISABLED) {
11264                 mtx_unlock(&lun->lun_lock);
11265                 return;
11266         }
11267
11268         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11269                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11270                         /* We are master */
11271                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11272                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11273                                         io->flags |= CTL_FLAG_ABORT;
11274                                         io->flags |= CTL_FLAG_FAILOVER;
11275                                 } else { /* This can be only due to DATAMOVE */
11276                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11277                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11278                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11279                                         io->port_status = 31340;
11280                                         ctl_enqueue_isc((union ctl_io *)io);
11281                                 }
11282                         }
11283                         /* We are slave */
11284                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11285                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11286                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11287                                         io->flags |= CTL_FLAG_FAILOVER;
11288                                 } else {
11289                                         ctl_set_busy(&((union ctl_io *)io)->
11290                                             scsiio);
11291                                         ctl_done((union ctl_io *)io);
11292                                 }
11293                         }
11294                 }
11295         } else { /* SERIALIZE modes */
11296                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11297                     next_io) {
11298                         /* We are master */
11299                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11300                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11301                                     blocked_links);
11302                                 io->flags &= ~CTL_FLAG_BLOCKED;
11303                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11304                                 ctl_free_io((union ctl_io *)io);
11305                         }
11306                 }
11307                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11308                         /* We are master */
11309                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11310                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11311                                 ctl_free_io((union ctl_io *)io);
11312                         }
11313                         /* We are slave */
11314                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11315                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11316                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11317                                         ctl_set_busy(&((union ctl_io *)io)->
11318                                             scsiio);
11319                                         ctl_done((union ctl_io *)io);
11320                                 }
11321                         }
11322                 }
11323                 ctl_check_blocked(lun);
11324         }
11325         mtx_unlock(&lun->lun_lock);
11326 }
11327
11328 static int
11329 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11330 {
11331         struct ctl_lun *lun;
11332         const struct ctl_cmd_entry *entry;
11333         uint32_t initidx, targ_lun;
11334         int retval = 0;
11335
11336         lun = NULL;
11337         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11338         if (targ_lun < ctl_max_luns)
11339                 lun = softc->ctl_luns[targ_lun];
11340         if (lun) {
11341                 /*
11342                  * If the LUN is invalid, pretend that it doesn't exist.
11343                  * It will go away as soon as all pending I/O has been
11344                  * completed.
11345                  */
11346                 mtx_lock(&lun->lun_lock);
11347                 if (lun->flags & CTL_LUN_DISABLED) {
11348                         mtx_unlock(&lun->lun_lock);
11349                         lun = NULL;
11350                 }
11351         }
11352         CTL_LUN(ctsio) = lun;
11353         if (lun) {
11354                 CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11355
11356                 /*
11357                  * Every I/O goes into the OOA queue for a particular LUN,
11358                  * and stays there until completion.
11359                  */
11360 #ifdef CTL_TIME_IO
11361                 if (TAILQ_EMPTY(&lun->ooa_queue))
11362                         lun->idle_time += getsbinuptime() - lun->last_busy;
11363 #endif
11364                 TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11365         }
11366
11367         /* Get command entry and return error if it is unsuppotyed. */
11368         entry = ctl_validate_command(ctsio);
11369         if (entry == NULL) {
11370                 if (lun)
11371                         mtx_unlock(&lun->lun_lock);
11372                 return (retval);
11373         }
11374
11375         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11376         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11377
11378         /*
11379          * Check to see whether we can send this command to LUNs that don't
11380          * exist.  This should pretty much only be the case for inquiry
11381          * and request sense.  Further checks, below, really require having
11382          * a LUN, so we can't really check the command anymore.  Just put
11383          * it on the rtr queue.
11384          */
11385         if (lun == NULL) {
11386                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11387                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11388                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11389                         return (retval);
11390                 }
11391
11392                 ctl_set_unsupported_lun(ctsio);
11393                 ctl_done((union ctl_io *)ctsio);
11394                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11395                 return (retval);
11396         } else {
11397                 /*
11398                  * Make sure we support this particular command on this LUN.
11399                  * e.g., we don't support writes to the control LUN.
11400                  */
11401                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11402                         mtx_unlock(&lun->lun_lock);
11403                         ctl_set_invalid_opcode(ctsio);
11404                         ctl_done((union ctl_io *)ctsio);
11405                         return (retval);
11406                 }
11407         }
11408
11409         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11410
11411         /*
11412          * If we've got a request sense, it'll clear the contingent
11413          * allegiance condition.  Otherwise, if we have a CA condition for
11414          * this initiator, clear it, because it sent down a command other
11415          * than request sense.
11416          */
11417         if (ctsio->cdb[0] != REQUEST_SENSE) {
11418                 struct scsi_sense_data *ps;
11419
11420                 ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11421                 if (ps != NULL)
11422                         ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11423         }
11424
11425         /*
11426          * If the command has this flag set, it handles its own unit
11427          * attention reporting, we shouldn't do anything.  Otherwise we
11428          * check for any pending unit attentions, and send them back to the
11429          * initiator.  We only do this when a command initially comes in,
11430          * not when we pull it off the blocked queue.
11431          *
11432          * According to SAM-3, section 5.3.2, the order that things get
11433          * presented back to the host is basically unit attentions caused
11434          * by some sort of reset event, busy status, reservation conflicts
11435          * or task set full, and finally any other status.
11436          *
11437          * One issue here is that some of the unit attentions we report
11438          * don't fall into the "reset" category (e.g. "reported luns data
11439          * has changed").  So reporting it here, before the reservation
11440          * check, may be technically wrong.  I guess the only thing to do
11441          * would be to check for and report the reset events here, and then
11442          * check for the other unit attention types after we check for a
11443          * reservation conflict.
11444          *
11445          * XXX KDM need to fix this
11446          */
11447         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11448                 ctl_ua_type ua_type;
11449                 u_int sense_len = 0;
11450
11451                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11452                     &sense_len, SSD_TYPE_NONE);
11453                 if (ua_type != CTL_UA_NONE) {
11454                         mtx_unlock(&lun->lun_lock);
11455                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11456                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11457                         ctsio->sense_len = sense_len;
11458                         ctl_done((union ctl_io *)ctsio);
11459                         return (retval);
11460                 }
11461         }
11462
11463
11464         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11465                 mtx_unlock(&lun->lun_lock);
11466                 ctl_done((union ctl_io *)ctsio);
11467                 return (retval);
11468         }
11469
11470         /*
11471          * XXX CHD this is where we want to send IO to other side if
11472          * this LUN is secondary on this SC. We will need to make a copy
11473          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11474          * the copy we send as FROM_OTHER.
11475          * We also need to stuff the address of the original IO so we can
11476          * find it easily. Something similar will need be done on the other
11477          * side so when we are done we can find the copy.
11478          */
11479         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11480             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11481             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11482                 union ctl_ha_msg msg_info;
11483                 int isc_retval;
11484
11485                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11486                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11487                 mtx_unlock(&lun->lun_lock);
11488
11489                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11490                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11491                 msg_info.hdr.serializing_sc = NULL;
11492                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11493                 msg_info.scsi.tag_num = ctsio->tag_num;
11494                 msg_info.scsi.tag_type = ctsio->tag_type;
11495                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11496                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11497
11498                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11499                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11500                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11501                         ctl_set_busy(ctsio);
11502                         ctl_done((union ctl_io *)ctsio);
11503                         return (retval);
11504                 }
11505                 return (retval);
11506         }
11507
11508         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11509                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11510                               ctl_ooaq, ooa_links))) {
11511         case CTL_ACTION_BLOCK:
11512                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11513                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11514                                   blocked_links);
11515                 mtx_unlock(&lun->lun_lock);
11516                 return (retval);
11517         case CTL_ACTION_PASS:
11518         case CTL_ACTION_SKIP:
11519                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11520                 mtx_unlock(&lun->lun_lock);
11521                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11522                 break;
11523         case CTL_ACTION_OVERLAP:
11524                 mtx_unlock(&lun->lun_lock);
11525                 ctl_set_overlapped_cmd(ctsio);
11526                 ctl_done((union ctl_io *)ctsio);
11527                 break;
11528         case CTL_ACTION_OVERLAP_TAG:
11529                 mtx_unlock(&lun->lun_lock);
11530                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11531                 ctl_done((union ctl_io *)ctsio);
11532                 break;
11533         case CTL_ACTION_ERROR:
11534         default:
11535                 mtx_unlock(&lun->lun_lock);
11536                 ctl_set_internal_failure(ctsio,
11537                                          /*sks_valid*/ 0,
11538                                          /*retry_count*/ 0);
11539                 ctl_done((union ctl_io *)ctsio);
11540                 break;
11541         }
11542         return (retval);
11543 }
11544
11545 const struct ctl_cmd_entry *
11546 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11547 {
11548         const struct ctl_cmd_entry *entry;
11549         int service_action;
11550
11551         entry = &ctl_cmd_table[ctsio->cdb[0]];
11552         if (sa)
11553                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11554         if (entry->flags & CTL_CMD_FLAG_SA5) {
11555                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11556                 entry = &((const struct ctl_cmd_entry *)
11557                     entry->execute)[service_action];
11558         }
11559         return (entry);
11560 }
11561
11562 const struct ctl_cmd_entry *
11563 ctl_validate_command(struct ctl_scsiio *ctsio)
11564 {
11565         const struct ctl_cmd_entry *entry;
11566         int i, sa;
11567         uint8_t diff;
11568
11569         entry = ctl_get_cmd_entry(ctsio, &sa);
11570         if (entry->execute == NULL) {
11571                 if (sa)
11572                         ctl_set_invalid_field(ctsio,
11573                                               /*sks_valid*/ 1,
11574                                               /*command*/ 1,
11575                                               /*field*/ 1,
11576                                               /*bit_valid*/ 1,
11577                                               /*bit*/ 4);
11578                 else
11579                         ctl_set_invalid_opcode(ctsio);
11580                 ctl_done((union ctl_io *)ctsio);
11581                 return (NULL);
11582         }
11583         KASSERT(entry->length > 0,
11584             ("Not defined length for command 0x%02x/0x%02x",
11585              ctsio->cdb[0], ctsio->cdb[1]));
11586         for (i = 1; i < entry->length; i++) {
11587                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11588                 if (diff == 0)
11589                         continue;
11590                 ctl_set_invalid_field(ctsio,
11591                                       /*sks_valid*/ 1,
11592                                       /*command*/ 1,
11593                                       /*field*/ i,
11594                                       /*bit_valid*/ 1,
11595                                       /*bit*/ fls(diff) - 1);
11596                 ctl_done((union ctl_io *)ctsio);
11597                 return (NULL);
11598         }
11599         return (entry);
11600 }
11601
11602 static int
11603 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11604 {
11605
11606         switch (lun_type) {
11607         case T_DIRECT:
11608                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11609                         return (0);
11610                 break;
11611         case T_PROCESSOR:
11612                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11613                         return (0);
11614                 break;
11615         case T_CDROM:
11616                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11617                         return (0);
11618                 break;
11619         default:
11620                 return (0);
11621         }
11622         return (1);
11623 }
11624
11625 static int
11626 ctl_scsiio(struct ctl_scsiio *ctsio)
11627 {
11628         int retval;
11629         const struct ctl_cmd_entry *entry;
11630
11631         retval = CTL_RETVAL_COMPLETE;
11632
11633         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11634
11635         entry = ctl_get_cmd_entry(ctsio, NULL);
11636
11637         /*
11638          * If this I/O has been aborted, just send it straight to
11639          * ctl_done() without executing it.
11640          */
11641         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11642                 ctl_done((union ctl_io *)ctsio);
11643                 goto bailout;
11644         }
11645
11646         /*
11647          * All the checks should have been handled by ctl_scsiio_precheck().
11648          * We should be clear now to just execute the I/O.
11649          */
11650         retval = entry->execute(ctsio);
11651
11652 bailout:
11653         return (retval);
11654 }
11655
11656 static int
11657 ctl_target_reset(union ctl_io *io)
11658 {
11659         struct ctl_softc *softc = CTL_SOFTC(io);
11660         struct ctl_port *port = CTL_PORT(io);
11661         struct ctl_lun *lun;
11662         uint32_t initidx;
11663         ctl_ua_type ua_type;
11664
11665         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11666                 union ctl_ha_msg msg_info;
11667
11668                 msg_info.hdr.nexus = io->io_hdr.nexus;
11669                 msg_info.task.task_action = io->taskio.task_action;
11670                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11671                 msg_info.hdr.original_sc = NULL;
11672                 msg_info.hdr.serializing_sc = NULL;
11673                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11674                     sizeof(msg_info.task), M_WAITOK);
11675         }
11676
11677         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11678         if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11679                 ua_type = CTL_UA_TARG_RESET;
11680         else
11681                 ua_type = CTL_UA_BUS_RESET;
11682         mtx_lock(&softc->ctl_lock);
11683         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11684                 if (port != NULL &&
11685                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11686                         continue;
11687                 ctl_do_lun_reset(lun, initidx, ua_type);
11688         }
11689         mtx_unlock(&softc->ctl_lock);
11690         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11691         return (0);
11692 }
11693
11694 /*
11695  * The LUN should always be set.  The I/O is optional, and is used to
11696  * distinguish between I/Os sent by this initiator, and by other
11697  * initiators.  We set unit attention for initiators other than this one.
11698  * SAM-3 is vague on this point.  It does say that a unit attention should
11699  * be established for other initiators when a LUN is reset (see section
11700  * 5.7.3), but it doesn't specifically say that the unit attention should
11701  * be established for this particular initiator when a LUN is reset.  Here
11702  * is the relevant text, from SAM-3 rev 8:
11703  *
11704  * 5.7.2 When a SCSI initiator port aborts its own tasks
11705  *
11706  * When a SCSI initiator port causes its own task(s) to be aborted, no
11707  * notification that the task(s) have been aborted shall be returned to
11708  * the SCSI initiator port other than the completion response for the
11709  * command or task management function action that caused the task(s) to
11710  * be aborted and notification(s) associated with related effects of the
11711  * action (e.g., a reset unit attention condition).
11712  *
11713  * XXX KDM for now, we're setting unit attention for all initiators.
11714  */
11715 static void
11716 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11717 {
11718         union ctl_io *xio;
11719         int i;
11720
11721         mtx_lock(&lun->lun_lock);
11722         /* Abort tasks. */
11723         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11724              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11725                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11726         }
11727         /* Clear CA. */
11728         for (i = 0; i < ctl_max_ports; i++) {
11729                 free(lun->pending_sense[i], M_CTL);
11730                 lun->pending_sense[i] = NULL;
11731         }
11732         /* Clear reservation. */
11733         lun->flags &= ~CTL_LUN_RESERVED;
11734         /* Clear prevent media removal. */
11735         if (lun->prevent) {
11736                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
11737                         ctl_clear_mask(lun->prevent, i);
11738                 lun->prevent_count = 0;
11739         }
11740         /* Clear TPC status */
11741         ctl_tpc_lun_clear(lun, -1);
11742         /* Establish UA. */
11743 #if 0
11744         ctl_est_ua_all(lun, initidx, ua_type);
11745 #else
11746         ctl_est_ua_all(lun, -1, ua_type);
11747 #endif
11748         mtx_unlock(&lun->lun_lock);
11749 }
11750
11751 static int
11752 ctl_lun_reset(union ctl_io *io)
11753 {
11754         struct ctl_softc *softc = CTL_SOFTC(io);
11755         struct ctl_lun *lun;
11756         uint32_t targ_lun, initidx;
11757
11758         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11759         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11760         mtx_lock(&softc->ctl_lock);
11761         if (targ_lun >= ctl_max_luns ||
11762             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11763                 mtx_unlock(&softc->ctl_lock);
11764                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11765                 return (1);
11766         }
11767         ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11768         mtx_unlock(&softc->ctl_lock);
11769         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11770
11771         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11772                 union ctl_ha_msg msg_info;
11773
11774                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11775                 msg_info.hdr.nexus = io->io_hdr.nexus;
11776                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11777                 msg_info.hdr.original_sc = NULL;
11778                 msg_info.hdr.serializing_sc = NULL;
11779                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11780                     sizeof(msg_info.task), M_WAITOK);
11781         }
11782         return (0);
11783 }
11784
11785 static void
11786 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11787     int other_sc)
11788 {
11789         union ctl_io *xio;
11790
11791         mtx_assert(&lun->lun_lock, MA_OWNED);
11792
11793         /*
11794          * Run through the OOA queue and attempt to find the given I/O.
11795          * The target port, initiator ID, tag type and tag number have to
11796          * match the values that we got from the initiator.  If we have an
11797          * untagged command to abort, simply abort the first untagged command
11798          * we come to.  We only allow one untagged command at a time of course.
11799          */
11800         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11801              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11802
11803                 if ((targ_port == UINT32_MAX ||
11804                      targ_port == xio->io_hdr.nexus.targ_port) &&
11805                     (init_id == UINT32_MAX ||
11806                      init_id == xio->io_hdr.nexus.initid)) {
11807                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11808                             init_id != xio->io_hdr.nexus.initid)
11809                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11810                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11811                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11812                                 union ctl_ha_msg msg_info;
11813
11814                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11815                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11816                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11817                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11818                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11819                                 msg_info.hdr.original_sc = NULL;
11820                                 msg_info.hdr.serializing_sc = NULL;
11821                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11822                                     sizeof(msg_info.task), M_NOWAIT);
11823                         }
11824                 }
11825         }
11826 }
11827
11828 static int
11829 ctl_abort_task_set(union ctl_io *io)
11830 {
11831         struct ctl_softc *softc = CTL_SOFTC(io);
11832         struct ctl_lun *lun;
11833         uint32_t targ_lun;
11834
11835         /*
11836          * Look up the LUN.
11837          */
11838         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11839         mtx_lock(&softc->ctl_lock);
11840         if (targ_lun >= ctl_max_luns ||
11841             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11842                 mtx_unlock(&softc->ctl_lock);
11843                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11844                 return (1);
11845         }
11846
11847         mtx_lock(&lun->lun_lock);
11848         mtx_unlock(&softc->ctl_lock);
11849         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11850                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11851                     io->io_hdr.nexus.initid,
11852                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11853         } else { /* CTL_TASK_CLEAR_TASK_SET */
11854                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11855                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11856         }
11857         mtx_unlock(&lun->lun_lock);
11858         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11859         return (0);
11860 }
11861
11862 static void
11863 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11864     ctl_ua_type ua_type)
11865 {
11866         struct ctl_lun *lun;
11867         struct scsi_sense_data *ps;
11868         uint32_t p, i;
11869
11870         p = initidx / CTL_MAX_INIT_PER_PORT;
11871         i = initidx % CTL_MAX_INIT_PER_PORT;
11872         mtx_lock(&softc->ctl_lock);
11873         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11874                 mtx_lock(&lun->lun_lock);
11875                 /* Abort tasks. */
11876                 ctl_abort_tasks_lun(lun, p, i, 1);
11877                 /* Clear CA. */
11878                 ps = lun->pending_sense[p];
11879                 if (ps != NULL)
11880                         ps[i].error_code = 0;
11881                 /* Clear reservation. */
11882                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11883                         lun->flags &= ~CTL_LUN_RESERVED;
11884                 /* Clear prevent media removal. */
11885                 if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11886                         ctl_clear_mask(lun->prevent, initidx);
11887                         lun->prevent_count--;
11888                 }
11889                 /* Clear TPC status */
11890                 ctl_tpc_lun_clear(lun, initidx);
11891                 /* Establish UA. */
11892                 ctl_est_ua(lun, initidx, ua_type);
11893                 mtx_unlock(&lun->lun_lock);
11894         }
11895         mtx_unlock(&softc->ctl_lock);
11896 }
11897
11898 static int
11899 ctl_i_t_nexus_reset(union ctl_io *io)
11900 {
11901         struct ctl_softc *softc = CTL_SOFTC(io);
11902         uint32_t initidx;
11903
11904         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11905                 union ctl_ha_msg msg_info;
11906
11907                 msg_info.hdr.nexus = io->io_hdr.nexus;
11908                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11909                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11910                 msg_info.hdr.original_sc = NULL;
11911                 msg_info.hdr.serializing_sc = NULL;
11912                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11913                     sizeof(msg_info.task), M_WAITOK);
11914         }
11915
11916         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11917         ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11918         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11919         return (0);
11920 }
11921
11922 static int
11923 ctl_abort_task(union ctl_io *io)
11924 {
11925         struct ctl_softc *softc = CTL_SOFTC(io);
11926         union ctl_io *xio;
11927         struct ctl_lun *lun;
11928 #if 0
11929         struct sbuf sb;
11930         char printbuf[128];
11931 #endif
11932         int found;
11933         uint32_t targ_lun;
11934
11935         found = 0;
11936
11937         /*
11938          * Look up the LUN.
11939          */
11940         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11941         mtx_lock(&softc->ctl_lock);
11942         if (targ_lun >= ctl_max_luns ||
11943             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11944                 mtx_unlock(&softc->ctl_lock);
11945                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11946                 return (1);
11947         }
11948
11949 #if 0
11950         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11951                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11952 #endif
11953
11954         mtx_lock(&lun->lun_lock);
11955         mtx_unlock(&softc->ctl_lock);
11956         /*
11957          * Run through the OOA queue and attempt to find the given I/O.
11958          * The target port, initiator ID, tag type and tag number have to
11959          * match the values that we got from the initiator.  If we have an
11960          * untagged command to abort, simply abort the first untagged command
11961          * we come to.  We only allow one untagged command at a time of course.
11962          */
11963         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11964              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11965 #if 0
11966                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11967
11968                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11969                             lun->lun, xio->scsiio.tag_num,
11970                             xio->scsiio.tag_type,
11971                             (xio->io_hdr.blocked_links.tqe_prev
11972                             == NULL) ? "" : " BLOCKED",
11973                             (xio->io_hdr.flags &
11974                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11975                             (xio->io_hdr.flags &
11976                             CTL_FLAG_ABORT) ? " ABORT" : "",
11977                             (xio->io_hdr.flags &
11978                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11979                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11980                 sbuf_finish(&sb);
11981                 printf("%s\n", sbuf_data(&sb));
11982 #endif
11983
11984                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11985                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11986                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11987                         continue;
11988
11989                 /*
11990                  * If the abort says that the task is untagged, the
11991                  * task in the queue must be untagged.  Otherwise,
11992                  * we just check to see whether the tag numbers
11993                  * match.  This is because the QLogic firmware
11994                  * doesn't pass back the tag type in an abort
11995                  * request.
11996                  */
11997 #if 0
11998                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11999                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12000                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12001 #endif
12002                 /*
12003                  * XXX KDM we've got problems with FC, because it
12004                  * doesn't send down a tag type with aborts.  So we
12005                  * can only really go by the tag number...
12006                  * This may cause problems with parallel SCSI.
12007                  * Need to figure that out!!
12008                  */
12009                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12010                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12011                         found = 1;
12012                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12013                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12014                                 union ctl_ha_msg msg_info;
12015
12016                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12017                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12018                                 msg_info.task.tag_num = io->taskio.tag_num;
12019                                 msg_info.task.tag_type = io->taskio.tag_type;
12020                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12021                                 msg_info.hdr.original_sc = NULL;
12022                                 msg_info.hdr.serializing_sc = NULL;
12023 #if 0
12024                                 printf("Sent Abort to other side\n");
12025 #endif
12026                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12027                                     sizeof(msg_info.task), M_NOWAIT);
12028                         }
12029 #if 0
12030                         printf("ctl_abort_task: found I/O to abort\n");
12031 #endif
12032                 }
12033         }
12034         mtx_unlock(&lun->lun_lock);
12035
12036         if (found == 0) {
12037                 /*
12038                  * This isn't really an error.  It's entirely possible for
12039                  * the abort and command completion to cross on the wire.
12040                  * This is more of an informative/diagnostic error.
12041                  */
12042 #if 0
12043                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12044                        "%u:%u:%u tag %d type %d\n",
12045                        io->io_hdr.nexus.initid,
12046                        io->io_hdr.nexus.targ_port,
12047                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12048                        io->taskio.tag_type);
12049 #endif
12050         }
12051         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12052         return (0);
12053 }
12054
12055 static int
12056 ctl_query_task(union ctl_io *io, int task_set)
12057 {
12058         struct ctl_softc *softc = CTL_SOFTC(io);
12059         union ctl_io *xio;
12060         struct ctl_lun *lun;
12061         int found = 0;
12062         uint32_t targ_lun;
12063
12064         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12065         mtx_lock(&softc->ctl_lock);
12066         if (targ_lun >= ctl_max_luns ||
12067             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12068                 mtx_unlock(&softc->ctl_lock);
12069                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12070                 return (1);
12071         }
12072         mtx_lock(&lun->lun_lock);
12073         mtx_unlock(&softc->ctl_lock);
12074         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12075              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12076
12077                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12078                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12079                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12080                         continue;
12081
12082                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12083                         found = 1;
12084                         break;
12085                 }
12086         }
12087         mtx_unlock(&lun->lun_lock);
12088         if (found)
12089                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12090         else
12091                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12092         return (0);
12093 }
12094
12095 static int
12096 ctl_query_async_event(union ctl_io *io)
12097 {
12098         struct ctl_softc *softc = CTL_SOFTC(io);
12099         struct ctl_lun *lun;
12100         ctl_ua_type ua;
12101         uint32_t targ_lun, initidx;
12102
12103         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12104         mtx_lock(&softc->ctl_lock);
12105         if (targ_lun >= ctl_max_luns ||
12106             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12107                 mtx_unlock(&softc->ctl_lock);
12108                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12109                 return (1);
12110         }
12111         mtx_lock(&lun->lun_lock);
12112         mtx_unlock(&softc->ctl_lock);
12113         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12114         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12115         mtx_unlock(&lun->lun_lock);
12116         if (ua != CTL_UA_NONE)
12117                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12118         else
12119                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12120         return (0);
12121 }
12122
12123 static void
12124 ctl_run_task(union ctl_io *io)
12125 {
12126         int retval = 1;
12127
12128         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12129         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12130             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12131         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12132         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12133         switch (io->taskio.task_action) {
12134         case CTL_TASK_ABORT_TASK:
12135                 retval = ctl_abort_task(io);
12136                 break;
12137         case CTL_TASK_ABORT_TASK_SET:
12138         case CTL_TASK_CLEAR_TASK_SET:
12139                 retval = ctl_abort_task_set(io);
12140                 break;
12141         case CTL_TASK_CLEAR_ACA:
12142                 break;
12143         case CTL_TASK_I_T_NEXUS_RESET:
12144                 retval = ctl_i_t_nexus_reset(io);
12145                 break;
12146         case CTL_TASK_LUN_RESET:
12147                 retval = ctl_lun_reset(io);
12148                 break;
12149         case CTL_TASK_TARGET_RESET:
12150         case CTL_TASK_BUS_RESET:
12151                 retval = ctl_target_reset(io);
12152                 break;
12153         case CTL_TASK_PORT_LOGIN:
12154                 break;
12155         case CTL_TASK_PORT_LOGOUT:
12156                 break;
12157         case CTL_TASK_QUERY_TASK:
12158                 retval = ctl_query_task(io, 0);
12159                 break;
12160         case CTL_TASK_QUERY_TASK_SET:
12161                 retval = ctl_query_task(io, 1);
12162                 break;
12163         case CTL_TASK_QUERY_ASYNC_EVENT:
12164                 retval = ctl_query_async_event(io);
12165                 break;
12166         default:
12167                 printf("%s: got unknown task management event %d\n",
12168                        __func__, io->taskio.task_action);
12169                 break;
12170         }
12171         if (retval == 0)
12172                 io->io_hdr.status = CTL_SUCCESS;
12173         else
12174                 io->io_hdr.status = CTL_ERROR;
12175         ctl_done(io);
12176 }
12177
12178 /*
12179  * For HA operation.  Handle commands that come in from the other
12180  * controller.
12181  */
12182 static void
12183 ctl_handle_isc(union ctl_io *io)
12184 {
12185         struct ctl_softc *softc = CTL_SOFTC(io);
12186         struct ctl_lun *lun;
12187         const struct ctl_cmd_entry *entry;
12188         uint32_t targ_lun;
12189
12190         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12191         switch (io->io_hdr.msg_type) {
12192         case CTL_MSG_SERIALIZE:
12193                 ctl_serialize_other_sc_cmd(&io->scsiio);
12194                 break;
12195         case CTL_MSG_R2R:               /* Only used in SER_ONLY mode. */
12196                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12197                 if (targ_lun >= ctl_max_luns ||
12198                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12199                         ctl_done(io);
12200                         break;
12201                 }
12202                 mtx_lock(&lun->lun_lock);
12203                 if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12204                         mtx_unlock(&lun->lun_lock);
12205                         ctl_done(io);
12206                         break;
12207                 }
12208                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12209                 mtx_unlock(&lun->lun_lock);
12210                 ctl_enqueue_rtr(io);
12211                 break;
12212         case CTL_MSG_FINISH_IO:
12213                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12214                         ctl_done(io);
12215                         break;
12216                 }
12217                 if (targ_lun >= ctl_max_luns ||
12218                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12219                         ctl_free_io(io);
12220                         break;
12221                 }
12222                 mtx_lock(&lun->lun_lock);
12223                 TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12224                 ctl_check_blocked(lun);
12225                 mtx_unlock(&lun->lun_lock);
12226                 ctl_free_io(io);
12227                 break;
12228         case CTL_MSG_PERS_ACTION:
12229                 ctl_hndl_per_res_out_on_other_sc(io);
12230                 ctl_free_io(io);
12231                 break;
12232         case CTL_MSG_BAD_JUJU:
12233                 ctl_done(io);
12234                 break;
12235         case CTL_MSG_DATAMOVE:          /* Only used in XFER mode */
12236                 ctl_datamove_remote(io);
12237                 break;
12238         case CTL_MSG_DATAMOVE_DONE:     /* Only used in XFER mode */
12239                 io->scsiio.be_move_done(io);
12240                 break;
12241         case CTL_MSG_FAILOVER:
12242                 ctl_failover_lun(io);
12243                 ctl_free_io(io);
12244                 break;
12245         default:
12246                 printf("%s: Invalid message type %d\n",
12247                        __func__, io->io_hdr.msg_type);
12248                 ctl_free_io(io);
12249                 break;
12250         }
12251
12252 }
12253
12254
12255 /*
12256  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12257  * there is no match.
12258  */
12259 static ctl_lun_error_pattern
12260 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12261 {
12262         const struct ctl_cmd_entry *entry;
12263         ctl_lun_error_pattern filtered_pattern, pattern;
12264
12265         pattern = desc->error_pattern;
12266
12267         /*
12268          * XXX KDM we need more data passed into this function to match a
12269          * custom pattern, and we actually need to implement custom pattern
12270          * matching.
12271          */
12272         if (pattern & CTL_LUN_PAT_CMD)
12273                 return (CTL_LUN_PAT_CMD);
12274
12275         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12276                 return (CTL_LUN_PAT_ANY);
12277
12278         entry = ctl_get_cmd_entry(ctsio, NULL);
12279
12280         filtered_pattern = entry->pattern & pattern;
12281
12282         /*
12283          * If the user requested specific flags in the pattern (e.g.
12284          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12285          * flags.
12286          *
12287          * If the user did not specify any flags, it doesn't matter whether
12288          * or not the command supports the flags.
12289          */
12290         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12291              (pattern & ~CTL_LUN_PAT_MASK))
12292                 return (CTL_LUN_PAT_NONE);
12293
12294         /*
12295          * If the user asked for a range check, see if the requested LBA
12296          * range overlaps with this command's LBA range.
12297          */
12298         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12299                 uint64_t lba1;
12300                 uint64_t len1;
12301                 ctl_action action;
12302                 int retval;
12303
12304                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12305                 if (retval != 0)
12306                         return (CTL_LUN_PAT_NONE);
12307
12308                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12309                                               desc->lba_range.len, FALSE);
12310                 /*
12311                  * A "pass" means that the LBA ranges don't overlap, so
12312                  * this doesn't match the user's range criteria.
12313                  */
12314                 if (action == CTL_ACTION_PASS)
12315                         return (CTL_LUN_PAT_NONE);
12316         }
12317
12318         return (filtered_pattern);
12319 }
12320
12321 static void
12322 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12323 {
12324         struct ctl_error_desc *desc, *desc2;
12325
12326         mtx_assert(&lun->lun_lock, MA_OWNED);
12327
12328         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12329                 ctl_lun_error_pattern pattern;
12330                 /*
12331                  * Check to see whether this particular command matches
12332                  * the pattern in the descriptor.
12333                  */
12334                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12335                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12336                         continue;
12337
12338                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12339                 case CTL_LUN_INJ_ABORTED:
12340                         ctl_set_aborted(&io->scsiio);
12341                         break;
12342                 case CTL_LUN_INJ_MEDIUM_ERR:
12343                         ctl_set_medium_error(&io->scsiio,
12344                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12345                              CTL_FLAG_DATA_OUT);
12346                         break;
12347                 case CTL_LUN_INJ_UA:
12348                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12349                          * OCCURRED */
12350                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12351                         break;
12352                 case CTL_LUN_INJ_CUSTOM:
12353                         /*
12354                          * We're assuming the user knows what he is doing.
12355                          * Just copy the sense information without doing
12356                          * checks.
12357                          */
12358                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12359                               MIN(sizeof(desc->custom_sense),
12360                                   sizeof(io->scsiio.sense_data)));
12361                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12362                         io->scsiio.sense_len = SSD_FULL_SIZE;
12363                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12364                         break;
12365                 case CTL_LUN_INJ_NONE:
12366                 default:
12367                         /*
12368                          * If this is an error injection type we don't know
12369                          * about, clear the continuous flag (if it is set)
12370                          * so it will get deleted below.
12371                          */
12372                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12373                         break;
12374                 }
12375                 /*
12376                  * By default, each error injection action is a one-shot
12377                  */
12378                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12379                         continue;
12380
12381                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12382
12383                 free(desc, M_CTL);
12384         }
12385 }
12386
12387 #ifdef CTL_IO_DELAY
12388 static void
12389 ctl_datamove_timer_wakeup(void *arg)
12390 {
12391         union ctl_io *io;
12392
12393         io = (union ctl_io *)arg;
12394
12395         ctl_datamove(io);
12396 }
12397 #endif /* CTL_IO_DELAY */
12398
12399 void
12400 ctl_datamove(union ctl_io *io)
12401 {
12402         void (*fe_datamove)(union ctl_io *io);
12403
12404         mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12405
12406         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12407
12408         /* No data transferred yet.  Frontend must update this when done. */
12409         io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12410
12411 #ifdef CTL_TIME_IO
12412         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12413                 char str[256];
12414                 char path_str[64];
12415                 struct sbuf sb;
12416
12417                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12418                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12419
12420                 sbuf_cat(&sb, path_str);
12421                 switch (io->io_hdr.io_type) {
12422                 case CTL_IO_SCSI:
12423                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12424                         sbuf_printf(&sb, "\n");
12425                         sbuf_cat(&sb, path_str);
12426                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12427                                     io->scsiio.tag_num, io->scsiio.tag_type);
12428                         break;
12429                 case CTL_IO_TASK:
12430                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12431                                     "Tag Type: %d\n", io->taskio.task_action,
12432                                     io->taskio.tag_num, io->taskio.tag_type);
12433                         break;
12434                 default:
12435                         panic("%s: Invalid CTL I/O type %d\n",
12436                             __func__, io->io_hdr.io_type);
12437                 }
12438                 sbuf_cat(&sb, path_str);
12439                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12440                             (intmax_t)time_uptime - io->io_hdr.start_time);
12441                 sbuf_finish(&sb);
12442                 printf("%s", sbuf_data(&sb));
12443         }
12444 #endif /* CTL_TIME_IO */
12445
12446 #ifdef CTL_IO_DELAY
12447         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12448                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12449         } else {
12450                 struct ctl_lun *lun;
12451
12452                 lun = CTL_LUN(io);
12453                 if ((lun != NULL)
12454                  && (lun->delay_info.datamove_delay > 0)) {
12455
12456                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12457                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12458                         callout_reset(&io->io_hdr.delay_callout,
12459                                       lun->delay_info.datamove_delay * hz,
12460                                       ctl_datamove_timer_wakeup, io);
12461                         if (lun->delay_info.datamove_type ==
12462                             CTL_DELAY_TYPE_ONESHOT)
12463                                 lun->delay_info.datamove_delay = 0;
12464                         return;
12465                 }
12466         }
12467 #endif
12468
12469         /*
12470          * This command has been aborted.  Set the port status, so we fail
12471          * the data move.
12472          */
12473         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12474                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12475                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12476                        io->io_hdr.nexus.targ_port,
12477                        io->io_hdr.nexus.targ_lun);
12478                 io->io_hdr.port_status = 31337;
12479                 /*
12480                  * Note that the backend, in this case, will get the
12481                  * callback in its context.  In other cases it may get
12482                  * called in the frontend's interrupt thread context.
12483                  */
12484                 io->scsiio.be_move_done(io);
12485                 return;
12486         }
12487
12488         /* Don't confuse frontend with zero length data move. */
12489         if (io->scsiio.kern_data_len == 0) {
12490                 io->scsiio.be_move_done(io);
12491                 return;
12492         }
12493
12494         fe_datamove = CTL_PORT(io)->fe_datamove;
12495         fe_datamove(io);
12496 }
12497
12498 static void
12499 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12500 {
12501         union ctl_ha_msg msg;
12502 #ifdef CTL_TIME_IO
12503         struct bintime cur_bt;
12504 #endif
12505
12506         memset(&msg, 0, sizeof(msg));
12507         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12508         msg.hdr.original_sc = io;
12509         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12510         msg.hdr.nexus = io->io_hdr.nexus;
12511         msg.hdr.status = io->io_hdr.status;
12512         msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12513         msg.scsi.tag_num = io->scsiio.tag_num;
12514         msg.scsi.tag_type = io->scsiio.tag_type;
12515         msg.scsi.scsi_status = io->scsiio.scsi_status;
12516         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12517                io->scsiio.sense_len);
12518         msg.scsi.sense_len = io->scsiio.sense_len;
12519         msg.scsi.port_status = io->io_hdr.port_status;
12520         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12521         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12522                 ctl_failover_io(io, /*have_lock*/ have_lock);
12523                 return;
12524         }
12525         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12526             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12527             msg.scsi.sense_len, M_WAITOK);
12528
12529 #ifdef CTL_TIME_IO
12530         getbinuptime(&cur_bt);
12531         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12532         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12533 #endif
12534         io->io_hdr.num_dmas++;
12535 }
12536
12537 /*
12538  * The DMA to the remote side is done, now we need to tell the other side
12539  * we're done so it can continue with its data movement.
12540  */
12541 static void
12542 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12543 {
12544         union ctl_io *io;
12545         uint32_t i;
12546
12547         io = rq->context;
12548
12549         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12550                 printf("%s: ISC DMA write failed with error %d", __func__,
12551                        rq->ret);
12552                 ctl_set_internal_failure(&io->scsiio,
12553                                          /*sks_valid*/ 1,
12554                                          /*retry_count*/ rq->ret);
12555         }
12556
12557         ctl_dt_req_free(rq);
12558
12559         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12560                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12561         free(io->io_hdr.remote_sglist, M_CTL);
12562         io->io_hdr.remote_sglist = NULL;
12563         io->io_hdr.local_sglist = NULL;
12564
12565         /*
12566          * The data is in local and remote memory, so now we need to send
12567          * status (good or back) back to the other side.
12568          */
12569         ctl_send_datamove_done(io, /*have_lock*/ 0);
12570 }
12571
12572 /*
12573  * We've moved the data from the host/controller into local memory.  Now we
12574  * need to push it over to the remote controller's memory.
12575  */
12576 static int
12577 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12578 {
12579         int retval;
12580
12581         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12582                                           ctl_datamove_remote_write_cb);
12583         return (retval);
12584 }
12585
12586 static void
12587 ctl_datamove_remote_write(union ctl_io *io)
12588 {
12589         int retval;
12590         void (*fe_datamove)(union ctl_io *io);
12591
12592         /*
12593          * - Get the data from the host/HBA into local memory.
12594          * - DMA memory from the local controller to the remote controller.
12595          * - Send status back to the remote controller.
12596          */
12597
12598         retval = ctl_datamove_remote_sgl_setup(io);
12599         if (retval != 0)
12600                 return;
12601
12602         /* Switch the pointer over so the FETD knows what to do */
12603         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12604
12605         /*
12606          * Use a custom move done callback, since we need to send completion
12607          * back to the other controller, not to the backend on this side.
12608          */
12609         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12610
12611         fe_datamove = CTL_PORT(io)->fe_datamove;
12612         fe_datamove(io);
12613 }
12614
12615 static int
12616 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12617 {
12618 #if 0
12619         char str[256];
12620         char path_str[64];
12621         struct sbuf sb;
12622 #endif
12623         uint32_t i;
12624
12625         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12626                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12627         free(io->io_hdr.remote_sglist, M_CTL);
12628         io->io_hdr.remote_sglist = NULL;
12629         io->io_hdr.local_sglist = NULL;
12630
12631 #if 0
12632         scsi_path_string(io, path_str, sizeof(path_str));
12633         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12634         sbuf_cat(&sb, path_str);
12635         scsi_command_string(&io->scsiio, NULL, &sb);
12636         sbuf_printf(&sb, "\n");
12637         sbuf_cat(&sb, path_str);
12638         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12639                     io->scsiio.tag_num, io->scsiio.tag_type);
12640         sbuf_cat(&sb, path_str);
12641         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12642                     io->io_hdr.flags, io->io_hdr.status);
12643         sbuf_finish(&sb);
12644         printk("%s", sbuf_data(&sb));
12645 #endif
12646
12647
12648         /*
12649          * The read is done, now we need to send status (good or bad) back
12650          * to the other side.
12651          */
12652         ctl_send_datamove_done(io, /*have_lock*/ 0);
12653
12654         return (0);
12655 }
12656
12657 static void
12658 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12659 {
12660         union ctl_io *io;
12661         void (*fe_datamove)(union ctl_io *io);
12662
12663         io = rq->context;
12664
12665         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12666                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12667                        rq->ret);
12668                 ctl_set_internal_failure(&io->scsiio,
12669                                          /*sks_valid*/ 1,
12670                                          /*retry_count*/ rq->ret);
12671         }
12672
12673         ctl_dt_req_free(rq);
12674
12675         /* Switch the pointer over so the FETD knows what to do */
12676         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12677
12678         /*
12679          * Use a custom move done callback, since we need to send completion
12680          * back to the other controller, not to the backend on this side.
12681          */
12682         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12683
12684         /* XXX KDM add checks like the ones in ctl_datamove? */
12685
12686         fe_datamove = CTL_PORT(io)->fe_datamove;
12687         fe_datamove(io);
12688 }
12689
12690 static int
12691 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12692 {
12693         struct ctl_sg_entry *local_sglist;
12694         uint32_t len_to_go;
12695         int retval;
12696         int i;
12697
12698         retval = 0;
12699         local_sglist = io->io_hdr.local_sglist;
12700         len_to_go = io->scsiio.kern_data_len;
12701
12702         /*
12703          * The difficult thing here is that the size of the various
12704          * S/G segments may be different than the size from the
12705          * remote controller.  That'll make it harder when DMAing
12706          * the data back to the other side.
12707          */
12708         for (i = 0; len_to_go > 0; i++) {
12709                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12710                 local_sglist[i].addr =
12711                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12712
12713                 len_to_go -= local_sglist[i].len;
12714         }
12715         /*
12716          * Reset the number of S/G entries accordingly.  The original
12717          * number of S/G entries is available in rem_sg_entries.
12718          */
12719         io->scsiio.kern_sg_entries = i;
12720
12721 #if 0
12722         printf("%s: kern_sg_entries = %d\n", __func__,
12723                io->scsiio.kern_sg_entries);
12724         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12725                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12726                        local_sglist[i].addr, local_sglist[i].len);
12727 #endif
12728
12729         return (retval);
12730 }
12731
12732 static int
12733 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12734                          ctl_ha_dt_cb callback)
12735 {
12736         struct ctl_ha_dt_req *rq;
12737         struct ctl_sg_entry *remote_sglist, *local_sglist;
12738         uint32_t local_used, remote_used, total_used;
12739         int i, j, isc_ret;
12740
12741         rq = ctl_dt_req_alloc();
12742
12743         /*
12744          * If we failed to allocate the request, and if the DMA didn't fail
12745          * anyway, set busy status.  This is just a resource allocation
12746          * failure.
12747          */
12748         if ((rq == NULL)
12749          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12750              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12751                 ctl_set_busy(&io->scsiio);
12752
12753         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12754             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12755
12756                 if (rq != NULL)
12757                         ctl_dt_req_free(rq);
12758
12759                 /*
12760                  * The data move failed.  We need to return status back
12761                  * to the other controller.  No point in trying to DMA
12762                  * data to the remote controller.
12763                  */
12764
12765                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12766
12767                 return (1);
12768         }
12769
12770         local_sglist = io->io_hdr.local_sglist;
12771         remote_sglist = io->io_hdr.remote_sglist;
12772         local_used = 0;
12773         remote_used = 0;
12774         total_used = 0;
12775
12776         /*
12777          * Pull/push the data over the wire from/to the other controller.
12778          * This takes into account the possibility that the local and
12779          * remote sglists may not be identical in terms of the size of
12780          * the elements and the number of elements.
12781          *
12782          * One fundamental assumption here is that the length allocated for
12783          * both the local and remote sglists is identical.  Otherwise, we've
12784          * essentially got a coding error of some sort.
12785          */
12786         isc_ret = CTL_HA_STATUS_SUCCESS;
12787         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12788                 uint32_t cur_len;
12789                 uint8_t *tmp_ptr;
12790
12791                 rq->command = command;
12792                 rq->context = io;
12793
12794                 /*
12795                  * Both pointers should be aligned.  But it is possible
12796                  * that the allocation length is not.  They should both
12797                  * also have enough slack left over at the end, though,
12798                  * to round up to the next 8 byte boundary.
12799                  */
12800                 cur_len = MIN(local_sglist[i].len - local_used,
12801                               remote_sglist[j].len - remote_used);
12802                 rq->size = cur_len;
12803
12804                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12805                 tmp_ptr += local_used;
12806
12807 #if 0
12808                 /* Use physical addresses when talking to ISC hardware */
12809                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12810                         /* XXX KDM use busdma */
12811                         rq->local = vtophys(tmp_ptr);
12812                 } else
12813                         rq->local = tmp_ptr;
12814 #else
12815                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12816                     ("HA does not support BUS_ADDR"));
12817                 rq->local = tmp_ptr;
12818 #endif
12819
12820                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12821                 tmp_ptr += remote_used;
12822                 rq->remote = tmp_ptr;
12823
12824                 rq->callback = NULL;
12825
12826                 local_used += cur_len;
12827                 if (local_used >= local_sglist[i].len) {
12828                         i++;
12829                         local_used = 0;
12830                 }
12831
12832                 remote_used += cur_len;
12833                 if (remote_used >= remote_sglist[j].len) {
12834                         j++;
12835                         remote_used = 0;
12836                 }
12837                 total_used += cur_len;
12838
12839                 if (total_used >= io->scsiio.kern_data_len)
12840                         rq->callback = callback;
12841
12842 #if 0
12843                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12844                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12845                        rq->local, rq->remote, rq->size);
12846 #endif
12847
12848                 isc_ret = ctl_dt_single(rq);
12849                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12850                         break;
12851         }
12852         if (isc_ret != CTL_HA_STATUS_WAIT) {
12853                 rq->ret = isc_ret;
12854                 callback(rq);
12855         }
12856
12857         return (0);
12858 }
12859
12860 static void
12861 ctl_datamove_remote_read(union ctl_io *io)
12862 {
12863         int retval;
12864         uint32_t i;
12865
12866         /*
12867          * This will send an error to the other controller in the case of a
12868          * failure.
12869          */
12870         retval = ctl_datamove_remote_sgl_setup(io);
12871         if (retval != 0)
12872                 return;
12873
12874         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12875                                           ctl_datamove_remote_read_cb);
12876         if (retval != 0) {
12877                 /*
12878                  * Make sure we free memory if there was an error..  The
12879                  * ctl_datamove_remote_xfer() function will send the
12880                  * datamove done message, or call the callback with an
12881                  * error if there is a problem.
12882                  */
12883                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12884                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12885                 free(io->io_hdr.remote_sglist, M_CTL);
12886                 io->io_hdr.remote_sglist = NULL;
12887                 io->io_hdr.local_sglist = NULL;
12888         }
12889 }
12890
12891 /*
12892  * Process a datamove request from the other controller.  This is used for
12893  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12894  * first.  Once that is complete, the data gets DMAed into the remote
12895  * controller's memory.  For reads, we DMA from the remote controller's
12896  * memory into our memory first, and then move it out to the FETD.
12897  */
12898 static void
12899 ctl_datamove_remote(union ctl_io *io)
12900 {
12901
12902         mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12903
12904         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12905                 ctl_failover_io(io, /*have_lock*/ 0);
12906                 return;
12907         }
12908
12909         /*
12910          * Note that we look for an aborted I/O here, but don't do some of
12911          * the other checks that ctl_datamove() normally does.
12912          * We don't need to run the datamove delay code, since that should
12913          * have been done if need be on the other controller.
12914          */
12915         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12916                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12917                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12918                        io->io_hdr.nexus.targ_port,
12919                        io->io_hdr.nexus.targ_lun);
12920                 io->io_hdr.port_status = 31338;
12921                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12922                 return;
12923         }
12924
12925         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12926                 ctl_datamove_remote_write(io);
12927         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12928                 ctl_datamove_remote_read(io);
12929         else {
12930                 io->io_hdr.port_status = 31339;
12931                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12932         }
12933 }
12934
12935 static void
12936 ctl_process_done(union ctl_io *io)
12937 {
12938         struct ctl_softc *softc = CTL_SOFTC(io);
12939         struct ctl_port *port = CTL_PORT(io);
12940         struct ctl_lun *lun = CTL_LUN(io);
12941         void (*fe_done)(union ctl_io *io);
12942         union ctl_ha_msg msg;
12943
12944         CTL_DEBUG_PRINT(("ctl_process_done\n"));
12945         fe_done = port->fe_done;
12946
12947 #ifdef CTL_TIME_IO
12948         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12949                 char str[256];
12950                 char path_str[64];
12951                 struct sbuf sb;
12952
12953                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12954                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12955
12956                 sbuf_cat(&sb, path_str);
12957                 switch (io->io_hdr.io_type) {
12958                 case CTL_IO_SCSI:
12959                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12960                         sbuf_printf(&sb, "\n");
12961                         sbuf_cat(&sb, path_str);
12962                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12963                                     io->scsiio.tag_num, io->scsiio.tag_type);
12964                         break;
12965                 case CTL_IO_TASK:
12966                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12967                                     "Tag Type: %d\n", io->taskio.task_action,
12968                                     io->taskio.tag_num, io->taskio.tag_type);
12969                         break;
12970                 default:
12971                         panic("%s: Invalid CTL I/O type %d\n",
12972                             __func__, io->io_hdr.io_type);
12973                 }
12974                 sbuf_cat(&sb, path_str);
12975                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12976                             (intmax_t)time_uptime - io->io_hdr.start_time);
12977                 sbuf_finish(&sb);
12978                 printf("%s", sbuf_data(&sb));
12979         }
12980 #endif /* CTL_TIME_IO */
12981
12982         switch (io->io_hdr.io_type) {
12983         case CTL_IO_SCSI:
12984                 break;
12985         case CTL_IO_TASK:
12986                 if (ctl_debug & CTL_DEBUG_INFO)
12987                         ctl_io_error_print(io, NULL);
12988                 fe_done(io);
12989                 return;
12990         default:
12991                 panic("%s: Invalid CTL I/O type %d\n",
12992                     __func__, io->io_hdr.io_type);
12993         }
12994
12995         if (lun == NULL) {
12996                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12997                                  io->io_hdr.nexus.targ_mapped_lun));
12998                 goto bailout;
12999         }
13000
13001         mtx_lock(&lun->lun_lock);
13002
13003         /*
13004          * Check to see if we have any informational exception and status
13005          * of this command can be modified to report it in form of either
13006          * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13007          */
13008         if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13009             io->io_hdr.status == CTL_SUCCESS &&
13010             (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13011                 uint8_t mrie = lun->MODE_IE.mrie;
13012                 uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13013                     (lun->MODE_VER.byte3 & SMS_VER_PER));
13014                 if (((mrie == SIEP_MRIE_REC_COND && per) ||
13015                      mrie == SIEP_MRIE_REC_UNCOND ||
13016                      mrie == SIEP_MRIE_NO_SENSE) &&
13017                     (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13018                      CTL_CMD_FLAG_NO_SENSE) == 0) {
13019                         ctl_set_sense(&io->scsiio,
13020                               /*current_error*/ 1,
13021                               /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13022                                 SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13023                               /*asc*/ lun->ie_asc,
13024                               /*ascq*/ lun->ie_ascq,
13025                               SSD_ELEM_NONE);
13026                         lun->ie_reported = 1;
13027                 }
13028         } else if (lun->ie_reported < 0)
13029                 lun->ie_reported = 0;
13030
13031         /*
13032          * Check to see if we have any errors to inject here.  We only
13033          * inject errors for commands that don't already have errors set.
13034          */
13035         if (!STAILQ_EMPTY(&lun->error_list) &&
13036             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13037             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13038                 ctl_inject_error(lun, io);
13039
13040         /*
13041          * XXX KDM how do we treat commands that aren't completed
13042          * successfully?
13043          *
13044          * XXX KDM should we also track I/O latency?
13045          */
13046         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13047             io->io_hdr.io_type == CTL_IO_SCSI) {
13048                 int type;
13049 #ifdef CTL_TIME_IO
13050                 struct bintime bt;
13051
13052                 getbinuptime(&bt);
13053                 bintime_sub(&bt, &io->io_hdr.start_bt);
13054 #endif
13055                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13056                     CTL_FLAG_DATA_IN)
13057                         type = CTL_STATS_READ;
13058                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13059                     CTL_FLAG_DATA_OUT)
13060                         type = CTL_STATS_WRITE;
13061                 else
13062                         type = CTL_STATS_NO_IO;
13063
13064 #ifdef CTL_LEGACY_STATS
13065                 uint32_t targ_port = port->targ_port;
13066                 lun->legacy_stats.ports[targ_port].bytes[type] +=
13067                     io->scsiio.kern_total_len;
13068                 lun->legacy_stats.ports[targ_port].operations[type] ++;
13069                 lun->legacy_stats.ports[targ_port].num_dmas[type] +=
13070                     io->io_hdr.num_dmas;
13071 #ifdef CTL_TIME_IO
13072                 bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
13073                    &io->io_hdr.dma_bt);
13074                 bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
13075                     &bt);
13076 #endif
13077 #endif /* CTL_LEGACY_STATS */
13078
13079                 lun->stats.bytes[type] += io->scsiio.kern_total_len;
13080                 lun->stats.operations[type] ++;
13081                 lun->stats.dmas[type] += io->io_hdr.num_dmas;
13082 #ifdef CTL_TIME_IO
13083                 bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13084                 bintime_add(&lun->stats.time[type], &bt);
13085 #endif
13086
13087                 mtx_lock(&port->port_lock);
13088                 port->stats.bytes[type] += io->scsiio.kern_total_len;
13089                 port->stats.operations[type] ++;
13090                 port->stats.dmas[type] += io->io_hdr.num_dmas;
13091 #ifdef CTL_TIME_IO
13092                 bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13093                 bintime_add(&port->stats.time[type], &bt);
13094 #endif
13095                 mtx_unlock(&port->port_lock);
13096         }
13097
13098         /*
13099          * Remove this from the OOA queue.
13100          */
13101         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13102 #ifdef CTL_TIME_IO
13103         if (TAILQ_EMPTY(&lun->ooa_queue))
13104                 lun->last_busy = getsbinuptime();
13105 #endif
13106
13107         /*
13108          * Run through the blocked queue on this LUN and see if anything
13109          * has become unblocked, now that this transaction is done.
13110          */
13111         ctl_check_blocked(lun);
13112
13113         /*
13114          * If the LUN has been invalidated, free it if there is nothing
13115          * left on its OOA queue.
13116          */
13117         if ((lun->flags & CTL_LUN_INVALID)
13118          && TAILQ_EMPTY(&lun->ooa_queue)) {
13119                 mtx_unlock(&lun->lun_lock);
13120                 ctl_free_lun(lun);
13121         } else
13122                 mtx_unlock(&lun->lun_lock);
13123
13124 bailout:
13125
13126         /*
13127          * If this command has been aborted, make sure we set the status
13128          * properly.  The FETD is responsible for freeing the I/O and doing
13129          * whatever it needs to do to clean up its state.
13130          */
13131         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13132                 ctl_set_task_aborted(&io->scsiio);
13133
13134         /*
13135          * If enabled, print command error status.
13136          */
13137         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13138             (ctl_debug & CTL_DEBUG_INFO) != 0)
13139                 ctl_io_error_print(io, NULL);
13140
13141         /*
13142          * Tell the FETD or the other shelf controller we're done with this
13143          * command.  Note that only SCSI commands get to this point.  Task
13144          * management commands are completed above.
13145          */
13146         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13147             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13148                 memset(&msg, 0, sizeof(msg));
13149                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13150                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13151                 msg.hdr.nexus = io->io_hdr.nexus;
13152                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13153                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13154                     M_WAITOK);
13155         }
13156
13157         fe_done(io);
13158 }
13159
13160 /*
13161  * Front end should call this if it doesn't do autosense.  When the request
13162  * sense comes back in from the initiator, we'll dequeue this and send it.
13163  */
13164 int
13165 ctl_queue_sense(union ctl_io *io)
13166 {
13167         struct ctl_softc *softc = CTL_SOFTC(io);
13168         struct ctl_port *port = CTL_PORT(io);
13169         struct ctl_lun *lun;
13170         struct scsi_sense_data *ps;
13171         uint32_t initidx, p, targ_lun;
13172
13173         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13174
13175         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13176
13177         /*
13178          * LUN lookup will likely move to the ctl_work_thread() once we
13179          * have our new queueing infrastructure (that doesn't put things on
13180          * a per-LUN queue initially).  That is so that we can handle
13181          * things like an INQUIRY to a LUN that we don't have enabled.  We
13182          * can't deal with that right now.
13183          * If we don't have a LUN for this, just toss the sense information.
13184          */
13185         mtx_lock(&softc->ctl_lock);
13186         if (targ_lun >= ctl_max_luns ||
13187             (lun = softc->ctl_luns[targ_lun]) == NULL) {
13188                 mtx_unlock(&softc->ctl_lock);
13189                 goto bailout;
13190         }
13191         mtx_lock(&lun->lun_lock);
13192         mtx_unlock(&softc->ctl_lock);
13193
13194         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13195         p = initidx / CTL_MAX_INIT_PER_PORT;
13196         if (lun->pending_sense[p] == NULL) {
13197                 lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13198                     M_CTL, M_NOWAIT | M_ZERO);
13199         }
13200         if ((ps = lun->pending_sense[p]) != NULL) {
13201                 ps += initidx % CTL_MAX_INIT_PER_PORT;
13202                 memset(ps, 0, sizeof(*ps));
13203                 memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13204         }
13205         mtx_unlock(&lun->lun_lock);
13206
13207 bailout:
13208         ctl_free_io(io);
13209         return (CTL_RETVAL_COMPLETE);
13210 }
13211
13212 /*
13213  * Primary command inlet from frontend ports.  All SCSI and task I/O
13214  * requests must go through this function.
13215  */
13216 int
13217 ctl_queue(union ctl_io *io)
13218 {
13219         struct ctl_port *port = CTL_PORT(io);
13220
13221         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13222
13223 #ifdef CTL_TIME_IO
13224         io->io_hdr.start_time = time_uptime;
13225         getbinuptime(&io->io_hdr.start_bt);
13226 #endif /* CTL_TIME_IO */
13227
13228         /* Map FE-specific LUN ID into global one. */
13229         io->io_hdr.nexus.targ_mapped_lun =
13230             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13231
13232         switch (io->io_hdr.io_type) {
13233         case CTL_IO_SCSI:
13234         case CTL_IO_TASK:
13235                 if (ctl_debug & CTL_DEBUG_CDB)
13236                         ctl_io_print(io);
13237                 ctl_enqueue_incoming(io);
13238                 break;
13239         default:
13240                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13241                 return (EINVAL);
13242         }
13243
13244         return (CTL_RETVAL_COMPLETE);
13245 }
13246
13247 #ifdef CTL_IO_DELAY
13248 static void
13249 ctl_done_timer_wakeup(void *arg)
13250 {
13251         union ctl_io *io;
13252
13253         io = (union ctl_io *)arg;
13254         ctl_done(io);
13255 }
13256 #endif /* CTL_IO_DELAY */
13257
13258 void
13259 ctl_serseq_done(union ctl_io *io)
13260 {
13261         struct ctl_lun *lun = CTL_LUN(io);;
13262
13263         if (lun->be_lun == NULL ||
13264             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13265                 return;
13266         mtx_lock(&lun->lun_lock);
13267         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13268         ctl_check_blocked(lun);
13269         mtx_unlock(&lun->lun_lock);
13270 }
13271
13272 void
13273 ctl_done(union ctl_io *io)
13274 {
13275
13276         /*
13277          * Enable this to catch duplicate completion issues.
13278          */
13279 #if 0
13280         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13281                 printf("%s: type %d msg %d cdb %x iptl: "
13282                        "%u:%u:%u tag 0x%04x "
13283                        "flag %#x status %x\n",
13284                         __func__,
13285                         io->io_hdr.io_type,
13286                         io->io_hdr.msg_type,
13287                         io->scsiio.cdb[0],
13288                         io->io_hdr.nexus.initid,
13289                         io->io_hdr.nexus.targ_port,
13290                         io->io_hdr.nexus.targ_lun,
13291                         (io->io_hdr.io_type ==
13292                         CTL_IO_TASK) ?
13293                         io->taskio.tag_num :
13294                         io->scsiio.tag_num,
13295                         io->io_hdr.flags,
13296                         io->io_hdr.status);
13297         } else
13298                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13299 #endif
13300
13301         /*
13302          * This is an internal copy of an I/O, and should not go through
13303          * the normal done processing logic.
13304          */
13305         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13306                 return;
13307
13308 #ifdef CTL_IO_DELAY
13309         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13310                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13311         } else {
13312                 struct ctl_lun *lun = CTL_LUN(io);
13313
13314                 if ((lun != NULL)
13315                  && (lun->delay_info.done_delay > 0)) {
13316
13317                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13318                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13319                         callout_reset(&io->io_hdr.delay_callout,
13320                                       lun->delay_info.done_delay * hz,
13321                                       ctl_done_timer_wakeup, io);
13322                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13323                                 lun->delay_info.done_delay = 0;
13324                         return;
13325                 }
13326         }
13327 #endif /* CTL_IO_DELAY */
13328
13329         ctl_enqueue_done(io);
13330 }
13331
13332 static void
13333 ctl_work_thread(void *arg)
13334 {
13335         struct ctl_thread *thr = (struct ctl_thread *)arg;
13336         struct ctl_softc *softc = thr->ctl_softc;
13337         union ctl_io *io;
13338         int retval;
13339
13340         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13341
13342         while (!softc->shutdown) {
13343                 /*
13344                  * We handle the queues in this order:
13345                  * - ISC
13346                  * - done queue (to free up resources, unblock other commands)
13347                  * - incoming queue
13348                  * - RtR queue
13349                  *
13350                  * If those queues are empty, we break out of the loop and
13351                  * go to sleep.
13352                  */
13353                 mtx_lock(&thr->queue_lock);
13354                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13355                 if (io != NULL) {
13356                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13357                         mtx_unlock(&thr->queue_lock);
13358                         ctl_handle_isc(io);
13359                         continue;
13360                 }
13361                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13362                 if (io != NULL) {
13363                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13364                         /* clear any blocked commands, call fe_done */
13365                         mtx_unlock(&thr->queue_lock);
13366                         ctl_process_done(io);
13367                         continue;
13368                 }
13369                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13370                 if (io != NULL) {
13371                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13372                         mtx_unlock(&thr->queue_lock);
13373                         if (io->io_hdr.io_type == CTL_IO_TASK)
13374                                 ctl_run_task(io);
13375                         else
13376                                 ctl_scsiio_precheck(softc, &io->scsiio);
13377                         continue;
13378                 }
13379                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13380                 if (io != NULL) {
13381                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13382                         mtx_unlock(&thr->queue_lock);
13383                         retval = ctl_scsiio(&io->scsiio);
13384                         if (retval != CTL_RETVAL_COMPLETE)
13385                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13386                         continue;
13387                 }
13388
13389                 /* Sleep until we have something to do. */
13390                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13391         }
13392         thr->thread = NULL;
13393         kthread_exit();
13394 }
13395
13396 static void
13397 ctl_lun_thread(void *arg)
13398 {
13399         struct ctl_softc *softc = (struct ctl_softc *)arg;
13400         struct ctl_be_lun *be_lun;
13401
13402         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13403
13404         while (!softc->shutdown) {
13405                 mtx_lock(&softc->ctl_lock);
13406                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13407                 if (be_lun != NULL) {
13408                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13409                         mtx_unlock(&softc->ctl_lock);
13410                         ctl_create_lun(be_lun);
13411                         continue;
13412                 }
13413
13414                 /* Sleep until we have something to do. */
13415                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13416                     PDROP | PRIBIO, "-", 0);
13417         }
13418         softc->lun_thread = NULL;
13419         kthread_exit();
13420 }
13421
13422 static void
13423 ctl_thresh_thread(void *arg)
13424 {
13425         struct ctl_softc *softc = (struct ctl_softc *)arg;
13426         struct ctl_lun *lun;
13427         struct ctl_logical_block_provisioning_page *page;
13428         const char *attr;
13429         union ctl_ha_msg msg;
13430         uint64_t thres, val;
13431         int i, e, set;
13432
13433         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13434
13435         while (!softc->shutdown) {
13436                 mtx_lock(&softc->ctl_lock);
13437                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13438                         if ((lun->flags & CTL_LUN_DISABLED) ||
13439                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13440                             lun->backend->lun_attr == NULL)
13441                                 continue;
13442                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13443                             softc->ha_mode == CTL_HA_MODE_XFER)
13444                                 continue;
13445                         if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13446                                 continue;
13447                         e = 0;
13448                         page = &lun->MODE_LBP;
13449                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13450                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13451                                         continue;
13452                                 thres = scsi_4btoul(page->descr[i].count);
13453                                 thres <<= CTL_LBP_EXPONENT;
13454                                 switch (page->descr[i].resource) {
13455                                 case 0x01:
13456                                         attr = "blocksavail";
13457                                         break;
13458                                 case 0x02:
13459                                         attr = "blocksused";
13460                                         break;
13461                                 case 0xf1:
13462                                         attr = "poolblocksavail";
13463                                         break;
13464                                 case 0xf2:
13465                                         attr = "poolblocksused";
13466                                         break;
13467                                 default:
13468                                         continue;
13469                                 }
13470                                 mtx_unlock(&softc->ctl_lock); // XXX
13471                                 val = lun->backend->lun_attr(
13472                                     lun->be_lun->be_lun, attr);
13473                                 mtx_lock(&softc->ctl_lock);
13474                                 if (val == UINT64_MAX)
13475                                         continue;
13476                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13477                                     == SLBPPD_ARMING_INC)
13478                                         e = (val >= thres);
13479                                 else
13480                                         e = (val <= thres);
13481                                 if (e)
13482                                         break;
13483                         }
13484                         mtx_lock(&lun->lun_lock);
13485                         if (e) {
13486                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13487                                     (uint8_t *)page, lun->ua_tpt_info);
13488                                 if (lun->lasttpt == 0 ||
13489                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13490                                         lun->lasttpt = time_uptime;
13491                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13492                                         set = 1;
13493                                 } else
13494                                         set = 0;
13495                         } else {
13496                                 lun->lasttpt = 0;
13497                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13498                                 set = -1;
13499                         }
13500                         mtx_unlock(&lun->lun_lock);
13501                         if (set != 0 &&
13502                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13503                                 /* Send msg to other side. */
13504                                 bzero(&msg.ua, sizeof(msg.ua));
13505                                 msg.hdr.msg_type = CTL_MSG_UA;
13506                                 msg.hdr.nexus.initid = -1;
13507                                 msg.hdr.nexus.targ_port = -1;
13508                                 msg.hdr.nexus.targ_lun = lun->lun;
13509                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13510                                 msg.ua.ua_all = 1;
13511                                 msg.ua.ua_set = (set > 0);
13512                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13513                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13514                                 mtx_unlock(&softc->ctl_lock); // XXX
13515                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13516                                     sizeof(msg.ua), M_WAITOK);
13517                                 mtx_lock(&softc->ctl_lock);
13518                         }
13519                 }
13520                 mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13521                     PDROP | PRIBIO, "-", CTL_LBP_PERIOD * hz);
13522         }
13523         softc->thresh_thread = NULL;
13524         kthread_exit();
13525 }
13526
13527 static void
13528 ctl_enqueue_incoming(union ctl_io *io)
13529 {
13530         struct ctl_softc *softc = CTL_SOFTC(io);
13531         struct ctl_thread *thr;
13532         u_int idx;
13533
13534         idx = (io->io_hdr.nexus.targ_port * 127 +
13535                io->io_hdr.nexus.initid) % worker_threads;
13536         thr = &softc->threads[idx];
13537         mtx_lock(&thr->queue_lock);
13538         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13539         mtx_unlock(&thr->queue_lock);
13540         wakeup(thr);
13541 }
13542
13543 static void
13544 ctl_enqueue_rtr(union ctl_io *io)
13545 {
13546         struct ctl_softc *softc = CTL_SOFTC(io);
13547         struct ctl_thread *thr;
13548
13549         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13550         mtx_lock(&thr->queue_lock);
13551         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13552         mtx_unlock(&thr->queue_lock);
13553         wakeup(thr);
13554 }
13555
13556 static void
13557 ctl_enqueue_done(union ctl_io *io)
13558 {
13559         struct ctl_softc *softc = CTL_SOFTC(io);
13560         struct ctl_thread *thr;
13561
13562         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13563         mtx_lock(&thr->queue_lock);
13564         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13565         mtx_unlock(&thr->queue_lock);
13566         wakeup(thr);
13567 }
13568
13569 static void
13570 ctl_enqueue_isc(union ctl_io *io)
13571 {
13572         struct ctl_softc *softc = CTL_SOFTC(io);
13573         struct ctl_thread *thr;
13574
13575         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13576         mtx_lock(&thr->queue_lock);
13577         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13578         mtx_unlock(&thr->queue_lock);
13579         wakeup(thr);
13580 }
13581
13582 /*
13583  *  vim: ts=8
13584  */