]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r310356: Add support for locally assigned RFC 4122 UUID LUN identifiers.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42
43 #define _CTL_C
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_cd.h>
73 #include <cam/scsi/scsi_da.h>
74 #include <cam/ctl/ctl_io.h>
75 #include <cam/ctl/ctl.h>
76 #include <cam/ctl/ctl_frontend.h>
77 #include <cam/ctl/ctl_util.h>
78 #include <cam/ctl/ctl_backend.h>
79 #include <cam/ctl/ctl_ioctl.h>
80 #include <cam/ctl/ctl_ha.h>
81 #include <cam/ctl/ctl_private.h>
82 #include <cam/ctl/ctl_debug.h>
83 #include <cam/ctl/ctl_scsi_all.h>
84 #include <cam/ctl/ctl_error.h>
85
86 struct ctl_softc *control_softc = NULL;
87
88 /*
89  * Template mode pages.
90  */
91
92 /*
93  * Note that these are default values only.  The actual values will be
94  * filled in when the user does a mode sense.
95  */
96 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
97         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100         /*read_retry_count*/0,
101         /*correction_span*/0,
102         /*head_offset_count*/0,
103         /*data_strobe_offset_cnt*/0,
104         /*byte8*/SMS_RWER_LBPERE,
105         /*write_retry_count*/0,
106         /*reserved2*/0,
107         /*recovery_time_limit*/{0, 0},
108 };
109
110 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113         /*byte3*/SMS_RWER_PER,
114         /*read_retry_count*/0,
115         /*correction_span*/0,
116         /*head_offset_count*/0,
117         /*data_strobe_offset_cnt*/0,
118         /*byte8*/SMS_RWER_LBPERE,
119         /*write_retry_count*/0,
120         /*reserved2*/0,
121         /*recovery_time_limit*/{0, 0},
122 };
123
124 const static struct scsi_format_page format_page_default = {
125         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
126         /*page_length*/sizeof(struct scsi_format_page) - 2,
127         /*tracks_per_zone*/ {0, 0},
128         /*alt_sectors_per_zone*/ {0, 0},
129         /*alt_tracks_per_zone*/ {0, 0},
130         /*alt_tracks_per_lun*/ {0, 0},
131         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133         /*bytes_per_sector*/ {0, 0},
134         /*interleave*/ {0, 0},
135         /*track_skew*/ {0, 0},
136         /*cylinder_skew*/ {0, 0},
137         /*flags*/ SFP_HSEC,
138         /*reserved*/ {0, 0, 0}
139 };
140
141 const static struct scsi_format_page format_page_changeable = {
142         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
143         /*page_length*/sizeof(struct scsi_format_page) - 2,
144         /*tracks_per_zone*/ {0, 0},
145         /*alt_sectors_per_zone*/ {0, 0},
146         /*alt_tracks_per_zone*/ {0, 0},
147         /*alt_tracks_per_lun*/ {0, 0},
148         /*sectors_per_track*/ {0, 0},
149         /*bytes_per_sector*/ {0, 0},
150         /*interleave*/ {0, 0},
151         /*track_skew*/ {0, 0},
152         /*cylinder_skew*/ {0, 0},
153         /*flags*/ 0,
154         /*reserved*/ {0, 0, 0}
155 };
156
157 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158         /*page_code*/SMS_RIGID_DISK_PAGE,
159         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160         /*cylinders*/ {0, 0, 0},
161         /*heads*/ CTL_DEFAULT_HEADS,
162         /*start_write_precomp*/ {0, 0, 0},
163         /*start_reduced_current*/ {0, 0, 0},
164         /*step_rate*/ {0, 0},
165         /*landing_zone_cylinder*/ {0, 0, 0},
166         /*rpl*/ SRDP_RPL_DISABLED,
167         /*rotational_offset*/ 0,
168         /*reserved1*/ 0,
169         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170                            CTL_DEFAULT_ROTATION_RATE & 0xff},
171         /*reserved2*/ {0, 0}
172 };
173
174 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175         /*page_code*/SMS_RIGID_DISK_PAGE,
176         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177         /*cylinders*/ {0, 0, 0},
178         /*heads*/ 0,
179         /*start_write_precomp*/ {0, 0, 0},
180         /*start_reduced_current*/ {0, 0, 0},
181         /*step_rate*/ {0, 0},
182         /*landing_zone_cylinder*/ {0, 0, 0},
183         /*rpl*/ 0,
184         /*rotational_offset*/ 0,
185         /*reserved1*/ 0,
186         /*rotation_rate*/ {0, 0},
187         /*reserved2*/ {0, 0}
188 };
189
190 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193         /*byte3*/0,
194         /*read_retry_count*/0,
195         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
196         /*recovery_time_limit*/{0, 0},
197 };
198
199 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202         /*byte3*/SMS_VER_PER,
203         /*read_retry_count*/0,
204         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
205         /*recovery_time_limit*/{0, 0},
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
265
266 const static struct scsi_control_ext_page control_ext_page_default = {
267         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268         /*subpage_code*/0x01,
269         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270         /*flags*/0,
271         /*prio*/0,
272         /*max_sense*/0
273 };
274
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277         /*subpage_code*/0x01,
278         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279         /*flags*/0,
280         /*prio*/0,
281         /*max_sense*/0
282 };
283
284 const static struct scsi_info_exceptions_page ie_page_default = {
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287         /*info_flags*/SIEP_FLAGS_EWASC,
288         /*mrie*/SIEP_MRIE_NO,
289         /*interval_timer*/{0, 0, 0, 0},
290         /*report_count*/{0, 0, 0, 1}
291 };
292
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296         /*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297             SIEP_FLAGS_LOGERR,
298         /*mrie*/0x0f,
299         /*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300         /*report_count*/{0xff, 0xff, 0xff, 0xff}
301 };
302
303 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307         /*subpage_code*/0x02,
308         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309         /*flags*/0,
310         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311         /*descr*/{}},
312         {{/*flags*/0,
313           /*resource*/0x01,
314           /*reserved*/{0, 0},
315           /*count*/{0, 0, 0, 0}},
316          {/*flags*/0,
317           /*resource*/0x02,
318           /*reserved*/{0, 0},
319           /*count*/{0, 0, 0, 0}},
320          {/*flags*/0,
321           /*resource*/0xf1,
322           /*reserved*/{0, 0},
323           /*count*/{0, 0, 0, 0}},
324          {/*flags*/0,
325           /*resource*/0xf2,
326           /*reserved*/{0, 0},
327           /*count*/{0, 0, 0, 0}}
328         }
329 };
330
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333         /*subpage_code*/0x02,
334         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335         /*flags*/0,
336         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337         /*descr*/{}},
338         {{/*flags*/0,
339           /*resource*/0,
340           /*reserved*/{0, 0},
341           /*count*/{0, 0, 0, 0}},
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         }
355 };
356
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358         /*page_code*/SMS_CDDVD_CAPS_PAGE,
359         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360         /*caps1*/0x3f,
361         /*caps2*/0x00,
362         /*caps3*/0xf0,
363         /*caps4*/0x00,
364         /*caps5*/0x29,
365         /*caps6*/0x00,
366         /*obsolete*/{0, 0},
367         /*nvol_levels*/{0, 0},
368         /*buffer_size*/{8, 0},
369         /*obsolete2*/{0, 0},
370         /*reserved*/0,
371         /*digital*/0,
372         /*obsolete3*/0,
373         /*copy_management*/0,
374         /*reserved2*/0,
375         /*rotation_control*/0,
376         /*cur_write_speed*/0,
377         /*num_speed_descr*/0,
378 };
379
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381         /*page_code*/SMS_CDDVD_CAPS_PAGE,
382         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383         /*caps1*/0,
384         /*caps2*/0,
385         /*caps3*/0,
386         /*caps4*/0,
387         /*caps5*/0,
388         /*caps6*/0,
389         /*obsolete*/{0, 0},
390         /*nvol_levels*/{0, 0},
391         /*buffer_size*/{0, 0},
392         /*obsolete2*/{0, 0},
393         /*reserved*/0,
394         /*digital*/0,
395         /*obsolete3*/0,
396         /*copy_management*/0,
397         /*reserved2*/0,
398         /*rotation_control*/0,
399         /*cur_write_speed*/0,
400         /*num_speed_descr*/0,
401 };
402
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407     &worker_threads, 1, "Number of worker threads");
408 static int ctl_debug = CTL_DEBUG_NONE;
409 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411     &ctl_debug, 0, "Enabled debug flags");
412
413 /*
414  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
415  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
416  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
417  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
418  */
419 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
420
421 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
422                                   int param);
423 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
424 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
425 static int ctl_init(void);
426 void ctl_shutdown(void);
427 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
428 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
429 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
430 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
431                               struct ctl_ooa *ooa_hdr,
432                               struct ctl_ooa_entry *kern_entries);
433 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
434                      struct thread *td);
435 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
436                          struct ctl_be_lun *be_lun);
437 static int ctl_free_lun(struct ctl_lun *lun);
438 static void ctl_create_lun(struct ctl_be_lun *be_lun);
439 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
440
441 static int ctl_do_mode_select(union ctl_io *io);
442 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443                            uint64_t res_key, uint64_t sa_res_key,
444                            uint8_t type, uint32_t residx,
445                            struct ctl_scsiio *ctsio,
446                            struct scsi_per_res_out *cdb,
447                            struct scsi_per_res_out_parms* param);
448 static void ctl_pro_preempt_other(struct ctl_lun *lun,
449                                   union ctl_ha_msg *msg);
450 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
451 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457                                          int alloc_len);
458 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459                                          int alloc_len);
460 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466     bool seq);
467 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469     union ctl_io *pending_io, union ctl_io *ooa_io);
470 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471                                 union ctl_io *starting_io);
472 static int ctl_check_blocked(struct ctl_lun *lun);
473 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474                                 const struct ctl_cmd_entry *entry,
475                                 struct ctl_scsiio *ctsio);
476 static void ctl_failover_lun(union ctl_io *io);
477 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478                                struct ctl_scsiio *ctsio);
479 static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483                             ctl_ua_type ua_type);
484 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485                          ctl_ua_type ua_type);
486 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487 static int ctl_abort_task(union ctl_io *io);
488 static int ctl_abort_task_set(union ctl_io *io);
489 static int ctl_query_task(union ctl_io *io, int task_set);
490 static int ctl_i_t_nexus_reset(union ctl_io *io);
491 static int ctl_query_async_event(union ctl_io *io);
492 static void ctl_run_task(union ctl_io *io);
493 #ifdef CTL_IO_DELAY
494 static void ctl_datamove_timer_wakeup(void *arg);
495 static void ctl_done_timer_wakeup(void *arg);
496 #endif /* CTL_IO_DELAY */
497
498 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501 static void ctl_datamove_remote_write(union ctl_io *io);
502 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506                                     ctl_ha_dt_cb callback);
507 static void ctl_datamove_remote_read(union ctl_io *io);
508 static void ctl_datamove_remote(union ctl_io *io);
509 static void ctl_process_done(union ctl_io *io);
510 static void ctl_lun_thread(void *arg);
511 static void ctl_thresh_thread(void *arg);
512 static void ctl_work_thread(void *arg);
513 static void ctl_enqueue_incoming(union ctl_io *io);
514 static void ctl_enqueue_rtr(union ctl_io *io);
515 static void ctl_enqueue_done(union ctl_io *io);
516 static void ctl_enqueue_isc(union ctl_io *io);
517 static const struct ctl_cmd_entry *
518     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519 static const struct ctl_cmd_entry *
520     ctl_validate_command(struct ctl_scsiio *ctsio);
521 static int ctl_cmd_applicable(uint8_t lun_type,
522     const struct ctl_cmd_entry *entry);
523
524 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528
529 /*
530  * Load the serialization table.  This isn't very pretty, but is probably
531  * the easiest way to do it.
532  */
533 #include "ctl_ser_table.c"
534
535 /*
536  * We only need to define open, close and ioctl routines for this driver.
537  */
538 static struct cdevsw ctl_cdevsw = {
539         .d_version =    D_VERSION,
540         .d_flags =      0,
541         .d_open =       ctl_open,
542         .d_close =      ctl_close,
543         .d_ioctl =      ctl_ioctl,
544         .d_name =       "ctl",
545 };
546
547
548 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549
550 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551
552 static moduledata_t ctl_moduledata = {
553         "ctl",
554         ctl_module_event_handler,
555         NULL
556 };
557
558 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559 MODULE_VERSION(ctl, 1);
560
561 static struct ctl_frontend ha_frontend =
562 {
563         .name = "ha",
564 };
565
566 static void
567 ctl_ha_datamove(union ctl_io *io)
568 {
569         struct ctl_lun *lun;
570         struct ctl_sg_entry *sgl;
571         union ctl_ha_msg msg;
572         uint32_t sg_entries_sent;
573         int do_sg_copy, i, j;
574
575         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
576         memset(&msg.dt, 0, sizeof(msg.dt));
577         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
578         msg.hdr.original_sc = io->io_hdr.original_sc;
579         msg.hdr.serializing_sc = io;
580         msg.hdr.nexus = io->io_hdr.nexus;
581         msg.hdr.status = io->io_hdr.status;
582         msg.dt.flags = io->io_hdr.flags;
583
584         /*
585          * We convert everything into a S/G list here.  We can't
586          * pass by reference, only by value between controllers.
587          * So we can't pass a pointer to the S/G list, only as many
588          * S/G entries as we can fit in here.  If it's possible for
589          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
590          * then we need to break this up into multiple transfers.
591          */
592         if (io->scsiio.kern_sg_entries == 0) {
593                 msg.dt.kern_sg_entries = 1;
594 #if 0
595                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
596                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
597                 } else {
598                         /* XXX KDM use busdma here! */
599                         msg.dt.sg_list[0].addr =
600                             (void *)vtophys(io->scsiio.kern_data_ptr);
601                 }
602 #else
603                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
604                     ("HA does not support BUS_ADDR"));
605                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
606 #endif
607                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
608                 do_sg_copy = 0;
609         } else {
610                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
611                 do_sg_copy = 1;
612         }
613
614         msg.dt.kern_data_len = io->scsiio.kern_data_len;
615         msg.dt.kern_total_len = io->scsiio.kern_total_len;
616         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
617         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
618         msg.dt.sg_sequence = 0;
619
620         /*
621          * Loop until we've sent all of the S/G entries.  On the
622          * other end, we'll recompose these S/G entries into one
623          * contiguous list before processing.
624          */
625         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
626             msg.dt.sg_sequence++) {
627                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
628                     sizeof(msg.dt.sg_list[0])),
629                     msg.dt.kern_sg_entries - sg_entries_sent);
630                 if (do_sg_copy != 0) {
631                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
632                         for (i = sg_entries_sent, j = 0;
633                              i < msg.dt.cur_sg_entries; i++, j++) {
634 #if 0
635                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
636                                         msg.dt.sg_list[j].addr = sgl[i].addr;
637                                 } else {
638                                         /* XXX KDM use busdma here! */
639                                         msg.dt.sg_list[j].addr =
640                                             (void *)vtophys(sgl[i].addr);
641                                 }
642 #else
643                                 KASSERT((io->io_hdr.flags &
644                                     CTL_FLAG_BUS_ADDR) == 0,
645                                     ("HA does not support BUS_ADDR"));
646                                 msg.dt.sg_list[j].addr = sgl[i].addr;
647 #endif
648                                 msg.dt.sg_list[j].len = sgl[i].len;
649                         }
650                 }
651
652                 sg_entries_sent += msg.dt.cur_sg_entries;
653                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
654                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
655                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
656                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
657                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
658                         io->io_hdr.port_status = 31341;
659                         io->scsiio.be_move_done(io);
660                         return;
661                 }
662                 msg.dt.sent_sg_entries = sg_entries_sent;
663         }
664
665         /*
666          * Officially handover the request from us to peer.
667          * If failover has just happened, then we must return error.
668          * If failover happen just after, then it is not our problem.
669          */
670         if (lun)
671                 mtx_lock(&lun->lun_lock);
672         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
673                 if (lun)
674                         mtx_unlock(&lun->lun_lock);
675                 io->io_hdr.port_status = 31342;
676                 io->scsiio.be_move_done(io);
677                 return;
678         }
679         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
680         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
681         if (lun)
682                 mtx_unlock(&lun->lun_lock);
683 }
684
685 static void
686 ctl_ha_done(union ctl_io *io)
687 {
688         union ctl_ha_msg msg;
689
690         if (io->io_hdr.io_type == CTL_IO_SCSI) {
691                 memset(&msg, 0, sizeof(msg));
692                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
693                 msg.hdr.original_sc = io->io_hdr.original_sc;
694                 msg.hdr.nexus = io->io_hdr.nexus;
695                 msg.hdr.status = io->io_hdr.status;
696                 msg.scsi.scsi_status = io->scsiio.scsi_status;
697                 msg.scsi.tag_num = io->scsiio.tag_num;
698                 msg.scsi.tag_type = io->scsiio.tag_type;
699                 msg.scsi.sense_len = io->scsiio.sense_len;
700                 msg.scsi.sense_residual = io->scsiio.sense_residual;
701                 msg.scsi.residual = io->scsiio.residual;
702                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
703                     io->scsiio.sense_len);
704                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
705                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
706                     msg.scsi.sense_len, M_WAITOK);
707         }
708         ctl_free_io(io);
709 }
710
711 static void
712 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
713                             union ctl_ha_msg *msg_info)
714 {
715         struct ctl_scsiio *ctsio;
716
717         if (msg_info->hdr.original_sc == NULL) {
718                 printf("%s: original_sc == NULL!\n", __func__);
719                 /* XXX KDM now what? */
720                 return;
721         }
722
723         ctsio = &msg_info->hdr.original_sc->scsiio;
724         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
725         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
726         ctsio->io_hdr.status = msg_info->hdr.status;
727         ctsio->scsi_status = msg_info->scsi.scsi_status;
728         ctsio->sense_len = msg_info->scsi.sense_len;
729         ctsio->sense_residual = msg_info->scsi.sense_residual;
730         ctsio->residual = msg_info->scsi.residual;
731         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
732                msg_info->scsi.sense_len);
733         ctl_enqueue_isc((union ctl_io *)ctsio);
734 }
735
736 static void
737 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
738                                 union ctl_ha_msg *msg_info)
739 {
740         struct ctl_scsiio *ctsio;
741
742         if (msg_info->hdr.serializing_sc == NULL) {
743                 printf("%s: serializing_sc == NULL!\n", __func__);
744                 /* XXX KDM now what? */
745                 return;
746         }
747
748         ctsio = &msg_info->hdr.serializing_sc->scsiio;
749         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
750         ctl_enqueue_isc((union ctl_io *)ctsio);
751 }
752
753 void
754 ctl_isc_announce_lun(struct ctl_lun *lun)
755 {
756         struct ctl_softc *softc = lun->ctl_softc;
757         union ctl_ha_msg *msg;
758         struct ctl_ha_msg_lun_pr_key pr_key;
759         int i, k;
760
761         if (softc->ha_link != CTL_HA_LINK_ONLINE)
762                 return;
763         mtx_lock(&lun->lun_lock);
764         i = sizeof(msg->lun);
765         if (lun->lun_devid)
766                 i += lun->lun_devid->len;
767         i += sizeof(pr_key) * lun->pr_key_count;
768 alloc:
769         mtx_unlock(&lun->lun_lock);
770         msg = malloc(i, M_CTL, M_WAITOK);
771         mtx_lock(&lun->lun_lock);
772         k = sizeof(msg->lun);
773         if (lun->lun_devid)
774                 k += lun->lun_devid->len;
775         k += sizeof(pr_key) * lun->pr_key_count;
776         if (i < k) {
777                 free(msg, M_CTL);
778                 i = k;
779                 goto alloc;
780         }
781         bzero(&msg->lun, sizeof(msg->lun));
782         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
783         msg->hdr.nexus.targ_lun = lun->lun;
784         msg->hdr.nexus.targ_mapped_lun = lun->lun;
785         msg->lun.flags = lun->flags;
786         msg->lun.pr_generation = lun->pr_generation;
787         msg->lun.pr_res_idx = lun->pr_res_idx;
788         msg->lun.pr_res_type = lun->pr_res_type;
789         msg->lun.pr_key_count = lun->pr_key_count;
790         i = 0;
791         if (lun->lun_devid) {
792                 msg->lun.lun_devid_len = lun->lun_devid->len;
793                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
794                     msg->lun.lun_devid_len);
795                 i += msg->lun.lun_devid_len;
796         }
797         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
798                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
799                         continue;
800                 pr_key.pr_iid = k;
801                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
802                 i += sizeof(pr_key);
803         }
804         mtx_unlock(&lun->lun_lock);
805         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
806             M_WAITOK);
807         free(msg, M_CTL);
808
809         if (lun->flags & CTL_LUN_PRIMARY_SC) {
810                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
811                         ctl_isc_announce_mode(lun, -1,
812                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
813                             lun->mode_pages.index[i].subpage);
814                 }
815         }
816 }
817
818 void
819 ctl_isc_announce_port(struct ctl_port *port)
820 {
821         struct ctl_softc *softc = port->ctl_softc;
822         union ctl_ha_msg *msg;
823         int i;
824
825         if (port->targ_port < softc->port_min ||
826             port->targ_port >= softc->port_max ||
827             softc->ha_link != CTL_HA_LINK_ONLINE)
828                 return;
829         i = sizeof(msg->port) + strlen(port->port_name) + 1;
830         if (port->lun_map)
831                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
832         if (port->port_devid)
833                 i += port->port_devid->len;
834         if (port->target_devid)
835                 i += port->target_devid->len;
836         if (port->init_devid)
837                 i += port->init_devid->len;
838         msg = malloc(i, M_CTL, M_WAITOK);
839         bzero(&msg->port, sizeof(msg->port));
840         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
841         msg->hdr.nexus.targ_port = port->targ_port;
842         msg->port.port_type = port->port_type;
843         msg->port.physical_port = port->physical_port;
844         msg->port.virtual_port = port->virtual_port;
845         msg->port.status = port->status;
846         i = 0;
847         msg->port.name_len = sprintf(&msg->port.data[i],
848             "%d:%s", softc->ha_id, port->port_name) + 1;
849         i += msg->port.name_len;
850         if (port->lun_map) {
851                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
852                 memcpy(&msg->port.data[i], port->lun_map,
853                     msg->port.lun_map_len);
854                 i += msg->port.lun_map_len;
855         }
856         if (port->port_devid) {
857                 msg->port.port_devid_len = port->port_devid->len;
858                 memcpy(&msg->port.data[i], port->port_devid->data,
859                     msg->port.port_devid_len);
860                 i += msg->port.port_devid_len;
861         }
862         if (port->target_devid) {
863                 msg->port.target_devid_len = port->target_devid->len;
864                 memcpy(&msg->port.data[i], port->target_devid->data,
865                     msg->port.target_devid_len);
866                 i += msg->port.target_devid_len;
867         }
868         if (port->init_devid) {
869                 msg->port.init_devid_len = port->init_devid->len;
870                 memcpy(&msg->port.data[i], port->init_devid->data,
871                     msg->port.init_devid_len);
872                 i += msg->port.init_devid_len;
873         }
874         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
875             M_WAITOK);
876         free(msg, M_CTL);
877 }
878
879 void
880 ctl_isc_announce_iid(struct ctl_port *port, int iid)
881 {
882         struct ctl_softc *softc = port->ctl_softc;
883         union ctl_ha_msg *msg;
884         int i, l;
885
886         if (port->targ_port < softc->port_min ||
887             port->targ_port >= softc->port_max ||
888             softc->ha_link != CTL_HA_LINK_ONLINE)
889                 return;
890         mtx_lock(&softc->ctl_lock);
891         i = sizeof(msg->iid);
892         l = 0;
893         if (port->wwpn_iid[iid].name)
894                 l = strlen(port->wwpn_iid[iid].name) + 1;
895         i += l;
896         msg = malloc(i, M_CTL, M_NOWAIT);
897         if (msg == NULL) {
898                 mtx_unlock(&softc->ctl_lock);
899                 return;
900         }
901         bzero(&msg->iid, sizeof(msg->iid));
902         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
903         msg->hdr.nexus.targ_port = port->targ_port;
904         msg->hdr.nexus.initid = iid;
905         msg->iid.in_use = port->wwpn_iid[iid].in_use;
906         msg->iid.name_len = l;
907         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
908         if (port->wwpn_iid[iid].name)
909                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
910         mtx_unlock(&softc->ctl_lock);
911         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
912         free(msg, M_CTL);
913 }
914
915 void
916 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
917     uint8_t page, uint8_t subpage)
918 {
919         struct ctl_softc *softc = lun->ctl_softc;
920         union ctl_ha_msg msg;
921         u_int i;
922
923         if (softc->ha_link != CTL_HA_LINK_ONLINE)
924                 return;
925         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
926                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
927                     page && lun->mode_pages.index[i].subpage == subpage)
928                         break;
929         }
930         if (i == CTL_NUM_MODE_PAGES)
931                 return;
932
933         /* Don't try to replicate pages not present on this device. */
934         if (lun->mode_pages.index[i].page_data == NULL)
935                 return;
936
937         bzero(&msg.mode, sizeof(msg.mode));
938         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
939         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
940         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
941         msg.hdr.nexus.targ_lun = lun->lun;
942         msg.hdr.nexus.targ_mapped_lun = lun->lun;
943         msg.mode.page_code = page;
944         msg.mode.subpage = subpage;
945         msg.mode.page_len = lun->mode_pages.index[i].page_len;
946         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
947             msg.mode.page_len);
948         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
949             M_WAITOK);
950 }
951
952 static void
953 ctl_isc_ha_link_up(struct ctl_softc *softc)
954 {
955         struct ctl_port *port;
956         struct ctl_lun *lun;
957         union ctl_ha_msg msg;
958         int i;
959
960         /* Announce this node parameters to peer for validation. */
961         msg.login.msg_type = CTL_MSG_LOGIN;
962         msg.login.version = CTL_HA_VERSION;
963         msg.login.ha_mode = softc->ha_mode;
964         msg.login.ha_id = softc->ha_id;
965         msg.login.max_luns = CTL_MAX_LUNS;
966         msg.login.max_ports = CTL_MAX_PORTS;
967         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
968         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
969             M_WAITOK);
970
971         STAILQ_FOREACH(port, &softc->port_list, links) {
972                 ctl_isc_announce_port(port);
973                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
974                         if (port->wwpn_iid[i].in_use)
975                                 ctl_isc_announce_iid(port, i);
976                 }
977         }
978         STAILQ_FOREACH(lun, &softc->lun_list, links)
979                 ctl_isc_announce_lun(lun);
980 }
981
982 static void
983 ctl_isc_ha_link_down(struct ctl_softc *softc)
984 {
985         struct ctl_port *port;
986         struct ctl_lun *lun;
987         union ctl_io *io;
988         int i;
989
990         mtx_lock(&softc->ctl_lock);
991         STAILQ_FOREACH(lun, &softc->lun_list, links) {
992                 mtx_lock(&lun->lun_lock);
993                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
994                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
995                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
996                 }
997                 mtx_unlock(&lun->lun_lock);
998
999                 mtx_unlock(&softc->ctl_lock);
1000                 io = ctl_alloc_io(softc->othersc_pool);
1001                 mtx_lock(&softc->ctl_lock);
1002                 ctl_zero_io(io);
1003                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1004                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1005                 ctl_enqueue_isc(io);
1006         }
1007
1008         STAILQ_FOREACH(port, &softc->port_list, links) {
1009                 if (port->targ_port >= softc->port_min &&
1010                     port->targ_port < softc->port_max)
1011                         continue;
1012                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1013                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1014                         port->wwpn_iid[i].in_use = 0;
1015                         free(port->wwpn_iid[i].name, M_CTL);
1016                         port->wwpn_iid[i].name = NULL;
1017                 }
1018         }
1019         mtx_unlock(&softc->ctl_lock);
1020 }
1021
1022 static void
1023 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1024 {
1025         struct ctl_lun *lun;
1026         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1027
1028         mtx_lock(&softc->ctl_lock);
1029         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1030             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1031                 mtx_lock(&lun->lun_lock);
1032                 mtx_unlock(&softc->ctl_lock);
1033                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1034                     msg->ua.ua_set)
1035                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1036                 if (msg->ua.ua_all) {
1037                         if (msg->ua.ua_set)
1038                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1039                         else
1040                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1041                 } else {
1042                         if (msg->ua.ua_set)
1043                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
1044                         else
1045                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
1046                 }
1047                 mtx_unlock(&lun->lun_lock);
1048         } else
1049                 mtx_unlock(&softc->ctl_lock);
1050 }
1051
1052 static void
1053 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1054 {
1055         struct ctl_lun *lun;
1056         struct ctl_ha_msg_lun_pr_key pr_key;
1057         int i, k;
1058         ctl_lun_flags oflags;
1059         uint32_t targ_lun;
1060
1061         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1062         mtx_lock(&softc->ctl_lock);
1063         if ((targ_lun >= CTL_MAX_LUNS) ||
1064             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1065                 mtx_unlock(&softc->ctl_lock);
1066                 return;
1067         }
1068         mtx_lock(&lun->lun_lock);
1069         mtx_unlock(&softc->ctl_lock);
1070         if (lun->flags & CTL_LUN_DISABLED) {
1071                 mtx_unlock(&lun->lun_lock);
1072                 return;
1073         }
1074         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1075         if (msg->lun.lun_devid_len != i || (i > 0 &&
1076             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1077                 mtx_unlock(&lun->lun_lock);
1078                 printf("%s: Received conflicting HA LUN %d\n",
1079                     __func__, msg->hdr.nexus.targ_lun);
1080                 return;
1081         } else {
1082                 /* Record whether peer is primary. */
1083                 oflags = lun->flags;
1084                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1085                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1086                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1087                 else
1088                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1089                 if (oflags != lun->flags)
1090                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1091
1092                 /* If peer is primary and we are not -- use data */
1093                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1094                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1095                         lun->pr_generation = msg->lun.pr_generation;
1096                         lun->pr_res_idx = msg->lun.pr_res_idx;
1097                         lun->pr_res_type = msg->lun.pr_res_type;
1098                         lun->pr_key_count = msg->lun.pr_key_count;
1099                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1100                                 ctl_clr_prkey(lun, k);
1101                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1102                                 memcpy(&pr_key, &msg->lun.data[i],
1103                                     sizeof(pr_key));
1104                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1105                                 ctl_set_prkey(lun, pr_key.pr_iid,
1106                                     pr_key.pr_key);
1107                                 i += sizeof(pr_key);
1108                         }
1109                 }
1110
1111                 mtx_unlock(&lun->lun_lock);
1112                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1113                     __func__, msg->hdr.nexus.targ_lun,
1114                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1115                     "primary" : "secondary"));
1116
1117                 /* If we are primary but peer doesn't know -- notify */
1118                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1119                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1120                         ctl_isc_announce_lun(lun);
1121         }
1122 }
1123
1124 static void
1125 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1126 {
1127         struct ctl_port *port;
1128         struct ctl_lun *lun;
1129         int i, new;
1130
1131         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1132         if (port == NULL) {
1133                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1134                     msg->hdr.nexus.targ_port));
1135                 new = 1;
1136                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1137                 port->frontend = &ha_frontend;
1138                 port->targ_port = msg->hdr.nexus.targ_port;
1139                 port->fe_datamove = ctl_ha_datamove;
1140                 port->fe_done = ctl_ha_done;
1141         } else if (port->frontend == &ha_frontend) {
1142                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1143                     msg->hdr.nexus.targ_port));
1144                 new = 0;
1145         } else {
1146                 printf("%s: Received conflicting HA port %d\n",
1147                     __func__, msg->hdr.nexus.targ_port);
1148                 return;
1149         }
1150         port->port_type = msg->port.port_type;
1151         port->physical_port = msg->port.physical_port;
1152         port->virtual_port = msg->port.virtual_port;
1153         port->status = msg->port.status;
1154         i = 0;
1155         free(port->port_name, M_CTL);
1156         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1157             M_CTL);
1158         i += msg->port.name_len;
1159         if (msg->port.lun_map_len != 0) {
1160                 if (port->lun_map == NULL)
1161                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1162                             M_CTL, M_WAITOK);
1163                 memcpy(port->lun_map, &msg->port.data[i],
1164                     sizeof(uint32_t) * CTL_MAX_LUNS);
1165                 i += msg->port.lun_map_len;
1166         } else {
1167                 free(port->lun_map, M_CTL);
1168                 port->lun_map = NULL;
1169         }
1170         if (msg->port.port_devid_len != 0) {
1171                 if (port->port_devid == NULL ||
1172                     port->port_devid->len != msg->port.port_devid_len) {
1173                         free(port->port_devid, M_CTL);
1174                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1175                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1176                 }
1177                 memcpy(port->port_devid->data, &msg->port.data[i],
1178                     msg->port.port_devid_len);
1179                 port->port_devid->len = msg->port.port_devid_len;
1180                 i += msg->port.port_devid_len;
1181         } else {
1182                 free(port->port_devid, M_CTL);
1183                 port->port_devid = NULL;
1184         }
1185         if (msg->port.target_devid_len != 0) {
1186                 if (port->target_devid == NULL ||
1187                     port->target_devid->len != msg->port.target_devid_len) {
1188                         free(port->target_devid, M_CTL);
1189                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1190                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1191                 }
1192                 memcpy(port->target_devid->data, &msg->port.data[i],
1193                     msg->port.target_devid_len);
1194                 port->target_devid->len = msg->port.target_devid_len;
1195                 i += msg->port.target_devid_len;
1196         } else {
1197                 free(port->target_devid, M_CTL);
1198                 port->target_devid = NULL;
1199         }
1200         if (msg->port.init_devid_len != 0) {
1201                 if (port->init_devid == NULL ||
1202                     port->init_devid->len != msg->port.init_devid_len) {
1203                         free(port->init_devid, M_CTL);
1204                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1205                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1206                 }
1207                 memcpy(port->init_devid->data, &msg->port.data[i],
1208                     msg->port.init_devid_len);
1209                 port->init_devid->len = msg->port.init_devid_len;
1210                 i += msg->port.init_devid_len;
1211         } else {
1212                 free(port->init_devid, M_CTL);
1213                 port->init_devid = NULL;
1214         }
1215         if (new) {
1216                 if (ctl_port_register(port) != 0) {
1217                         printf("%s: ctl_port_register() failed with error\n",
1218                             __func__);
1219                 }
1220         }
1221         mtx_lock(&softc->ctl_lock);
1222         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1223                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1224                         continue;
1225                 mtx_lock(&lun->lun_lock);
1226                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1227                 mtx_unlock(&lun->lun_lock);
1228         }
1229         mtx_unlock(&softc->ctl_lock);
1230 }
1231
1232 static void
1233 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1234 {
1235         struct ctl_port *port;
1236         int iid;
1237
1238         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1239         if (port == NULL) {
1240                 printf("%s: Received IID for unknown port %d\n",
1241                     __func__, msg->hdr.nexus.targ_port);
1242                 return;
1243         }
1244         iid = msg->hdr.nexus.initid;
1245         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1246         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1247         free(port->wwpn_iid[iid].name, M_CTL);
1248         if (msg->iid.name_len) {
1249                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1250                     msg->iid.name_len, M_CTL);
1251         } else
1252                 port->wwpn_iid[iid].name = NULL;
1253 }
1254
1255 static void
1256 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1257 {
1258
1259         if (msg->login.version != CTL_HA_VERSION) {
1260                 printf("CTL HA peers have different versions %d != %d\n",
1261                     msg->login.version, CTL_HA_VERSION);
1262                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1263                 return;
1264         }
1265         if (msg->login.ha_mode != softc->ha_mode) {
1266                 printf("CTL HA peers have different ha_mode %d != %d\n",
1267                     msg->login.ha_mode, softc->ha_mode);
1268                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1269                 return;
1270         }
1271         if (msg->login.ha_id == softc->ha_id) {
1272                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1273                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274                 return;
1275         }
1276         if (msg->login.max_luns != CTL_MAX_LUNS ||
1277             msg->login.max_ports != CTL_MAX_PORTS ||
1278             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1279                 printf("CTL HA peers have different limits\n");
1280                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281                 return;
1282         }
1283 }
1284
1285 static void
1286 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1287 {
1288         struct ctl_lun *lun;
1289         u_int i;
1290         uint32_t initidx, targ_lun;
1291
1292         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1293         mtx_lock(&softc->ctl_lock);
1294         if ((targ_lun >= CTL_MAX_LUNS) ||
1295             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1296                 mtx_unlock(&softc->ctl_lock);
1297                 return;
1298         }
1299         mtx_lock(&lun->lun_lock);
1300         mtx_unlock(&softc->ctl_lock);
1301         if (lun->flags & CTL_LUN_DISABLED) {
1302                 mtx_unlock(&lun->lun_lock);
1303                 return;
1304         }
1305         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1306                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1307                     msg->mode.page_code &&
1308                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1309                         break;
1310         }
1311         if (i == CTL_NUM_MODE_PAGES) {
1312                 mtx_unlock(&lun->lun_lock);
1313                 return;
1314         }
1315         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1316             lun->mode_pages.index[i].page_len);
1317         initidx = ctl_get_initindex(&msg->hdr.nexus);
1318         if (initidx != -1)
1319                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1320         mtx_unlock(&lun->lun_lock);
1321 }
1322
1323 /*
1324  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1325  * subsystem come in here.
1326  */
1327 static void
1328 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1329 {
1330         struct ctl_softc *softc = control_softc;
1331         union ctl_io *io;
1332         struct ctl_prio *presio;
1333         ctl_ha_status isc_status;
1334
1335         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1336         if (event == CTL_HA_EVT_MSG_RECV) {
1337                 union ctl_ha_msg *msg, msgbuf;
1338
1339                 if (param > sizeof(msgbuf))
1340                         msg = malloc(param, M_CTL, M_WAITOK);
1341                 else
1342                         msg = &msgbuf;
1343                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1344                     M_WAITOK);
1345                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1346                         printf("%s: Error receiving message: %d\n",
1347                             __func__, isc_status);
1348                         if (msg != &msgbuf)
1349                                 free(msg, M_CTL);
1350                         return;
1351                 }
1352
1353                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1354                 switch (msg->hdr.msg_type) {
1355                 case CTL_MSG_SERIALIZE:
1356                         io = ctl_alloc_io(softc->othersc_pool);
1357                         ctl_zero_io(io);
1358                         // populate ctsio from msg
1359                         io->io_hdr.io_type = CTL_IO_SCSI;
1360                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1361                         io->io_hdr.original_sc = msg->hdr.original_sc;
1362                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1363                                             CTL_FLAG_IO_ACTIVE;
1364                         /*
1365                          * If we're in serialization-only mode, we don't
1366                          * want to go through full done processing.  Thus
1367                          * the COPY flag.
1368                          *
1369                          * XXX KDM add another flag that is more specific.
1370                          */
1371                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1372                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1373                         io->io_hdr.nexus = msg->hdr.nexus;
1374 #if 0
1375                         printf("port %u, iid %u, lun %u\n",
1376                                io->io_hdr.nexus.targ_port,
1377                                io->io_hdr.nexus.initid,
1378                                io->io_hdr.nexus.targ_lun);
1379 #endif
1380                         io->scsiio.tag_num = msg->scsi.tag_num;
1381                         io->scsiio.tag_type = msg->scsi.tag_type;
1382 #ifdef CTL_TIME_IO
1383                         io->io_hdr.start_time = time_uptime;
1384                         getbinuptime(&io->io_hdr.start_bt);
1385 #endif /* CTL_TIME_IO */
1386                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1387                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1388                                CTL_MAX_CDBLEN);
1389                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1390                                 const struct ctl_cmd_entry *entry;
1391
1392                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1393                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1394                                 io->io_hdr.flags |=
1395                                         entry->flags & CTL_FLAG_DATA_MASK;
1396                         }
1397                         ctl_enqueue_isc(io);
1398                         break;
1399
1400                 /* Performed on the Originating SC, XFER mode only */
1401                 case CTL_MSG_DATAMOVE: {
1402                         struct ctl_sg_entry *sgl;
1403                         int i, j;
1404
1405                         io = msg->hdr.original_sc;
1406                         if (io == NULL) {
1407                                 printf("%s: original_sc == NULL!\n", __func__);
1408                                 /* XXX KDM do something here */
1409                                 break;
1410                         }
1411                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1412                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1413                         /*
1414                          * Keep track of this, we need to send it back over
1415                          * when the datamove is complete.
1416                          */
1417                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1418                         if (msg->hdr.status == CTL_SUCCESS)
1419                                 io->io_hdr.status = msg->hdr.status;
1420
1421                         if (msg->dt.sg_sequence == 0) {
1422 #ifdef CTL_TIME_IO
1423                                 getbinuptime(&io->io_hdr.dma_start_bt);
1424 #endif
1425                                 i = msg->dt.kern_sg_entries +
1426                                     msg->dt.kern_data_len /
1427                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1428                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1429                                     M_WAITOK | M_ZERO);
1430                                 io->io_hdr.remote_sglist = sgl;
1431                                 io->io_hdr.local_sglist =
1432                                     &sgl[msg->dt.kern_sg_entries];
1433
1434                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1435
1436                                 io->scsiio.kern_sg_entries =
1437                                         msg->dt.kern_sg_entries;
1438                                 io->scsiio.rem_sg_entries =
1439                                         msg->dt.kern_sg_entries;
1440                                 io->scsiio.kern_data_len =
1441                                         msg->dt.kern_data_len;
1442                                 io->scsiio.kern_total_len =
1443                                         msg->dt.kern_total_len;
1444                                 io->scsiio.kern_data_resid =
1445                                         msg->dt.kern_data_resid;
1446                                 io->scsiio.kern_rel_offset =
1447                                         msg->dt.kern_rel_offset;
1448                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1449                                 io->io_hdr.flags |= msg->dt.flags &
1450                                     CTL_FLAG_BUS_ADDR;
1451                         } else
1452                                 sgl = (struct ctl_sg_entry *)
1453                                         io->scsiio.kern_data_ptr;
1454
1455                         for (i = msg->dt.sent_sg_entries, j = 0;
1456                              i < (msg->dt.sent_sg_entries +
1457                              msg->dt.cur_sg_entries); i++, j++) {
1458                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1459                                 sgl[i].len = msg->dt.sg_list[j].len;
1460
1461 #if 0
1462                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1463                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1464 #endif
1465                         }
1466
1467                         /*
1468                          * If this is the last piece of the I/O, we've got
1469                          * the full S/G list.  Queue processing in the thread.
1470                          * Otherwise wait for the next piece.
1471                          */
1472                         if (msg->dt.sg_last != 0)
1473                                 ctl_enqueue_isc(io);
1474                         break;
1475                 }
1476                 /* Performed on the Serializing (primary) SC, XFER mode only */
1477                 case CTL_MSG_DATAMOVE_DONE: {
1478                         if (msg->hdr.serializing_sc == NULL) {
1479                                 printf("%s: serializing_sc == NULL!\n",
1480                                        __func__);
1481                                 /* XXX KDM now what? */
1482                                 break;
1483                         }
1484                         /*
1485                          * We grab the sense information here in case
1486                          * there was a failure, so we can return status
1487                          * back to the initiator.
1488                          */
1489                         io = msg->hdr.serializing_sc;
1490                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1491                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1492                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1493                         io->io_hdr.port_status = msg->scsi.fetd_status;
1494                         io->scsiio.residual = msg->scsi.residual;
1495                         if (msg->hdr.status != CTL_STATUS_NONE) {
1496                                 io->io_hdr.status = msg->hdr.status;
1497                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1498                                 io->scsiio.sense_len = msg->scsi.sense_len;
1499                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1500                                 memcpy(&io->scsiio.sense_data,
1501                                     &msg->scsi.sense_data,
1502                                     msg->scsi.sense_len);
1503                                 if (msg->hdr.status == CTL_SUCCESS)
1504                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1505                         }
1506                         ctl_enqueue_isc(io);
1507                         break;
1508                 }
1509
1510                 /* Preformed on Originating SC, SER_ONLY mode */
1511                 case CTL_MSG_R2R:
1512                         io = msg->hdr.original_sc;
1513                         if (io == NULL) {
1514                                 printf("%s: original_sc == NULL!\n",
1515                                     __func__);
1516                                 break;
1517                         }
1518                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1519                         io->io_hdr.msg_type = CTL_MSG_R2R;
1520                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1521                         ctl_enqueue_isc(io);
1522                         break;
1523
1524                 /*
1525                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1526                  * mode.
1527                  * Performed on the Originating (i.e. secondary) SC in XFER
1528                  * mode
1529                  */
1530                 case CTL_MSG_FINISH_IO:
1531                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1532                                 ctl_isc_handler_finish_xfer(softc, msg);
1533                         else
1534                                 ctl_isc_handler_finish_ser_only(softc, msg);
1535                         break;
1536
1537                 /* Preformed on Originating SC */
1538                 case CTL_MSG_BAD_JUJU:
1539                         io = msg->hdr.original_sc;
1540                         if (io == NULL) {
1541                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1542                                        __func__);
1543                                 break;
1544                         }
1545                         ctl_copy_sense_data(msg, io);
1546                         /*
1547                          * IO should have already been cleaned up on other
1548                          * SC so clear this flag so we won't send a message
1549                          * back to finish the IO there.
1550                          */
1551                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1552                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1553
1554                         /* io = msg->hdr.serializing_sc; */
1555                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1556                         ctl_enqueue_isc(io);
1557                         break;
1558
1559                 /* Handle resets sent from the other side */
1560                 case CTL_MSG_MANAGE_TASKS: {
1561                         struct ctl_taskio *taskio;
1562                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1563                             softc->othersc_pool);
1564                         ctl_zero_io((union ctl_io *)taskio);
1565                         taskio->io_hdr.io_type = CTL_IO_TASK;
1566                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1567                         taskio->io_hdr.nexus = msg->hdr.nexus;
1568                         taskio->task_action = msg->task.task_action;
1569                         taskio->tag_num = msg->task.tag_num;
1570                         taskio->tag_type = msg->task.tag_type;
1571 #ifdef CTL_TIME_IO
1572                         taskio->io_hdr.start_time = time_uptime;
1573                         getbinuptime(&taskio->io_hdr.start_bt);
1574 #endif /* CTL_TIME_IO */
1575                         ctl_run_task((union ctl_io *)taskio);
1576                         break;
1577                 }
1578                 /* Persistent Reserve action which needs attention */
1579                 case CTL_MSG_PERS_ACTION:
1580                         presio = (struct ctl_prio *)ctl_alloc_io(
1581                             softc->othersc_pool);
1582                         ctl_zero_io((union ctl_io *)presio);
1583                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1584                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1585                         presio->io_hdr.nexus = msg->hdr.nexus;
1586                         presio->pr_msg = msg->pr;
1587                         ctl_enqueue_isc((union ctl_io *)presio);
1588                         break;
1589                 case CTL_MSG_UA:
1590                         ctl_isc_ua(softc, msg, param);
1591                         break;
1592                 case CTL_MSG_PORT_SYNC:
1593                         ctl_isc_port_sync(softc, msg, param);
1594                         break;
1595                 case CTL_MSG_LUN_SYNC:
1596                         ctl_isc_lun_sync(softc, msg, param);
1597                         break;
1598                 case CTL_MSG_IID_SYNC:
1599                         ctl_isc_iid_sync(softc, msg, param);
1600                         break;
1601                 case CTL_MSG_LOGIN:
1602                         ctl_isc_login(softc, msg, param);
1603                         break;
1604                 case CTL_MSG_MODE_SYNC:
1605                         ctl_isc_mode_sync(softc, msg, param);
1606                         break;
1607                 default:
1608                         printf("Received HA message of unknown type %d\n",
1609                             msg->hdr.msg_type);
1610                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1611                         break;
1612                 }
1613                 if (msg != &msgbuf)
1614                         free(msg, M_CTL);
1615         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1616                 printf("CTL: HA link status changed from %d to %d\n",
1617                     softc->ha_link, param);
1618                 if (param == softc->ha_link)
1619                         return;
1620                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1621                         softc->ha_link = param;
1622                         ctl_isc_ha_link_down(softc);
1623                 } else {
1624                         softc->ha_link = param;
1625                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1626                                 ctl_isc_ha_link_up(softc);
1627                 }
1628                 return;
1629         } else {
1630                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1631                 return;
1632         }
1633 }
1634
1635 static void
1636 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1637 {
1638
1639         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1640             src->scsi.sense_len);
1641         dest->scsiio.scsi_status = src->scsi.scsi_status;
1642         dest->scsiio.sense_len = src->scsi.sense_len;
1643         dest->io_hdr.status = src->hdr.status;
1644 }
1645
1646 static void
1647 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1648 {
1649
1650         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1651             src->scsiio.sense_len);
1652         dest->scsi.scsi_status = src->scsiio.scsi_status;
1653         dest->scsi.sense_len = src->scsiio.sense_len;
1654         dest->hdr.status = src->io_hdr.status;
1655 }
1656
1657 void
1658 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1659 {
1660         struct ctl_softc *softc = lun->ctl_softc;
1661         ctl_ua_type *pu;
1662
1663         if (initidx < softc->init_min || initidx >= softc->init_max)
1664                 return;
1665         mtx_assert(&lun->lun_lock, MA_OWNED);
1666         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1667         if (pu == NULL)
1668                 return;
1669         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1670 }
1671
1672 void
1673 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1674 {
1675         int i;
1676
1677         mtx_assert(&lun->lun_lock, MA_OWNED);
1678         if (lun->pending_ua[port] == NULL)
1679                 return;
1680         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1681                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1682                         continue;
1683                 lun->pending_ua[port][i] |= ua;
1684         }
1685 }
1686
1687 void
1688 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1689 {
1690         struct ctl_softc *softc = lun->ctl_softc;
1691         int i;
1692
1693         mtx_assert(&lun->lun_lock, MA_OWNED);
1694         for (i = softc->port_min; i < softc->port_max; i++)
1695                 ctl_est_ua_port(lun, i, except, ua);
1696 }
1697
1698 void
1699 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1700 {
1701         struct ctl_softc *softc = lun->ctl_softc;
1702         ctl_ua_type *pu;
1703
1704         if (initidx < softc->init_min || initidx >= softc->init_max)
1705                 return;
1706         mtx_assert(&lun->lun_lock, MA_OWNED);
1707         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1708         if (pu == NULL)
1709                 return;
1710         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1711 }
1712
1713 void
1714 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1715 {
1716         struct ctl_softc *softc = lun->ctl_softc;
1717         int i, j;
1718
1719         mtx_assert(&lun->lun_lock, MA_OWNED);
1720         for (i = softc->port_min; i < softc->port_max; i++) {
1721                 if (lun->pending_ua[i] == NULL)
1722                         continue;
1723                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1724                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1725                                 continue;
1726                         lun->pending_ua[i][j] &= ~ua;
1727                 }
1728         }
1729 }
1730
1731 void
1732 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1733     ctl_ua_type ua_type)
1734 {
1735         struct ctl_lun *lun;
1736
1737         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1738         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1739                 mtx_lock(&lun->lun_lock);
1740                 ctl_clr_ua(lun, initidx, ua_type);
1741                 mtx_unlock(&lun->lun_lock);
1742         }
1743 }
1744
1745 static int
1746 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1747 {
1748         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1749         struct ctl_lun *lun;
1750         struct ctl_lun_req ireq;
1751         int error, value;
1752
1753         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1754         error = sysctl_handle_int(oidp, &value, 0, req);
1755         if ((error != 0) || (req->newptr == NULL))
1756                 return (error);
1757
1758         mtx_lock(&softc->ctl_lock);
1759         if (value == 0)
1760                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1761         else
1762                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1763         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1764                 mtx_unlock(&softc->ctl_lock);
1765                 bzero(&ireq, sizeof(ireq));
1766                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1767                 ireq.reqdata.modify.lun_id = lun->lun;
1768                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1769                     curthread);
1770                 if (ireq.status != CTL_LUN_OK) {
1771                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1772                             __func__, ireq.status, ireq.error_str);
1773                 }
1774                 mtx_lock(&softc->ctl_lock);
1775         }
1776         mtx_unlock(&softc->ctl_lock);
1777         return (0);
1778 }
1779
1780 static int
1781 ctl_init(void)
1782 {
1783         struct make_dev_args args;
1784         struct ctl_softc *softc;
1785         void *other_pool;
1786         int i, error;
1787
1788         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1789                                M_WAITOK | M_ZERO);
1790
1791         make_dev_args_init(&args);
1792         args.mda_devsw = &ctl_cdevsw;
1793         args.mda_uid = UID_ROOT;
1794         args.mda_gid = GID_OPERATOR;
1795         args.mda_mode = 0600;
1796         args.mda_si_drv1 = softc;
1797         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1798         if (error != 0) {
1799                 free(control_softc, M_DEVBUF);
1800                 return (error);
1801         }
1802
1803         sysctl_ctx_init(&softc->sysctl_ctx);
1804         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1805                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1806                 CTLFLAG_RD, 0, "CAM Target Layer");
1807
1808         if (softc->sysctl_tree == NULL) {
1809                 printf("%s: unable to allocate sysctl tree\n", __func__);
1810                 destroy_dev(softc->dev);
1811                 free(control_softc, M_DEVBUF);
1812                 control_softc = NULL;
1813                 return (ENOMEM);
1814         }
1815
1816         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1817         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1818             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1819         softc->flags = 0;
1820
1821         TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1822         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1823             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1824             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1825
1826         /*
1827          * In Copan's HA scheme, the "master" and "slave" roles are
1828          * figured out through the slot the controller is in.  Although it
1829          * is an active/active system, someone has to be in charge.
1830          */
1831         TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1832         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1833             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1834             "HA head ID (0 - no HA)");
1835         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1836                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1837                 softc->is_single = 1;
1838                 softc->port_cnt = CTL_MAX_PORTS;
1839                 softc->port_min = 0;
1840         } else {
1841                 softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1842                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1843         }
1844         softc->port_max = softc->port_min + softc->port_cnt;
1845         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1846         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1847
1848         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1849             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1850             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1851
1852         STAILQ_INIT(&softc->lun_list);
1853         STAILQ_INIT(&softc->pending_lun_queue);
1854         STAILQ_INIT(&softc->fe_list);
1855         STAILQ_INIT(&softc->port_list);
1856         STAILQ_INIT(&softc->be_list);
1857         ctl_tpc_init(softc);
1858
1859         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1860                             &other_pool) != 0)
1861         {
1862                 printf("ctl: can't allocate %d entry other SC pool, "
1863                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1864                 return (ENOMEM);
1865         }
1866         softc->othersc_pool = other_pool;
1867
1868         if (worker_threads <= 0)
1869                 worker_threads = max(1, mp_ncpus / 4);
1870         if (worker_threads > CTL_MAX_THREADS)
1871                 worker_threads = CTL_MAX_THREADS;
1872
1873         for (i = 0; i < worker_threads; i++) {
1874                 struct ctl_thread *thr = &softc->threads[i];
1875
1876                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1877                 thr->ctl_softc = softc;
1878                 STAILQ_INIT(&thr->incoming_queue);
1879                 STAILQ_INIT(&thr->rtr_queue);
1880                 STAILQ_INIT(&thr->done_queue);
1881                 STAILQ_INIT(&thr->isc_queue);
1882
1883                 error = kproc_kthread_add(ctl_work_thread, thr,
1884                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1885                 if (error != 0) {
1886                         printf("error creating CTL work thread!\n");
1887                         ctl_pool_free(other_pool);
1888                         return (error);
1889                 }
1890         }
1891         error = kproc_kthread_add(ctl_lun_thread, softc,
1892             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1893         if (error != 0) {
1894                 printf("error creating CTL lun thread!\n");
1895                 ctl_pool_free(other_pool);
1896                 return (error);
1897         }
1898         error = kproc_kthread_add(ctl_thresh_thread, softc,
1899             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1900         if (error != 0) {
1901                 printf("error creating CTL threshold thread!\n");
1902                 ctl_pool_free(other_pool);
1903                 return (error);
1904         }
1905
1906         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1907             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1908             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1909
1910         if (softc->is_single == 0) {
1911                 ctl_frontend_register(&ha_frontend);
1912                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1913                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1914                         softc->is_single = 1;
1915                 } else
1916                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1917                     != CTL_HA_STATUS_SUCCESS) {
1918                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1919                         softc->is_single = 1;
1920                 }
1921         }
1922         return (0);
1923 }
1924
1925 void
1926 ctl_shutdown(void)
1927 {
1928         struct ctl_softc *softc = control_softc;
1929         struct ctl_lun *lun, *next_lun;
1930
1931         if (softc->is_single == 0) {
1932                 ctl_ha_msg_shutdown(softc);
1933                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1934                     != CTL_HA_STATUS_SUCCESS)
1935                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1936                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1937                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1938                 ctl_frontend_deregister(&ha_frontend);
1939         }
1940
1941         mtx_lock(&softc->ctl_lock);
1942
1943         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1944                 ctl_free_lun(lun);
1945
1946         mtx_unlock(&softc->ctl_lock);
1947
1948 #if 0
1949         ctl_shutdown_thread(softc->work_thread);
1950         mtx_destroy(&softc->queue_lock);
1951 #endif
1952
1953         ctl_tpc_shutdown(softc);
1954         uma_zdestroy(softc->io_zone);
1955         mtx_destroy(&softc->ctl_lock);
1956
1957         destroy_dev(softc->dev);
1958
1959         sysctl_ctx_free(&softc->sysctl_ctx);
1960
1961         free(control_softc, M_DEVBUF);
1962         control_softc = NULL;
1963 }
1964
1965 static int
1966 ctl_module_event_handler(module_t mod, int what, void *arg)
1967 {
1968
1969         switch (what) {
1970         case MOD_LOAD:
1971                 return (ctl_init());
1972         case MOD_UNLOAD:
1973                 return (EBUSY);
1974         default:
1975                 return (EOPNOTSUPP);
1976         }
1977 }
1978
1979 /*
1980  * XXX KDM should we do some access checks here?  Bump a reference count to
1981  * prevent a CTL module from being unloaded while someone has it open?
1982  */
1983 static int
1984 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1985 {
1986         return (0);
1987 }
1988
1989 static int
1990 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1991 {
1992         return (0);
1993 }
1994
1995 /*
1996  * Remove an initiator by port number and initiator ID.
1997  * Returns 0 for success, -1 for failure.
1998  */
1999 int
2000 ctl_remove_initiator(struct ctl_port *port, int iid)
2001 {
2002         struct ctl_softc *softc = port->ctl_softc;
2003
2004         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2005
2006         if (iid > CTL_MAX_INIT_PER_PORT) {
2007                 printf("%s: initiator ID %u > maximun %u!\n",
2008                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2009                 return (-1);
2010         }
2011
2012         mtx_lock(&softc->ctl_lock);
2013         port->wwpn_iid[iid].in_use--;
2014         port->wwpn_iid[iid].last_use = time_uptime;
2015         mtx_unlock(&softc->ctl_lock);
2016         ctl_isc_announce_iid(port, iid);
2017
2018         return (0);
2019 }
2020
2021 /*
2022  * Add an initiator to the initiator map.
2023  * Returns iid for success, < 0 for failure.
2024  */
2025 int
2026 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2027 {
2028         struct ctl_softc *softc = port->ctl_softc;
2029         time_t best_time;
2030         int i, best;
2031
2032         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2033
2034         if (iid >= CTL_MAX_INIT_PER_PORT) {
2035                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2036                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2037                 free(name, M_CTL);
2038                 return (-1);
2039         }
2040
2041         mtx_lock(&softc->ctl_lock);
2042
2043         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2044                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2045                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2046                                 iid = i;
2047                                 break;
2048                         }
2049                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2050                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2051                                 iid = i;
2052                                 break;
2053                         }
2054                 }
2055         }
2056
2057         if (iid < 0) {
2058                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2059                         if (port->wwpn_iid[i].in_use == 0 &&
2060                             port->wwpn_iid[i].wwpn == 0 &&
2061                             port->wwpn_iid[i].name == NULL) {
2062                                 iid = i;
2063                                 break;
2064                         }
2065                 }
2066         }
2067
2068         if (iid < 0) {
2069                 best = -1;
2070                 best_time = INT32_MAX;
2071                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2072                         if (port->wwpn_iid[i].in_use == 0) {
2073                                 if (port->wwpn_iid[i].last_use < best_time) {
2074                                         best = i;
2075                                         best_time = port->wwpn_iid[i].last_use;
2076                                 }
2077                         }
2078                 }
2079                 iid = best;
2080         }
2081
2082         if (iid < 0) {
2083                 mtx_unlock(&softc->ctl_lock);
2084                 free(name, M_CTL);
2085                 return (-2);
2086         }
2087
2088         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2089                 /*
2090                  * This is not an error yet.
2091                  */
2092                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2093 #if 0
2094                         printf("%s: port %d iid %u WWPN %#jx arrived"
2095                             " again\n", __func__, port->targ_port,
2096                             iid, (uintmax_t)wwpn);
2097 #endif
2098                         goto take;
2099                 }
2100                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2101                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2102 #if 0
2103                         printf("%s: port %d iid %u name '%s' arrived"
2104                             " again\n", __func__, port->targ_port,
2105                             iid, name);
2106 #endif
2107                         goto take;
2108                 }
2109
2110                 /*
2111                  * This is an error, but what do we do about it?  The
2112                  * driver is telling us we have a new WWPN for this
2113                  * initiator ID, so we pretty much need to use it.
2114                  */
2115                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2116                     " but WWPN %#jx '%s' is still at that address\n",
2117                     __func__, port->targ_port, iid, wwpn, name,
2118                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2119                     port->wwpn_iid[iid].name);
2120
2121                 /*
2122                  * XXX KDM clear have_ca and ua_pending on each LUN for
2123                  * this initiator.
2124                  */
2125         }
2126 take:
2127         free(port->wwpn_iid[iid].name, M_CTL);
2128         port->wwpn_iid[iid].name = name;
2129         port->wwpn_iid[iid].wwpn = wwpn;
2130         port->wwpn_iid[iid].in_use++;
2131         mtx_unlock(&softc->ctl_lock);
2132         ctl_isc_announce_iid(port, iid);
2133
2134         return (iid);
2135 }
2136
2137 static int
2138 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2139 {
2140         int len;
2141
2142         switch (port->port_type) {
2143         case CTL_PORT_FC:
2144         {
2145                 struct scsi_transportid_fcp *id =
2146                     (struct scsi_transportid_fcp *)buf;
2147                 if (port->wwpn_iid[iid].wwpn == 0)
2148                         return (0);
2149                 memset(id, 0, sizeof(*id));
2150                 id->format_protocol = SCSI_PROTO_FC;
2151                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2152                 return (sizeof(*id));
2153         }
2154         case CTL_PORT_ISCSI:
2155         {
2156                 struct scsi_transportid_iscsi_port *id =
2157                     (struct scsi_transportid_iscsi_port *)buf;
2158                 if (port->wwpn_iid[iid].name == NULL)
2159                         return (0);
2160                 memset(id, 0, 256);
2161                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2162                     SCSI_PROTO_ISCSI;
2163                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2164                 len = roundup2(min(len, 252), 4);
2165                 scsi_ulto2b(len, id->additional_length);
2166                 return (sizeof(*id) + len);
2167         }
2168         case CTL_PORT_SAS:
2169         {
2170                 struct scsi_transportid_sas *id =
2171                     (struct scsi_transportid_sas *)buf;
2172                 if (port->wwpn_iid[iid].wwpn == 0)
2173                         return (0);
2174                 memset(id, 0, sizeof(*id));
2175                 id->format_protocol = SCSI_PROTO_SAS;
2176                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2177                 return (sizeof(*id));
2178         }
2179         default:
2180         {
2181                 struct scsi_transportid_spi *id =
2182                     (struct scsi_transportid_spi *)buf;
2183                 memset(id, 0, sizeof(*id));
2184                 id->format_protocol = SCSI_PROTO_SPI;
2185                 scsi_ulto2b(iid, id->scsi_addr);
2186                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2187                 return (sizeof(*id));
2188         }
2189         }
2190 }
2191
2192 /*
2193  * Serialize a command that went down the "wrong" side, and so was sent to
2194  * this controller for execution.  The logic is a little different than the
2195  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2196  * sent back to the other side, but in the success case, we execute the
2197  * command on this side (XFER mode) or tell the other side to execute it
2198  * (SER_ONLY mode).
2199  */
2200 static int
2201 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2202 {
2203         struct ctl_softc *softc = control_softc;
2204         union ctl_ha_msg msg_info;
2205         struct ctl_port *port;
2206         struct ctl_lun *lun;
2207         const struct ctl_cmd_entry *entry;
2208         int retval = 0;
2209         uint32_t targ_lun;
2210
2211         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2212         mtx_lock(&softc->ctl_lock);
2213
2214         /* Make sure that we know about this port. */
2215         port = ctl_io_port(&ctsio->io_hdr);
2216         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2217                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2218                                          /*retry_count*/ 1);
2219                 goto badjuju;
2220         }
2221
2222         /* Make sure that we know about this LUN. */
2223         if ((targ_lun < CTL_MAX_LUNS) &&
2224             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2225                 mtx_lock(&lun->lun_lock);
2226                 mtx_unlock(&softc->ctl_lock);
2227                 /*
2228                  * If the LUN is invalid, pretend that it doesn't exist.
2229                  * It will go away as soon as all pending I/O has been
2230                  * completed.
2231                  */
2232                 if (lun->flags & CTL_LUN_DISABLED) {
2233                         mtx_unlock(&lun->lun_lock);
2234                         lun = NULL;
2235                 }
2236         } else {
2237                 mtx_unlock(&softc->ctl_lock);
2238                 lun = NULL;
2239         }
2240         if (lun == NULL) {
2241                 /*
2242                  * The other node would not send this request to us unless
2243                  * received announce that we are primary node for this LUN.
2244                  * If this LUN does not exist now, it is probably result of
2245                  * a race, so respond to initiator in the most opaque way.
2246                  */
2247                 ctl_set_busy(ctsio);
2248                 goto badjuju;
2249         }
2250
2251         entry = ctl_get_cmd_entry(ctsio, NULL);
2252         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2253                 mtx_unlock(&lun->lun_lock);
2254                 goto badjuju;
2255         }
2256
2257         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2258         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2259
2260         /*
2261          * Every I/O goes into the OOA queue for a
2262          * particular LUN, and stays there until completion.
2263          */
2264 #ifdef CTL_TIME_IO
2265         if (TAILQ_EMPTY(&lun->ooa_queue))
2266                 lun->idle_time += getsbinuptime() - lun->last_busy;
2267 #endif
2268         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2269
2270         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2271                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2272                  ooa_links))) {
2273         case CTL_ACTION_BLOCK:
2274                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2275                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2276                                   blocked_links);
2277                 mtx_unlock(&lun->lun_lock);
2278                 break;
2279         case CTL_ACTION_PASS:
2280         case CTL_ACTION_SKIP:
2281                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2282                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2283                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2284                         mtx_unlock(&lun->lun_lock);
2285                 } else {
2286                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2287                         mtx_unlock(&lun->lun_lock);
2288
2289                         /* send msg back to other side */
2290                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2291                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2292                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2293                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2294                             sizeof(msg_info.hdr), M_WAITOK);
2295                 }
2296                 break;
2297         case CTL_ACTION_OVERLAP:
2298                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2299                 mtx_unlock(&lun->lun_lock);
2300                 ctl_set_overlapped_cmd(ctsio);
2301                 goto badjuju;
2302         case CTL_ACTION_OVERLAP_TAG:
2303                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2304                 mtx_unlock(&lun->lun_lock);
2305                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2306                 goto badjuju;
2307         case CTL_ACTION_ERROR:
2308         default:
2309                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2310                 mtx_unlock(&lun->lun_lock);
2311
2312                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2313                                          /*retry_count*/ 0);
2314 badjuju:
2315                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2316                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2317                 msg_info.hdr.serializing_sc = NULL;
2318                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2319                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2320                     sizeof(msg_info.scsi), M_WAITOK);
2321                 retval = 1;
2322                 break;
2323         }
2324         return (retval);
2325 }
2326
2327 /*
2328  * Returns 0 for success, errno for failure.
2329  */
2330 static void
2331 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2332                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2333 {
2334         union ctl_io *io;
2335
2336         mtx_lock(&lun->lun_lock);
2337         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2338              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2339              ooa_links)) {
2340                 struct ctl_ooa_entry *entry;
2341
2342                 /*
2343                  * If we've got more than we can fit, just count the
2344                  * remaining entries.
2345                  */
2346                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2347                         continue;
2348
2349                 entry = &kern_entries[*cur_fill_num];
2350
2351                 entry->tag_num = io->scsiio.tag_num;
2352                 entry->lun_num = lun->lun;
2353 #ifdef CTL_TIME_IO
2354                 entry->start_bt = io->io_hdr.start_bt;
2355 #endif
2356                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2357                 entry->cdb_len = io->scsiio.cdb_len;
2358                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2359                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2360
2361                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2362                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2363
2364                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2365                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2366
2367                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2368                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2369
2370                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2371                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2372         }
2373         mtx_unlock(&lun->lun_lock);
2374 }
2375
2376 static void *
2377 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2378                  size_t error_str_len)
2379 {
2380         void *kptr;
2381
2382         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2383
2384         if (copyin(user_addr, kptr, len) != 0) {
2385                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2386                          "from user address %p to kernel address %p", len,
2387                          user_addr, kptr);
2388                 free(kptr, M_CTL);
2389                 return (NULL);
2390         }
2391
2392         return (kptr);
2393 }
2394
2395 static void
2396 ctl_free_args(int num_args, struct ctl_be_arg *args)
2397 {
2398         int i;
2399
2400         if (args == NULL)
2401                 return;
2402
2403         for (i = 0; i < num_args; i++) {
2404                 free(args[i].kname, M_CTL);
2405                 free(args[i].kvalue, M_CTL);
2406         }
2407
2408         free(args, M_CTL);
2409 }
2410
2411 static struct ctl_be_arg *
2412 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2413                 char *error_str, size_t error_str_len)
2414 {
2415         struct ctl_be_arg *args;
2416         int i;
2417
2418         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2419                                 error_str, error_str_len);
2420
2421         if (args == NULL)
2422                 goto bailout;
2423
2424         for (i = 0; i < num_args; i++) {
2425                 args[i].kname = NULL;
2426                 args[i].kvalue = NULL;
2427         }
2428
2429         for (i = 0; i < num_args; i++) {
2430                 uint8_t *tmpptr;
2431
2432                 args[i].kname = ctl_copyin_alloc(args[i].name,
2433                         args[i].namelen, error_str, error_str_len);
2434                 if (args[i].kname == NULL)
2435                         goto bailout;
2436
2437                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2438                         snprintf(error_str, error_str_len, "Argument %d "
2439                                  "name is not NUL-terminated", i);
2440                         goto bailout;
2441                 }
2442
2443                 if (args[i].flags & CTL_BEARG_RD) {
2444                         tmpptr = ctl_copyin_alloc(args[i].value,
2445                                 args[i].vallen, error_str, error_str_len);
2446                         if (tmpptr == NULL)
2447                                 goto bailout;
2448                         if ((args[i].flags & CTL_BEARG_ASCII)
2449                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2450                                 snprintf(error_str, error_str_len, "Argument "
2451                                     "%d value is not NUL-terminated", i);
2452                                 free(tmpptr, M_CTL);
2453                                 goto bailout;
2454                         }
2455                         args[i].kvalue = tmpptr;
2456                 } else {
2457                         args[i].kvalue = malloc(args[i].vallen,
2458                             M_CTL, M_WAITOK | M_ZERO);
2459                 }
2460         }
2461
2462         return (args);
2463 bailout:
2464
2465         ctl_free_args(num_args, args);
2466
2467         return (NULL);
2468 }
2469
2470 static void
2471 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2472 {
2473         int i;
2474
2475         for (i = 0; i < num_args; i++) {
2476                 if (args[i].flags & CTL_BEARG_WR)
2477                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2478         }
2479 }
2480
2481 /*
2482  * Escape characters that are illegal or not recommended in XML.
2483  */
2484 int
2485 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2486 {
2487         char *end = str + size;
2488         int retval;
2489
2490         retval = 0;
2491
2492         for (; *str && str < end; str++) {
2493                 switch (*str) {
2494                 case '&':
2495                         retval = sbuf_printf(sb, "&amp;");
2496                         break;
2497                 case '>':
2498                         retval = sbuf_printf(sb, "&gt;");
2499                         break;
2500                 case '<':
2501                         retval = sbuf_printf(sb, "&lt;");
2502                         break;
2503                 default:
2504                         retval = sbuf_putc(sb, *str);
2505                         break;
2506                 }
2507
2508                 if (retval != 0)
2509                         break;
2510
2511         }
2512
2513         return (retval);
2514 }
2515
2516 static void
2517 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2518 {
2519         struct scsi_vpd_id_descriptor *desc;
2520         int i;
2521
2522         if (id == NULL || id->len < 4)
2523                 return;
2524         desc = (struct scsi_vpd_id_descriptor *)id->data;
2525         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2526         case SVPD_ID_TYPE_T10:
2527                 sbuf_printf(sb, "t10.");
2528                 break;
2529         case SVPD_ID_TYPE_EUI64:
2530                 sbuf_printf(sb, "eui.");
2531                 break;
2532         case SVPD_ID_TYPE_NAA:
2533                 sbuf_printf(sb, "naa.");
2534                 break;
2535         case SVPD_ID_TYPE_SCSI_NAME:
2536                 break;
2537         }
2538         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2539         case SVPD_ID_CODESET_BINARY:
2540                 for (i = 0; i < desc->length; i++)
2541                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2542                 break;
2543         case SVPD_ID_CODESET_ASCII:
2544                 sbuf_printf(sb, "%.*s", (int)desc->length,
2545                     (char *)desc->identifier);
2546                 break;
2547         case SVPD_ID_CODESET_UTF8:
2548                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2549                 break;
2550         }
2551 }
2552
2553 static int
2554 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2555           struct thread *td)
2556 {
2557         struct ctl_softc *softc = dev->si_drv1;
2558         struct ctl_lun *lun;
2559         int retval;
2560
2561         retval = 0;
2562
2563         switch (cmd) {
2564         case CTL_IO:
2565                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2566                 break;
2567         case CTL_ENABLE_PORT:
2568         case CTL_DISABLE_PORT:
2569         case CTL_SET_PORT_WWNS: {
2570                 struct ctl_port *port;
2571                 struct ctl_port_entry *entry;
2572
2573                 entry = (struct ctl_port_entry *)addr;
2574                 
2575                 mtx_lock(&softc->ctl_lock);
2576                 STAILQ_FOREACH(port, &softc->port_list, links) {
2577                         int action, done;
2578
2579                         if (port->targ_port < softc->port_min ||
2580                             port->targ_port >= softc->port_max)
2581                                 continue;
2582
2583                         action = 0;
2584                         done = 0;
2585                         if ((entry->port_type == CTL_PORT_NONE)
2586                          && (entry->targ_port == port->targ_port)) {
2587                                 /*
2588                                  * If the user only wants to enable or
2589                                  * disable or set WWNs on a specific port,
2590                                  * do the operation and we're done.
2591                                  */
2592                                 action = 1;
2593                                 done = 1;
2594                         } else if (entry->port_type & port->port_type) {
2595                                 /*
2596                                  * Compare the user's type mask with the
2597                                  * particular frontend type to see if we
2598                                  * have a match.
2599                                  */
2600                                 action = 1;
2601                                 done = 0;
2602
2603                                 /*
2604                                  * Make sure the user isn't trying to set
2605                                  * WWNs on multiple ports at the same time.
2606                                  */
2607                                 if (cmd == CTL_SET_PORT_WWNS) {
2608                                         printf("%s: Can't set WWNs on "
2609                                                "multiple ports\n", __func__);
2610                                         retval = EINVAL;
2611                                         break;
2612                                 }
2613                         }
2614                         if (action == 0)
2615                                 continue;
2616
2617                         /*
2618                          * XXX KDM we have to drop the lock here, because
2619                          * the online/offline operations can potentially
2620                          * block.  We need to reference count the frontends
2621                          * so they can't go away,
2622                          */
2623                         if (cmd == CTL_ENABLE_PORT) {
2624                                 mtx_unlock(&softc->ctl_lock);
2625                                 ctl_port_online(port);
2626                                 mtx_lock(&softc->ctl_lock);
2627                         } else if (cmd == CTL_DISABLE_PORT) {
2628                                 mtx_unlock(&softc->ctl_lock);
2629                                 ctl_port_offline(port);
2630                                 mtx_lock(&softc->ctl_lock);
2631                         } else if (cmd == CTL_SET_PORT_WWNS) {
2632                                 ctl_port_set_wwns(port,
2633                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2634                                     1 : 0, entry->wwnn,
2635                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2636                                     1 : 0, entry->wwpn);
2637                         }
2638                         if (done != 0)
2639                                 break;
2640                 }
2641                 mtx_unlock(&softc->ctl_lock);
2642                 break;
2643         }
2644         case CTL_GET_OOA: {
2645                 struct ctl_ooa *ooa_hdr;
2646                 struct ctl_ooa_entry *entries;
2647                 uint32_t cur_fill_num;
2648
2649                 ooa_hdr = (struct ctl_ooa *)addr;
2650
2651                 if ((ooa_hdr->alloc_len == 0)
2652                  || (ooa_hdr->alloc_num == 0)) {
2653                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2654                                "must be non-zero\n", __func__,
2655                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2656                         retval = EINVAL;
2657                         break;
2658                 }
2659
2660                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2661                     sizeof(struct ctl_ooa_entry))) {
2662                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2663                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2664                                __func__, ooa_hdr->alloc_len,
2665                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2666                         retval = EINVAL;
2667                         break;
2668                 }
2669
2670                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2671                 if (entries == NULL) {
2672                         printf("%s: could not allocate %d bytes for OOA "
2673                                "dump\n", __func__, ooa_hdr->alloc_len);
2674                         retval = ENOMEM;
2675                         break;
2676                 }
2677
2678                 mtx_lock(&softc->ctl_lock);
2679                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2680                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2681                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2682                         mtx_unlock(&softc->ctl_lock);
2683                         free(entries, M_CTL);
2684                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2685                                __func__, (uintmax_t)ooa_hdr->lun_num);
2686                         retval = EINVAL;
2687                         break;
2688                 }
2689
2690                 cur_fill_num = 0;
2691
2692                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2693                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2694                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2695                                     ooa_hdr, entries);
2696                         }
2697                 } else {
2698                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2699                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2700                             entries);
2701                 }
2702                 mtx_unlock(&softc->ctl_lock);
2703
2704                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2705                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2706                         sizeof(struct ctl_ooa_entry);
2707                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2708                 if (retval != 0) {
2709                         printf("%s: error copying out %d bytes for OOA dump\n", 
2710                                __func__, ooa_hdr->fill_len);
2711                 }
2712
2713                 getbinuptime(&ooa_hdr->cur_bt);
2714
2715                 if (cur_fill_num > ooa_hdr->alloc_num) {
2716                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2717                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2718                 } else {
2719                         ooa_hdr->dropped_num = 0;
2720                         ooa_hdr->status = CTL_OOA_OK;
2721                 }
2722
2723                 free(entries, M_CTL);
2724                 break;
2725         }
2726         case CTL_DELAY_IO: {
2727                 struct ctl_io_delay_info *delay_info;
2728
2729                 delay_info = (struct ctl_io_delay_info *)addr;
2730
2731 #ifdef CTL_IO_DELAY
2732                 mtx_lock(&softc->ctl_lock);
2733
2734                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2735                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2736                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2737                 } else {
2738                         lun = softc->ctl_luns[delay_info->lun_id];
2739                         mtx_lock(&lun->lun_lock);
2740
2741                         delay_info->status = CTL_DELAY_STATUS_OK;
2742
2743                         switch (delay_info->delay_type) {
2744                         case CTL_DELAY_TYPE_CONT:
2745                                 break;
2746                         case CTL_DELAY_TYPE_ONESHOT:
2747                                 break;
2748                         default:
2749                                 delay_info->status =
2750                                         CTL_DELAY_STATUS_INVALID_TYPE;
2751                                 break;
2752                         }
2753
2754                         switch (delay_info->delay_loc) {
2755                         case CTL_DELAY_LOC_DATAMOVE:
2756                                 lun->delay_info.datamove_type =
2757                                         delay_info->delay_type;
2758                                 lun->delay_info.datamove_delay =
2759                                         delay_info->delay_secs;
2760                                 break;
2761                         case CTL_DELAY_LOC_DONE:
2762                                 lun->delay_info.done_type =
2763                                         delay_info->delay_type;
2764                                 lun->delay_info.done_delay =
2765                                         delay_info->delay_secs;
2766                                 break;
2767                         default:
2768                                 delay_info->status =
2769                                         CTL_DELAY_STATUS_INVALID_LOC;
2770                                 break;
2771                         }
2772                         mtx_unlock(&lun->lun_lock);
2773                 }
2774
2775                 mtx_unlock(&softc->ctl_lock);
2776 #else
2777                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2778 #endif /* CTL_IO_DELAY */
2779                 break;
2780         }
2781         case CTL_GETSTATS: {
2782                 struct ctl_stats *stats;
2783                 int i;
2784
2785                 stats = (struct ctl_stats *)addr;
2786
2787                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2788                      stats->alloc_len) {
2789                         stats->status = CTL_SS_NEED_MORE_SPACE;
2790                         stats->num_luns = softc->num_luns;
2791                         break;
2792                 }
2793                 /*
2794                  * XXX KDM no locking here.  If the LUN list changes,
2795                  * things can blow up.
2796                  */
2797                 i = 0;
2798                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2799                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2800                                          sizeof(lun->stats));
2801                         if (retval != 0)
2802                                 break;
2803                 }
2804                 stats->num_luns = softc->num_luns;
2805                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2806                                  softc->num_luns;
2807                 stats->status = CTL_SS_OK;
2808 #ifdef CTL_TIME_IO
2809                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2810 #else
2811                 stats->flags = CTL_STATS_FLAG_NONE;
2812 #endif
2813                 getnanouptime(&stats->timestamp);
2814                 break;
2815         }
2816         case CTL_ERROR_INJECT: {
2817                 struct ctl_error_desc *err_desc, *new_err_desc;
2818
2819                 err_desc = (struct ctl_error_desc *)addr;
2820
2821                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2822                                       M_WAITOK | M_ZERO);
2823                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2824
2825                 mtx_lock(&softc->ctl_lock);
2826                 lun = softc->ctl_luns[err_desc->lun_id];
2827                 if (lun == NULL) {
2828                         mtx_unlock(&softc->ctl_lock);
2829                         free(new_err_desc, M_CTL);
2830                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2831                                __func__, (uintmax_t)err_desc->lun_id);
2832                         retval = EINVAL;
2833                         break;
2834                 }
2835                 mtx_lock(&lun->lun_lock);
2836                 mtx_unlock(&softc->ctl_lock);
2837
2838                 /*
2839                  * We could do some checking here to verify the validity
2840                  * of the request, but given the complexity of error
2841                  * injection requests, the checking logic would be fairly
2842                  * complex.
2843                  *
2844                  * For now, if the request is invalid, it just won't get
2845                  * executed and might get deleted.
2846                  */
2847                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2848
2849                 /*
2850                  * XXX KDM check to make sure the serial number is unique,
2851                  * in case we somehow manage to wrap.  That shouldn't
2852                  * happen for a very long time, but it's the right thing to
2853                  * do.
2854                  */
2855                 new_err_desc->serial = lun->error_serial;
2856                 err_desc->serial = lun->error_serial;
2857                 lun->error_serial++;
2858
2859                 mtx_unlock(&lun->lun_lock);
2860                 break;
2861         }
2862         case CTL_ERROR_INJECT_DELETE: {
2863                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2864                 int delete_done;
2865
2866                 delete_desc = (struct ctl_error_desc *)addr;
2867                 delete_done = 0;
2868
2869                 mtx_lock(&softc->ctl_lock);
2870                 lun = softc->ctl_luns[delete_desc->lun_id];
2871                 if (lun == NULL) {
2872                         mtx_unlock(&softc->ctl_lock);
2873                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2874                                __func__, (uintmax_t)delete_desc->lun_id);
2875                         retval = EINVAL;
2876                         break;
2877                 }
2878                 mtx_lock(&lun->lun_lock);
2879                 mtx_unlock(&softc->ctl_lock);
2880                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2881                         if (desc->serial != delete_desc->serial)
2882                                 continue;
2883
2884                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2885                                       links);
2886                         free(desc, M_CTL);
2887                         delete_done = 1;
2888                 }
2889                 mtx_unlock(&lun->lun_lock);
2890                 if (delete_done == 0) {
2891                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2892                                "error serial %ju on LUN %u\n", __func__, 
2893                                delete_desc->serial, delete_desc->lun_id);
2894                         retval = EINVAL;
2895                         break;
2896                 }
2897                 break;
2898         }
2899         case CTL_DUMP_STRUCTS: {
2900                 int i, j, k;
2901                 struct ctl_port *port;
2902                 struct ctl_frontend *fe;
2903
2904                 mtx_lock(&softc->ctl_lock);
2905                 printf("CTL Persistent Reservation information start:\n");
2906                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2907                         lun = softc->ctl_luns[i];
2908
2909                         if ((lun == NULL)
2910                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2911                                 continue;
2912
2913                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2914                                 if (lun->pr_keys[j] == NULL)
2915                                         continue;
2916                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2917                                         if (lun->pr_keys[j][k] == 0)
2918                                                 continue;
2919                                         printf("  LUN %d port %d iid %d key "
2920                                                "%#jx\n", i, j, k,
2921                                                (uintmax_t)lun->pr_keys[j][k]);
2922                                 }
2923                         }
2924                 }
2925                 printf("CTL Persistent Reservation information end\n");
2926                 printf("CTL Ports:\n");
2927                 STAILQ_FOREACH(port, &softc->port_list, links) {
2928                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2929                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2930                                port->frontend->name, port->port_type,
2931                                port->physical_port, port->virtual_port,
2932                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2933                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2934                                 if (port->wwpn_iid[j].in_use == 0 &&
2935                                     port->wwpn_iid[j].wwpn == 0 &&
2936                                     port->wwpn_iid[j].name == NULL)
2937                                         continue;
2938
2939                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2940                                     j, port->wwpn_iid[j].in_use,
2941                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2942                                     port->wwpn_iid[j].name);
2943                         }
2944                 }
2945                 printf("CTL Port information end\n");
2946                 mtx_unlock(&softc->ctl_lock);
2947                 /*
2948                  * XXX KDM calling this without a lock.  We'd likely want
2949                  * to drop the lock before calling the frontend's dump
2950                  * routine anyway.
2951                  */
2952                 printf("CTL Frontends:\n");
2953                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2954                         printf("  Frontend '%s'\n", fe->name);
2955                         if (fe->fe_dump != NULL)
2956                                 fe->fe_dump();
2957                 }
2958                 printf("CTL Frontend information end\n");
2959                 break;
2960         }
2961         case CTL_LUN_REQ: {
2962                 struct ctl_lun_req *lun_req;
2963                 struct ctl_backend_driver *backend;
2964
2965                 lun_req = (struct ctl_lun_req *)addr;
2966
2967                 backend = ctl_backend_find(lun_req->backend);
2968                 if (backend == NULL) {
2969                         lun_req->status = CTL_LUN_ERROR;
2970                         snprintf(lun_req->error_str,
2971                                  sizeof(lun_req->error_str),
2972                                  "Backend \"%s\" not found.",
2973                                  lun_req->backend);
2974                         break;
2975                 }
2976                 if (lun_req->num_be_args > 0) {
2977                         lun_req->kern_be_args = ctl_copyin_args(
2978                                 lun_req->num_be_args,
2979                                 lun_req->be_args,
2980                                 lun_req->error_str,
2981                                 sizeof(lun_req->error_str));
2982                         if (lun_req->kern_be_args == NULL) {
2983                                 lun_req->status = CTL_LUN_ERROR;
2984                                 break;
2985                         }
2986                 }
2987
2988                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2989
2990                 if (lun_req->num_be_args > 0) {
2991                         ctl_copyout_args(lun_req->num_be_args,
2992                                       lun_req->kern_be_args);
2993                         ctl_free_args(lun_req->num_be_args,
2994                                       lun_req->kern_be_args);
2995                 }
2996                 break;
2997         }
2998         case CTL_LUN_LIST: {
2999                 struct sbuf *sb;
3000                 struct ctl_lun_list *list;
3001                 struct ctl_option *opt;
3002
3003                 list = (struct ctl_lun_list *)addr;
3004
3005                 /*
3006                  * Allocate a fixed length sbuf here, based on the length
3007                  * of the user's buffer.  We could allocate an auto-extending
3008                  * buffer, and then tell the user how much larger our
3009                  * amount of data is than his buffer, but that presents
3010                  * some problems:
3011                  *
3012                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3013                  *     we can't hold a lock while calling them with an
3014                  *     auto-extending buffer.
3015                  *
3016                  * 2.  There is not currently a LUN reference counting
3017                  *     mechanism, outside of outstanding transactions on
3018                  *     the LUN's OOA queue.  So a LUN could go away on us
3019                  *     while we're getting the LUN number, backend-specific
3020                  *     information, etc.  Thus, given the way things
3021                  *     currently work, we need to hold the CTL lock while
3022                  *     grabbing LUN information.
3023                  *
3024                  * So, from the user's standpoint, the best thing to do is
3025                  * allocate what he thinks is a reasonable buffer length,
3026                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3027                  * double the buffer length and try again.  (And repeat
3028                  * that until he succeeds.)
3029                  */
3030                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3031                 if (sb == NULL) {
3032                         list->status = CTL_LUN_LIST_ERROR;
3033                         snprintf(list->error_str, sizeof(list->error_str),
3034                                  "Unable to allocate %d bytes for LUN list",
3035                                  list->alloc_len);
3036                         break;
3037                 }
3038
3039                 sbuf_printf(sb, "<ctllunlist>\n");
3040
3041                 mtx_lock(&softc->ctl_lock);
3042                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3043                         mtx_lock(&lun->lun_lock);
3044                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3045                                              (uintmax_t)lun->lun);
3046
3047                         /*
3048                          * Bail out as soon as we see that we've overfilled
3049                          * the buffer.
3050                          */
3051                         if (retval != 0)
3052                                 break;
3053
3054                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3055                                              "</backend_type>\n",
3056                                              (lun->backend == NULL) ?  "none" :
3057                                              lun->backend->name);
3058
3059                         if (retval != 0)
3060                                 break;
3061
3062                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3063                                              lun->be_lun->lun_type);
3064
3065                         if (retval != 0)
3066                                 break;
3067
3068                         if (lun->backend == NULL) {
3069                                 retval = sbuf_printf(sb, "</lun>\n");
3070                                 if (retval != 0)
3071                                         break;
3072                                 continue;
3073                         }
3074
3075                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3076                                              (lun->be_lun->maxlba > 0) ?
3077                                              lun->be_lun->maxlba + 1 : 0);
3078
3079                         if (retval != 0)
3080                                 break;
3081
3082                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3083                                              lun->be_lun->blocksize);
3084
3085                         if (retval != 0)
3086                                 break;
3087
3088                         retval = sbuf_printf(sb, "\t<serial_number>");
3089
3090                         if (retval != 0)
3091                                 break;
3092
3093                         retval = ctl_sbuf_printf_esc(sb,
3094                             lun->be_lun->serial_num,
3095                             sizeof(lun->be_lun->serial_num));
3096
3097                         if (retval != 0)
3098                                 break;
3099
3100                         retval = sbuf_printf(sb, "</serial_number>\n");
3101                 
3102                         if (retval != 0)
3103                                 break;
3104
3105                         retval = sbuf_printf(sb, "\t<device_id>");
3106
3107                         if (retval != 0)
3108                                 break;
3109
3110                         retval = ctl_sbuf_printf_esc(sb,
3111                             lun->be_lun->device_id,
3112                             sizeof(lun->be_lun->device_id));
3113
3114                         if (retval != 0)
3115                                 break;
3116
3117                         retval = sbuf_printf(sb, "</device_id>\n");
3118
3119                         if (retval != 0)
3120                                 break;
3121
3122                         if (lun->backend->lun_info != NULL) {
3123                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3124                                 if (retval != 0)
3125                                         break;
3126                         }
3127                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3128                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3129                                     opt->name, opt->value, opt->name);
3130                                 if (retval != 0)
3131                                         break;
3132                         }
3133
3134                         retval = sbuf_printf(sb, "</lun>\n");
3135
3136                         if (retval != 0)
3137                                 break;
3138                         mtx_unlock(&lun->lun_lock);
3139                 }
3140                 if (lun != NULL)
3141                         mtx_unlock(&lun->lun_lock);
3142                 mtx_unlock(&softc->ctl_lock);
3143
3144                 if ((retval != 0)
3145                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3146                         retval = 0;
3147                         sbuf_delete(sb);
3148                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3149                         snprintf(list->error_str, sizeof(list->error_str),
3150                                  "Out of space, %d bytes is too small",
3151                                  list->alloc_len);
3152                         break;
3153                 }
3154
3155                 sbuf_finish(sb);
3156
3157                 retval = copyout(sbuf_data(sb), list->lun_xml,
3158                                  sbuf_len(sb) + 1);
3159
3160                 list->fill_len = sbuf_len(sb) + 1;
3161                 list->status = CTL_LUN_LIST_OK;
3162                 sbuf_delete(sb);
3163                 break;
3164         }
3165         case CTL_ISCSI: {
3166                 struct ctl_iscsi *ci;
3167                 struct ctl_frontend *fe;
3168
3169                 ci = (struct ctl_iscsi *)addr;
3170
3171                 fe = ctl_frontend_find("iscsi");
3172                 if (fe == NULL) {
3173                         ci->status = CTL_ISCSI_ERROR;
3174                         snprintf(ci->error_str, sizeof(ci->error_str),
3175                             "Frontend \"iscsi\" not found.");
3176                         break;
3177                 }
3178
3179                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3180                 break;
3181         }
3182         case CTL_PORT_REQ: {
3183                 struct ctl_req *req;
3184                 struct ctl_frontend *fe;
3185
3186                 req = (struct ctl_req *)addr;
3187
3188                 fe = ctl_frontend_find(req->driver);
3189                 if (fe == NULL) {
3190                         req->status = CTL_LUN_ERROR;
3191                         snprintf(req->error_str, sizeof(req->error_str),
3192                             "Frontend \"%s\" not found.", req->driver);
3193                         break;
3194                 }
3195                 if (req->num_args > 0) {
3196                         req->kern_args = ctl_copyin_args(req->num_args,
3197                             req->args, req->error_str, sizeof(req->error_str));
3198                         if (req->kern_args == NULL) {
3199                                 req->status = CTL_LUN_ERROR;
3200                                 break;
3201                         }
3202                 }
3203
3204                 if (fe->ioctl)
3205                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3206                 else
3207                         retval = ENODEV;
3208
3209                 if (req->num_args > 0) {
3210                         ctl_copyout_args(req->num_args, req->kern_args);
3211                         ctl_free_args(req->num_args, req->kern_args);
3212                 }
3213                 break;
3214         }
3215         case CTL_PORT_LIST: {
3216                 struct sbuf *sb;
3217                 struct ctl_port *port;
3218                 struct ctl_lun_list *list;
3219                 struct ctl_option *opt;
3220                 int j;
3221                 uint32_t plun;
3222
3223                 list = (struct ctl_lun_list *)addr;
3224
3225                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226                 if (sb == NULL) {
3227                         list->status = CTL_LUN_LIST_ERROR;
3228                         snprintf(list->error_str, sizeof(list->error_str),
3229                                  "Unable to allocate %d bytes for LUN list",
3230                                  list->alloc_len);
3231                         break;
3232                 }
3233
3234                 sbuf_printf(sb, "<ctlportlist>\n");
3235
3236                 mtx_lock(&softc->ctl_lock);
3237                 STAILQ_FOREACH(port, &softc->port_list, links) {
3238                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3239                                              (uintmax_t)port->targ_port);
3240
3241                         /*
3242                          * Bail out as soon as we see that we've overfilled
3243                          * the buffer.
3244                          */
3245                         if (retval != 0)
3246                                 break;
3247
3248                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3249                             "</frontend_type>\n", port->frontend->name);
3250                         if (retval != 0)
3251                                 break;
3252
3253                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3254                                              port->port_type);
3255                         if (retval != 0)
3256                                 break;
3257
3258                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3259                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3260                         if (retval != 0)
3261                                 break;
3262
3263                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3264                             port->port_name);
3265                         if (retval != 0)
3266                                 break;
3267
3268                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3269                             port->physical_port);
3270                         if (retval != 0)
3271                                 break;
3272
3273                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3274                             port->virtual_port);
3275                         if (retval != 0)
3276                                 break;
3277
3278                         if (port->target_devid != NULL) {
3279                                 sbuf_printf(sb, "\t<target>");
3280                                 ctl_id_sbuf(port->target_devid, sb);
3281                                 sbuf_printf(sb, "</target>\n");
3282                         }
3283
3284                         if (port->port_devid != NULL) {
3285                                 sbuf_printf(sb, "\t<port>");
3286                                 ctl_id_sbuf(port->port_devid, sb);
3287                                 sbuf_printf(sb, "</port>\n");
3288                         }
3289
3290                         if (port->port_info != NULL) {
3291                                 retval = port->port_info(port->onoff_arg, sb);
3292                                 if (retval != 0)
3293                                         break;
3294                         }
3295                         STAILQ_FOREACH(opt, &port->options, links) {
3296                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3297                                     opt->name, opt->value, opt->name);
3298                                 if (retval != 0)
3299                                         break;
3300                         }
3301
3302                         if (port->lun_map != NULL) {
3303                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3304                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3305                                         plun = ctl_lun_map_from_port(port, j);
3306                                         if (plun >= CTL_MAX_LUNS)
3307                                                 continue;
3308                                         sbuf_printf(sb,
3309                                             "\t<lun id=\"%u\">%u</lun>\n",
3310                                             j, plun);
3311                                 }
3312                         }
3313
3314                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3315                                 if (port->wwpn_iid[j].in_use == 0 ||
3316                                     (port->wwpn_iid[j].wwpn == 0 &&
3317                                      port->wwpn_iid[j].name == NULL))
3318                                         continue;
3319
3320                                 if (port->wwpn_iid[j].name != NULL)
3321                                         retval = sbuf_printf(sb,
3322                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3323                                             j, port->wwpn_iid[j].name);
3324                                 else
3325                                         retval = sbuf_printf(sb,
3326                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3327                                             j, port->wwpn_iid[j].wwpn);
3328                                 if (retval != 0)
3329                                         break;
3330                         }
3331                         if (retval != 0)
3332                                 break;
3333
3334                         retval = sbuf_printf(sb, "</targ_port>\n");
3335                         if (retval != 0)
3336                                 break;
3337                 }
3338                 mtx_unlock(&softc->ctl_lock);
3339
3340                 if ((retval != 0)
3341                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3342                         retval = 0;
3343                         sbuf_delete(sb);
3344                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3345                         snprintf(list->error_str, sizeof(list->error_str),
3346                                  "Out of space, %d bytes is too small",
3347                                  list->alloc_len);
3348                         break;
3349                 }
3350
3351                 sbuf_finish(sb);
3352
3353                 retval = copyout(sbuf_data(sb), list->lun_xml,
3354                                  sbuf_len(sb) + 1);
3355
3356                 list->fill_len = sbuf_len(sb) + 1;
3357                 list->status = CTL_LUN_LIST_OK;
3358                 sbuf_delete(sb);
3359                 break;
3360         }
3361         case CTL_LUN_MAP: {
3362                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3363                 struct ctl_port *port;
3364
3365                 mtx_lock(&softc->ctl_lock);
3366                 if (lm->port < softc->port_min ||
3367                     lm->port >= softc->port_max ||
3368                     (port = softc->ctl_ports[lm->port]) == NULL) {
3369                         mtx_unlock(&softc->ctl_lock);
3370                         return (ENXIO);
3371                 }
3372                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3373                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3374                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3375                                     CTL_MAX_LUNS)
3376                                         continue;
3377                                 mtx_lock(&lun->lun_lock);
3378                                 ctl_est_ua_port(lun, lm->port, -1,
3379                                     CTL_UA_LUN_CHANGE);
3380                                 mtx_unlock(&lun->lun_lock);
3381                         }
3382                 }
3383                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3384                 if (lm->plun < CTL_MAX_LUNS) {
3385                         if (lm->lun == UINT32_MAX)
3386                                 retval = ctl_lun_map_unset(port, lm->plun);
3387                         else if (lm->lun < CTL_MAX_LUNS &&
3388                             softc->ctl_luns[lm->lun] != NULL)
3389                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3390                         else
3391                                 return (ENXIO);
3392                 } else if (lm->plun == UINT32_MAX) {
3393                         if (lm->lun == UINT32_MAX)
3394                                 retval = ctl_lun_map_deinit(port);
3395                         else
3396                                 retval = ctl_lun_map_init(port);
3397                 } else
3398                         return (ENXIO);
3399                 if (port->status & CTL_PORT_STATUS_ONLINE)
3400                         ctl_isc_announce_port(port);
3401                 break;
3402         }
3403         default: {
3404                 /* XXX KDM should we fix this? */
3405 #if 0
3406                 struct ctl_backend_driver *backend;
3407                 unsigned int type;
3408                 int found;
3409
3410                 found = 0;
3411
3412                 /*
3413                  * We encode the backend type as the ioctl type for backend
3414                  * ioctls.  So parse it out here, and then search for a
3415                  * backend of this type.
3416                  */
3417                 type = _IOC_TYPE(cmd);
3418
3419                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3420                         if (backend->type == type) {
3421                                 found = 1;
3422                                 break;
3423                         }
3424                 }
3425                 if (found == 0) {
3426                         printf("ctl: unknown ioctl command %#lx or backend "
3427                                "%d\n", cmd, type);
3428                         retval = EINVAL;
3429                         break;
3430                 }
3431                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3432 #endif
3433                 retval = ENOTTY;
3434                 break;
3435         }
3436         }
3437         return (retval);
3438 }
3439
3440 uint32_t
3441 ctl_get_initindex(struct ctl_nexus *nexus)
3442 {
3443         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3444 }
3445
3446 int
3447 ctl_lun_map_init(struct ctl_port *port)
3448 {
3449         struct ctl_softc *softc = port->ctl_softc;
3450         struct ctl_lun *lun;
3451         uint32_t i;
3452
3453         if (port->lun_map == NULL)
3454                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3455                     M_CTL, M_NOWAIT);
3456         if (port->lun_map == NULL)
3457                 return (ENOMEM);
3458         for (i = 0; i < CTL_MAX_LUNS; i++)
3459                 port->lun_map[i] = UINT32_MAX;
3460         if (port->status & CTL_PORT_STATUS_ONLINE) {
3461                 if (port->lun_disable != NULL) {
3462                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3463                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3464                 }
3465                 ctl_isc_announce_port(port);
3466         }
3467         return (0);
3468 }
3469
3470 int
3471 ctl_lun_map_deinit(struct ctl_port *port)
3472 {
3473         struct ctl_softc *softc = port->ctl_softc;
3474         struct ctl_lun *lun;
3475
3476         if (port->lun_map == NULL)
3477                 return (0);
3478         free(port->lun_map, M_CTL);
3479         port->lun_map = NULL;
3480         if (port->status & CTL_PORT_STATUS_ONLINE) {
3481                 if (port->lun_enable != NULL) {
3482                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3483                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3484                 }
3485                 ctl_isc_announce_port(port);
3486         }
3487         return (0);
3488 }
3489
3490 int
3491 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3492 {
3493         int status;
3494         uint32_t old;
3495
3496         if (port->lun_map == NULL) {
3497                 status = ctl_lun_map_init(port);
3498                 if (status != 0)
3499                         return (status);
3500         }
3501         old = port->lun_map[plun];
3502         port->lun_map[plun] = glun;
3503         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3504                 if (port->lun_enable != NULL)
3505                         port->lun_enable(port->targ_lun_arg, plun);
3506                 ctl_isc_announce_port(port);
3507         }
3508         return (0);
3509 }
3510
3511 int
3512 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3513 {
3514         uint32_t old;
3515
3516         if (port->lun_map == NULL)
3517                 return (0);
3518         old = port->lun_map[plun];
3519         port->lun_map[plun] = UINT32_MAX;
3520         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3521                 if (port->lun_disable != NULL)
3522                         port->lun_disable(port->targ_lun_arg, plun);
3523                 ctl_isc_announce_port(port);
3524         }
3525         return (0);
3526 }
3527
3528 uint32_t
3529 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3530 {
3531
3532         if (port == NULL)
3533                 return (UINT32_MAX);
3534         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3535                 return (lun_id);
3536         return (port->lun_map[lun_id]);
3537 }
3538
3539 uint32_t
3540 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3541 {
3542         uint32_t i;
3543
3544         if (port == NULL)
3545                 return (UINT32_MAX);
3546         if (port->lun_map == NULL)
3547                 return (lun_id);
3548         for (i = 0; i < CTL_MAX_LUNS; i++) {
3549                 if (port->lun_map[i] == lun_id)
3550                         return (i);
3551         }
3552         return (UINT32_MAX);
3553 }
3554
3555 uint32_t
3556 ctl_decode_lun(uint64_t encoded)
3557 {
3558         uint8_t lun[8];
3559         uint32_t result = 0xffffffff;
3560
3561         be64enc(lun, encoded);
3562         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3563         case RPL_LUNDATA_ATYP_PERIPH:
3564                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3565                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3566                         result = lun[1];
3567                 break;
3568         case RPL_LUNDATA_ATYP_FLAT:
3569                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3570                     lun[6] == 0 && lun[7] == 0)
3571                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3572                 break;
3573         case RPL_LUNDATA_ATYP_EXTLUN:
3574                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3575                 case 0x02:
3576                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3577                         case 0x00:
3578                                 result = lun[1];
3579                                 break;
3580                         case 0x10:
3581                                 result = (lun[1] << 16) + (lun[2] << 8) +
3582                                     lun[3];
3583                                 break;
3584                         case 0x20:
3585                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3586                                         result = (lun[2] << 24) +
3587                                             (lun[3] << 16) + (lun[4] << 8) +
3588                                             lun[5];
3589                                 break;
3590                         }
3591                         break;
3592                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3593                         result = 0xffffffff;
3594                         break;
3595                 }
3596                 break;
3597         }
3598         return (result);
3599 }
3600
3601 uint64_t
3602 ctl_encode_lun(uint32_t decoded)
3603 {
3604         uint64_t l = decoded;
3605
3606         if (l <= 0xff)
3607                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3608         if (l <= 0x3fff)
3609                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3610         if (l <= 0xffffff)
3611                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3612                     (l << 32));
3613         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3614 }
3615
3616 static struct ctl_port *
3617 ctl_io_port(struct ctl_io_hdr *io_hdr)
3618 {
3619
3620         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3621 }
3622
3623 int
3624 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3625 {
3626         int i;
3627
3628         for (i = first; i < last; i++) {
3629                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3630                         return (i);
3631         }
3632         return (-1);
3633 }
3634
3635 int
3636 ctl_set_mask(uint32_t *mask, uint32_t bit)
3637 {
3638         uint32_t chunk, piece;
3639
3640         chunk = bit >> 5;
3641         piece = bit % (sizeof(uint32_t) * 8);
3642
3643         if ((mask[chunk] & (1 << piece)) != 0)
3644                 return (-1);
3645         else
3646                 mask[chunk] |= (1 << piece);
3647
3648         return (0);
3649 }
3650
3651 int
3652 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3653 {
3654         uint32_t chunk, piece;
3655
3656         chunk = bit >> 5;
3657         piece = bit % (sizeof(uint32_t) * 8);
3658
3659         if ((mask[chunk] & (1 << piece)) == 0)
3660                 return (-1);
3661         else
3662                 mask[chunk] &= ~(1 << piece);
3663
3664         return (0);
3665 }
3666
3667 int
3668 ctl_is_set(uint32_t *mask, uint32_t bit)
3669 {
3670         uint32_t chunk, piece;
3671
3672         chunk = bit >> 5;
3673         piece = bit % (sizeof(uint32_t) * 8);
3674
3675         if ((mask[chunk] & (1 << piece)) == 0)
3676                 return (0);
3677         else
3678                 return (1);
3679 }
3680
3681 static uint64_t
3682 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3683 {
3684         uint64_t *t;
3685
3686         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3687         if (t == NULL)
3688                 return (0);
3689         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3690 }
3691
3692 static void
3693 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3694 {
3695         uint64_t *t;
3696
3697         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3698         if (t == NULL)
3699                 return;
3700         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3701 }
3702
3703 static void
3704 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3705 {
3706         uint64_t *p;
3707         u_int i;
3708
3709         i = residx/CTL_MAX_INIT_PER_PORT;
3710         if (lun->pr_keys[i] != NULL)
3711                 return;
3712         mtx_unlock(&lun->lun_lock);
3713         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3714             M_WAITOK | M_ZERO);
3715         mtx_lock(&lun->lun_lock);
3716         if (lun->pr_keys[i] == NULL)
3717                 lun->pr_keys[i] = p;
3718         else
3719                 free(p, M_CTL);
3720 }
3721
3722 static void
3723 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3724 {
3725         uint64_t *t;
3726
3727         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3728         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3729         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3730 }
3731
3732 /*
3733  * ctl_softc, pool_name, total_ctl_io are passed in.
3734  * npool is passed out.
3735  */
3736 int
3737 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3738                 uint32_t total_ctl_io, void **npool)
3739 {
3740 #ifdef IO_POOLS
3741         struct ctl_io_pool *pool;
3742
3743         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3744                                             M_NOWAIT | M_ZERO);
3745         if (pool == NULL)
3746                 return (ENOMEM);
3747
3748         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3749         pool->ctl_softc = ctl_softc;
3750         pool->zone = uma_zsecond_create(pool->name, NULL,
3751             NULL, NULL, NULL, ctl_softc->io_zone);
3752         /* uma_prealloc(pool->zone, total_ctl_io); */
3753
3754         *npool = pool;
3755 #else
3756         *npool = ctl_softc->io_zone;
3757 #endif
3758         return (0);
3759 }
3760
3761 void
3762 ctl_pool_free(struct ctl_io_pool *pool)
3763 {
3764
3765         if (pool == NULL)
3766                 return;
3767
3768 #ifdef IO_POOLS
3769         uma_zdestroy(pool->zone);
3770         free(pool, M_CTL);
3771 #endif
3772 }
3773
3774 union ctl_io *
3775 ctl_alloc_io(void *pool_ref)
3776 {
3777         union ctl_io *io;
3778 #ifdef IO_POOLS
3779         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3780
3781         io = uma_zalloc(pool->zone, M_WAITOK);
3782 #else
3783         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3784 #endif
3785         if (io != NULL)
3786                 io->io_hdr.pool = pool_ref;
3787         return (io);
3788 }
3789
3790 union ctl_io *
3791 ctl_alloc_io_nowait(void *pool_ref)
3792 {
3793         union ctl_io *io;
3794 #ifdef IO_POOLS
3795         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3796
3797         io = uma_zalloc(pool->zone, M_NOWAIT);
3798 #else
3799         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3800 #endif
3801         if (io != NULL)
3802                 io->io_hdr.pool = pool_ref;
3803         return (io);
3804 }
3805
3806 void
3807 ctl_free_io(union ctl_io *io)
3808 {
3809 #ifdef IO_POOLS
3810         struct ctl_io_pool *pool;
3811 #endif
3812
3813         if (io == NULL)
3814                 return;
3815
3816 #ifdef IO_POOLS
3817         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3818         uma_zfree(pool->zone, io);
3819 #else
3820         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3821 #endif
3822 }
3823
3824 void
3825 ctl_zero_io(union ctl_io *io)
3826 {
3827         void *pool_ref;
3828
3829         if (io == NULL)
3830                 return;
3831
3832         /*
3833          * May need to preserve linked list pointers at some point too.
3834          */
3835         pool_ref = io->io_hdr.pool;
3836         memset(io, 0, sizeof(*io));
3837         io->io_hdr.pool = pool_ref;
3838 }
3839
3840 int
3841 ctl_expand_number(const char *buf, uint64_t *num)
3842 {
3843         char *endptr;
3844         uint64_t number;
3845         unsigned shift;
3846
3847         number = strtoq(buf, &endptr, 0);
3848
3849         switch (tolower((unsigned char)*endptr)) {
3850         case 'e':
3851                 shift = 60;
3852                 break;
3853         case 'p':
3854                 shift = 50;
3855                 break;
3856         case 't':
3857                 shift = 40;
3858                 break;
3859         case 'g':
3860                 shift = 30;
3861                 break;
3862         case 'm':
3863                 shift = 20;
3864                 break;
3865         case 'k':
3866                 shift = 10;
3867                 break;
3868         case 'b':
3869         case '\0': /* No unit. */
3870                 *num = number;
3871                 return (0);
3872         default:
3873                 /* Unrecognized unit. */
3874                 return (-1);
3875         }
3876
3877         if ((number << shift) >> shift != number) {
3878                 /* Overflow */
3879                 return (-1);
3880         }
3881         *num = number << shift;
3882         return (0);
3883 }
3884
3885
3886 /*
3887  * This routine could be used in the future to load default and/or saved
3888  * mode page parameters for a particuar lun.
3889  */
3890 static int
3891 ctl_init_page_index(struct ctl_lun *lun)
3892 {
3893         int i, page_code;
3894         struct ctl_page_index *page_index;
3895         const char *value;
3896         uint64_t ival;
3897
3898         memcpy(&lun->mode_pages.index, page_index_template,
3899                sizeof(page_index_template));
3900
3901         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3902
3903                 page_index = &lun->mode_pages.index[i];
3904                 if (lun->be_lun->lun_type == T_DIRECT &&
3905                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3906                         continue;
3907                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3908                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3909                         continue;
3910                 if (lun->be_lun->lun_type == T_CDROM &&
3911                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3912                         continue;
3913
3914                 page_code = page_index->page_code & SMPH_PC_MASK;
3915                 switch (page_code) {
3916                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3917                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3918                             ("subpage %#x for page %#x is incorrect!",
3919                             page_index->subpage, page_code));
3920                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3921                                &rw_er_page_default,
3922                                sizeof(rw_er_page_default));
3923                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3924                                &rw_er_page_changeable,
3925                                sizeof(rw_er_page_changeable));
3926                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3927                                &rw_er_page_default,
3928                                sizeof(rw_er_page_default));
3929                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3930                                &rw_er_page_default,
3931                                sizeof(rw_er_page_default));
3932                         page_index->page_data =
3933                                 (uint8_t *)lun->mode_pages.rw_er_page;
3934                         break;
3935                 }
3936                 case SMS_FORMAT_DEVICE_PAGE: {
3937                         struct scsi_format_page *format_page;
3938
3939                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3940                             ("subpage %#x for page %#x is incorrect!",
3941                             page_index->subpage, page_code));
3942
3943                         /*
3944                          * Sectors per track are set above.  Bytes per
3945                          * sector need to be set here on a per-LUN basis.
3946                          */
3947                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3948                                &format_page_default,
3949                                sizeof(format_page_default));
3950                         memcpy(&lun->mode_pages.format_page[
3951                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3952                                sizeof(format_page_changeable));
3953                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3954                                &format_page_default,
3955                                sizeof(format_page_default));
3956                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3957                                &format_page_default,
3958                                sizeof(format_page_default));
3959
3960                         format_page = &lun->mode_pages.format_page[
3961                                 CTL_PAGE_CURRENT];
3962                         scsi_ulto2b(lun->be_lun->blocksize,
3963                                     format_page->bytes_per_sector);
3964
3965                         format_page = &lun->mode_pages.format_page[
3966                                 CTL_PAGE_DEFAULT];
3967                         scsi_ulto2b(lun->be_lun->blocksize,
3968                                     format_page->bytes_per_sector);
3969
3970                         format_page = &lun->mode_pages.format_page[
3971                                 CTL_PAGE_SAVED];
3972                         scsi_ulto2b(lun->be_lun->blocksize,
3973                                     format_page->bytes_per_sector);
3974
3975                         page_index->page_data =
3976                                 (uint8_t *)lun->mode_pages.format_page;
3977                         break;
3978                 }
3979                 case SMS_RIGID_DISK_PAGE: {
3980                         struct scsi_rigid_disk_page *rigid_disk_page;
3981                         uint32_t sectors_per_cylinder;
3982                         uint64_t cylinders;
3983 #ifndef __XSCALE__
3984                         int shift;
3985 #endif /* !__XSCALE__ */
3986
3987                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3988                             ("subpage %#x for page %#x is incorrect!",
3989                             page_index->subpage, page_code));
3990
3991                         /*
3992                          * Rotation rate and sectors per track are set
3993                          * above.  We calculate the cylinders here based on
3994                          * capacity.  Due to the number of heads and
3995                          * sectors per track we're using, smaller arrays
3996                          * may turn out to have 0 cylinders.  Linux and
3997                          * FreeBSD don't pay attention to these mode pages
3998                          * to figure out capacity, but Solaris does.  It
3999                          * seems to deal with 0 cylinders just fine, and
4000                          * works out a fake geometry based on the capacity.
4001                          */
4002                         memcpy(&lun->mode_pages.rigid_disk_page[
4003                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4004                                sizeof(rigid_disk_page_default));
4005                         memcpy(&lun->mode_pages.rigid_disk_page[
4006                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4007                                sizeof(rigid_disk_page_changeable));
4008
4009                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4010                                 CTL_DEFAULT_HEADS;
4011
4012                         /*
4013                          * The divide method here will be more accurate,
4014                          * probably, but results in floating point being
4015                          * used in the kernel on i386 (__udivdi3()).  On the
4016                          * XScale, though, __udivdi3() is implemented in
4017                          * software.
4018                          *
4019                          * The shift method for cylinder calculation is
4020                          * accurate if sectors_per_cylinder is a power of
4021                          * 2.  Otherwise it might be slightly off -- you
4022                          * might have a bit of a truncation problem.
4023                          */
4024 #ifdef  __XSCALE__
4025                         cylinders = (lun->be_lun->maxlba + 1) /
4026                                 sectors_per_cylinder;
4027 #else
4028                         for (shift = 31; shift > 0; shift--) {
4029                                 if (sectors_per_cylinder & (1 << shift))
4030                                         break;
4031                         }
4032                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4033 #endif
4034
4035                         /*
4036                          * We've basically got 3 bytes, or 24 bits for the
4037                          * cylinder size in the mode page.  If we're over,
4038                          * just round down to 2^24.
4039                          */
4040                         if (cylinders > 0xffffff)
4041                                 cylinders = 0xffffff;
4042
4043                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4044                                 CTL_PAGE_DEFAULT];
4045                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4046
4047                         if ((value = ctl_get_opt(&lun->be_lun->options,
4048                             "rpm")) != NULL) {
4049                                 scsi_ulto2b(strtol(value, NULL, 0),
4050                                      rigid_disk_page->rotation_rate);
4051                         }
4052
4053                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4054                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4055                                sizeof(rigid_disk_page_default));
4056                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4057                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4058                                sizeof(rigid_disk_page_default));
4059
4060                         page_index->page_data =
4061                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4062                         break;
4063                 }
4064                 case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4065                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4066                             ("subpage %#x for page %#x is incorrect!",
4067                             page_index->subpage, page_code));
4068                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4069                                &verify_er_page_default,
4070                                sizeof(verify_er_page_default));
4071                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4072                                &verify_er_page_changeable,
4073                                sizeof(verify_er_page_changeable));
4074                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4075                                &verify_er_page_default,
4076                                sizeof(verify_er_page_default));
4077                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4078                                &verify_er_page_default,
4079                                sizeof(verify_er_page_default));
4080                         page_index->page_data =
4081                                 (uint8_t *)lun->mode_pages.verify_er_page;
4082                         break;
4083                 }
4084                 case SMS_CACHING_PAGE: {
4085                         struct scsi_caching_page *caching_page;
4086
4087                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4088                             ("subpage %#x for page %#x is incorrect!",
4089                             page_index->subpage, page_code));
4090                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4091                                &caching_page_default,
4092                                sizeof(caching_page_default));
4093                         memcpy(&lun->mode_pages.caching_page[
4094                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4095                                sizeof(caching_page_changeable));
4096                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4097                                &caching_page_default,
4098                                sizeof(caching_page_default));
4099                         caching_page = &lun->mode_pages.caching_page[
4100                             CTL_PAGE_SAVED];
4101                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4102                         if (value != NULL && strcmp(value, "off") == 0)
4103                                 caching_page->flags1 &= ~SCP_WCE;
4104                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4105                         if (value != NULL && strcmp(value, "off") == 0)
4106                                 caching_page->flags1 |= SCP_RCD;
4107                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4108                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4109                                sizeof(caching_page_default));
4110                         page_index->page_data =
4111                                 (uint8_t *)lun->mode_pages.caching_page;
4112                         break;
4113                 }
4114                 case SMS_CONTROL_MODE_PAGE: {
4115                         switch (page_index->subpage) {
4116                         case SMS_SUBPAGE_PAGE_0: {
4117                                 struct scsi_control_page *control_page;
4118
4119                                 memcpy(&lun->mode_pages.control_page[
4120                                     CTL_PAGE_DEFAULT],
4121                                        &control_page_default,
4122                                        sizeof(control_page_default));
4123                                 memcpy(&lun->mode_pages.control_page[
4124                                     CTL_PAGE_CHANGEABLE],
4125                                        &control_page_changeable,
4126                                        sizeof(control_page_changeable));
4127                                 memcpy(&lun->mode_pages.control_page[
4128                                     CTL_PAGE_SAVED],
4129                                        &control_page_default,
4130                                        sizeof(control_page_default));
4131                                 control_page = &lun->mode_pages.control_page[
4132                                     CTL_PAGE_SAVED];
4133                                 value = ctl_get_opt(&lun->be_lun->options,
4134                                     "reordering");
4135                                 if (value != NULL &&
4136                                     strcmp(value, "unrestricted") == 0) {
4137                                         control_page->queue_flags &=
4138                                             ~SCP_QUEUE_ALG_MASK;
4139                                         control_page->queue_flags |=
4140                                             SCP_QUEUE_ALG_UNRESTRICTED;
4141                                 }
4142                                 memcpy(&lun->mode_pages.control_page[
4143                                     CTL_PAGE_CURRENT],
4144                                        &lun->mode_pages.control_page[
4145                                     CTL_PAGE_SAVED],
4146                                        sizeof(control_page_default));
4147                                 page_index->page_data =
4148                                     (uint8_t *)lun->mode_pages.control_page;
4149                                 break;
4150                         }
4151                         case 0x01:
4152                                 memcpy(&lun->mode_pages.control_ext_page[
4153                                     CTL_PAGE_DEFAULT],
4154                                        &control_ext_page_default,
4155                                        sizeof(control_ext_page_default));
4156                                 memcpy(&lun->mode_pages.control_ext_page[
4157                                     CTL_PAGE_CHANGEABLE],
4158                                        &control_ext_page_changeable,
4159                                        sizeof(control_ext_page_changeable));
4160                                 memcpy(&lun->mode_pages.control_ext_page[
4161                                     CTL_PAGE_SAVED],
4162                                        &control_ext_page_default,
4163                                        sizeof(control_ext_page_default));
4164                                 memcpy(&lun->mode_pages.control_ext_page[
4165                                     CTL_PAGE_CURRENT],
4166                                        &lun->mode_pages.control_ext_page[
4167                                     CTL_PAGE_SAVED],
4168                                        sizeof(control_ext_page_default));
4169                                 page_index->page_data =
4170                                     (uint8_t *)lun->mode_pages.control_ext_page;
4171                                 break;
4172                         default:
4173                                 panic("subpage %#x for page %#x is incorrect!",
4174                                       page_index->subpage, page_code);
4175                         }
4176                         break;
4177                 }
4178                 case SMS_INFO_EXCEPTIONS_PAGE: {
4179                         switch (page_index->subpage) {
4180                         case SMS_SUBPAGE_PAGE_0:
4181                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4182                                        &ie_page_default,
4183                                        sizeof(ie_page_default));
4184                                 memcpy(&lun->mode_pages.ie_page[
4185                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4186                                        sizeof(ie_page_changeable));
4187                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4188                                        &ie_page_default,
4189                                        sizeof(ie_page_default));
4190                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4191                                        &ie_page_default,
4192                                        sizeof(ie_page_default));
4193                                 page_index->page_data =
4194                                         (uint8_t *)lun->mode_pages.ie_page;
4195                                 break;
4196                         case 0x02: {
4197                                 struct ctl_logical_block_provisioning_page *page;
4198
4199                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4200                                        &lbp_page_default,
4201                                        sizeof(lbp_page_default));
4202                                 memcpy(&lun->mode_pages.lbp_page[
4203                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4204                                        sizeof(lbp_page_changeable));
4205                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4206                                        &lbp_page_default,
4207                                        sizeof(lbp_page_default));
4208                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4209                                 value = ctl_get_opt(&lun->be_lun->options,
4210                                     "avail-threshold");
4211                                 if (value != NULL &&
4212                                     ctl_expand_number(value, &ival) == 0) {
4213                                         page->descr[0].flags |= SLBPPD_ENABLED |
4214                                             SLBPPD_ARMING_DEC;
4215                                         if (lun->be_lun->blocksize)
4216                                                 ival /= lun->be_lun->blocksize;
4217                                         else
4218                                                 ival /= 512;
4219                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4220                                             page->descr[0].count);
4221                                 }
4222                                 value = ctl_get_opt(&lun->be_lun->options,
4223                                     "used-threshold");
4224                                 if (value != NULL &&
4225                                     ctl_expand_number(value, &ival) == 0) {
4226                                         page->descr[1].flags |= SLBPPD_ENABLED |
4227                                             SLBPPD_ARMING_INC;
4228                                         if (lun->be_lun->blocksize)
4229                                                 ival /= lun->be_lun->blocksize;
4230                                         else
4231                                                 ival /= 512;
4232                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4233                                             page->descr[1].count);
4234                                 }
4235                                 value = ctl_get_opt(&lun->be_lun->options,
4236                                     "pool-avail-threshold");
4237                                 if (value != NULL &&
4238                                     ctl_expand_number(value, &ival) == 0) {
4239                                         page->descr[2].flags |= SLBPPD_ENABLED |
4240                                             SLBPPD_ARMING_DEC;
4241                                         if (lun->be_lun->blocksize)
4242                                                 ival /= lun->be_lun->blocksize;
4243                                         else
4244                                                 ival /= 512;
4245                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4246                                             page->descr[2].count);
4247                                 }
4248                                 value = ctl_get_opt(&lun->be_lun->options,
4249                                     "pool-used-threshold");
4250                                 if (value != NULL &&
4251                                     ctl_expand_number(value, &ival) == 0) {
4252                                         page->descr[3].flags |= SLBPPD_ENABLED |
4253                                             SLBPPD_ARMING_INC;
4254                                         if (lun->be_lun->blocksize)
4255                                                 ival /= lun->be_lun->blocksize;
4256                                         else
4257                                                 ival /= 512;
4258                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4259                                             page->descr[3].count);
4260                                 }
4261                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4262                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4263                                        sizeof(lbp_page_default));
4264                                 page_index->page_data =
4265                                         (uint8_t *)lun->mode_pages.lbp_page;
4266                                 break;
4267                         }
4268                         default:
4269                                 panic("subpage %#x for page %#x is incorrect!",
4270                                       page_index->subpage, page_code);
4271                         }
4272                         break;
4273                 }
4274                 case SMS_CDDVD_CAPS_PAGE:{
4275                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4276                             ("subpage %#x for page %#x is incorrect!",
4277                             page_index->subpage, page_code));
4278                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4279                                &cddvd_page_default,
4280                                sizeof(cddvd_page_default));
4281                         memcpy(&lun->mode_pages.cddvd_page[
4282                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4283                                sizeof(cddvd_page_changeable));
4284                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4285                                &cddvd_page_default,
4286                                sizeof(cddvd_page_default));
4287                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4288                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4289                                sizeof(cddvd_page_default));
4290                         page_index->page_data =
4291                                 (uint8_t *)lun->mode_pages.cddvd_page;
4292                         break;
4293                 }
4294                 default:
4295                         panic("invalid page code value %#x", page_code);
4296                 }
4297         }
4298
4299         return (CTL_RETVAL_COMPLETE);
4300 }
4301
4302 static int
4303 ctl_init_log_page_index(struct ctl_lun *lun)
4304 {
4305         struct ctl_page_index *page_index;
4306         int i, j, k, prev;
4307
4308         memcpy(&lun->log_pages.index, log_page_index_template,
4309                sizeof(log_page_index_template));
4310
4311         prev = -1;
4312         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4313
4314                 page_index = &lun->log_pages.index[i];
4315                 if (lun->be_lun->lun_type == T_DIRECT &&
4316                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4317                         continue;
4318                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4319                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4320                         continue;
4321                 if (lun->be_lun->lun_type == T_CDROM &&
4322                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4323                         continue;
4324
4325                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4326                     lun->backend->lun_attr == NULL)
4327                         continue;
4328
4329                 if (page_index->page_code != prev) {
4330                         lun->log_pages.pages_page[j] = page_index->page_code;
4331                         prev = page_index->page_code;
4332                         j++;
4333                 }
4334                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4335                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4336                 k++;
4337         }
4338         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4339         lun->log_pages.index[0].page_len = j;
4340         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4341         lun->log_pages.index[1].page_len = k * 2;
4342         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4343         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4344         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4345         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4346         lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4347         lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4348
4349         return (CTL_RETVAL_COMPLETE);
4350 }
4351
4352 static int
4353 hex2bin(const char *str, uint8_t *buf, int buf_size)
4354 {
4355         int i;
4356         u_char c;
4357
4358         memset(buf, 0, buf_size);
4359         while (isspace(str[0]))
4360                 str++;
4361         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4362                 str += 2;
4363         buf_size *= 2;
4364         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4365                 while (str[i] == '-')   /* Skip dashes in UUIDs. */
4366                         str++;
4367                 c = str[i];
4368                 if (isdigit(c))
4369                         c -= '0';
4370                 else if (isalpha(c))
4371                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4372                 else
4373                         break;
4374                 if (c >= 16)
4375                         break;
4376                 if ((i & 1) == 0)
4377                         buf[i / 2] |= (c << 4);
4378                 else
4379                         buf[i / 2] |= c;
4380         }
4381         return ((i + 1) / 2);
4382 }
4383
4384 /*
4385  * LUN allocation.
4386  *
4387  * Requirements:
4388  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4389  *   wants us to allocate the LUN and he can block.
4390  * - ctl_softc is always set
4391  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4392  *
4393  * Returns 0 for success, non-zero (errno) for failure.
4394  */
4395 static int
4396 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4397               struct ctl_be_lun *const be_lun)
4398 {
4399         struct ctl_lun *nlun, *lun;
4400         struct scsi_vpd_id_descriptor *desc;
4401         struct scsi_vpd_id_t10 *t10id;
4402         const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4403         int lun_number, i, lun_malloced;
4404         int devidlen, idlen1, idlen2 = 0, len;
4405
4406         if (be_lun == NULL)
4407                 return (EINVAL);
4408
4409         /*
4410          * We currently only support Direct Access or Processor LUN types.
4411          */
4412         switch (be_lun->lun_type) {
4413         case T_DIRECT:
4414         case T_PROCESSOR:
4415         case T_CDROM:
4416                 break;
4417         case T_SEQUENTIAL:
4418         case T_CHANGER:
4419         default:
4420                 be_lun->lun_config_status(be_lun->be_lun,
4421                                           CTL_LUN_CONFIG_FAILURE);
4422                 break;
4423         }
4424         if (ctl_lun == NULL) {
4425                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4426                 lun_malloced = 1;
4427         } else {
4428                 lun_malloced = 0;
4429                 lun = ctl_lun;
4430         }
4431
4432         memset(lun, 0, sizeof(*lun));
4433         if (lun_malloced)
4434                 lun->flags = CTL_LUN_MALLOCED;
4435
4436         /* Generate LUN ID. */
4437         devidlen = max(CTL_DEVID_MIN_LEN,
4438             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4439         idlen1 = sizeof(*t10id) + devidlen;
4440         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4441         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4442         if (scsiname != NULL) {
4443                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4444                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4445         }
4446         eui = ctl_get_opt(&be_lun->options, "eui");
4447         if (eui != NULL) {
4448                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4449         }
4450         naa = ctl_get_opt(&be_lun->options, "naa");
4451         if (naa != NULL) {
4452                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4453         }
4454         uuid = ctl_get_opt(&be_lun->options, "uuid");
4455         if (uuid != NULL) {
4456                 len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4457         }
4458         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4459             M_CTL, M_WAITOK | M_ZERO);
4460         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4461         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4462         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4463         desc->length = idlen1;
4464         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4465         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4466         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4467                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4468         } else {
4469                 strncpy(t10id->vendor, vendor,
4470                     min(sizeof(t10id->vendor), strlen(vendor)));
4471         }
4472         strncpy((char *)t10id->vendor_spec_id,
4473             (char *)be_lun->device_id, devidlen);
4474         if (scsiname != NULL) {
4475                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4476                     desc->length);
4477                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4478                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4479                     SVPD_ID_TYPE_SCSI_NAME;
4480                 desc->length = idlen2;
4481                 strlcpy(desc->identifier, scsiname, idlen2);
4482         }
4483         if (eui != NULL) {
4484                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4485                     desc->length);
4486                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4487                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4488                     SVPD_ID_TYPE_EUI64;
4489                 desc->length = hex2bin(eui, desc->identifier, 16);
4490                 desc->length = desc->length > 12 ? 16 :
4491                     (desc->length > 8 ? 12 : 8);
4492                 len -= 16 - desc->length;
4493         }
4494         if (naa != NULL) {
4495                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4496                     desc->length);
4497                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4498                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4499                     SVPD_ID_TYPE_NAA;
4500                 desc->length = hex2bin(naa, desc->identifier, 16);
4501                 desc->length = desc->length > 8 ? 16 : 8;
4502                 len -= 16 - desc->length;
4503         }
4504         if (uuid != NULL) {
4505                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4506                     desc->length);
4507                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4508                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4509                     SVPD_ID_TYPE_UUID;
4510                 desc->identifier[0] = 0x10;
4511                 hex2bin(uuid, &desc->identifier[2], 16);
4512                 desc->length = 18;
4513         }
4514         lun->lun_devid->len = len;
4515
4516         mtx_lock(&ctl_softc->ctl_lock);
4517         /*
4518          * See if the caller requested a particular LUN number.  If so, see
4519          * if it is available.  Otherwise, allocate the first available LUN.
4520          */
4521         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4522                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4523                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4524                         mtx_unlock(&ctl_softc->ctl_lock);
4525                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4526                                 printf("ctl: requested LUN ID %d is higher "
4527                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4528                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4529                         } else {
4530                                 /*
4531                                  * XXX KDM return an error, or just assign
4532                                  * another LUN ID in this case??
4533                                  */
4534                                 printf("ctl: requested LUN ID %d is already "
4535                                        "in use\n", be_lun->req_lun_id);
4536                         }
4537                         if (lun->flags & CTL_LUN_MALLOCED)
4538                                 free(lun, M_CTL);
4539                         be_lun->lun_config_status(be_lun->be_lun,
4540                                                   CTL_LUN_CONFIG_FAILURE);
4541                         return (ENOSPC);
4542                 }
4543                 lun_number = be_lun->req_lun_id;
4544         } else {
4545                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4546                 if (lun_number == -1) {
4547                         mtx_unlock(&ctl_softc->ctl_lock);
4548                         printf("ctl: can't allocate LUN, out of LUNs\n");
4549                         if (lun->flags & CTL_LUN_MALLOCED)
4550                                 free(lun, M_CTL);
4551                         be_lun->lun_config_status(be_lun->be_lun,
4552                                                   CTL_LUN_CONFIG_FAILURE);
4553                         return (ENOSPC);
4554                 }
4555         }
4556         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4557
4558         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4559         lun->lun = lun_number;
4560         lun->be_lun = be_lun;
4561         /*
4562          * The processor LUN is always enabled.  Disk LUNs come on line
4563          * disabled, and must be enabled by the backend.
4564          */
4565         lun->flags |= CTL_LUN_DISABLED;
4566         lun->backend = be_lun->be;
4567         be_lun->ctl_lun = lun;
4568         be_lun->lun_id = lun_number;
4569         atomic_add_int(&be_lun->be->num_luns, 1);
4570         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4571                 lun->flags |= CTL_LUN_EJECTED;
4572         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4573                 lun->flags |= CTL_LUN_NO_MEDIA;
4574         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4575                 lun->flags |= CTL_LUN_STOPPED;
4576
4577         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4578                 lun->flags |= CTL_LUN_PRIMARY_SC;
4579
4580         value = ctl_get_opt(&be_lun->options, "removable");
4581         if (value != NULL) {
4582                 if (strcmp(value, "on") == 0)
4583                         lun->flags |= CTL_LUN_REMOVABLE;
4584         } else if (be_lun->lun_type == T_CDROM)
4585                 lun->flags |= CTL_LUN_REMOVABLE;
4586
4587         lun->ctl_softc = ctl_softc;
4588 #ifdef CTL_TIME_IO
4589         lun->last_busy = getsbinuptime();
4590 #endif
4591         TAILQ_INIT(&lun->ooa_queue);
4592         TAILQ_INIT(&lun->blocked_queue);
4593         STAILQ_INIT(&lun->error_list);
4594         lun->ie_reported = 1;
4595         callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4596         ctl_tpc_lun_init(lun);
4597
4598         /*
4599          * Initialize the mode and log page index.
4600          */
4601         ctl_init_page_index(lun);
4602         ctl_init_log_page_index(lun);
4603
4604         /*
4605          * Now, before we insert this lun on the lun list, set the lun
4606          * inventory changed UA for all other luns.
4607          */
4608         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4609                 mtx_lock(&nlun->lun_lock);
4610                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4611                 mtx_unlock(&nlun->lun_lock);
4612         }
4613
4614         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4615
4616         ctl_softc->ctl_luns[lun_number] = lun;
4617
4618         ctl_softc->num_luns++;
4619
4620         /* Setup statistics gathering */
4621         lun->stats.device_type = be_lun->lun_type;
4622         lun->stats.lun_number = lun_number;
4623         lun->stats.blocksize = be_lun->blocksize;
4624         if (be_lun->blocksize == 0)
4625                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4626         for (i = 0;i < CTL_MAX_PORTS;i++)
4627                 lun->stats.ports[i].targ_port = i;
4628
4629         mtx_unlock(&ctl_softc->ctl_lock);
4630
4631         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4632         return (0);
4633 }
4634
4635 /*
4636  * Delete a LUN.
4637  * Assumptions:
4638  * - LUN has already been marked invalid and any pending I/O has been taken
4639  *   care of.
4640  */
4641 static int
4642 ctl_free_lun(struct ctl_lun *lun)
4643 {
4644         struct ctl_softc *softc;
4645         struct ctl_lun *nlun;
4646         int i;
4647
4648         softc = lun->ctl_softc;
4649
4650         mtx_assert(&softc->ctl_lock, MA_OWNED);
4651
4652         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4653
4654         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4655
4656         softc->ctl_luns[lun->lun] = NULL;
4657
4658         if (!TAILQ_EMPTY(&lun->ooa_queue))
4659                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4660
4661         softc->num_luns--;
4662
4663         /*
4664          * Tell the backend to free resources, if this LUN has a backend.
4665          */
4666         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4667         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4668
4669         lun->ie_reportcnt = UINT32_MAX;
4670         callout_drain(&lun->ie_callout);
4671
4672         ctl_tpc_lun_shutdown(lun);
4673         mtx_destroy(&lun->lun_lock);
4674         free(lun->lun_devid, M_CTL);
4675         for (i = 0; i < CTL_MAX_PORTS; i++)
4676                 free(lun->pending_ua[i], M_CTL);
4677         for (i = 0; i < CTL_MAX_PORTS; i++)
4678                 free(lun->pr_keys[i], M_CTL);
4679         free(lun->write_buffer, M_CTL);
4680         if (lun->flags & CTL_LUN_MALLOCED)
4681                 free(lun, M_CTL);
4682
4683         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4684                 mtx_lock(&nlun->lun_lock);
4685                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4686                 mtx_unlock(&nlun->lun_lock);
4687         }
4688
4689         return (0);
4690 }
4691
4692 static void
4693 ctl_create_lun(struct ctl_be_lun *be_lun)
4694 {
4695
4696         /*
4697          * ctl_alloc_lun() should handle all potential failure cases.
4698          */
4699         ctl_alloc_lun(control_softc, NULL, be_lun);
4700 }
4701
4702 int
4703 ctl_add_lun(struct ctl_be_lun *be_lun)
4704 {
4705         struct ctl_softc *softc = control_softc;
4706
4707         mtx_lock(&softc->ctl_lock);
4708         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4709         mtx_unlock(&softc->ctl_lock);
4710         wakeup(&softc->pending_lun_queue);
4711
4712         return (0);
4713 }
4714
4715 int
4716 ctl_enable_lun(struct ctl_be_lun *be_lun)
4717 {
4718         struct ctl_softc *softc;
4719         struct ctl_port *port, *nport;
4720         struct ctl_lun *lun;
4721         int retval;
4722
4723         lun = (struct ctl_lun *)be_lun->ctl_lun;
4724         softc = lun->ctl_softc;
4725
4726         mtx_lock(&softc->ctl_lock);
4727         mtx_lock(&lun->lun_lock);
4728         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4729                 /*
4730                  * eh?  Why did we get called if the LUN is already
4731                  * enabled?
4732                  */
4733                 mtx_unlock(&lun->lun_lock);
4734                 mtx_unlock(&softc->ctl_lock);
4735                 return (0);
4736         }
4737         lun->flags &= ~CTL_LUN_DISABLED;
4738         mtx_unlock(&lun->lun_lock);
4739
4740         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4741                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4742                     port->lun_map != NULL || port->lun_enable == NULL)
4743                         continue;
4744
4745                 /*
4746                  * Drop the lock while we call the FETD's enable routine.
4747                  * This can lead to a callback into CTL (at least in the
4748                  * case of the internal initiator frontend.
4749                  */
4750                 mtx_unlock(&softc->ctl_lock);
4751                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4752                 mtx_lock(&softc->ctl_lock);
4753                 if (retval != 0) {
4754                         printf("%s: FETD %s port %d returned error "
4755                                "%d for lun_enable on lun %jd\n",
4756                                __func__, port->port_name, port->targ_port,
4757                                retval, (intmax_t)lun->lun);
4758                 }
4759         }
4760
4761         mtx_unlock(&softc->ctl_lock);
4762         ctl_isc_announce_lun(lun);
4763
4764         return (0);
4765 }
4766
4767 int
4768 ctl_disable_lun(struct ctl_be_lun *be_lun)
4769 {
4770         struct ctl_softc *softc;
4771         struct ctl_port *port;
4772         struct ctl_lun *lun;
4773         int retval;
4774
4775         lun = (struct ctl_lun *)be_lun->ctl_lun;
4776         softc = lun->ctl_softc;
4777
4778         mtx_lock(&softc->ctl_lock);
4779         mtx_lock(&lun->lun_lock);
4780         if (lun->flags & CTL_LUN_DISABLED) {
4781                 mtx_unlock(&lun->lun_lock);
4782                 mtx_unlock(&softc->ctl_lock);
4783                 return (0);
4784         }
4785         lun->flags |= CTL_LUN_DISABLED;
4786         mtx_unlock(&lun->lun_lock);
4787
4788         STAILQ_FOREACH(port, &softc->port_list, links) {
4789                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4790                     port->lun_map != NULL || port->lun_disable == NULL)
4791                         continue;
4792
4793                 /*
4794                  * Drop the lock before we call the frontend's disable
4795                  * routine, to avoid lock order reversals.
4796                  *
4797                  * XXX KDM what happens if the frontend list changes while
4798                  * we're traversing it?  It's unlikely, but should be handled.
4799                  */
4800                 mtx_unlock(&softc->ctl_lock);
4801                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4802                 mtx_lock(&softc->ctl_lock);
4803                 if (retval != 0) {
4804                         printf("%s: FETD %s port %d returned error "
4805                                "%d for lun_disable on lun %jd\n",
4806                                __func__, port->port_name, port->targ_port,
4807                                retval, (intmax_t)lun->lun);
4808                 }
4809         }
4810
4811         mtx_unlock(&softc->ctl_lock);
4812         ctl_isc_announce_lun(lun);
4813
4814         return (0);
4815 }
4816
4817 int
4818 ctl_start_lun(struct ctl_be_lun *be_lun)
4819 {
4820         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4821
4822         mtx_lock(&lun->lun_lock);
4823         lun->flags &= ~CTL_LUN_STOPPED;
4824         mtx_unlock(&lun->lun_lock);
4825         return (0);
4826 }
4827
4828 int
4829 ctl_stop_lun(struct ctl_be_lun *be_lun)
4830 {
4831         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4832
4833         mtx_lock(&lun->lun_lock);
4834         lun->flags |= CTL_LUN_STOPPED;
4835         mtx_unlock(&lun->lun_lock);
4836         return (0);
4837 }
4838
4839 int
4840 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4841 {
4842         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4843
4844         mtx_lock(&lun->lun_lock);
4845         lun->flags |= CTL_LUN_NO_MEDIA;
4846         mtx_unlock(&lun->lun_lock);
4847         return (0);
4848 }
4849
4850 int
4851 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4852 {
4853         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4854         union ctl_ha_msg msg;
4855
4856         mtx_lock(&lun->lun_lock);
4857         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4858         if (lun->flags & CTL_LUN_REMOVABLE)
4859                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4860         mtx_unlock(&lun->lun_lock);
4861         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4862             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4863                 bzero(&msg.ua, sizeof(msg.ua));
4864                 msg.hdr.msg_type = CTL_MSG_UA;
4865                 msg.hdr.nexus.initid = -1;
4866                 msg.hdr.nexus.targ_port = -1;
4867                 msg.hdr.nexus.targ_lun = lun->lun;
4868                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4869                 msg.ua.ua_all = 1;
4870                 msg.ua.ua_set = 1;
4871                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4872                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4873                     M_WAITOK);
4874         }
4875         return (0);
4876 }
4877
4878 int
4879 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4880 {
4881         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4882
4883         mtx_lock(&lun->lun_lock);
4884         lun->flags |= CTL_LUN_EJECTED;
4885         mtx_unlock(&lun->lun_lock);
4886         return (0);
4887 }
4888
4889 int
4890 ctl_lun_primary(struct ctl_be_lun *be_lun)
4891 {
4892         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4893
4894         mtx_lock(&lun->lun_lock);
4895         lun->flags |= CTL_LUN_PRIMARY_SC;
4896         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4897         mtx_unlock(&lun->lun_lock);
4898         ctl_isc_announce_lun(lun);
4899         return (0);
4900 }
4901
4902 int
4903 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4904 {
4905         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4906
4907         mtx_lock(&lun->lun_lock);
4908         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4909         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4910         mtx_unlock(&lun->lun_lock);
4911         ctl_isc_announce_lun(lun);
4912         return (0);
4913 }
4914
4915 int
4916 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4917 {
4918         struct ctl_softc *softc;
4919         struct ctl_lun *lun;
4920
4921         lun = (struct ctl_lun *)be_lun->ctl_lun;
4922         softc = lun->ctl_softc;
4923
4924         mtx_lock(&lun->lun_lock);
4925
4926         /*
4927          * The LUN needs to be disabled before it can be marked invalid.
4928          */
4929         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4930                 mtx_unlock(&lun->lun_lock);
4931                 return (-1);
4932         }
4933         /*
4934          * Mark the LUN invalid.
4935          */
4936         lun->flags |= CTL_LUN_INVALID;
4937
4938         /*
4939          * If there is nothing in the OOA queue, go ahead and free the LUN.
4940          * If we have something in the OOA queue, we'll free it when the
4941          * last I/O completes.
4942          */
4943         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4944                 mtx_unlock(&lun->lun_lock);
4945                 mtx_lock(&softc->ctl_lock);
4946                 ctl_free_lun(lun);
4947                 mtx_unlock(&softc->ctl_lock);
4948         } else
4949                 mtx_unlock(&lun->lun_lock);
4950
4951         return (0);
4952 }
4953
4954 void
4955 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4956 {
4957         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4958         union ctl_ha_msg msg;
4959
4960         mtx_lock(&lun->lun_lock);
4961         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4962         mtx_unlock(&lun->lun_lock);
4963         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4964                 /* Send msg to other side. */
4965                 bzero(&msg.ua, sizeof(msg.ua));
4966                 msg.hdr.msg_type = CTL_MSG_UA;
4967                 msg.hdr.nexus.initid = -1;
4968                 msg.hdr.nexus.targ_port = -1;
4969                 msg.hdr.nexus.targ_lun = lun->lun;
4970                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4971                 msg.ua.ua_all = 1;
4972                 msg.ua.ua_set = 1;
4973                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4974                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4975                     M_WAITOK);
4976         }
4977 }
4978
4979 /*
4980  * Backend "memory move is complete" callback for requests that never
4981  * make it down to say RAIDCore's configuration code.
4982  */
4983 int
4984 ctl_config_move_done(union ctl_io *io)
4985 {
4986         int retval;
4987
4988         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4989         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4990             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4991
4992         if ((io->io_hdr.port_status != 0) &&
4993             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4994              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4995                 /*
4996                  * For hardware error sense keys, the sense key
4997                  * specific value is defined to be a retry count,
4998                  * but we use it to pass back an internal FETD
4999                  * error code.  XXX KDM  Hopefully the FETD is only
5000                  * using 16 bits for an error code, since that's
5001                  * all the space we have in the sks field.
5002                  */
5003                 ctl_set_internal_failure(&io->scsiio,
5004                                          /*sks_valid*/ 1,
5005                                          /*retry_count*/
5006                                          io->io_hdr.port_status);
5007         }
5008
5009         if (ctl_debug & CTL_DEBUG_CDB_DATA)
5010                 ctl_data_print(io);
5011         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5012             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5013              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5014             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5015                 /*
5016                  * XXX KDM just assuming a single pointer here, and not a
5017                  * S/G list.  If we start using S/G lists for config data,
5018                  * we'll need to know how to clean them up here as well.
5019                  */
5020                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5021                         free(io->scsiio.kern_data_ptr, M_CTL);
5022                 ctl_done(io);
5023                 retval = CTL_RETVAL_COMPLETE;
5024         } else {
5025                 /*
5026                  * XXX KDM now we need to continue data movement.  Some
5027                  * options:
5028                  * - call ctl_scsiio() again?  We don't do this for data
5029                  *   writes, because for those at least we know ahead of
5030                  *   time where the write will go and how long it is.  For
5031                  *   config writes, though, that information is largely
5032                  *   contained within the write itself, thus we need to
5033                  *   parse out the data again.
5034                  *
5035                  * - Call some other function once the data is in?
5036                  */
5037
5038                 /*
5039                  * XXX KDM call ctl_scsiio() again for now, and check flag
5040                  * bits to see whether we're allocated or not.
5041                  */
5042                 retval = ctl_scsiio(&io->scsiio);
5043         }
5044         return (retval);
5045 }
5046
5047 /*
5048  * This gets called by a backend driver when it is done with a
5049  * data_submit method.
5050  */
5051 void
5052 ctl_data_submit_done(union ctl_io *io)
5053 {
5054         /*
5055          * If the IO_CONT flag is set, we need to call the supplied
5056          * function to continue processing the I/O, instead of completing
5057          * the I/O just yet.
5058          *
5059          * If there is an error, though, we don't want to keep processing.
5060          * Instead, just send status back to the initiator.
5061          */
5062         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5063             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5064             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5065              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5066                 io->scsiio.io_cont(io);
5067                 return;
5068         }
5069         ctl_done(io);
5070 }
5071
5072 /*
5073  * This gets called by a backend driver when it is done with a
5074  * configuration write.
5075  */
5076 void
5077 ctl_config_write_done(union ctl_io *io)
5078 {
5079         uint8_t *buf;
5080
5081         /*
5082          * If the IO_CONT flag is set, we need to call the supplied
5083          * function to continue processing the I/O, instead of completing
5084          * the I/O just yet.
5085          *
5086          * If there is an error, though, we don't want to keep processing.
5087          * Instead, just send status back to the initiator.
5088          */
5089         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5090             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5091             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5092              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5093                 io->scsiio.io_cont(io);
5094                 return;
5095         }
5096         /*
5097          * Since a configuration write can be done for commands that actually
5098          * have data allocated, like write buffer, and commands that have
5099          * no data, like start/stop unit, we need to check here.
5100          */
5101         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5102                 buf = io->scsiio.kern_data_ptr;
5103         else
5104                 buf = NULL;
5105         ctl_done(io);
5106         if (buf)
5107                 free(buf, M_CTL);
5108 }
5109
5110 void
5111 ctl_config_read_done(union ctl_io *io)
5112 {
5113         uint8_t *buf;
5114
5115         /*
5116          * If there is some error -- we are done, skip data transfer.
5117          */
5118         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5119             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5120              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5121                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5122                         buf = io->scsiio.kern_data_ptr;
5123                 else
5124                         buf = NULL;
5125                 ctl_done(io);
5126                 if (buf)
5127                         free(buf, M_CTL);
5128                 return;
5129         }
5130
5131         /*
5132          * If the IO_CONT flag is set, we need to call the supplied
5133          * function to continue processing the I/O, instead of completing
5134          * the I/O just yet.
5135          */
5136         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5137                 io->scsiio.io_cont(io);
5138                 return;
5139         }
5140
5141         ctl_datamove(io);
5142 }
5143
5144 /*
5145  * SCSI release command.
5146  */
5147 int
5148 ctl_scsi_release(struct ctl_scsiio *ctsio)
5149 {
5150         struct ctl_lun *lun;
5151         uint32_t residx;
5152
5153         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5154
5155         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5156         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5157
5158         /*
5159          * XXX KDM right now, we only support LUN reservation.  We don't
5160          * support 3rd party reservations, or extent reservations, which
5161          * might actually need the parameter list.  If we've gotten this
5162          * far, we've got a LUN reservation.  Anything else got kicked out
5163          * above.  So, according to SPC, ignore the length.
5164          */
5165
5166         mtx_lock(&lun->lun_lock);
5167
5168         /*
5169          * According to SPC, it is not an error for an intiator to attempt
5170          * to release a reservation on a LUN that isn't reserved, or that
5171          * is reserved by another initiator.  The reservation can only be
5172          * released, though, by the initiator who made it or by one of
5173          * several reset type events.
5174          */
5175         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5176                         lun->flags &= ~CTL_LUN_RESERVED;
5177
5178         mtx_unlock(&lun->lun_lock);
5179
5180         ctl_set_success(ctsio);
5181         ctl_done((union ctl_io *)ctsio);
5182         return (CTL_RETVAL_COMPLETE);
5183 }
5184
5185 int
5186 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5187 {
5188         struct ctl_lun *lun;
5189         uint32_t residx;
5190
5191         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5192
5193         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5194         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5195
5196         /*
5197          * XXX KDM right now, we only support LUN reservation.  We don't
5198          * support 3rd party reservations, or extent reservations, which
5199          * might actually need the parameter list.  If we've gotten this
5200          * far, we've got a LUN reservation.  Anything else got kicked out
5201          * above.  So, according to SPC, ignore the length.
5202          */
5203
5204         mtx_lock(&lun->lun_lock);
5205         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5206                 ctl_set_reservation_conflict(ctsio);
5207                 goto bailout;
5208         }
5209
5210         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5211         if (lun->flags & CTL_LUN_PR_RESERVED) {
5212                 ctl_set_success(ctsio);
5213                 goto bailout;
5214         }
5215
5216         lun->flags |= CTL_LUN_RESERVED;
5217         lun->res_idx = residx;
5218         ctl_set_success(ctsio);
5219
5220 bailout:
5221         mtx_unlock(&lun->lun_lock);
5222         ctl_done((union ctl_io *)ctsio);
5223         return (CTL_RETVAL_COMPLETE);
5224 }
5225
5226 int
5227 ctl_start_stop(struct ctl_scsiio *ctsio)
5228 {
5229         struct scsi_start_stop_unit *cdb;
5230         struct ctl_lun *lun;
5231         int retval;
5232
5233         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5234
5235         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5236         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5237
5238         if ((cdb->how & SSS_PC_MASK) == 0) {
5239                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5240                     (cdb->how & SSS_START) == 0) {
5241                         uint32_t residx;
5242
5243                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5244                         if (ctl_get_prkey(lun, residx) == 0 ||
5245                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5246
5247                                 ctl_set_reservation_conflict(ctsio);
5248                                 ctl_done((union ctl_io *)ctsio);
5249                                 return (CTL_RETVAL_COMPLETE);
5250                         }
5251                 }
5252
5253                 if ((cdb->how & SSS_LOEJ) &&
5254                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5255                         ctl_set_invalid_field(ctsio,
5256                                               /*sks_valid*/ 1,
5257                                               /*command*/ 1,
5258                                               /*field*/ 4,
5259                                               /*bit_valid*/ 1,
5260                                               /*bit*/ 1);
5261                         ctl_done((union ctl_io *)ctsio);
5262                         return (CTL_RETVAL_COMPLETE);
5263                 }
5264
5265                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5266                     lun->prevent_count > 0) {
5267                         /* "Medium removal prevented" */
5268                         ctl_set_sense(ctsio, /*current_error*/ 1,
5269                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5270                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5271                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5272                         ctl_done((union ctl_io *)ctsio);
5273                         return (CTL_RETVAL_COMPLETE);
5274                 }
5275         }
5276
5277         retval = lun->backend->config_write((union ctl_io *)ctsio);
5278         return (retval);
5279 }
5280
5281 int
5282 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5283 {
5284         struct ctl_lun *lun;
5285         struct scsi_prevent *cdb;
5286         int retval;
5287         uint32_t initidx;
5288
5289         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5290
5291         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5292         cdb = (struct scsi_prevent *)ctsio->cdb;
5293
5294         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5295                 ctl_set_invalid_opcode(ctsio);
5296                 ctl_done((union ctl_io *)ctsio);
5297                 return (CTL_RETVAL_COMPLETE);
5298         }
5299
5300         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5301         mtx_lock(&lun->lun_lock);
5302         if ((cdb->how & PR_PREVENT) &&
5303             ctl_is_set(lun->prevent, initidx) == 0) {
5304                 ctl_set_mask(lun->prevent, initidx);
5305                 lun->prevent_count++;
5306         } else if ((cdb->how & PR_PREVENT) == 0 &&
5307             ctl_is_set(lun->prevent, initidx)) {
5308                 ctl_clear_mask(lun->prevent, initidx);
5309                 lun->prevent_count--;
5310         }
5311         mtx_unlock(&lun->lun_lock);
5312         retval = lun->backend->config_write((union ctl_io *)ctsio);
5313         return (retval);
5314 }
5315
5316 /*
5317  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5318  * we don't really do anything with the LBA and length fields if the user
5319  * passes them in.  Instead we'll just flush out the cache for the entire
5320  * LUN.
5321  */
5322 int
5323 ctl_sync_cache(struct ctl_scsiio *ctsio)
5324 {
5325         struct ctl_lun *lun;
5326         struct ctl_softc *softc;
5327         struct ctl_lba_len_flags *lbalen;
5328         uint64_t starting_lba;
5329         uint32_t block_count;
5330         int retval;
5331         uint8_t byte2;
5332
5333         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5334
5335         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5336         softc = lun->ctl_softc;
5337         retval = 0;
5338
5339         switch (ctsio->cdb[0]) {
5340         case SYNCHRONIZE_CACHE: {
5341                 struct scsi_sync_cache *cdb;
5342                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5343
5344                 starting_lba = scsi_4btoul(cdb->begin_lba);
5345                 block_count = scsi_2btoul(cdb->lb_count);
5346                 byte2 = cdb->byte2;
5347                 break;
5348         }
5349         case SYNCHRONIZE_CACHE_16: {
5350                 struct scsi_sync_cache_16 *cdb;
5351                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5352
5353                 starting_lba = scsi_8btou64(cdb->begin_lba);
5354                 block_count = scsi_4btoul(cdb->lb_count);
5355                 byte2 = cdb->byte2;
5356                 break;
5357         }
5358         default:
5359                 ctl_set_invalid_opcode(ctsio);
5360                 ctl_done((union ctl_io *)ctsio);
5361                 goto bailout;
5362                 break; /* NOTREACHED */
5363         }
5364
5365         /*
5366          * We check the LBA and length, but don't do anything with them.
5367          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5368          * get flushed.  This check will just help satisfy anyone who wants
5369          * to see an error for an out of range LBA.
5370          */
5371         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5372                 ctl_set_lba_out_of_range(ctsio,
5373                     MAX(starting_lba, lun->be_lun->maxlba + 1));
5374                 ctl_done((union ctl_io *)ctsio);
5375                 goto bailout;
5376         }
5377
5378         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5379         lbalen->lba = starting_lba;
5380         lbalen->len = block_count;
5381         lbalen->flags = byte2;
5382         retval = lun->backend->config_write((union ctl_io *)ctsio);
5383
5384 bailout:
5385         return (retval);
5386 }
5387
5388 int
5389 ctl_format(struct ctl_scsiio *ctsio)
5390 {
5391         struct scsi_format *cdb;
5392         struct ctl_lun *lun;
5393         int length, defect_list_len;
5394
5395         CTL_DEBUG_PRINT(("ctl_format\n"));
5396
5397         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5398
5399         cdb = (struct scsi_format *)ctsio->cdb;
5400
5401         length = 0;
5402         if (cdb->byte2 & SF_FMTDATA) {
5403                 if (cdb->byte2 & SF_LONGLIST)
5404                         length = sizeof(struct scsi_format_header_long);
5405                 else
5406                         length = sizeof(struct scsi_format_header_short);
5407         }
5408
5409         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5410          && (length > 0)) {
5411                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5412                 ctsio->kern_data_len = length;
5413                 ctsio->kern_total_len = length;
5414                 ctsio->kern_data_resid = 0;
5415                 ctsio->kern_rel_offset = 0;
5416                 ctsio->kern_sg_entries = 0;
5417                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5418                 ctsio->be_move_done = ctl_config_move_done;
5419                 ctl_datamove((union ctl_io *)ctsio);
5420
5421                 return (CTL_RETVAL_COMPLETE);
5422         }
5423
5424         defect_list_len = 0;
5425
5426         if (cdb->byte2 & SF_FMTDATA) {
5427                 if (cdb->byte2 & SF_LONGLIST) {
5428                         struct scsi_format_header_long *header;
5429
5430                         header = (struct scsi_format_header_long *)
5431                                 ctsio->kern_data_ptr;
5432
5433                         defect_list_len = scsi_4btoul(header->defect_list_len);
5434                         if (defect_list_len != 0) {
5435                                 ctl_set_invalid_field(ctsio,
5436                                                       /*sks_valid*/ 1,
5437                                                       /*command*/ 0,
5438                                                       /*field*/ 2,
5439                                                       /*bit_valid*/ 0,
5440                                                       /*bit*/ 0);
5441                                 goto bailout;
5442                         }
5443                 } else {
5444                         struct scsi_format_header_short *header;
5445
5446                         header = (struct scsi_format_header_short *)
5447                                 ctsio->kern_data_ptr;
5448
5449                         defect_list_len = scsi_2btoul(header->defect_list_len);
5450                         if (defect_list_len != 0) {
5451                                 ctl_set_invalid_field(ctsio,
5452                                                       /*sks_valid*/ 1,
5453                                                       /*command*/ 0,
5454                                                       /*field*/ 2,
5455                                                       /*bit_valid*/ 0,
5456                                                       /*bit*/ 0);
5457                                 goto bailout;
5458                         }
5459                 }
5460         }
5461
5462         ctl_set_success(ctsio);
5463 bailout:
5464
5465         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5466                 free(ctsio->kern_data_ptr, M_CTL);
5467                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5468         }
5469
5470         ctl_done((union ctl_io *)ctsio);
5471         return (CTL_RETVAL_COMPLETE);
5472 }
5473
5474 int
5475 ctl_read_buffer(struct ctl_scsiio *ctsio)
5476 {
5477         struct ctl_lun *lun;
5478         uint64_t buffer_offset;
5479         uint32_t len;
5480         uint8_t byte2;
5481         static uint8_t descr[4];
5482         static uint8_t echo_descr[4] = { 0 };
5483
5484         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5485         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5486         switch (ctsio->cdb[0]) {
5487         case READ_BUFFER: {
5488                 struct scsi_read_buffer *cdb;
5489
5490                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5491                 buffer_offset = scsi_3btoul(cdb->offset);
5492                 len = scsi_3btoul(cdb->length);
5493                 byte2 = cdb->byte2;
5494                 break;
5495         }
5496         case READ_BUFFER_16: {
5497                 struct scsi_read_buffer_16 *cdb;
5498
5499                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5500                 buffer_offset = scsi_8btou64(cdb->offset);
5501                 len = scsi_4btoul(cdb->length);
5502                 byte2 = cdb->byte2;
5503                 break;
5504         }
5505         default: /* This shouldn't happen. */
5506                 ctl_set_invalid_opcode(ctsio);
5507                 ctl_done((union ctl_io *)ctsio);
5508                 return (CTL_RETVAL_COMPLETE);
5509         }
5510
5511         if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5512             (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5513             (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5514                 ctl_set_invalid_field(ctsio,
5515                                       /*sks_valid*/ 1,
5516                                       /*command*/ 1,
5517                                       /*field*/ 1,
5518                                       /*bit_valid*/ 1,
5519                                       /*bit*/ 4);
5520                 ctl_done((union ctl_io *)ctsio);
5521                 return (CTL_RETVAL_COMPLETE);
5522         }
5523
5524         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5525             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5526                 ctl_set_invalid_field(ctsio,
5527                                       /*sks_valid*/ 1,
5528                                       /*command*/ 1,
5529                                       /*field*/ 6,
5530                                       /*bit_valid*/ 0,
5531                                       /*bit*/ 0);
5532                 ctl_done((union ctl_io *)ctsio);
5533                 return (CTL_RETVAL_COMPLETE);
5534         }
5535
5536         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5537                 descr[0] = 0;
5538                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5539                 ctsio->kern_data_ptr = descr;
5540                 len = min(len, sizeof(descr));
5541         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5542                 ctsio->kern_data_ptr = echo_descr;
5543                 len = min(len, sizeof(echo_descr));
5544         } else {
5545                 if (lun->write_buffer == NULL) {
5546                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5547                             M_CTL, M_WAITOK);
5548                 }
5549                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5550         }
5551         ctsio->kern_data_len = len;
5552         ctsio->kern_total_len = len;
5553         ctsio->kern_data_resid = 0;
5554         ctsio->kern_rel_offset = 0;
5555         ctsio->kern_sg_entries = 0;
5556         ctl_set_success(ctsio);
5557         ctsio->be_move_done = ctl_config_move_done;
5558         ctl_datamove((union ctl_io *)ctsio);
5559         return (CTL_RETVAL_COMPLETE);
5560 }
5561
5562 int
5563 ctl_write_buffer(struct ctl_scsiio *ctsio)
5564 {
5565         struct scsi_write_buffer *cdb;
5566         struct ctl_lun *lun;
5567         int buffer_offset, len;
5568
5569         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5570
5571         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5572         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5573
5574         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5575                 ctl_set_invalid_field(ctsio,
5576                                       /*sks_valid*/ 1,
5577                                       /*command*/ 1,
5578                                       /*field*/ 1,
5579                                       /*bit_valid*/ 1,
5580                                       /*bit*/ 4);
5581                 ctl_done((union ctl_io *)ctsio);
5582                 return (CTL_RETVAL_COMPLETE);
5583         }
5584
5585         len = scsi_3btoul(cdb->length);
5586         buffer_offset = scsi_3btoul(cdb->offset);
5587
5588         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5589                 ctl_set_invalid_field(ctsio,
5590                                       /*sks_valid*/ 1,
5591                                       /*command*/ 1,
5592                                       /*field*/ 6,
5593                                       /*bit_valid*/ 0,
5594                                       /*bit*/ 0);
5595                 ctl_done((union ctl_io *)ctsio);
5596                 return (CTL_RETVAL_COMPLETE);
5597         }
5598
5599         /*
5600          * If we've got a kernel request that hasn't been malloced yet,
5601          * malloc it and tell the caller the data buffer is here.
5602          */
5603         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5604                 if (lun->write_buffer == NULL) {
5605                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5606                             M_CTL, M_WAITOK);
5607                 }
5608                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5609                 ctsio->kern_data_len = len;
5610                 ctsio->kern_total_len = len;
5611                 ctsio->kern_data_resid = 0;
5612                 ctsio->kern_rel_offset = 0;
5613                 ctsio->kern_sg_entries = 0;
5614                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5615                 ctsio->be_move_done = ctl_config_move_done;
5616                 ctl_datamove((union ctl_io *)ctsio);
5617
5618                 return (CTL_RETVAL_COMPLETE);
5619         }
5620
5621         ctl_set_success(ctsio);
5622         ctl_done((union ctl_io *)ctsio);
5623         return (CTL_RETVAL_COMPLETE);
5624 }
5625
5626 int
5627 ctl_write_same(struct ctl_scsiio *ctsio)
5628 {
5629         struct ctl_lun *lun;
5630         struct ctl_lba_len_flags *lbalen;
5631         uint64_t lba;
5632         uint32_t num_blocks;
5633         int len, retval;
5634         uint8_t byte2;
5635
5636         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5637
5638         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5639
5640         switch (ctsio->cdb[0]) {
5641         case WRITE_SAME_10: {
5642                 struct scsi_write_same_10 *cdb;
5643
5644                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5645
5646                 lba = scsi_4btoul(cdb->addr);
5647                 num_blocks = scsi_2btoul(cdb->length);
5648                 byte2 = cdb->byte2;
5649                 break;
5650         }
5651         case WRITE_SAME_16: {
5652                 struct scsi_write_same_16 *cdb;
5653
5654                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5655
5656                 lba = scsi_8btou64(cdb->addr);
5657                 num_blocks = scsi_4btoul(cdb->length);
5658                 byte2 = cdb->byte2;
5659                 break;
5660         }
5661         default:
5662                 /*
5663                  * We got a command we don't support.  This shouldn't
5664                  * happen, commands should be filtered out above us.
5665                  */
5666                 ctl_set_invalid_opcode(ctsio);
5667                 ctl_done((union ctl_io *)ctsio);
5668
5669                 return (CTL_RETVAL_COMPLETE);
5670                 break; /* NOTREACHED */
5671         }
5672
5673         /* ANCHOR flag can be used only together with UNMAP */
5674         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5675                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5676                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5677                 ctl_done((union ctl_io *)ctsio);
5678                 return (CTL_RETVAL_COMPLETE);
5679         }
5680
5681         /*
5682          * The first check is to make sure we're in bounds, the second
5683          * check is to catch wrap-around problems.  If the lba + num blocks
5684          * is less than the lba, then we've wrapped around and the block
5685          * range is invalid anyway.
5686          */
5687         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5688          || ((lba + num_blocks) < lba)) {
5689                 ctl_set_lba_out_of_range(ctsio,
5690                     MAX(lba, lun->be_lun->maxlba + 1));
5691                 ctl_done((union ctl_io *)ctsio);
5692                 return (CTL_RETVAL_COMPLETE);
5693         }
5694
5695         /* Zero number of blocks means "to the last logical block" */
5696         if (num_blocks == 0) {
5697                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5698                         ctl_set_invalid_field(ctsio,
5699                                               /*sks_valid*/ 0,
5700                                               /*command*/ 1,
5701                                               /*field*/ 0,
5702                                               /*bit_valid*/ 0,
5703                                               /*bit*/ 0);
5704                         ctl_done((union ctl_io *)ctsio);
5705                         return (CTL_RETVAL_COMPLETE);
5706                 }
5707                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5708         }
5709
5710         len = lun->be_lun->blocksize;
5711
5712         /*
5713          * If we've got a kernel request that hasn't been malloced yet,
5714          * malloc it and tell the caller the data buffer is here.
5715          */
5716         if ((byte2 & SWS_NDOB) == 0 &&
5717             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5718                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5719                 ctsio->kern_data_len = len;
5720                 ctsio->kern_total_len = len;
5721                 ctsio->kern_data_resid = 0;
5722                 ctsio->kern_rel_offset = 0;
5723                 ctsio->kern_sg_entries = 0;
5724                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5725                 ctsio->be_move_done = ctl_config_move_done;
5726                 ctl_datamove((union ctl_io *)ctsio);
5727
5728                 return (CTL_RETVAL_COMPLETE);
5729         }
5730
5731         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5732         lbalen->lba = lba;
5733         lbalen->len = num_blocks;
5734         lbalen->flags = byte2;
5735         retval = lun->backend->config_write((union ctl_io *)ctsio);
5736
5737         return (retval);
5738 }
5739
5740 int
5741 ctl_unmap(struct ctl_scsiio *ctsio)
5742 {
5743         struct ctl_lun *lun;
5744         struct scsi_unmap *cdb;
5745         struct ctl_ptr_len_flags *ptrlen;
5746         struct scsi_unmap_header *hdr;
5747         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5748         uint64_t lba;
5749         uint32_t num_blocks;
5750         int len, retval;
5751         uint8_t byte2;
5752
5753         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5754
5755         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5756         cdb = (struct scsi_unmap *)ctsio->cdb;
5757
5758         len = scsi_2btoul(cdb->length);
5759         byte2 = cdb->byte2;
5760
5761         /*
5762          * If we've got a kernel request that hasn't been malloced yet,
5763          * malloc it and tell the caller the data buffer is here.
5764          */
5765         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5766                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5767                 ctsio->kern_data_len = len;
5768                 ctsio->kern_total_len = len;
5769                 ctsio->kern_data_resid = 0;
5770                 ctsio->kern_rel_offset = 0;
5771                 ctsio->kern_sg_entries = 0;
5772                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5773                 ctsio->be_move_done = ctl_config_move_done;
5774                 ctl_datamove((union ctl_io *)ctsio);
5775
5776                 return (CTL_RETVAL_COMPLETE);
5777         }
5778
5779         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5780         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5781         if (len < sizeof (*hdr) ||
5782             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5783             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5784             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5785                 ctl_set_invalid_field(ctsio,
5786                                       /*sks_valid*/ 0,
5787                                       /*command*/ 0,
5788                                       /*field*/ 0,
5789                                       /*bit_valid*/ 0,
5790                                       /*bit*/ 0);
5791                 goto done;
5792         }
5793         len = scsi_2btoul(hdr->desc_length);
5794         buf = (struct scsi_unmap_desc *)(hdr + 1);
5795         end = buf + len / sizeof(*buf);
5796
5797         endnz = buf;
5798         for (range = buf; range < end; range++) {
5799                 lba = scsi_8btou64(range->lba);
5800                 num_blocks = scsi_4btoul(range->length);
5801                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5802                  || ((lba + num_blocks) < lba)) {
5803                         ctl_set_lba_out_of_range(ctsio,
5804                             MAX(lba, lun->be_lun->maxlba + 1));
5805                         ctl_done((union ctl_io *)ctsio);
5806                         return (CTL_RETVAL_COMPLETE);
5807                 }
5808                 if (num_blocks != 0)
5809                         endnz = range + 1;
5810         }
5811
5812         /*
5813          * Block backend can not handle zero last range.
5814          * Filter it out and return if there is nothing left.
5815          */
5816         len = (uint8_t *)endnz - (uint8_t *)buf;
5817         if (len == 0) {
5818                 ctl_set_success(ctsio);
5819                 goto done;
5820         }
5821
5822         mtx_lock(&lun->lun_lock);
5823         ptrlen = (struct ctl_ptr_len_flags *)
5824             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5825         ptrlen->ptr = (void *)buf;
5826         ptrlen->len = len;
5827         ptrlen->flags = byte2;
5828         ctl_check_blocked(lun);
5829         mtx_unlock(&lun->lun_lock);
5830
5831         retval = lun->backend->config_write((union ctl_io *)ctsio);
5832         return (retval);
5833
5834 done:
5835         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5836                 free(ctsio->kern_data_ptr, M_CTL);
5837                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5838         }
5839         ctl_done((union ctl_io *)ctsio);
5840         return (CTL_RETVAL_COMPLETE);
5841 }
5842
5843 int
5844 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5845                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5846 {
5847         struct ctl_lun *lun;
5848         uint8_t *current_cp, *saved_cp;
5849         int set_ua;
5850         uint32_t initidx;
5851
5852         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5853         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5854         set_ua = 0;
5855
5856         current_cp = (page_index->page_data + (page_index->page_len *
5857             CTL_PAGE_CURRENT));
5858         saved_cp = (page_index->page_data + (page_index->page_len *
5859             CTL_PAGE_SAVED));
5860
5861         mtx_lock(&lun->lun_lock);
5862         if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5863                 memcpy(current_cp, page_ptr, page_index->page_len);
5864                 memcpy(saved_cp, page_ptr, page_index->page_len);
5865                 set_ua = 1;
5866         }
5867         if (set_ua != 0)
5868                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5869         mtx_unlock(&lun->lun_lock);
5870         if (set_ua) {
5871                 ctl_isc_announce_mode(lun,
5872                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5873                     page_index->page_code, page_index->subpage);
5874         }
5875         return (CTL_RETVAL_COMPLETE);
5876 }
5877
5878 static void
5879 ctl_ie_timer(void *arg)
5880 {
5881         struct ctl_lun *lun = arg;
5882         uint64_t t;
5883
5884         if (lun->ie_asc == 0)
5885                 return;
5886
5887         if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5888                 ctl_est_ua_all(lun, -1, CTL_UA_IE);
5889         else
5890                 lun->ie_reported = 0;
5891
5892         if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5893                 lun->ie_reportcnt++;
5894                 t = scsi_4btoul(lun->MODE_IE.interval_timer);
5895                 if (t == 0 || t == UINT32_MAX)
5896                         t = 3000;  /* 5 min */
5897                 callout_schedule(&lun->ie_callout, t * hz / 10);
5898         }
5899 }
5900
5901 int
5902 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5903                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5904 {
5905         struct scsi_info_exceptions_page *pg;
5906         struct ctl_lun *lun;
5907         uint64_t t;
5908
5909         (void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5910
5911         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5912         pg = (struct scsi_info_exceptions_page *)page_ptr;
5913         mtx_lock(&lun->lun_lock);
5914         if (pg->info_flags & SIEP_FLAGS_TEST) {
5915                 lun->ie_asc = 0x5d;
5916                 lun->ie_ascq = 0xff;
5917                 if (pg->mrie == SIEP_MRIE_UA) {
5918                         ctl_est_ua_all(lun, -1, CTL_UA_IE);
5919                         lun->ie_reported = 1;
5920                 } else {
5921                         ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5922                         lun->ie_reported = -1;
5923                 }
5924                 lun->ie_reportcnt = 1;
5925                 if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5926                         lun->ie_reportcnt++;
5927                         t = scsi_4btoul(pg->interval_timer);
5928                         if (t == 0 || t == UINT32_MAX)
5929                                 t = 3000;  /* 5 min */
5930                         callout_reset(&lun->ie_callout, t * hz / 10,
5931                             ctl_ie_timer, lun);
5932                 }
5933         } else {
5934                 lun->ie_asc = 0;
5935                 lun->ie_ascq = 0;
5936                 lun->ie_reported = 1;
5937                 ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5938                 lun->ie_reportcnt = UINT32_MAX;
5939                 callout_stop(&lun->ie_callout);
5940         }
5941         mtx_unlock(&lun->lun_lock);
5942         return (CTL_RETVAL_COMPLETE);
5943 }
5944
5945 static int
5946 ctl_do_mode_select(union ctl_io *io)
5947 {
5948         struct scsi_mode_page_header *page_header;
5949         struct ctl_page_index *page_index;
5950         struct ctl_scsiio *ctsio;
5951         int page_len, page_len_offset, page_len_size;
5952         union ctl_modepage_info *modepage_info;
5953         struct ctl_lun *lun;
5954         int *len_left, *len_used;
5955         int retval, i;
5956
5957         ctsio = &io->scsiio;
5958         page_index = NULL;
5959         page_len = 0;
5960         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5961
5962         modepage_info = (union ctl_modepage_info *)
5963                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5964         len_left = &modepage_info->header.len_left;
5965         len_used = &modepage_info->header.len_used;
5966
5967 do_next_page:
5968
5969         page_header = (struct scsi_mode_page_header *)
5970                 (ctsio->kern_data_ptr + *len_used);
5971
5972         if (*len_left == 0) {
5973                 free(ctsio->kern_data_ptr, M_CTL);
5974                 ctl_set_success(ctsio);
5975                 ctl_done((union ctl_io *)ctsio);
5976                 return (CTL_RETVAL_COMPLETE);
5977         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5978
5979                 free(ctsio->kern_data_ptr, M_CTL);
5980                 ctl_set_param_len_error(ctsio);
5981                 ctl_done((union ctl_io *)ctsio);
5982                 return (CTL_RETVAL_COMPLETE);
5983
5984         } else if ((page_header->page_code & SMPH_SPF)
5985                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5986
5987                 free(ctsio->kern_data_ptr, M_CTL);
5988                 ctl_set_param_len_error(ctsio);
5989                 ctl_done((union ctl_io *)ctsio);
5990                 return (CTL_RETVAL_COMPLETE);
5991         }
5992
5993
5994         /*
5995          * XXX KDM should we do something with the block descriptor?
5996          */
5997         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5998                 page_index = &lun->mode_pages.index[i];
5999                 if (lun->be_lun->lun_type == T_DIRECT &&
6000                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6001                         continue;
6002                 if (lun->be_lun->lun_type == T_PROCESSOR &&
6003                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6004                         continue;
6005                 if (lun->be_lun->lun_type == T_CDROM &&
6006                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6007                         continue;
6008
6009                 if ((page_index->page_code & SMPH_PC_MASK) !=
6010                     (page_header->page_code & SMPH_PC_MASK))
6011                         continue;
6012
6013                 /*
6014                  * If neither page has a subpage code, then we've got a
6015                  * match.
6016                  */
6017                 if (((page_index->page_code & SMPH_SPF) == 0)
6018                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6019                         page_len = page_header->page_length;
6020                         break;
6021                 }
6022
6023                 /*
6024                  * If both pages have subpages, then the subpage numbers
6025                  * have to match.
6026                  */
6027                 if ((page_index->page_code & SMPH_SPF)
6028                   && (page_header->page_code & SMPH_SPF)) {
6029                         struct scsi_mode_page_header_sp *sph;
6030
6031                         sph = (struct scsi_mode_page_header_sp *)page_header;
6032                         if (page_index->subpage == sph->subpage) {
6033                                 page_len = scsi_2btoul(sph->page_length);
6034                                 break;
6035                         }
6036                 }
6037         }
6038
6039         /*
6040          * If we couldn't find the page, or if we don't have a mode select
6041          * handler for it, send back an error to the user.
6042          */
6043         if ((i >= CTL_NUM_MODE_PAGES)
6044          || (page_index->select_handler == NULL)) {
6045                 ctl_set_invalid_field(ctsio,
6046                                       /*sks_valid*/ 1,
6047                                       /*command*/ 0,
6048                                       /*field*/ *len_used,
6049                                       /*bit_valid*/ 0,
6050                                       /*bit*/ 0);
6051                 free(ctsio->kern_data_ptr, M_CTL);
6052                 ctl_done((union ctl_io *)ctsio);
6053                 return (CTL_RETVAL_COMPLETE);
6054         }
6055
6056         if (page_index->page_code & SMPH_SPF) {
6057                 page_len_offset = 2;
6058                 page_len_size = 2;
6059         } else {
6060                 page_len_size = 1;
6061                 page_len_offset = 1;
6062         }
6063
6064         /*
6065          * If the length the initiator gives us isn't the one we specify in
6066          * the mode page header, or if they didn't specify enough data in
6067          * the CDB to avoid truncating this page, kick out the request.
6068          */
6069         if ((page_len != (page_index->page_len - page_len_offset -
6070                           page_len_size))
6071          || (*len_left < page_index->page_len)) {
6072
6073
6074                 ctl_set_invalid_field(ctsio,
6075                                       /*sks_valid*/ 1,
6076                                       /*command*/ 0,
6077                                       /*field*/ *len_used + page_len_offset,
6078                                       /*bit_valid*/ 0,
6079                                       /*bit*/ 0);
6080                 free(ctsio->kern_data_ptr, M_CTL);
6081                 ctl_done((union ctl_io *)ctsio);
6082                 return (CTL_RETVAL_COMPLETE);
6083         }
6084
6085         /*
6086          * Run through the mode page, checking to make sure that the bits
6087          * the user changed are actually legal for him to change.
6088          */
6089         for (i = 0; i < page_index->page_len; i++) {
6090                 uint8_t *user_byte, *change_mask, *current_byte;
6091                 int bad_bit;
6092                 int j;
6093
6094                 user_byte = (uint8_t *)page_header + i;
6095                 change_mask = page_index->page_data +
6096                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6097                 current_byte = page_index->page_data +
6098                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6099
6100                 /*
6101                  * Check to see whether the user set any bits in this byte
6102                  * that he is not allowed to set.
6103                  */
6104                 if ((*user_byte & ~(*change_mask)) ==
6105                     (*current_byte & ~(*change_mask)))
6106                         continue;
6107
6108                 /*
6109                  * Go through bit by bit to determine which one is illegal.
6110                  */
6111                 bad_bit = 0;
6112                 for (j = 7; j >= 0; j--) {
6113                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6114                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6115                                 bad_bit = i;
6116                                 break;
6117                         }
6118                 }
6119                 ctl_set_invalid_field(ctsio,
6120                                       /*sks_valid*/ 1,
6121                                       /*command*/ 0,
6122                                       /*field*/ *len_used + i,
6123                                       /*bit_valid*/ 1,
6124                                       /*bit*/ bad_bit);
6125                 free(ctsio->kern_data_ptr, M_CTL);
6126                 ctl_done((union ctl_io *)ctsio);
6127                 return (CTL_RETVAL_COMPLETE);
6128         }
6129
6130         /*
6131          * Decrement these before we call the page handler, since we may
6132          * end up getting called back one way or another before the handler
6133          * returns to this context.
6134          */
6135         *len_left -= page_index->page_len;
6136         *len_used += page_index->page_len;
6137
6138         retval = page_index->select_handler(ctsio, page_index,
6139                                             (uint8_t *)page_header);
6140
6141         /*
6142          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6143          * wait until this queued command completes to finish processing
6144          * the mode page.  If it returns anything other than
6145          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6146          * already set the sense information, freed the data pointer, and
6147          * completed the io for us.
6148          */
6149         if (retval != CTL_RETVAL_COMPLETE)
6150                 goto bailout_no_done;
6151
6152         /*
6153          * If the initiator sent us more than one page, parse the next one.
6154          */
6155         if (*len_left > 0)
6156                 goto do_next_page;
6157
6158         ctl_set_success(ctsio);
6159         free(ctsio->kern_data_ptr, M_CTL);
6160         ctl_done((union ctl_io *)ctsio);
6161
6162 bailout_no_done:
6163
6164         return (CTL_RETVAL_COMPLETE);
6165
6166 }
6167
6168 int
6169 ctl_mode_select(struct ctl_scsiio *ctsio)
6170 {
6171         int param_len, pf, sp;
6172         int header_size, bd_len;
6173         union ctl_modepage_info *modepage_info;
6174
6175         switch (ctsio->cdb[0]) {
6176         case MODE_SELECT_6: {
6177                 struct scsi_mode_select_6 *cdb;
6178
6179                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6180
6181                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6182                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6183                 param_len = cdb->length;
6184                 header_size = sizeof(struct scsi_mode_header_6);
6185                 break;
6186         }
6187         case MODE_SELECT_10: {
6188                 struct scsi_mode_select_10 *cdb;
6189
6190                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6191
6192                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6193                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6194                 param_len = scsi_2btoul(cdb->length);
6195                 header_size = sizeof(struct scsi_mode_header_10);
6196                 break;
6197         }
6198         default:
6199                 ctl_set_invalid_opcode(ctsio);
6200                 ctl_done((union ctl_io *)ctsio);
6201                 return (CTL_RETVAL_COMPLETE);
6202         }
6203
6204         /*
6205          * From SPC-3:
6206          * "A parameter list length of zero indicates that the Data-Out Buffer
6207          * shall be empty. This condition shall not be considered as an error."
6208          */
6209         if (param_len == 0) {
6210                 ctl_set_success(ctsio);
6211                 ctl_done((union ctl_io *)ctsio);
6212                 return (CTL_RETVAL_COMPLETE);
6213         }
6214
6215         /*
6216          * Since we'll hit this the first time through, prior to
6217          * allocation, we don't need to free a data buffer here.
6218          */
6219         if (param_len < header_size) {
6220                 ctl_set_param_len_error(ctsio);
6221                 ctl_done((union ctl_io *)ctsio);
6222                 return (CTL_RETVAL_COMPLETE);
6223         }
6224
6225         /*
6226          * Allocate the data buffer and grab the user's data.  In theory,
6227          * we shouldn't have to sanity check the parameter list length here
6228          * because the maximum size is 64K.  We should be able to malloc
6229          * that much without too many problems.
6230          */
6231         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6232                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6233                 ctsio->kern_data_len = param_len;
6234                 ctsio->kern_total_len = param_len;
6235                 ctsio->kern_data_resid = 0;
6236                 ctsio->kern_rel_offset = 0;
6237                 ctsio->kern_sg_entries = 0;
6238                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6239                 ctsio->be_move_done = ctl_config_move_done;
6240                 ctl_datamove((union ctl_io *)ctsio);
6241
6242                 return (CTL_RETVAL_COMPLETE);
6243         }
6244
6245         switch (ctsio->cdb[0]) {
6246         case MODE_SELECT_6: {
6247                 struct scsi_mode_header_6 *mh6;
6248
6249                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6250                 bd_len = mh6->blk_desc_len;
6251                 break;
6252         }
6253         case MODE_SELECT_10: {
6254                 struct scsi_mode_header_10 *mh10;
6255
6256                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6257                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6258                 break;
6259         }
6260         default:
6261                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6262         }
6263
6264         if (param_len < (header_size + bd_len)) {
6265                 free(ctsio->kern_data_ptr, M_CTL);
6266                 ctl_set_param_len_error(ctsio);
6267                 ctl_done((union ctl_io *)ctsio);
6268                 return (CTL_RETVAL_COMPLETE);
6269         }
6270
6271         /*
6272          * Set the IO_CONT flag, so that if this I/O gets passed to
6273          * ctl_config_write_done(), it'll get passed back to
6274          * ctl_do_mode_select() for further processing, or completion if
6275          * we're all done.
6276          */
6277         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6278         ctsio->io_cont = ctl_do_mode_select;
6279
6280         modepage_info = (union ctl_modepage_info *)
6281                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6282         memset(modepage_info, 0, sizeof(*modepage_info));
6283         modepage_info->header.len_left = param_len - header_size - bd_len;
6284         modepage_info->header.len_used = header_size + bd_len;
6285
6286         return (ctl_do_mode_select((union ctl_io *)ctsio));
6287 }
6288
6289 int
6290 ctl_mode_sense(struct ctl_scsiio *ctsio)
6291 {
6292         struct ctl_lun *lun;
6293         int pc, page_code, dbd, llba, subpage;
6294         int alloc_len, page_len, header_len, total_len;
6295         struct scsi_mode_block_descr *block_desc;
6296         struct ctl_page_index *page_index;
6297
6298         dbd = 0;
6299         llba = 0;
6300         block_desc = NULL;
6301
6302         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6303
6304         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6305         switch (ctsio->cdb[0]) {
6306         case MODE_SENSE_6: {
6307                 struct scsi_mode_sense_6 *cdb;
6308
6309                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6310
6311                 header_len = sizeof(struct scsi_mode_hdr_6);
6312                 if (cdb->byte2 & SMS_DBD)
6313                         dbd = 1;
6314                 else
6315                         header_len += sizeof(struct scsi_mode_block_descr);
6316
6317                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6318                 page_code = cdb->page & SMS_PAGE_CODE;
6319                 subpage = cdb->subpage;
6320                 alloc_len = cdb->length;
6321                 break;
6322         }
6323         case MODE_SENSE_10: {
6324                 struct scsi_mode_sense_10 *cdb;
6325
6326                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6327
6328                 header_len = sizeof(struct scsi_mode_hdr_10);
6329
6330                 if (cdb->byte2 & SMS_DBD)
6331                         dbd = 1;
6332                 else
6333                         header_len += sizeof(struct scsi_mode_block_descr);
6334                 if (cdb->byte2 & SMS10_LLBAA)
6335                         llba = 1;
6336                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6337                 page_code = cdb->page & SMS_PAGE_CODE;
6338                 subpage = cdb->subpage;
6339                 alloc_len = scsi_2btoul(cdb->length);
6340                 break;
6341         }
6342         default:
6343                 ctl_set_invalid_opcode(ctsio);
6344                 ctl_done((union ctl_io *)ctsio);
6345                 return (CTL_RETVAL_COMPLETE);
6346                 break; /* NOTREACHED */
6347         }
6348
6349         /*
6350          * We have to make a first pass through to calculate the size of
6351          * the pages that match the user's query.  Then we allocate enough
6352          * memory to hold it, and actually copy the data into the buffer.
6353          */
6354         switch (page_code) {
6355         case SMS_ALL_PAGES_PAGE: {
6356                 u_int i;
6357
6358                 page_len = 0;
6359
6360                 /*
6361                  * At the moment, values other than 0 and 0xff here are
6362                  * reserved according to SPC-3.
6363                  */
6364                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6365                  && (subpage != SMS_SUBPAGE_ALL)) {
6366                         ctl_set_invalid_field(ctsio,
6367                                               /*sks_valid*/ 1,
6368                                               /*command*/ 1,
6369                                               /*field*/ 3,
6370                                               /*bit_valid*/ 0,
6371                                               /*bit*/ 0);
6372                         ctl_done((union ctl_io *)ctsio);
6373                         return (CTL_RETVAL_COMPLETE);
6374                 }
6375
6376                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6377                         page_index = &lun->mode_pages.index[i];
6378
6379                         /* Make sure the page is supported for this dev type */
6380                         if (lun->be_lun->lun_type == T_DIRECT &&
6381                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6382                                 continue;
6383                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6384                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6385                                 continue;
6386                         if (lun->be_lun->lun_type == T_CDROM &&
6387                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6388                                 continue;
6389
6390                         /*
6391                          * We don't use this subpage if the user didn't
6392                          * request all subpages.
6393                          */
6394                         if ((page_index->subpage != 0)
6395                          && (subpage == SMS_SUBPAGE_PAGE_0))
6396                                 continue;
6397
6398 #if 0
6399                         printf("found page %#x len %d\n",
6400                                page_index->page_code & SMPH_PC_MASK,
6401                                page_index->page_len);
6402 #endif
6403                         page_len += page_index->page_len;
6404                 }
6405                 break;
6406         }
6407         default: {
6408                 u_int i;
6409
6410                 page_len = 0;
6411
6412                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6413                         page_index = &lun->mode_pages.index[i];
6414
6415                         /* Make sure the page is supported for this dev type */
6416                         if (lun->be_lun->lun_type == T_DIRECT &&
6417                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6418                                 continue;
6419                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6420                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6421                                 continue;
6422                         if (lun->be_lun->lun_type == T_CDROM &&
6423                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6424                                 continue;
6425
6426                         /* Look for the right page code */
6427                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6428                                 continue;
6429
6430                         /* Look for the right subpage or the subpage wildcard*/
6431                         if ((page_index->subpage != subpage)
6432                          && (subpage != SMS_SUBPAGE_ALL))
6433                                 continue;
6434
6435 #if 0
6436                         printf("found page %#x len %d\n",
6437                                page_index->page_code & SMPH_PC_MASK,
6438                                page_index->page_len);
6439 #endif
6440
6441                         page_len += page_index->page_len;
6442                 }
6443
6444                 if (page_len == 0) {
6445                         ctl_set_invalid_field(ctsio,
6446                                               /*sks_valid*/ 1,
6447                                               /*command*/ 1,
6448                                               /*field*/ 2,
6449                                               /*bit_valid*/ 1,
6450                                               /*bit*/ 5);
6451                         ctl_done((union ctl_io *)ctsio);
6452                         return (CTL_RETVAL_COMPLETE);
6453                 }
6454                 break;
6455         }
6456         }
6457
6458         total_len = header_len + page_len;
6459 #if 0
6460         printf("header_len = %d, page_len = %d, total_len = %d\n",
6461                header_len, page_len, total_len);
6462 #endif
6463
6464         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6465         ctsio->kern_sg_entries = 0;
6466         ctsio->kern_data_resid = 0;
6467         ctsio->kern_rel_offset = 0;
6468         if (total_len < alloc_len) {
6469                 ctsio->residual = alloc_len - total_len;
6470                 ctsio->kern_data_len = total_len;
6471                 ctsio->kern_total_len = total_len;
6472         } else {
6473                 ctsio->residual = 0;
6474                 ctsio->kern_data_len = alloc_len;
6475                 ctsio->kern_total_len = alloc_len;
6476         }
6477
6478         switch (ctsio->cdb[0]) {
6479         case MODE_SENSE_6: {
6480                 struct scsi_mode_hdr_6 *header;
6481
6482                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6483
6484                 header->datalen = MIN(total_len - 1, 254);
6485                 if (lun->be_lun->lun_type == T_DIRECT) {
6486                         header->dev_specific = 0x10; /* DPOFUA */
6487                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6488                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6489                                 header->dev_specific |= 0x80; /* WP */
6490                 }
6491                 if (dbd)
6492                         header->block_descr_len = 0;
6493                 else
6494                         header->block_descr_len =
6495                                 sizeof(struct scsi_mode_block_descr);
6496                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6497                 break;
6498         }
6499         case MODE_SENSE_10: {
6500                 struct scsi_mode_hdr_10 *header;
6501                 int datalen;
6502
6503                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6504
6505                 datalen = MIN(total_len - 2, 65533);
6506                 scsi_ulto2b(datalen, header->datalen);
6507                 if (lun->be_lun->lun_type == T_DIRECT) {
6508                         header->dev_specific = 0x10; /* DPOFUA */
6509                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6510                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6511                                 header->dev_specific |= 0x80; /* WP */
6512                 }
6513                 if (dbd)
6514                         scsi_ulto2b(0, header->block_descr_len);
6515                 else
6516                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6517                                     header->block_descr_len);
6518                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6519                 break;
6520         }
6521         default:
6522                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6523         }
6524
6525         /*
6526          * If we've got a disk, use its blocksize in the block
6527          * descriptor.  Otherwise, just set it to 0.
6528          */
6529         if (dbd == 0) {
6530                 if (lun->be_lun->lun_type == T_DIRECT)
6531                         scsi_ulto3b(lun->be_lun->blocksize,
6532                                     block_desc->block_len);
6533                 else
6534                         scsi_ulto3b(0, block_desc->block_len);
6535         }
6536
6537         switch (page_code) {
6538         case SMS_ALL_PAGES_PAGE: {
6539                 int i, data_used;
6540
6541                 data_used = header_len;
6542                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6543                         struct ctl_page_index *page_index;
6544
6545                         page_index = &lun->mode_pages.index[i];
6546                         if (lun->be_lun->lun_type == T_DIRECT &&
6547                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6548                                 continue;
6549                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6550                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6551                                 continue;
6552                         if (lun->be_lun->lun_type == T_CDROM &&
6553                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6554                                 continue;
6555
6556                         /*
6557                          * We don't use this subpage if the user didn't
6558                          * request all subpages.  We already checked (above)
6559                          * to make sure the user only specified a subpage
6560                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6561                          */
6562                         if ((page_index->subpage != 0)
6563                          && (subpage == SMS_SUBPAGE_PAGE_0))
6564                                 continue;
6565
6566                         /*
6567                          * Call the handler, if it exists, to update the
6568                          * page to the latest values.
6569                          */
6570                         if (page_index->sense_handler != NULL)
6571                                 page_index->sense_handler(ctsio, page_index,pc);
6572
6573                         memcpy(ctsio->kern_data_ptr + data_used,
6574                                page_index->page_data +
6575                                (page_index->page_len * pc),
6576                                page_index->page_len);
6577                         data_used += page_index->page_len;
6578                 }
6579                 break;
6580         }
6581         default: {
6582                 int i, data_used;
6583
6584                 data_used = header_len;
6585
6586                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6587                         struct ctl_page_index *page_index;
6588
6589                         page_index = &lun->mode_pages.index[i];
6590
6591                         /* Look for the right page code */
6592                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6593                                 continue;
6594
6595                         /* Look for the right subpage or the subpage wildcard*/
6596                         if ((page_index->subpage != subpage)
6597                          && (subpage != SMS_SUBPAGE_ALL))
6598                                 continue;
6599
6600                         /* Make sure the page is supported for this dev type */
6601                         if (lun->be_lun->lun_type == T_DIRECT &&
6602                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6603                                 continue;
6604                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6605                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6606                                 continue;
6607                         if (lun->be_lun->lun_type == T_CDROM &&
6608                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6609                                 continue;
6610
6611                         /*
6612                          * Call the handler, if it exists, to update the
6613                          * page to the latest values.
6614                          */
6615                         if (page_index->sense_handler != NULL)
6616                                 page_index->sense_handler(ctsio, page_index,pc);
6617
6618                         memcpy(ctsio->kern_data_ptr + data_used,
6619                                page_index->page_data +
6620                                (page_index->page_len * pc),
6621                                page_index->page_len);
6622                         data_used += page_index->page_len;
6623                 }
6624                 break;
6625         }
6626         }
6627
6628         ctl_set_success(ctsio);
6629         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6630         ctsio->be_move_done = ctl_config_move_done;
6631         ctl_datamove((union ctl_io *)ctsio);
6632         return (CTL_RETVAL_COMPLETE);
6633 }
6634
6635 int
6636 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6637                                struct ctl_page_index *page_index,
6638                                int pc)
6639 {
6640         struct ctl_lun *lun;
6641         struct scsi_log_param_header *phdr;
6642         uint8_t *data;
6643         uint64_t val;
6644
6645         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6646         data = page_index->page_data;
6647
6648         if (lun->backend->lun_attr != NULL &&
6649             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6650              != UINT64_MAX) {
6651                 phdr = (struct scsi_log_param_header *)data;
6652                 scsi_ulto2b(0x0001, phdr->param_code);
6653                 phdr->param_control = SLP_LBIN | SLP_LP;
6654                 phdr->param_len = 8;
6655                 data = (uint8_t *)(phdr + 1);
6656                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6657                 data[4] = 0x02; /* per-pool */
6658                 data += phdr->param_len;
6659         }
6660
6661         if (lun->backend->lun_attr != NULL &&
6662             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6663              != UINT64_MAX) {
6664                 phdr = (struct scsi_log_param_header *)data;
6665                 scsi_ulto2b(0x0002, phdr->param_code);
6666                 phdr->param_control = SLP_LBIN | SLP_LP;
6667                 phdr->param_len = 8;
6668                 data = (uint8_t *)(phdr + 1);
6669                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6670                 data[4] = 0x01; /* per-LUN */
6671                 data += phdr->param_len;
6672         }
6673
6674         if (lun->backend->lun_attr != NULL &&
6675             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6676              != UINT64_MAX) {
6677                 phdr = (struct scsi_log_param_header *)data;
6678                 scsi_ulto2b(0x00f1, phdr->param_code);
6679                 phdr->param_control = SLP_LBIN | SLP_LP;
6680                 phdr->param_len = 8;
6681                 data = (uint8_t *)(phdr + 1);
6682                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6683                 data[4] = 0x02; /* per-pool */
6684                 data += phdr->param_len;
6685         }
6686
6687         if (lun->backend->lun_attr != NULL &&
6688             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6689              != UINT64_MAX) {
6690                 phdr = (struct scsi_log_param_header *)data;
6691                 scsi_ulto2b(0x00f2, phdr->param_code);
6692                 phdr->param_control = SLP_LBIN | SLP_LP;
6693                 phdr->param_len = 8;
6694                 data = (uint8_t *)(phdr + 1);
6695                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6696                 data[4] = 0x02; /* per-pool */
6697                 data += phdr->param_len;
6698         }
6699
6700         page_index->page_len = data - page_index->page_data;
6701         return (0);
6702 }
6703
6704 int
6705 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6706                                struct ctl_page_index *page_index,
6707                                int pc)
6708 {
6709         struct ctl_lun *lun;
6710         struct stat_page *data;
6711         uint64_t rn, wn, rb, wb;
6712         struct bintime rt, wt;
6713         int i;
6714
6715         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6716         data = (struct stat_page *)page_index->page_data;
6717
6718         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6719         data->sap.hdr.param_control = SLP_LBIN;
6720         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6721             sizeof(struct scsi_log_param_header);
6722         rn = wn = rb = wb = 0;
6723         bintime_clear(&rt);
6724         bintime_clear(&wt);
6725         for (i = 0; i < CTL_MAX_PORTS; i++) {
6726                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6727                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6728                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6729                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6730                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6731                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6732         }
6733         scsi_u64to8b(rn, data->sap.read_num);
6734         scsi_u64to8b(wn, data->sap.write_num);
6735         if (lun->stats.blocksize > 0) {
6736                 scsi_u64to8b(wb / lun->stats.blocksize,
6737                     data->sap.recvieved_lba);
6738                 scsi_u64to8b(rb / lun->stats.blocksize,
6739                     data->sap.transmitted_lba);
6740         }
6741         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6742             data->sap.read_int);
6743         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6744             data->sap.write_int);
6745         scsi_u64to8b(0, data->sap.weighted_num);
6746         scsi_u64to8b(0, data->sap.weighted_int);
6747         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6748         data->it.hdr.param_control = SLP_LBIN;
6749         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6750             sizeof(struct scsi_log_param_header);
6751 #ifdef CTL_TIME_IO
6752         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6753 #endif
6754         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6755         data->it.hdr.param_control = SLP_LBIN;
6756         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6757             sizeof(struct scsi_log_param_header);
6758         scsi_ulto4b(3, data->ti.exponent);
6759         scsi_ulto4b(1, data->ti.integer);
6760         return (0);
6761 }
6762
6763 int
6764 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6765                                struct ctl_page_index *page_index,
6766                                int pc)
6767 {
6768         struct ctl_lun *lun;
6769         struct scsi_log_informational_exceptions *data;
6770
6771         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6772         data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6773
6774         scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6775         data->hdr.param_control = SLP_LBIN;
6776         data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6777             sizeof(struct scsi_log_param_header);
6778         data->ie_asc = lun->ie_asc;
6779         data->ie_ascq = lun->ie_ascq;
6780         data->temperature = 0xff;
6781         return (0);
6782 }
6783
6784 int
6785 ctl_log_sense(struct ctl_scsiio *ctsio)
6786 {
6787         struct ctl_lun *lun;
6788         int i, pc, page_code, subpage;
6789         int alloc_len, total_len;
6790         struct ctl_page_index *page_index;
6791         struct scsi_log_sense *cdb;
6792         struct scsi_log_header *header;
6793
6794         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6795
6796         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6797         cdb = (struct scsi_log_sense *)ctsio->cdb;
6798         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6799         page_code = cdb->page & SLS_PAGE_CODE;
6800         subpage = cdb->subpage;
6801         alloc_len = scsi_2btoul(cdb->length);
6802
6803         page_index = NULL;
6804         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6805                 page_index = &lun->log_pages.index[i];
6806
6807                 /* Look for the right page code */
6808                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6809                         continue;
6810
6811                 /* Look for the right subpage or the subpage wildcard*/
6812                 if (page_index->subpage != subpage)
6813                         continue;
6814
6815                 break;
6816         }
6817         if (i >= CTL_NUM_LOG_PAGES) {
6818                 ctl_set_invalid_field(ctsio,
6819                                       /*sks_valid*/ 1,
6820                                       /*command*/ 1,
6821                                       /*field*/ 2,
6822                                       /*bit_valid*/ 0,
6823                                       /*bit*/ 0);
6824                 ctl_done((union ctl_io *)ctsio);
6825                 return (CTL_RETVAL_COMPLETE);
6826         }
6827
6828         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6829
6830         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6831         ctsio->kern_sg_entries = 0;
6832         ctsio->kern_data_resid = 0;
6833         ctsio->kern_rel_offset = 0;
6834         if (total_len < alloc_len) {
6835                 ctsio->residual = alloc_len - total_len;
6836                 ctsio->kern_data_len = total_len;
6837                 ctsio->kern_total_len = total_len;
6838         } else {
6839                 ctsio->residual = 0;
6840                 ctsio->kern_data_len = alloc_len;
6841                 ctsio->kern_total_len = alloc_len;
6842         }
6843
6844         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6845         header->page = page_index->page_code;
6846         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6847                 header->page |= SL_DS;
6848         if (page_index->subpage) {
6849                 header->page |= SL_SPF;
6850                 header->subpage = page_index->subpage;
6851         }
6852         scsi_ulto2b(page_index->page_len, header->datalen);
6853
6854         /*
6855          * Call the handler, if it exists, to update the
6856          * page to the latest values.
6857          */
6858         if (page_index->sense_handler != NULL)
6859                 page_index->sense_handler(ctsio, page_index, pc);
6860
6861         memcpy(header + 1, page_index->page_data, page_index->page_len);
6862
6863         ctl_set_success(ctsio);
6864         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6865         ctsio->be_move_done = ctl_config_move_done;
6866         ctl_datamove((union ctl_io *)ctsio);
6867         return (CTL_RETVAL_COMPLETE);
6868 }
6869
6870 int
6871 ctl_read_capacity(struct ctl_scsiio *ctsio)
6872 {
6873         struct scsi_read_capacity *cdb;
6874         struct scsi_read_capacity_data *data;
6875         struct ctl_lun *lun;
6876         uint32_t lba;
6877
6878         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6879
6880         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6881
6882         lba = scsi_4btoul(cdb->addr);
6883         if (((cdb->pmi & SRC_PMI) == 0)
6884          && (lba != 0)) {
6885                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6886                                       /*sks_valid*/ 1,
6887                                       /*command*/ 1,
6888                                       /*field*/ 2,
6889                                       /*bit_valid*/ 0,
6890                                       /*bit*/ 0);
6891                 ctl_done((union ctl_io *)ctsio);
6892                 return (CTL_RETVAL_COMPLETE);
6893         }
6894
6895         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6896
6897         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6898         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6899         ctsio->residual = 0;
6900         ctsio->kern_data_len = sizeof(*data);
6901         ctsio->kern_total_len = sizeof(*data);
6902         ctsio->kern_data_resid = 0;
6903         ctsio->kern_rel_offset = 0;
6904         ctsio->kern_sg_entries = 0;
6905
6906         /*
6907          * If the maximum LBA is greater than 0xfffffffe, the user must
6908          * issue a SERVICE ACTION IN (16) command, with the read capacity
6909          * serivce action set.
6910          */
6911         if (lun->be_lun->maxlba > 0xfffffffe)
6912                 scsi_ulto4b(0xffffffff, data->addr);
6913         else
6914                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6915
6916         /*
6917          * XXX KDM this may not be 512 bytes...
6918          */
6919         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6920
6921         ctl_set_success(ctsio);
6922         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6923         ctsio->be_move_done = ctl_config_move_done;
6924         ctl_datamove((union ctl_io *)ctsio);
6925         return (CTL_RETVAL_COMPLETE);
6926 }
6927
6928 int
6929 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6930 {
6931         struct scsi_read_capacity_16 *cdb;
6932         struct scsi_read_capacity_data_long *data;
6933         struct ctl_lun *lun;
6934         uint64_t lba;
6935         uint32_t alloc_len;
6936
6937         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6938
6939         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6940
6941         alloc_len = scsi_4btoul(cdb->alloc_len);
6942         lba = scsi_8btou64(cdb->addr);
6943
6944         if ((cdb->reladr & SRC16_PMI)
6945          && (lba != 0)) {
6946                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6947                                       /*sks_valid*/ 1,
6948                                       /*command*/ 1,
6949                                       /*field*/ 2,
6950                                       /*bit_valid*/ 0,
6951                                       /*bit*/ 0);
6952                 ctl_done((union ctl_io *)ctsio);
6953                 return (CTL_RETVAL_COMPLETE);
6954         }
6955
6956         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6957
6958         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6959         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6960
6961         if (sizeof(*data) < alloc_len) {
6962                 ctsio->residual = alloc_len - sizeof(*data);
6963                 ctsio->kern_data_len = sizeof(*data);
6964                 ctsio->kern_total_len = sizeof(*data);
6965         } else {
6966                 ctsio->residual = 0;
6967                 ctsio->kern_data_len = alloc_len;
6968                 ctsio->kern_total_len = alloc_len;
6969         }
6970         ctsio->kern_data_resid = 0;
6971         ctsio->kern_rel_offset = 0;
6972         ctsio->kern_sg_entries = 0;
6973
6974         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6975         /* XXX KDM this may not be 512 bytes... */
6976         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6977         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6978         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6979         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6980                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6981
6982         ctl_set_success(ctsio);
6983         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6984         ctsio->be_move_done = ctl_config_move_done;
6985         ctl_datamove((union ctl_io *)ctsio);
6986         return (CTL_RETVAL_COMPLETE);
6987 }
6988
6989 int
6990 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6991 {
6992         struct scsi_get_lba_status *cdb;
6993         struct scsi_get_lba_status_data *data;
6994         struct ctl_lun *lun;
6995         struct ctl_lba_len_flags *lbalen;
6996         uint64_t lba;
6997         uint32_t alloc_len, total_len;
6998         int retval;
6999
7000         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7001
7002         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7003         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7004         lba = scsi_8btou64(cdb->addr);
7005         alloc_len = scsi_4btoul(cdb->alloc_len);
7006
7007         if (lba > lun->be_lun->maxlba) {
7008                 ctl_set_lba_out_of_range(ctsio, lba);
7009                 ctl_done((union ctl_io *)ctsio);
7010                 return (CTL_RETVAL_COMPLETE);
7011         }
7012
7013         total_len = sizeof(*data) + sizeof(data->descr[0]);
7014         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7015         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7016
7017         if (total_len < alloc_len) {
7018                 ctsio->residual = alloc_len - total_len;
7019                 ctsio->kern_data_len = total_len;
7020                 ctsio->kern_total_len = total_len;
7021         } else {
7022                 ctsio->residual = 0;
7023                 ctsio->kern_data_len = alloc_len;
7024                 ctsio->kern_total_len = alloc_len;
7025         }
7026         ctsio->kern_data_resid = 0;
7027         ctsio->kern_rel_offset = 0;
7028         ctsio->kern_sg_entries = 0;
7029
7030         /* Fill dummy data in case backend can't tell anything. */
7031         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7032         scsi_u64to8b(lba, data->descr[0].addr);
7033         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7034             data->descr[0].length);
7035         data->descr[0].status = 0; /* Mapped or unknown. */
7036
7037         ctl_set_success(ctsio);
7038         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7039         ctsio->be_move_done = ctl_config_move_done;
7040
7041         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7042         lbalen->lba = lba;
7043         lbalen->len = total_len;
7044         lbalen->flags = 0;
7045         retval = lun->backend->config_read((union ctl_io *)ctsio);
7046         return (CTL_RETVAL_COMPLETE);
7047 }
7048
7049 int
7050 ctl_read_defect(struct ctl_scsiio *ctsio)
7051 {
7052         struct scsi_read_defect_data_10 *ccb10;
7053         struct scsi_read_defect_data_12 *ccb12;
7054         struct scsi_read_defect_data_hdr_10 *data10;
7055         struct scsi_read_defect_data_hdr_12 *data12;
7056         uint32_t alloc_len, data_len;
7057         uint8_t format;
7058
7059         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7060
7061         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7062                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7063                 format = ccb10->format;
7064                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7065                 data_len = sizeof(*data10);
7066         } else {
7067                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7068                 format = ccb12->format;
7069                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7070                 data_len = sizeof(*data12);
7071         }
7072         if (alloc_len == 0) {
7073                 ctl_set_success(ctsio);
7074                 ctl_done((union ctl_io *)ctsio);
7075                 return (CTL_RETVAL_COMPLETE);
7076         }
7077
7078         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7079         if (data_len < alloc_len) {
7080                 ctsio->residual = alloc_len - data_len;
7081                 ctsio->kern_data_len = data_len;
7082                 ctsio->kern_total_len = data_len;
7083         } else {
7084                 ctsio->residual = 0;
7085                 ctsio->kern_data_len = alloc_len;
7086                 ctsio->kern_total_len = alloc_len;
7087         }
7088         ctsio->kern_data_resid = 0;
7089         ctsio->kern_rel_offset = 0;
7090         ctsio->kern_sg_entries = 0;
7091
7092         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7093                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7094                     ctsio->kern_data_ptr;
7095                 data10->format = format;
7096                 scsi_ulto2b(0, data10->length);
7097         } else {
7098                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7099                     ctsio->kern_data_ptr;
7100                 data12->format = format;
7101                 scsi_ulto2b(0, data12->generation);
7102                 scsi_ulto4b(0, data12->length);
7103         }
7104
7105         ctl_set_success(ctsio);
7106         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7107         ctsio->be_move_done = ctl_config_move_done;
7108         ctl_datamove((union ctl_io *)ctsio);
7109         return (CTL_RETVAL_COMPLETE);
7110 }
7111
7112 int
7113 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7114 {
7115         struct scsi_maintenance_in *cdb;
7116         int retval;
7117         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7118         int num_ha_groups, num_target_ports, shared_group;
7119         struct ctl_lun *lun;
7120         struct ctl_softc *softc;
7121         struct ctl_port *port;
7122         struct scsi_target_group_data *rtg_ptr;
7123         struct scsi_target_group_data_extended *rtg_ext_ptr;
7124         struct scsi_target_port_group_descriptor *tpg_desc;
7125
7126         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7127
7128         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7129         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7130         softc = lun->ctl_softc;
7131
7132         retval = CTL_RETVAL_COMPLETE;
7133
7134         switch (cdb->byte2 & STG_PDF_MASK) {
7135         case STG_PDF_LENGTH:
7136                 ext = 0;
7137                 break;
7138         case STG_PDF_EXTENDED:
7139                 ext = 1;
7140                 break;
7141         default:
7142                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7143                                       /*sks_valid*/ 1,
7144                                       /*command*/ 1,
7145                                       /*field*/ 2,
7146                                       /*bit_valid*/ 1,
7147                                       /*bit*/ 5);
7148                 ctl_done((union ctl_io *)ctsio);
7149                 return(retval);
7150         }
7151
7152         num_target_ports = 0;
7153         shared_group = (softc->is_single != 0);
7154         mtx_lock(&softc->ctl_lock);
7155         STAILQ_FOREACH(port, &softc->port_list, links) {
7156                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7157                         continue;
7158                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7159                         continue;
7160                 num_target_ports++;
7161                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7162                         shared_group = 1;
7163         }
7164         mtx_unlock(&softc->ctl_lock);
7165         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7166
7167         if (ext)
7168                 total_len = sizeof(struct scsi_target_group_data_extended);
7169         else
7170                 total_len = sizeof(struct scsi_target_group_data);
7171         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7172                 (shared_group + num_ha_groups) +
7173             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7174
7175         alloc_len = scsi_4btoul(cdb->length);
7176
7177         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7178
7179         ctsio->kern_sg_entries = 0;
7180
7181         if (total_len < alloc_len) {
7182                 ctsio->residual = alloc_len - total_len;
7183                 ctsio->kern_data_len = total_len;
7184                 ctsio->kern_total_len = total_len;
7185         } else {
7186                 ctsio->residual = 0;
7187                 ctsio->kern_data_len = alloc_len;
7188                 ctsio->kern_total_len = alloc_len;
7189         }
7190         ctsio->kern_data_resid = 0;
7191         ctsio->kern_rel_offset = 0;
7192
7193         if (ext) {
7194                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7195                     ctsio->kern_data_ptr;
7196                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7197                 rtg_ext_ptr->format_type = 0x10;
7198                 rtg_ext_ptr->implicit_transition_time = 0;
7199                 tpg_desc = &rtg_ext_ptr->groups[0];
7200         } else {
7201                 rtg_ptr = (struct scsi_target_group_data *)
7202                     ctsio->kern_data_ptr;
7203                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7204                 tpg_desc = &rtg_ptr->groups[0];
7205         }
7206
7207         mtx_lock(&softc->ctl_lock);
7208         pg = softc->port_min / softc->port_cnt;
7209         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7210                 /* Some shelf is known to be primary. */
7211                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7212                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7213                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7214                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7215                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7216                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7217                 else
7218                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7219                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7220                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7221                 } else {
7222                         ts = os;
7223                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7224                 }
7225         } else {
7226                 /* No known primary shelf. */
7227                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7228                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7229                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7230                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7231                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7232                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7233                 } else {
7234                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7235                 }
7236         }
7237         if (shared_group) {
7238                 tpg_desc->pref_state = ts;
7239                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7240                     TPG_U_SUP | TPG_T_SUP;
7241                 scsi_ulto2b(1, tpg_desc->target_port_group);
7242                 tpg_desc->status = TPG_IMPLICIT;
7243                 pc = 0;
7244                 STAILQ_FOREACH(port, &softc->port_list, links) {
7245                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7246                                 continue;
7247                         if (!softc->is_single &&
7248                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7249                                 continue;
7250                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7251                                 continue;
7252                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7253                             relative_target_port_identifier);
7254                         pc++;
7255                 }
7256                 tpg_desc->target_port_count = pc;
7257                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7258                     &tpg_desc->descriptors[pc];
7259         }
7260         for (g = 0; g < num_ha_groups; g++) {
7261                 tpg_desc->pref_state = (g == pg) ? ts : os;
7262                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7263                     TPG_U_SUP | TPG_T_SUP;
7264                 scsi_ulto2b(2 + g, 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->targ_port < g * softc->port_cnt ||
7269                             port->targ_port >= (g + 1) * softc->port_cnt)
7270                                 continue;
7271                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7272                                 continue;
7273                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7274                                 continue;
7275                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7276                                 continue;
7277                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7278                             relative_target_port_identifier);
7279                         pc++;
7280                 }
7281                 tpg_desc->target_port_count = pc;
7282                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7283                     &tpg_desc->descriptors[pc];
7284         }
7285         mtx_unlock(&softc->ctl_lock);
7286
7287         ctl_set_success(ctsio);
7288         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7289         ctsio->be_move_done = ctl_config_move_done;
7290         ctl_datamove((union ctl_io *)ctsio);
7291         return(retval);
7292 }
7293
7294 int
7295 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7296 {
7297         struct ctl_lun *lun;
7298         struct scsi_report_supported_opcodes *cdb;
7299         const struct ctl_cmd_entry *entry, *sentry;
7300         struct scsi_report_supported_opcodes_all *all;
7301         struct scsi_report_supported_opcodes_descr *descr;
7302         struct scsi_report_supported_opcodes_one *one;
7303         int retval;
7304         int alloc_len, total_len;
7305         int opcode, service_action, i, j, num;
7306
7307         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7308
7309         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7310         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7311
7312         retval = CTL_RETVAL_COMPLETE;
7313
7314         opcode = cdb->requested_opcode;
7315         service_action = scsi_2btoul(cdb->requested_service_action);
7316         switch (cdb->options & RSO_OPTIONS_MASK) {
7317         case RSO_OPTIONS_ALL:
7318                 num = 0;
7319                 for (i = 0; i < 256; i++) {
7320                         entry = &ctl_cmd_table[i];
7321                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7322                                 for (j = 0; j < 32; j++) {
7323                                         sentry = &((const struct ctl_cmd_entry *)
7324                                             entry->execute)[j];
7325                                         if (ctl_cmd_applicable(
7326                                             lun->be_lun->lun_type, sentry))
7327                                                 num++;
7328                                 }
7329                         } else {
7330                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7331                                     entry))
7332                                         num++;
7333                         }
7334                 }
7335                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7336                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7337                 break;
7338         case RSO_OPTIONS_OC:
7339                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7340                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7341                                               /*sks_valid*/ 1,
7342                                               /*command*/ 1,
7343                                               /*field*/ 2,
7344                                               /*bit_valid*/ 1,
7345                                               /*bit*/ 2);
7346                         ctl_done((union ctl_io *)ctsio);
7347                         return (CTL_RETVAL_COMPLETE);
7348                 }
7349                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7350                 break;
7351         case RSO_OPTIONS_OC_SA:
7352                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7353                     service_action >= 32) {
7354                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7355                                               /*sks_valid*/ 1,
7356                                               /*command*/ 1,
7357                                               /*field*/ 2,
7358                                               /*bit_valid*/ 1,
7359                                               /*bit*/ 2);
7360                         ctl_done((union ctl_io *)ctsio);
7361                         return (CTL_RETVAL_COMPLETE);
7362                 }
7363                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7364                 break;
7365         default:
7366                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7367                                       /*sks_valid*/ 1,
7368                                       /*command*/ 1,
7369                                       /*field*/ 2,
7370                                       /*bit_valid*/ 1,
7371                                       /*bit*/ 2);
7372                 ctl_done((union ctl_io *)ctsio);
7373                 return (CTL_RETVAL_COMPLETE);
7374         }
7375
7376         alloc_len = scsi_4btoul(cdb->length);
7377
7378         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7379
7380         ctsio->kern_sg_entries = 0;
7381
7382         if (total_len < alloc_len) {
7383                 ctsio->residual = alloc_len - total_len;
7384                 ctsio->kern_data_len = total_len;
7385                 ctsio->kern_total_len = total_len;
7386         } else {
7387                 ctsio->residual = 0;
7388                 ctsio->kern_data_len = alloc_len;
7389                 ctsio->kern_total_len = alloc_len;
7390         }
7391         ctsio->kern_data_resid = 0;
7392         ctsio->kern_rel_offset = 0;
7393
7394         switch (cdb->options & RSO_OPTIONS_MASK) {
7395         case RSO_OPTIONS_ALL:
7396                 all = (struct scsi_report_supported_opcodes_all *)
7397                     ctsio->kern_data_ptr;
7398                 num = 0;
7399                 for (i = 0; i < 256; i++) {
7400                         entry = &ctl_cmd_table[i];
7401                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7402                                 for (j = 0; j < 32; j++) {
7403                                         sentry = &((const struct ctl_cmd_entry *)
7404                                             entry->execute)[j];
7405                                         if (!ctl_cmd_applicable(
7406                                             lun->be_lun->lun_type, sentry))
7407                                                 continue;
7408                                         descr = &all->descr[num++];
7409                                         descr->opcode = i;
7410                                         scsi_ulto2b(j, descr->service_action);
7411                                         descr->flags = RSO_SERVACTV;
7412                                         scsi_ulto2b(sentry->length,
7413                                             descr->cdb_length);
7414                                 }
7415                         } else {
7416                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7417                                     entry))
7418                                         continue;
7419                                 descr = &all->descr[num++];
7420                                 descr->opcode = i;
7421                                 scsi_ulto2b(0, descr->service_action);
7422                                 descr->flags = 0;
7423                                 scsi_ulto2b(entry->length, descr->cdb_length);
7424                         }
7425                 }
7426                 scsi_ulto4b(
7427                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7428                     all->length);
7429                 break;
7430         case RSO_OPTIONS_OC:
7431                 one = (struct scsi_report_supported_opcodes_one *)
7432                     ctsio->kern_data_ptr;
7433                 entry = &ctl_cmd_table[opcode];
7434                 goto fill_one;
7435         case RSO_OPTIONS_OC_SA:
7436                 one = (struct scsi_report_supported_opcodes_one *)
7437                     ctsio->kern_data_ptr;
7438                 entry = &ctl_cmd_table[opcode];
7439                 entry = &((const struct ctl_cmd_entry *)
7440                     entry->execute)[service_action];
7441 fill_one:
7442                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7443                         one->support = 3;
7444                         scsi_ulto2b(entry->length, one->cdb_length);
7445                         one->cdb_usage[0] = opcode;
7446                         memcpy(&one->cdb_usage[1], entry->usage,
7447                             entry->length - 1);
7448                 } else
7449                         one->support = 1;
7450                 break;
7451         }
7452
7453         ctl_set_success(ctsio);
7454         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7455         ctsio->be_move_done = ctl_config_move_done;
7456         ctl_datamove((union ctl_io *)ctsio);
7457         return(retval);
7458 }
7459
7460 int
7461 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7462 {
7463         struct scsi_report_supported_tmf *cdb;
7464         struct scsi_report_supported_tmf_data *data;
7465         int retval;
7466         int alloc_len, total_len;
7467
7468         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7469
7470         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7471
7472         retval = CTL_RETVAL_COMPLETE;
7473
7474         total_len = sizeof(struct scsi_report_supported_tmf_data);
7475         alloc_len = scsi_4btoul(cdb->length);
7476
7477         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7478
7479         ctsio->kern_sg_entries = 0;
7480
7481         if (total_len < alloc_len) {
7482                 ctsio->residual = alloc_len - total_len;
7483                 ctsio->kern_data_len = total_len;
7484                 ctsio->kern_total_len = total_len;
7485         } else {
7486                 ctsio->residual = 0;
7487                 ctsio->kern_data_len = alloc_len;
7488                 ctsio->kern_total_len = alloc_len;
7489         }
7490         ctsio->kern_data_resid = 0;
7491         ctsio->kern_rel_offset = 0;
7492
7493         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7494         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7495             RST_TRS;
7496         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7497
7498         ctl_set_success(ctsio);
7499         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7500         ctsio->be_move_done = ctl_config_move_done;
7501         ctl_datamove((union ctl_io *)ctsio);
7502         return (retval);
7503 }
7504
7505 int
7506 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7507 {
7508         struct scsi_report_timestamp *cdb;
7509         struct scsi_report_timestamp_data *data;
7510         struct timeval tv;
7511         int64_t timestamp;
7512         int retval;
7513         int alloc_len, total_len;
7514
7515         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7516
7517         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7518
7519         retval = CTL_RETVAL_COMPLETE;
7520
7521         total_len = sizeof(struct scsi_report_timestamp_data);
7522         alloc_len = scsi_4btoul(cdb->length);
7523
7524         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7525
7526         ctsio->kern_sg_entries = 0;
7527
7528         if (total_len < alloc_len) {
7529                 ctsio->residual = alloc_len - total_len;
7530                 ctsio->kern_data_len = total_len;
7531                 ctsio->kern_total_len = total_len;
7532         } else {
7533                 ctsio->residual = 0;
7534                 ctsio->kern_data_len = alloc_len;
7535                 ctsio->kern_total_len = alloc_len;
7536         }
7537         ctsio->kern_data_resid = 0;
7538         ctsio->kern_rel_offset = 0;
7539
7540         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7541         scsi_ulto2b(sizeof(*data) - 2, data->length);
7542         data->origin = RTS_ORIG_OUTSIDE;
7543         getmicrotime(&tv);
7544         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7545         scsi_ulto4b(timestamp >> 16, data->timestamp);
7546         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7547
7548         ctl_set_success(ctsio);
7549         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7550         ctsio->be_move_done = ctl_config_move_done;
7551         ctl_datamove((union ctl_io *)ctsio);
7552         return (retval);
7553 }
7554
7555 int
7556 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7557 {
7558         struct scsi_per_res_in *cdb;
7559         int alloc_len, total_len = 0;
7560         /* struct scsi_per_res_in_rsrv in_data; */
7561         struct ctl_lun *lun;
7562         struct ctl_softc *softc;
7563         uint64_t key;
7564
7565         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7566
7567         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7568
7569         alloc_len = scsi_2btoul(cdb->length);
7570
7571         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7572         softc = lun->ctl_softc;
7573
7574 retry:
7575         mtx_lock(&lun->lun_lock);
7576         switch (cdb->action) {
7577         case SPRI_RK: /* read keys */
7578                 total_len = sizeof(struct scsi_per_res_in_keys) +
7579                         lun->pr_key_count *
7580                         sizeof(struct scsi_per_res_key);
7581                 break;
7582         case SPRI_RR: /* read reservation */
7583                 if (lun->flags & CTL_LUN_PR_RESERVED)
7584                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7585                 else
7586                         total_len = sizeof(struct scsi_per_res_in_header);
7587                 break;
7588         case SPRI_RC: /* report capabilities */
7589                 total_len = sizeof(struct scsi_per_res_cap);
7590                 break;
7591         case SPRI_RS: /* read full status */
7592                 total_len = sizeof(struct scsi_per_res_in_header) +
7593                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7594                     lun->pr_key_count;
7595                 break;
7596         default:
7597                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7598         }
7599         mtx_unlock(&lun->lun_lock);
7600
7601         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7602
7603         if (total_len < alloc_len) {
7604                 ctsio->residual = alloc_len - total_len;
7605                 ctsio->kern_data_len = total_len;
7606                 ctsio->kern_total_len = total_len;
7607         } else {
7608                 ctsio->residual = 0;
7609                 ctsio->kern_data_len = alloc_len;
7610                 ctsio->kern_total_len = alloc_len;
7611         }
7612
7613         ctsio->kern_data_resid = 0;
7614         ctsio->kern_rel_offset = 0;
7615         ctsio->kern_sg_entries = 0;
7616
7617         mtx_lock(&lun->lun_lock);
7618         switch (cdb->action) {
7619         case SPRI_RK: { // read keys
7620         struct scsi_per_res_in_keys *res_keys;
7621                 int i, key_count;
7622
7623                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7624
7625                 /*
7626                  * We had to drop the lock to allocate our buffer, which
7627                  * leaves time for someone to come in with another
7628                  * persistent reservation.  (That is unlikely, though,
7629                  * since this should be the only persistent reservation
7630                  * command active right now.)
7631                  */
7632                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7633                     (lun->pr_key_count *
7634                      sizeof(struct scsi_per_res_key)))){
7635                         mtx_unlock(&lun->lun_lock);
7636                         free(ctsio->kern_data_ptr, M_CTL);
7637                         printf("%s: reservation length changed, retrying\n",
7638                                __func__);
7639                         goto retry;
7640                 }
7641
7642                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7643
7644                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7645                              lun->pr_key_count, res_keys->header.length);
7646
7647                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7648                         if ((key = ctl_get_prkey(lun, i)) == 0)
7649                                 continue;
7650
7651                         /*
7652                          * We used lun->pr_key_count to calculate the
7653                          * size to allocate.  If it turns out the number of
7654                          * initiators with the registered flag set is
7655                          * larger than that (i.e. they haven't been kept in
7656                          * sync), we've got a problem.
7657                          */
7658                         if (key_count >= lun->pr_key_count) {
7659                                 key_count++;
7660                                 continue;
7661                         }
7662                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7663                         key_count++;
7664                 }
7665                 break;
7666         }
7667         case SPRI_RR: { // read reservation
7668                 struct scsi_per_res_in_rsrv *res;
7669                 int tmp_len, header_only;
7670
7671                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7672
7673                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7674
7675                 if (lun->flags & CTL_LUN_PR_RESERVED)
7676                 {
7677                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7678                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7679                                     res->header.length);
7680                         header_only = 0;
7681                 } else {
7682                         tmp_len = sizeof(struct scsi_per_res_in_header);
7683                         scsi_ulto4b(0, res->header.length);
7684                         header_only = 1;
7685                 }
7686
7687                 /*
7688                  * We had to drop the lock to allocate our buffer, which
7689                  * leaves time for someone to come in with another
7690                  * persistent reservation.  (That is unlikely, though,
7691                  * since this should be the only persistent reservation
7692                  * command active right now.)
7693                  */
7694                 if (tmp_len != total_len) {
7695                         mtx_unlock(&lun->lun_lock);
7696                         free(ctsio->kern_data_ptr, M_CTL);
7697                         printf("%s: reservation status changed, retrying\n",
7698                                __func__);
7699                         goto retry;
7700                 }
7701
7702                 /*
7703                  * No reservation held, so we're done.
7704                  */
7705                 if (header_only != 0)
7706                         break;
7707
7708                 /*
7709                  * If the registration is an All Registrants type, the key
7710                  * is 0, since it doesn't really matter.
7711                  */
7712                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7713                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7714                             res->data.reservation);
7715                 }
7716                 res->data.scopetype = lun->pr_res_type;
7717                 break;
7718         }
7719         case SPRI_RC:     //report capabilities
7720         {
7721                 struct scsi_per_res_cap *res_cap;
7722                 uint16_t type_mask;
7723
7724                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7725                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7726                 res_cap->flags1 = SPRI_CRH;
7727                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7728                 type_mask = SPRI_TM_WR_EX_AR |
7729                             SPRI_TM_EX_AC_RO |
7730                             SPRI_TM_WR_EX_RO |
7731                             SPRI_TM_EX_AC |
7732                             SPRI_TM_WR_EX |
7733                             SPRI_TM_EX_AC_AR;
7734                 scsi_ulto2b(type_mask, res_cap->type_mask);
7735                 break;
7736         }
7737         case SPRI_RS: { // read full status
7738                 struct scsi_per_res_in_full *res_status;
7739                 struct scsi_per_res_in_full_desc *res_desc;
7740                 struct ctl_port *port;
7741                 int i, len;
7742
7743                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7744
7745                 /*
7746                  * We had to drop the lock to allocate our buffer, which
7747                  * leaves time for someone to come in with another
7748                  * persistent reservation.  (That is unlikely, though,
7749                  * since this should be the only persistent reservation
7750                  * command active right now.)
7751                  */
7752                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7753                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7754                      lun->pr_key_count)){
7755                         mtx_unlock(&lun->lun_lock);
7756                         free(ctsio->kern_data_ptr, M_CTL);
7757                         printf("%s: reservation length changed, retrying\n",
7758                                __func__);
7759                         goto retry;
7760                 }
7761
7762                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7763
7764                 res_desc = &res_status->desc[0];
7765                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7766                         if ((key = ctl_get_prkey(lun, i)) == 0)
7767                                 continue;
7768
7769                         scsi_u64to8b(key, res_desc->res_key.key);
7770                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7771                             (lun->pr_res_idx == i ||
7772                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7773                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7774                                 res_desc->scopetype = lun->pr_res_type;
7775                         }
7776                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7777                             res_desc->rel_trgt_port_id);
7778                         len = 0;
7779                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7780                         if (port != NULL)
7781                                 len = ctl_create_iid(port,
7782                                     i % CTL_MAX_INIT_PER_PORT,
7783                                     res_desc->transport_id);
7784                         scsi_ulto4b(len, res_desc->additional_length);
7785                         res_desc = (struct scsi_per_res_in_full_desc *)
7786                             &res_desc->transport_id[len];
7787                 }
7788                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7789                     res_status->header.length);
7790                 break;
7791         }
7792         default:
7793                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7794         }
7795         mtx_unlock(&lun->lun_lock);
7796
7797         ctl_set_success(ctsio);
7798         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7799         ctsio->be_move_done = ctl_config_move_done;
7800         ctl_datamove((union ctl_io *)ctsio);
7801         return (CTL_RETVAL_COMPLETE);
7802 }
7803
7804 /*
7805  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7806  * it should return.
7807  */
7808 static int
7809 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7810                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7811                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7812                 struct scsi_per_res_out_parms* param)
7813 {
7814         union ctl_ha_msg persis_io;
7815         int i;
7816
7817         mtx_lock(&lun->lun_lock);
7818         if (sa_res_key == 0) {
7819                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7820                         /* validate scope and type */
7821                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7822                              SPR_LU_SCOPE) {
7823                                 mtx_unlock(&lun->lun_lock);
7824                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7825                                                       /*sks_valid*/ 1,
7826                                                       /*command*/ 1,
7827                                                       /*field*/ 2,
7828                                                       /*bit_valid*/ 1,
7829                                                       /*bit*/ 4);
7830                                 ctl_done((union ctl_io *)ctsio);
7831                                 return (1);
7832                         }
7833
7834                         if (type>8 || type==2 || type==4 || type==0) {
7835                                 mtx_unlock(&lun->lun_lock);
7836                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7837                                                       /*sks_valid*/ 1,
7838                                                       /*command*/ 1,
7839                                                       /*field*/ 2,
7840                                                       /*bit_valid*/ 1,
7841                                                       /*bit*/ 0);
7842                                 ctl_done((union ctl_io *)ctsio);
7843                                 return (1);
7844                         }
7845
7846                         /*
7847                          * Unregister everybody else and build UA for
7848                          * them
7849                          */
7850                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7851                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7852                                         continue;
7853
7854                                 ctl_clr_prkey(lun, i);
7855                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7856                         }
7857                         lun->pr_key_count = 1;
7858                         lun->pr_res_type = type;
7859                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7860                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7861                                 lun->pr_res_idx = residx;
7862                         lun->pr_generation++;
7863                         mtx_unlock(&lun->lun_lock);
7864
7865                         /* send msg to other side */
7866                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7867                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7868                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7869                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7870                         persis_io.pr.pr_info.res_type = type;
7871                         memcpy(persis_io.pr.pr_info.sa_res_key,
7872                                param->serv_act_res_key,
7873                                sizeof(param->serv_act_res_key));
7874                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7875                             sizeof(persis_io.pr), M_WAITOK);
7876                 } else {
7877                         /* not all registrants */
7878                         mtx_unlock(&lun->lun_lock);
7879                         free(ctsio->kern_data_ptr, M_CTL);
7880                         ctl_set_invalid_field(ctsio,
7881                                               /*sks_valid*/ 1,
7882                                               /*command*/ 0,
7883                                               /*field*/ 8,
7884                                               /*bit_valid*/ 0,
7885                                               /*bit*/ 0);
7886                         ctl_done((union ctl_io *)ctsio);
7887                         return (1);
7888                 }
7889         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7890                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7891                 int found = 0;
7892
7893                 if (res_key == sa_res_key) {
7894                         /* special case */
7895                         /*
7896                          * The spec implies this is not good but doesn't
7897                          * say what to do. There are two choices either
7898                          * generate a res conflict or check condition
7899                          * with illegal field in parameter data. Since
7900                          * that is what is done when the sa_res_key is
7901                          * zero I'll take that approach since this has
7902                          * to do with the sa_res_key.
7903                          */
7904                         mtx_unlock(&lun->lun_lock);
7905                         free(ctsio->kern_data_ptr, M_CTL);
7906                         ctl_set_invalid_field(ctsio,
7907                                               /*sks_valid*/ 1,
7908                                               /*command*/ 0,
7909                                               /*field*/ 8,
7910                                               /*bit_valid*/ 0,
7911                                               /*bit*/ 0);
7912                         ctl_done((union ctl_io *)ctsio);
7913                         return (1);
7914                 }
7915
7916                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7917                         if (ctl_get_prkey(lun, i) != sa_res_key)
7918                                 continue;
7919
7920                         found = 1;
7921                         ctl_clr_prkey(lun, i);
7922                         lun->pr_key_count--;
7923                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7924                 }
7925                 if (!found) {
7926                         mtx_unlock(&lun->lun_lock);
7927                         free(ctsio->kern_data_ptr, M_CTL);
7928                         ctl_set_reservation_conflict(ctsio);
7929                         ctl_done((union ctl_io *)ctsio);
7930                         return (CTL_RETVAL_COMPLETE);
7931                 }
7932                 lun->pr_generation++;
7933                 mtx_unlock(&lun->lun_lock);
7934
7935                 /* send msg to other side */
7936                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7937                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7938                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7939                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7940                 persis_io.pr.pr_info.res_type = type;
7941                 memcpy(persis_io.pr.pr_info.sa_res_key,
7942                        param->serv_act_res_key,
7943                        sizeof(param->serv_act_res_key));
7944                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7945                     sizeof(persis_io.pr), M_WAITOK);
7946         } else {
7947                 /* Reserved but not all registrants */
7948                 /* sa_res_key is res holder */
7949                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7950                         /* validate scope and type */
7951                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7952                              SPR_LU_SCOPE) {
7953                                 mtx_unlock(&lun->lun_lock);
7954                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7955                                                       /*sks_valid*/ 1,
7956                                                       /*command*/ 1,
7957                                                       /*field*/ 2,
7958                                                       /*bit_valid*/ 1,
7959                                                       /*bit*/ 4);
7960                                 ctl_done((union ctl_io *)ctsio);
7961                                 return (1);
7962                         }
7963
7964                         if (type>8 || type==2 || type==4 || type==0) {
7965                                 mtx_unlock(&lun->lun_lock);
7966                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7967                                                       /*sks_valid*/ 1,
7968                                                       /*command*/ 1,
7969                                                       /*field*/ 2,
7970                                                       /*bit_valid*/ 1,
7971                                                       /*bit*/ 0);
7972                                 ctl_done((union ctl_io *)ctsio);
7973                                 return (1);
7974                         }
7975
7976                         /*
7977                          * Do the following:
7978                          * if sa_res_key != res_key remove all
7979                          * registrants w/sa_res_key and generate UA
7980                          * for these registrants(Registrations
7981                          * Preempted) if it wasn't an exclusive
7982                          * reservation generate UA(Reservations
7983                          * Preempted) for all other registered nexuses
7984                          * if the type has changed. Establish the new
7985                          * reservation and holder. If res_key and
7986                          * sa_res_key are the same do the above
7987                          * except don't unregister the res holder.
7988                          */
7989
7990                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7991                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7992                                         continue;
7993
7994                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7995                                         ctl_clr_prkey(lun, i);
7996                                         lun->pr_key_count--;
7997                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7998                                 } else if (type != lun->pr_res_type &&
7999                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8000                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8001                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8002                                 }
8003                         }
8004                         lun->pr_res_type = type;
8005                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8006                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8007                                 lun->pr_res_idx = residx;
8008                         else
8009                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8010                         lun->pr_generation++;
8011                         mtx_unlock(&lun->lun_lock);
8012
8013                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8014                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8015                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8016                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8017                         persis_io.pr.pr_info.res_type = type;
8018                         memcpy(persis_io.pr.pr_info.sa_res_key,
8019                                param->serv_act_res_key,
8020                                sizeof(param->serv_act_res_key));
8021                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8022                             sizeof(persis_io.pr), M_WAITOK);
8023                 } else {
8024                         /*
8025                          * sa_res_key is not the res holder just
8026                          * remove registrants
8027                          */
8028                         int found=0;
8029
8030                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8031                                 if (sa_res_key != ctl_get_prkey(lun, i))
8032                                         continue;
8033
8034                                 found = 1;
8035                                 ctl_clr_prkey(lun, i);
8036                                 lun->pr_key_count--;
8037                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8038                         }
8039
8040                         if (!found) {
8041                                 mtx_unlock(&lun->lun_lock);
8042                                 free(ctsio->kern_data_ptr, M_CTL);
8043                                 ctl_set_reservation_conflict(ctsio);
8044                                 ctl_done((union ctl_io *)ctsio);
8045                                 return (1);
8046                         }
8047                         lun->pr_generation++;
8048                         mtx_unlock(&lun->lun_lock);
8049
8050                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8051                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8052                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8053                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8054                         persis_io.pr.pr_info.res_type = type;
8055                         memcpy(persis_io.pr.pr_info.sa_res_key,
8056                                param->serv_act_res_key,
8057                                sizeof(param->serv_act_res_key));
8058                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8059                             sizeof(persis_io.pr), M_WAITOK);
8060                 }
8061         }
8062         return (0);
8063 }
8064
8065 static void
8066 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8067 {
8068         uint64_t sa_res_key;
8069         int i;
8070
8071         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8072
8073         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8074          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8075          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8076                 if (sa_res_key == 0) {
8077                         /*
8078                          * Unregister everybody else and build UA for
8079                          * them
8080                          */
8081                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8082                                 if (i == msg->pr.pr_info.residx ||
8083                                     ctl_get_prkey(lun, i) == 0)
8084                                         continue;
8085
8086                                 ctl_clr_prkey(lun, i);
8087                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8088                         }
8089
8090                         lun->pr_key_count = 1;
8091                         lun->pr_res_type = msg->pr.pr_info.res_type;
8092                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8093                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8094                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8095                 } else {
8096                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8097                                 if (sa_res_key == ctl_get_prkey(lun, i))
8098                                         continue;
8099
8100                                 ctl_clr_prkey(lun, i);
8101                                 lun->pr_key_count--;
8102                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8103                         }
8104                 }
8105         } else {
8106                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8107                         if (i == msg->pr.pr_info.residx ||
8108                             ctl_get_prkey(lun, i) == 0)
8109                                 continue;
8110
8111                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8112                                 ctl_clr_prkey(lun, i);
8113                                 lun->pr_key_count--;
8114                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8115                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8116                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8117                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8118                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8119                         }
8120                 }
8121                 lun->pr_res_type = msg->pr.pr_info.res_type;
8122                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8123                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8124                         lun->pr_res_idx = msg->pr.pr_info.residx;
8125                 else
8126                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8127         }
8128         lun->pr_generation++;
8129
8130 }
8131
8132
8133 int
8134 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8135 {
8136         int retval;
8137         u_int32_t param_len;
8138         struct scsi_per_res_out *cdb;
8139         struct ctl_lun *lun;
8140         struct scsi_per_res_out_parms* param;
8141         struct ctl_softc *softc;
8142         uint32_t residx;
8143         uint64_t res_key, sa_res_key, key;
8144         uint8_t type;
8145         union ctl_ha_msg persis_io;
8146         int    i;
8147
8148         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8149
8150         retval = CTL_RETVAL_COMPLETE;
8151
8152         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8153         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8154         softc = lun->ctl_softc;
8155
8156         /*
8157          * We only support whole-LUN scope.  The scope & type are ignored for
8158          * register, register and ignore existing key and clear.
8159          * We sometimes ignore scope and type on preempts too!!
8160          * Verify reservation type here as well.
8161          */
8162         type = cdb->scope_type & SPR_TYPE_MASK;
8163         if ((cdb->action == SPRO_RESERVE)
8164          || (cdb->action == SPRO_RELEASE)) {
8165                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8166                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8167                                               /*sks_valid*/ 1,
8168                                               /*command*/ 1,
8169                                               /*field*/ 2,
8170                                               /*bit_valid*/ 1,
8171                                               /*bit*/ 4);
8172                         ctl_done((union ctl_io *)ctsio);
8173                         return (CTL_RETVAL_COMPLETE);
8174                 }
8175
8176                 if (type>8 || type==2 || type==4 || type==0) {
8177                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8178                                               /*sks_valid*/ 1,
8179                                               /*command*/ 1,
8180                                               /*field*/ 2,
8181                                               /*bit_valid*/ 1,
8182                                               /*bit*/ 0);
8183                         ctl_done((union ctl_io *)ctsio);
8184                         return (CTL_RETVAL_COMPLETE);
8185                 }
8186         }
8187
8188         param_len = scsi_4btoul(cdb->length);
8189
8190         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8191                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8192                 ctsio->kern_data_len = param_len;
8193                 ctsio->kern_total_len = param_len;
8194                 ctsio->kern_data_resid = 0;
8195                 ctsio->kern_rel_offset = 0;
8196                 ctsio->kern_sg_entries = 0;
8197                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8198                 ctsio->be_move_done = ctl_config_move_done;
8199                 ctl_datamove((union ctl_io *)ctsio);
8200
8201                 return (CTL_RETVAL_COMPLETE);
8202         }
8203
8204         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8205
8206         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8207         res_key = scsi_8btou64(param->res_key.key);
8208         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8209
8210         /*
8211          * Validate the reservation key here except for SPRO_REG_IGNO
8212          * This must be done for all other service actions
8213          */
8214         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8215                 mtx_lock(&lun->lun_lock);
8216                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8217                         if (res_key != key) {
8218                                 /*
8219                                  * The current key passed in doesn't match
8220                                  * the one the initiator previously
8221                                  * registered.
8222                                  */
8223                                 mtx_unlock(&lun->lun_lock);
8224                                 free(ctsio->kern_data_ptr, M_CTL);
8225                                 ctl_set_reservation_conflict(ctsio);
8226                                 ctl_done((union ctl_io *)ctsio);
8227                                 return (CTL_RETVAL_COMPLETE);
8228                         }
8229                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8230                         /*
8231                          * We are not registered
8232                          */
8233                         mtx_unlock(&lun->lun_lock);
8234                         free(ctsio->kern_data_ptr, M_CTL);
8235                         ctl_set_reservation_conflict(ctsio);
8236                         ctl_done((union ctl_io *)ctsio);
8237                         return (CTL_RETVAL_COMPLETE);
8238                 } else if (res_key != 0) {
8239                         /*
8240                          * We are not registered and trying to register but
8241                          * the register key isn't zero.
8242                          */
8243                         mtx_unlock(&lun->lun_lock);
8244                         free(ctsio->kern_data_ptr, M_CTL);
8245                         ctl_set_reservation_conflict(ctsio);
8246                         ctl_done((union ctl_io *)ctsio);
8247                         return (CTL_RETVAL_COMPLETE);
8248                 }
8249                 mtx_unlock(&lun->lun_lock);
8250         }
8251
8252         switch (cdb->action & SPRO_ACTION_MASK) {
8253         case SPRO_REGISTER:
8254         case SPRO_REG_IGNO: {
8255
8256 #if 0
8257                 printf("Registration received\n");
8258 #endif
8259
8260                 /*
8261                  * We don't support any of these options, as we report in
8262                  * the read capabilities request (see
8263                  * ctl_persistent_reserve_in(), above).
8264                  */
8265                 if ((param->flags & SPR_SPEC_I_PT)
8266                  || (param->flags & SPR_ALL_TG_PT)
8267                  || (param->flags & SPR_APTPL)) {
8268                         int bit_ptr;
8269
8270                         if (param->flags & SPR_APTPL)
8271                                 bit_ptr = 0;
8272                         else if (param->flags & SPR_ALL_TG_PT)
8273                                 bit_ptr = 2;
8274                         else /* SPR_SPEC_I_PT */
8275                                 bit_ptr = 3;
8276
8277                         free(ctsio->kern_data_ptr, M_CTL);
8278                         ctl_set_invalid_field(ctsio,
8279                                               /*sks_valid*/ 1,
8280                                               /*command*/ 0,
8281                                               /*field*/ 20,
8282                                               /*bit_valid*/ 1,
8283                                               /*bit*/ bit_ptr);
8284                         ctl_done((union ctl_io *)ctsio);
8285                         return (CTL_RETVAL_COMPLETE);
8286                 }
8287
8288                 mtx_lock(&lun->lun_lock);
8289
8290                 /*
8291                  * The initiator wants to clear the
8292                  * key/unregister.
8293                  */
8294                 if (sa_res_key == 0) {
8295                         if ((res_key == 0
8296                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8297                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8298                           && ctl_get_prkey(lun, residx) == 0)) {
8299                                 mtx_unlock(&lun->lun_lock);
8300                                 goto done;
8301                         }
8302
8303                         ctl_clr_prkey(lun, residx);
8304                         lun->pr_key_count--;
8305
8306                         if (residx == lun->pr_res_idx) {
8307                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8308                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8309
8310                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8311                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8312                                     lun->pr_key_count) {
8313                                         /*
8314                                          * If the reservation is a registrants
8315                                          * only type we need to generate a UA
8316                                          * for other registered inits.  The
8317                                          * sense code should be RESERVATIONS
8318                                          * RELEASED
8319                                          */
8320
8321                                         for (i = softc->init_min; i < softc->init_max; i++){
8322                                                 if (ctl_get_prkey(lun, i) == 0)
8323                                                         continue;
8324                                                 ctl_est_ua(lun, i,
8325                                                     CTL_UA_RES_RELEASE);
8326                                         }
8327                                 }
8328                                 lun->pr_res_type = 0;
8329                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8330                                 if (lun->pr_key_count==0) {
8331                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8332                                         lun->pr_res_type = 0;
8333                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8334                                 }
8335                         }
8336                         lun->pr_generation++;
8337                         mtx_unlock(&lun->lun_lock);
8338
8339                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8340                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8341                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8342                         persis_io.pr.pr_info.residx = residx;
8343                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8344                             sizeof(persis_io.pr), M_WAITOK);
8345                 } else /* sa_res_key != 0 */ {
8346
8347                         /*
8348                          * If we aren't registered currently then increment
8349                          * the key count and set the registered flag.
8350                          */
8351                         ctl_alloc_prkey(lun, residx);
8352                         if (ctl_get_prkey(lun, residx) == 0)
8353                                 lun->pr_key_count++;
8354                         ctl_set_prkey(lun, residx, sa_res_key);
8355                         lun->pr_generation++;
8356                         mtx_unlock(&lun->lun_lock);
8357
8358                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8359                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8360                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8361                         persis_io.pr.pr_info.residx = residx;
8362                         memcpy(persis_io.pr.pr_info.sa_res_key,
8363                                param->serv_act_res_key,
8364                                sizeof(param->serv_act_res_key));
8365                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8366                             sizeof(persis_io.pr), M_WAITOK);
8367                 }
8368
8369                 break;
8370         }
8371         case SPRO_RESERVE:
8372 #if 0
8373                 printf("Reserve executed type %d\n", type);
8374 #endif
8375                 mtx_lock(&lun->lun_lock);
8376                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8377                         /*
8378                          * if this isn't the reservation holder and it's
8379                          * not a "all registrants" type or if the type is
8380                          * different then we have a conflict
8381                          */
8382                         if ((lun->pr_res_idx != residx
8383                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8384                          || lun->pr_res_type != type) {
8385                                 mtx_unlock(&lun->lun_lock);
8386                                 free(ctsio->kern_data_ptr, M_CTL);
8387                                 ctl_set_reservation_conflict(ctsio);
8388                                 ctl_done((union ctl_io *)ctsio);
8389                                 return (CTL_RETVAL_COMPLETE);
8390                         }
8391                         mtx_unlock(&lun->lun_lock);
8392                 } else /* create a reservation */ {
8393                         /*
8394                          * If it's not an "all registrants" type record
8395                          * reservation holder
8396                          */
8397                         if (type != SPR_TYPE_WR_EX_AR
8398                          && type != SPR_TYPE_EX_AC_AR)
8399                                 lun->pr_res_idx = residx; /* Res holder */
8400                         else
8401                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8402
8403                         lun->flags |= CTL_LUN_PR_RESERVED;
8404                         lun->pr_res_type = type;
8405
8406                         mtx_unlock(&lun->lun_lock);
8407
8408                         /* send msg to other side */
8409                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8410                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8411                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8412                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8413                         persis_io.pr.pr_info.res_type = type;
8414                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8415                             sizeof(persis_io.pr), M_WAITOK);
8416                 }
8417                 break;
8418
8419         case SPRO_RELEASE:
8420                 mtx_lock(&lun->lun_lock);
8421                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8422                         /* No reservation exists return good status */
8423                         mtx_unlock(&lun->lun_lock);
8424                         goto done;
8425                 }
8426                 /*
8427                  * Is this nexus a reservation holder?
8428                  */
8429                 if (lun->pr_res_idx != residx
8430                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8431                         /*
8432                          * not a res holder return good status but
8433                          * do nothing
8434                          */
8435                         mtx_unlock(&lun->lun_lock);
8436                         goto done;
8437                 }
8438
8439                 if (lun->pr_res_type != type) {
8440                         mtx_unlock(&lun->lun_lock);
8441                         free(ctsio->kern_data_ptr, M_CTL);
8442                         ctl_set_illegal_pr_release(ctsio);
8443                         ctl_done((union ctl_io *)ctsio);
8444                         return (CTL_RETVAL_COMPLETE);
8445                 }
8446
8447                 /* okay to release */
8448                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8449                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8450                 lun->pr_res_type = 0;
8451
8452                 /*
8453                  * If this isn't an exclusive access reservation and NUAR
8454                  * is not set, generate UA for all other registrants.
8455                  */
8456                 if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8457                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8458                         for (i = softc->init_min; i < softc->init_max; i++) {
8459                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8460                                         continue;
8461                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8462                         }
8463                 }
8464                 mtx_unlock(&lun->lun_lock);
8465
8466                 /* Send msg to other side */
8467                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8468                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8469                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8470                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8471                      sizeof(persis_io.pr), M_WAITOK);
8472                 break;
8473
8474         case SPRO_CLEAR:
8475                 /* send msg to other side */
8476
8477                 mtx_lock(&lun->lun_lock);
8478                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8479                 lun->pr_res_type = 0;
8480                 lun->pr_key_count = 0;
8481                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8482
8483                 ctl_clr_prkey(lun, residx);
8484                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8485                         if (ctl_get_prkey(lun, i) != 0) {
8486                                 ctl_clr_prkey(lun, i);
8487                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8488                         }
8489                 lun->pr_generation++;
8490                 mtx_unlock(&lun->lun_lock);
8491
8492                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8493                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8494                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8495                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8496                      sizeof(persis_io.pr), M_WAITOK);
8497                 break;
8498
8499         case SPRO_PREEMPT:
8500         case SPRO_PRE_ABO: {
8501                 int nretval;
8502
8503                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8504                                           residx, ctsio, cdb, param);
8505                 if (nretval != 0)
8506                         return (CTL_RETVAL_COMPLETE);
8507                 break;
8508         }
8509         default:
8510                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8511         }
8512
8513 done:
8514         free(ctsio->kern_data_ptr, M_CTL);
8515         ctl_set_success(ctsio);
8516         ctl_done((union ctl_io *)ctsio);
8517
8518         return (retval);
8519 }
8520
8521 /*
8522  * This routine is for handling a message from the other SC pertaining to
8523  * persistent reserve out. All the error checking will have been done
8524  * so only perorming the action need be done here to keep the two
8525  * in sync.
8526  */
8527 static void
8528 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8529 {
8530         struct ctl_softc *softc = control_softc;
8531         struct ctl_lun *lun;
8532         int i;
8533         uint32_t residx, targ_lun;
8534
8535         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8536         mtx_lock(&softc->ctl_lock);
8537         if ((targ_lun >= CTL_MAX_LUNS) ||
8538             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8539                 mtx_unlock(&softc->ctl_lock);
8540                 return;
8541         }
8542         mtx_lock(&lun->lun_lock);
8543         mtx_unlock(&softc->ctl_lock);
8544         if (lun->flags & CTL_LUN_DISABLED) {
8545                 mtx_unlock(&lun->lun_lock);
8546                 return;
8547         }
8548         residx = ctl_get_initindex(&msg->hdr.nexus);
8549         switch(msg->pr.pr_info.action) {
8550         case CTL_PR_REG_KEY:
8551                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8552                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8553                         lun->pr_key_count++;
8554                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8555                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8556                 lun->pr_generation++;
8557                 break;
8558
8559         case CTL_PR_UNREG_KEY:
8560                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8561                 lun->pr_key_count--;
8562
8563                 /* XXX Need to see if the reservation has been released */
8564                 /* if so do we need to generate UA? */
8565                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8566                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8567                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8568
8569                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8570                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8571                             lun->pr_key_count) {
8572                                 /*
8573                                  * If the reservation is a registrants
8574                                  * only type we need to generate a UA
8575                                  * for other registered inits.  The
8576                                  * sense code should be RESERVATIONS
8577                                  * RELEASED
8578                                  */
8579
8580                                 for (i = softc->init_min; i < softc->init_max; i++) {
8581                                         if (ctl_get_prkey(lun, i) == 0)
8582                                                 continue;
8583
8584                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8585                                 }
8586                         }
8587                         lun->pr_res_type = 0;
8588                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8589                         if (lun->pr_key_count==0) {
8590                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8591                                 lun->pr_res_type = 0;
8592                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8593                         }
8594                 }
8595                 lun->pr_generation++;
8596                 break;
8597
8598         case CTL_PR_RESERVE:
8599                 lun->flags |= CTL_LUN_PR_RESERVED;
8600                 lun->pr_res_type = msg->pr.pr_info.res_type;
8601                 lun->pr_res_idx = msg->pr.pr_info.residx;
8602
8603                 break;
8604
8605         case CTL_PR_RELEASE:
8606                 /*
8607                  * If this isn't an exclusive access reservation and NUAR
8608                  * is not set, generate UA for all other registrants.
8609                  */
8610                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8611                     lun->pr_res_type != SPR_TYPE_WR_EX &&
8612                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8613                         for (i = softc->init_min; i < softc->init_max; i++)
8614                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8615                                         continue;
8616                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8617                 }
8618
8619                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8620                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8621                 lun->pr_res_type = 0;
8622                 break;
8623
8624         case CTL_PR_PREEMPT:
8625                 ctl_pro_preempt_other(lun, msg);
8626                 break;
8627         case CTL_PR_CLEAR:
8628                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8629                 lun->pr_res_type = 0;
8630                 lun->pr_key_count = 0;
8631                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8632
8633                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8634                         if (ctl_get_prkey(lun, i) == 0)
8635                                 continue;
8636                         ctl_clr_prkey(lun, i);
8637                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8638                 }
8639                 lun->pr_generation++;
8640                 break;
8641         }
8642
8643         mtx_unlock(&lun->lun_lock);
8644 }
8645
8646 int
8647 ctl_read_write(struct ctl_scsiio *ctsio)
8648 {
8649         struct ctl_lun *lun;
8650         struct ctl_lba_len_flags *lbalen;
8651         uint64_t lba;
8652         uint32_t num_blocks;
8653         int flags, retval;
8654         int isread;
8655
8656         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8657
8658         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8659
8660         flags = 0;
8661         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8662               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8663         switch (ctsio->cdb[0]) {
8664         case READ_6:
8665         case WRITE_6: {
8666                 struct scsi_rw_6 *cdb;
8667
8668                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8669
8670                 lba = scsi_3btoul(cdb->addr);
8671                 /* only 5 bits are valid in the most significant address byte */
8672                 lba &= 0x1fffff;
8673                 num_blocks = cdb->length;
8674                 /*
8675                  * This is correct according to SBC-2.
8676                  */
8677                 if (num_blocks == 0)
8678                         num_blocks = 256;
8679                 break;
8680         }
8681         case READ_10:
8682         case WRITE_10: {
8683                 struct scsi_rw_10 *cdb;
8684
8685                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8686                 if (cdb->byte2 & SRW10_FUA)
8687                         flags |= CTL_LLF_FUA;
8688                 if (cdb->byte2 & SRW10_DPO)
8689                         flags |= CTL_LLF_DPO;
8690                 lba = scsi_4btoul(cdb->addr);
8691                 num_blocks = scsi_2btoul(cdb->length);
8692                 break;
8693         }
8694         case WRITE_VERIFY_10: {
8695                 struct scsi_write_verify_10 *cdb;
8696
8697                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8698                 flags |= CTL_LLF_FUA;
8699                 if (cdb->byte2 & SWV_DPO)
8700                         flags |= CTL_LLF_DPO;
8701                 lba = scsi_4btoul(cdb->addr);
8702                 num_blocks = scsi_2btoul(cdb->length);
8703                 break;
8704         }
8705         case READ_12:
8706         case WRITE_12: {
8707                 struct scsi_rw_12 *cdb;
8708
8709                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8710                 if (cdb->byte2 & SRW12_FUA)
8711                         flags |= CTL_LLF_FUA;
8712                 if (cdb->byte2 & SRW12_DPO)
8713                         flags |= CTL_LLF_DPO;
8714                 lba = scsi_4btoul(cdb->addr);
8715                 num_blocks = scsi_4btoul(cdb->length);
8716                 break;
8717         }
8718         case WRITE_VERIFY_12: {
8719                 struct scsi_write_verify_12 *cdb;
8720
8721                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8722                 flags |= CTL_LLF_FUA;
8723                 if (cdb->byte2 & SWV_DPO)
8724                         flags |= CTL_LLF_DPO;
8725                 lba = scsi_4btoul(cdb->addr);
8726                 num_blocks = scsi_4btoul(cdb->length);
8727                 break;
8728         }
8729         case READ_16:
8730         case WRITE_16: {
8731                 struct scsi_rw_16 *cdb;
8732
8733                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8734                 if (cdb->byte2 & SRW12_FUA)
8735                         flags |= CTL_LLF_FUA;
8736                 if (cdb->byte2 & SRW12_DPO)
8737                         flags |= CTL_LLF_DPO;
8738                 lba = scsi_8btou64(cdb->addr);
8739                 num_blocks = scsi_4btoul(cdb->length);
8740                 break;
8741         }
8742         case WRITE_ATOMIC_16: {
8743                 struct scsi_write_atomic_16 *cdb;
8744
8745                 if (lun->be_lun->atomicblock == 0) {
8746                         ctl_set_invalid_opcode(ctsio);
8747                         ctl_done((union ctl_io *)ctsio);
8748                         return (CTL_RETVAL_COMPLETE);
8749                 }
8750
8751                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8752                 if (cdb->byte2 & SRW12_FUA)
8753                         flags |= CTL_LLF_FUA;
8754                 if (cdb->byte2 & SRW12_DPO)
8755                         flags |= CTL_LLF_DPO;
8756                 lba = scsi_8btou64(cdb->addr);
8757                 num_blocks = scsi_2btoul(cdb->length);
8758                 if (num_blocks > lun->be_lun->atomicblock) {
8759                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8760                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8761                             /*bit*/ 0);
8762                         ctl_done((union ctl_io *)ctsio);
8763                         return (CTL_RETVAL_COMPLETE);
8764                 }
8765                 break;
8766         }
8767         case WRITE_VERIFY_16: {
8768                 struct scsi_write_verify_16 *cdb;
8769
8770                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8771                 flags |= CTL_LLF_FUA;
8772                 if (cdb->byte2 & SWV_DPO)
8773                         flags |= CTL_LLF_DPO;
8774                 lba = scsi_8btou64(cdb->addr);
8775                 num_blocks = scsi_4btoul(cdb->length);
8776                 break;
8777         }
8778         default:
8779                 /*
8780                  * We got a command we don't support.  This shouldn't
8781                  * happen, commands should be filtered out above us.
8782                  */
8783                 ctl_set_invalid_opcode(ctsio);
8784                 ctl_done((union ctl_io *)ctsio);
8785
8786                 return (CTL_RETVAL_COMPLETE);
8787                 break; /* NOTREACHED */
8788         }
8789
8790         /*
8791          * The first check is to make sure we're in bounds, the second
8792          * check is to catch wrap-around problems.  If the lba + num blocks
8793          * is less than the lba, then we've wrapped around and the block
8794          * range is invalid anyway.
8795          */
8796         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8797          || ((lba + num_blocks) < lba)) {
8798                 ctl_set_lba_out_of_range(ctsio,
8799                     MAX(lba, lun->be_lun->maxlba + 1));
8800                 ctl_done((union ctl_io *)ctsio);
8801                 return (CTL_RETVAL_COMPLETE);
8802         }
8803
8804         /*
8805          * According to SBC-3, a transfer length of 0 is not an error.
8806          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8807          * translates to 256 blocks for those commands.
8808          */
8809         if (num_blocks == 0) {
8810                 ctl_set_success(ctsio);
8811                 ctl_done((union ctl_io *)ctsio);
8812                 return (CTL_RETVAL_COMPLETE);
8813         }
8814
8815         /* Set FUA and/or DPO if caches are disabled. */
8816         if (isread) {
8817                 if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8818                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8819         } else {
8820                 if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8821                         flags |= CTL_LLF_FUA;
8822         }
8823
8824         lbalen = (struct ctl_lba_len_flags *)
8825             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8826         lbalen->lba = lba;
8827         lbalen->len = num_blocks;
8828         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8829
8830         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8831         ctsio->kern_rel_offset = 0;
8832
8833         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8834
8835         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8836         return (retval);
8837 }
8838
8839 static int
8840 ctl_cnw_cont(union ctl_io *io)
8841 {
8842         struct ctl_scsiio *ctsio;
8843         struct ctl_lun *lun;
8844         struct ctl_lba_len_flags *lbalen;
8845         int retval;
8846
8847         ctsio = &io->scsiio;
8848         ctsio->io_hdr.status = CTL_STATUS_NONE;
8849         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8850         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8851         lbalen = (struct ctl_lba_len_flags *)
8852             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8853         lbalen->flags &= ~CTL_LLF_COMPARE;
8854         lbalen->flags |= CTL_LLF_WRITE;
8855
8856         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8857         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8858         return (retval);
8859 }
8860
8861 int
8862 ctl_cnw(struct ctl_scsiio *ctsio)
8863 {
8864         struct ctl_lun *lun;
8865         struct ctl_lba_len_flags *lbalen;
8866         uint64_t lba;
8867         uint32_t num_blocks;
8868         int flags, retval;
8869
8870         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8871
8872         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8873
8874         flags = 0;
8875         switch (ctsio->cdb[0]) {
8876         case COMPARE_AND_WRITE: {
8877                 struct scsi_compare_and_write *cdb;
8878
8879                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8880                 if (cdb->byte2 & SRW10_FUA)
8881                         flags |= CTL_LLF_FUA;
8882                 if (cdb->byte2 & SRW10_DPO)
8883                         flags |= CTL_LLF_DPO;
8884                 lba = scsi_8btou64(cdb->addr);
8885                 num_blocks = cdb->length;
8886                 break;
8887         }
8888         default:
8889                 /*
8890                  * We got a command we don't support.  This shouldn't
8891                  * happen, commands should be filtered out above us.
8892                  */
8893                 ctl_set_invalid_opcode(ctsio);
8894                 ctl_done((union ctl_io *)ctsio);
8895
8896                 return (CTL_RETVAL_COMPLETE);
8897                 break; /* NOTREACHED */
8898         }
8899
8900         /*
8901          * The first check is to make sure we're in bounds, the second
8902          * check is to catch wrap-around problems.  If the lba + num blocks
8903          * is less than the lba, then we've wrapped around and the block
8904          * range is invalid anyway.
8905          */
8906         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8907          || ((lba + num_blocks) < lba)) {
8908                 ctl_set_lba_out_of_range(ctsio,
8909                     MAX(lba, lun->be_lun->maxlba + 1));
8910                 ctl_done((union ctl_io *)ctsio);
8911                 return (CTL_RETVAL_COMPLETE);
8912         }
8913
8914         /*
8915          * According to SBC-3, a transfer length of 0 is not an error.
8916          */
8917         if (num_blocks == 0) {
8918                 ctl_set_success(ctsio);
8919                 ctl_done((union ctl_io *)ctsio);
8920                 return (CTL_RETVAL_COMPLETE);
8921         }
8922
8923         /* Set FUA if write cache is disabled. */
8924         if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8925                 flags |= CTL_LLF_FUA;
8926
8927         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8928         ctsio->kern_rel_offset = 0;
8929
8930         /*
8931          * Set the IO_CONT flag, so that if this I/O gets passed to
8932          * ctl_data_submit_done(), it'll get passed back to
8933          * ctl_ctl_cnw_cont() for further processing.
8934          */
8935         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8936         ctsio->io_cont = ctl_cnw_cont;
8937
8938         lbalen = (struct ctl_lba_len_flags *)
8939             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8940         lbalen->lba = lba;
8941         lbalen->len = num_blocks;
8942         lbalen->flags = CTL_LLF_COMPARE | flags;
8943
8944         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8945         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8946         return (retval);
8947 }
8948
8949 int
8950 ctl_verify(struct ctl_scsiio *ctsio)
8951 {
8952         struct ctl_lun *lun;
8953         struct ctl_lba_len_flags *lbalen;
8954         uint64_t lba;
8955         uint32_t num_blocks;
8956         int bytchk, flags;
8957         int retval;
8958
8959         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8960
8961         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8962
8963         bytchk = 0;
8964         flags = CTL_LLF_FUA;
8965         switch (ctsio->cdb[0]) {
8966         case VERIFY_10: {
8967                 struct scsi_verify_10 *cdb;
8968
8969                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8970                 if (cdb->byte2 & SVFY_BYTCHK)
8971                         bytchk = 1;
8972                 if (cdb->byte2 & SVFY_DPO)
8973                         flags |= CTL_LLF_DPO;
8974                 lba = scsi_4btoul(cdb->addr);
8975                 num_blocks = scsi_2btoul(cdb->length);
8976                 break;
8977         }
8978         case VERIFY_12: {
8979                 struct scsi_verify_12 *cdb;
8980
8981                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8982                 if (cdb->byte2 & SVFY_BYTCHK)
8983                         bytchk = 1;
8984                 if (cdb->byte2 & SVFY_DPO)
8985                         flags |= CTL_LLF_DPO;
8986                 lba = scsi_4btoul(cdb->addr);
8987                 num_blocks = scsi_4btoul(cdb->length);
8988                 break;
8989         }
8990         case VERIFY_16: {
8991                 struct scsi_rw_16 *cdb;
8992
8993                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8994                 if (cdb->byte2 & SVFY_BYTCHK)
8995                         bytchk = 1;
8996                 if (cdb->byte2 & SVFY_DPO)
8997                         flags |= CTL_LLF_DPO;
8998                 lba = scsi_8btou64(cdb->addr);
8999                 num_blocks = scsi_4btoul(cdb->length);
9000                 break;
9001         }
9002         default:
9003                 /*
9004                  * We got a command we don't support.  This shouldn't
9005                  * happen, commands should be filtered out above us.
9006                  */
9007                 ctl_set_invalid_opcode(ctsio);
9008                 ctl_done((union ctl_io *)ctsio);
9009                 return (CTL_RETVAL_COMPLETE);
9010         }
9011
9012         /*
9013          * The first check is to make sure we're in bounds, the second
9014          * check is to catch wrap-around problems.  If the lba + num blocks
9015          * is less than the lba, then we've wrapped around and the block
9016          * range is invalid anyway.
9017          */
9018         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9019          || ((lba + num_blocks) < lba)) {
9020                 ctl_set_lba_out_of_range(ctsio,
9021                     MAX(lba, lun->be_lun->maxlba + 1));
9022                 ctl_done((union ctl_io *)ctsio);
9023                 return (CTL_RETVAL_COMPLETE);
9024         }
9025
9026         /*
9027          * According to SBC-3, a transfer length of 0 is not an error.
9028          */
9029         if (num_blocks == 0) {
9030                 ctl_set_success(ctsio);
9031                 ctl_done((union ctl_io *)ctsio);
9032                 return (CTL_RETVAL_COMPLETE);
9033         }
9034
9035         lbalen = (struct ctl_lba_len_flags *)
9036             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9037         lbalen->lba = lba;
9038         lbalen->len = num_blocks;
9039         if (bytchk) {
9040                 lbalen->flags = CTL_LLF_COMPARE | flags;
9041                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9042         } else {
9043                 lbalen->flags = CTL_LLF_VERIFY | flags;
9044                 ctsio->kern_total_len = 0;
9045         }
9046         ctsio->kern_rel_offset = 0;
9047
9048         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9049         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9050         return (retval);
9051 }
9052
9053 int
9054 ctl_report_luns(struct ctl_scsiio *ctsio)
9055 {
9056         struct ctl_softc *softc;
9057         struct scsi_report_luns *cdb;
9058         struct scsi_report_luns_data *lun_data;
9059         struct ctl_lun *lun, *request_lun;
9060         struct ctl_port *port;
9061         int num_luns, retval;
9062         uint32_t alloc_len, lun_datalen;
9063         int num_filled;
9064         uint32_t initidx, targ_lun_id, lun_id;
9065
9066         retval = CTL_RETVAL_COMPLETE;
9067         cdb = (struct scsi_report_luns *)ctsio->cdb;
9068         port = ctl_io_port(&ctsio->io_hdr);
9069         softc = port->ctl_softc;
9070
9071         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9072
9073         mtx_lock(&softc->ctl_lock);
9074         num_luns = 0;
9075         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9076                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9077                         num_luns++;
9078         }
9079         mtx_unlock(&softc->ctl_lock);
9080
9081         switch (cdb->select_report) {
9082         case RPL_REPORT_DEFAULT:
9083         case RPL_REPORT_ALL:
9084         case RPL_REPORT_NONSUBSID:
9085                 break;
9086         case RPL_REPORT_WELLKNOWN:
9087         case RPL_REPORT_ADMIN:
9088         case RPL_REPORT_CONGLOM:
9089                 num_luns = 0;
9090                 break;
9091         default:
9092                 ctl_set_invalid_field(ctsio,
9093                                       /*sks_valid*/ 1,
9094                                       /*command*/ 1,
9095                                       /*field*/ 2,
9096                                       /*bit_valid*/ 0,
9097                                       /*bit*/ 0);
9098                 ctl_done((union ctl_io *)ctsio);
9099                 return (retval);
9100                 break; /* NOTREACHED */
9101         }
9102
9103         alloc_len = scsi_4btoul(cdb->length);
9104         /*
9105          * The initiator has to allocate at least 16 bytes for this request,
9106          * so he can at least get the header and the first LUN.  Otherwise
9107          * we reject the request (per SPC-3 rev 14, section 6.21).
9108          */
9109         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9110             sizeof(struct scsi_report_luns_lundata))) {
9111                 ctl_set_invalid_field(ctsio,
9112                                       /*sks_valid*/ 1,
9113                                       /*command*/ 1,
9114                                       /*field*/ 6,
9115                                       /*bit_valid*/ 0,
9116                                       /*bit*/ 0);
9117                 ctl_done((union ctl_io *)ctsio);
9118                 return (retval);
9119         }
9120
9121         request_lun = (struct ctl_lun *)
9122                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9123
9124         lun_datalen = sizeof(*lun_data) +
9125                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9126
9127         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9128         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9129         ctsio->kern_sg_entries = 0;
9130
9131         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9132
9133         mtx_lock(&softc->ctl_lock);
9134         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9135                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9136                 if (lun_id >= CTL_MAX_LUNS)
9137                         continue;
9138                 lun = softc->ctl_luns[lun_id];
9139                 if (lun == NULL)
9140                         continue;
9141
9142                 be64enc(lun_data->luns[num_filled++].lundata,
9143                     ctl_encode_lun(targ_lun_id));
9144
9145                 /*
9146                  * According to SPC-3, rev 14 section 6.21:
9147                  *
9148                  * "The execution of a REPORT LUNS command to any valid and
9149                  * installed logical unit shall clear the REPORTED LUNS DATA
9150                  * HAS CHANGED unit attention condition for all logical
9151                  * units of that target with respect to the requesting
9152                  * initiator. A valid and installed logical unit is one
9153                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9154                  * INQUIRY data (see 6.4.2)."
9155                  *
9156                  * If request_lun is NULL, the LUN this report luns command
9157                  * was issued to is either disabled or doesn't exist. In that
9158                  * case, we shouldn't clear any pending lun change unit
9159                  * attention.
9160                  */
9161                 if (request_lun != NULL) {
9162                         mtx_lock(&lun->lun_lock);
9163                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9164                         mtx_unlock(&lun->lun_lock);
9165                 }
9166         }
9167         mtx_unlock(&softc->ctl_lock);
9168
9169         /*
9170          * It's quite possible that we've returned fewer LUNs than we allocated
9171          * space for.  Trim it.
9172          */
9173         lun_datalen = sizeof(*lun_data) +
9174                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9175
9176         if (lun_datalen < alloc_len) {
9177                 ctsio->residual = alloc_len - lun_datalen;
9178                 ctsio->kern_data_len = lun_datalen;
9179                 ctsio->kern_total_len = lun_datalen;
9180         } else {
9181                 ctsio->residual = 0;
9182                 ctsio->kern_data_len = alloc_len;
9183                 ctsio->kern_total_len = alloc_len;
9184         }
9185         ctsio->kern_data_resid = 0;
9186         ctsio->kern_rel_offset = 0;
9187         ctsio->kern_sg_entries = 0;
9188
9189         /*
9190          * We set this to the actual data length, regardless of how much
9191          * space we actually have to return results.  If the user looks at
9192          * this value, he'll know whether or not he allocated enough space
9193          * and reissue the command if necessary.  We don't support well
9194          * known logical units, so if the user asks for that, return none.
9195          */
9196         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9197
9198         /*
9199          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9200          * this request.
9201          */
9202         ctl_set_success(ctsio);
9203         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9204         ctsio->be_move_done = ctl_config_move_done;
9205         ctl_datamove((union ctl_io *)ctsio);
9206         return (retval);
9207 }
9208
9209 int
9210 ctl_request_sense(struct ctl_scsiio *ctsio)
9211 {
9212         struct scsi_request_sense *cdb;
9213         struct scsi_sense_data *sense_ptr;
9214         struct ctl_softc *softc;
9215         struct ctl_lun *lun;
9216         uint32_t initidx;
9217         int have_error;
9218         scsi_sense_data_type sense_format;
9219         ctl_ua_type ua_type;
9220         uint8_t asc = 0, ascq = 0;
9221
9222         cdb = (struct scsi_request_sense *)ctsio->cdb;
9223
9224         softc = control_softc;
9225         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9226
9227         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9228
9229         /*
9230          * Determine which sense format the user wants.
9231          */
9232         if (cdb->byte2 & SRS_DESC)
9233                 sense_format = SSD_TYPE_DESC;
9234         else
9235                 sense_format = SSD_TYPE_FIXED;
9236
9237         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9238         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9239         ctsio->kern_sg_entries = 0;
9240
9241         /*
9242          * struct scsi_sense_data, which is currently set to 256 bytes, is
9243          * larger than the largest allowed value for the length field in the
9244          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9245          */
9246         ctsio->residual = 0;
9247         ctsio->kern_data_len = cdb->length;
9248         ctsio->kern_total_len = cdb->length;
9249
9250         ctsio->kern_data_resid = 0;
9251         ctsio->kern_rel_offset = 0;
9252         ctsio->kern_sg_entries = 0;
9253
9254         /*
9255          * If we don't have a LUN, we don't have any pending sense.
9256          */
9257         if (lun == NULL ||
9258             ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9259              softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9260                 /* "Logical unit not supported" */
9261                 ctl_set_sense_data(sense_ptr, NULL, sense_format,
9262                     /*current_error*/ 1,
9263                     /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9264                     /*asc*/ 0x25,
9265                     /*ascq*/ 0x00,
9266                     SSD_ELEM_NONE);
9267                 goto send;
9268         }
9269
9270         have_error = 0;
9271         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9272         /*
9273          * Check for pending sense, and then for pending unit attentions.
9274          * Pending sense gets returned first, then pending unit attentions.
9275          */
9276         mtx_lock(&lun->lun_lock);
9277 #ifdef CTL_WITH_CA
9278         if (ctl_is_set(lun->have_ca, initidx)) {
9279                 scsi_sense_data_type stored_format;
9280
9281                 /*
9282                  * Check to see which sense format was used for the stored
9283                  * sense data.
9284                  */
9285                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9286
9287                 /*
9288                  * If the user requested a different sense format than the
9289                  * one we stored, then we need to convert it to the other
9290                  * format.  If we're going from descriptor to fixed format
9291                  * sense data, we may lose things in translation, depending
9292                  * on what options were used.
9293                  *
9294                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9295                  * for some reason we'll just copy it out as-is.
9296                  */
9297                 if ((stored_format == SSD_TYPE_FIXED)
9298                  && (sense_format == SSD_TYPE_DESC))
9299                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9300                             &lun->pending_sense[initidx],
9301                             (struct scsi_sense_data_desc *)sense_ptr);
9302                 else if ((stored_format == SSD_TYPE_DESC)
9303                       && (sense_format == SSD_TYPE_FIXED))
9304                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9305                             &lun->pending_sense[initidx],
9306                             (struct scsi_sense_data_fixed *)sense_ptr);
9307                 else
9308                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9309                                MIN(sizeof(*sense_ptr),
9310                                sizeof(lun->pending_sense[initidx])));
9311
9312                 ctl_clear_mask(lun->have_ca, initidx);
9313                 have_error = 1;
9314         } else
9315 #endif
9316         if (have_error == 0) {
9317                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9318                 if (ua_type != CTL_UA_NONE)
9319                         have_error = 1;
9320                 if (ua_type == CTL_UA_LUN_CHANGE) {
9321                         mtx_unlock(&lun->lun_lock);
9322                         mtx_lock(&softc->ctl_lock);
9323                         ctl_clr_ua_allluns(softc, initidx, ua_type);
9324                         mtx_unlock(&softc->ctl_lock);
9325                         mtx_lock(&lun->lun_lock);
9326                 }
9327         }
9328         if (have_error == 0) {
9329                 /*
9330                  * Report informational exception if have one and allowed.
9331                  */
9332                 if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9333                         asc = lun->ie_asc;
9334                         ascq = lun->ie_ascq;
9335                 }
9336                 ctl_set_sense_data(sense_ptr, lun, sense_format,
9337                     /*current_error*/ 1,
9338                     /*sense_key*/ SSD_KEY_NO_SENSE,
9339                     /*asc*/ asc,
9340                     /*ascq*/ ascq,
9341                     SSD_ELEM_NONE);
9342         }
9343         mtx_unlock(&lun->lun_lock);
9344
9345 send:
9346         /*
9347          * We report the SCSI status as OK, since the status of the command
9348          * itself is OK.  We're reporting sense as parameter data.
9349          */
9350         ctl_set_success(ctsio);
9351         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9352         ctsio->be_move_done = ctl_config_move_done;
9353         ctl_datamove((union ctl_io *)ctsio);
9354         return (CTL_RETVAL_COMPLETE);
9355 }
9356
9357 int
9358 ctl_tur(struct ctl_scsiio *ctsio)
9359 {
9360
9361         CTL_DEBUG_PRINT(("ctl_tur\n"));
9362
9363         ctl_set_success(ctsio);
9364         ctl_done((union ctl_io *)ctsio);
9365
9366         return (CTL_RETVAL_COMPLETE);
9367 }
9368
9369 /*
9370  * SCSI VPD page 0x00, the Supported VPD Pages page.
9371  */
9372 static int
9373 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9374 {
9375         struct scsi_vpd_supported_pages *pages;
9376         int sup_page_size;
9377         struct ctl_lun *lun;
9378         int p;
9379
9380         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9381
9382         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9383             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9384         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9385         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9386         ctsio->kern_sg_entries = 0;
9387
9388         if (sup_page_size < alloc_len) {
9389                 ctsio->residual = alloc_len - sup_page_size;
9390                 ctsio->kern_data_len = sup_page_size;
9391                 ctsio->kern_total_len = sup_page_size;
9392         } else {
9393                 ctsio->residual = 0;
9394                 ctsio->kern_data_len = alloc_len;
9395                 ctsio->kern_total_len = alloc_len;
9396         }
9397         ctsio->kern_data_resid = 0;
9398         ctsio->kern_rel_offset = 0;
9399         ctsio->kern_sg_entries = 0;
9400
9401         /*
9402          * The control device is always connected.  The disk device, on the
9403          * other hand, may not be online all the time.  Need to change this
9404          * to figure out whether the disk device is actually online or not.
9405          */
9406         if (lun != NULL)
9407                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9408                                 lun->be_lun->lun_type;
9409         else
9410                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9411
9412         p = 0;
9413         /* Supported VPD pages */
9414         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9415         /* Serial Number */
9416         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9417         /* Device Identification */
9418         pages->page_list[p++] = SVPD_DEVICE_ID;
9419         /* Extended INQUIRY Data */
9420         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9421         /* Mode Page Policy */
9422         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9423         /* SCSI Ports */
9424         pages->page_list[p++] = SVPD_SCSI_PORTS;
9425         /* Third-party Copy */
9426         pages->page_list[p++] = SVPD_SCSI_TPC;
9427         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9428                 /* Block limits */
9429                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9430                 /* Block Device Characteristics */
9431                 pages->page_list[p++] = SVPD_BDC;
9432                 /* Logical Block Provisioning */
9433                 pages->page_list[p++] = SVPD_LBP;
9434         }
9435         pages->length = p;
9436
9437         ctl_set_success(ctsio);
9438         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9439         ctsio->be_move_done = ctl_config_move_done;
9440         ctl_datamove((union ctl_io *)ctsio);
9441         return (CTL_RETVAL_COMPLETE);
9442 }
9443
9444 /*
9445  * SCSI VPD page 0x80, the Unit Serial Number page.
9446  */
9447 static int
9448 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9449 {
9450         struct scsi_vpd_unit_serial_number *sn_ptr;
9451         struct ctl_lun *lun;
9452         int data_len;
9453
9454         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9455
9456         data_len = 4 + CTL_SN_LEN;
9457         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9458         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9459         if (data_len < alloc_len) {
9460                 ctsio->residual = alloc_len - data_len;
9461                 ctsio->kern_data_len = data_len;
9462                 ctsio->kern_total_len = data_len;
9463         } else {
9464                 ctsio->residual = 0;
9465                 ctsio->kern_data_len = alloc_len;
9466                 ctsio->kern_total_len = alloc_len;
9467         }
9468         ctsio->kern_data_resid = 0;
9469         ctsio->kern_rel_offset = 0;
9470         ctsio->kern_sg_entries = 0;
9471
9472         /*
9473          * The control device is always connected.  The disk device, on the
9474          * other hand, may not be online all the time.  Need to change this
9475          * to figure out whether the disk device is actually online or not.
9476          */
9477         if (lun != NULL)
9478                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9479                                   lun->be_lun->lun_type;
9480         else
9481                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9482
9483         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9484         sn_ptr->length = CTL_SN_LEN;
9485         /*
9486          * If we don't have a LUN, we just leave the serial number as
9487          * all spaces.
9488          */
9489         if (lun != NULL) {
9490                 strncpy((char *)sn_ptr->serial_num,
9491                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9492         } else
9493                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9494
9495         ctl_set_success(ctsio);
9496         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9497         ctsio->be_move_done = ctl_config_move_done;
9498         ctl_datamove((union ctl_io *)ctsio);
9499         return (CTL_RETVAL_COMPLETE);
9500 }
9501
9502
9503 /*
9504  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9505  */
9506 static int
9507 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9508 {
9509         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9510         struct ctl_lun *lun;
9511         int data_len;
9512
9513         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9514
9515         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9516         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9517         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9518         ctsio->kern_sg_entries = 0;
9519
9520         if (data_len < alloc_len) {
9521                 ctsio->residual = alloc_len - data_len;
9522                 ctsio->kern_data_len = data_len;
9523                 ctsio->kern_total_len = data_len;
9524         } else {
9525                 ctsio->residual = 0;
9526                 ctsio->kern_data_len = alloc_len;
9527                 ctsio->kern_total_len = alloc_len;
9528         }
9529         ctsio->kern_data_resid = 0;
9530         ctsio->kern_rel_offset = 0;
9531         ctsio->kern_sg_entries = 0;
9532
9533         /*
9534          * The control device is always connected.  The disk device, on the
9535          * other hand, may not be online all the time.
9536          */
9537         if (lun != NULL)
9538                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9539                                      lun->be_lun->lun_type;
9540         else
9541                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9542         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9543         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9544         /*
9545          * We support head of queue, ordered and simple tags.
9546          */
9547         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9548         /*
9549          * Volatile cache supported.
9550          */
9551         eid_ptr->flags3 = SVPD_EID_V_SUP;
9552
9553         /*
9554          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9555          * attention for a particular IT nexus on all LUNs once we report
9556          * it to that nexus once.  This bit is required as of SPC-4.
9557          */
9558         eid_ptr->flags4 = SVPD_EID_LUICLR;
9559
9560         /*
9561          * XXX KDM in order to correctly answer this, we would need
9562          * information from the SIM to determine how much sense data it
9563          * can send.  So this would really be a path inquiry field, most
9564          * likely.  This can be set to a maximum of 252 according to SPC-4,
9565          * but the hardware may or may not be able to support that much.
9566          * 0 just means that the maximum sense data length is not reported.
9567          */
9568         eid_ptr->max_sense_length = 0;
9569
9570         ctl_set_success(ctsio);
9571         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9572         ctsio->be_move_done = ctl_config_move_done;
9573         ctl_datamove((union ctl_io *)ctsio);
9574         return (CTL_RETVAL_COMPLETE);
9575 }
9576
9577 static int
9578 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9579 {
9580         struct scsi_vpd_mode_page_policy *mpp_ptr;
9581         struct ctl_lun *lun;
9582         int data_len;
9583
9584         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9585
9586         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9587             sizeof(struct scsi_vpd_mode_page_policy_descr);
9588
9589         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9590         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9591         ctsio->kern_sg_entries = 0;
9592
9593         if (data_len < alloc_len) {
9594                 ctsio->residual = alloc_len - data_len;
9595                 ctsio->kern_data_len = data_len;
9596                 ctsio->kern_total_len = data_len;
9597         } else {
9598                 ctsio->residual = 0;
9599                 ctsio->kern_data_len = alloc_len;
9600                 ctsio->kern_total_len = alloc_len;
9601         }
9602         ctsio->kern_data_resid = 0;
9603         ctsio->kern_rel_offset = 0;
9604         ctsio->kern_sg_entries = 0;
9605
9606         /*
9607          * The control device is always connected.  The disk device, on the
9608          * other hand, may not be online all the time.
9609          */
9610         if (lun != NULL)
9611                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9612                                      lun->be_lun->lun_type;
9613         else
9614                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9615         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9616         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9617         mpp_ptr->descr[0].page_code = 0x3f;
9618         mpp_ptr->descr[0].subpage_code = 0xff;
9619         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9620
9621         ctl_set_success(ctsio);
9622         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9623         ctsio->be_move_done = ctl_config_move_done;
9624         ctl_datamove((union ctl_io *)ctsio);
9625         return (CTL_RETVAL_COMPLETE);
9626 }
9627
9628 /*
9629  * SCSI VPD page 0x83, the Device Identification page.
9630  */
9631 static int
9632 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9633 {
9634         struct scsi_vpd_device_id *devid_ptr;
9635         struct scsi_vpd_id_descriptor *desc;
9636         struct ctl_softc *softc;
9637         struct ctl_lun *lun;
9638         struct ctl_port *port;
9639         int data_len, g;
9640         uint8_t proto;
9641
9642         softc = control_softc;
9643
9644         port = ctl_io_port(&ctsio->io_hdr);
9645         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9646
9647         data_len = sizeof(struct scsi_vpd_device_id) +
9648             sizeof(struct scsi_vpd_id_descriptor) +
9649                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9650             sizeof(struct scsi_vpd_id_descriptor) +
9651                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9652         if (lun && lun->lun_devid)
9653                 data_len += lun->lun_devid->len;
9654         if (port && port->port_devid)
9655                 data_len += port->port_devid->len;
9656         if (port && port->target_devid)
9657                 data_len += port->target_devid->len;
9658
9659         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9660         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9661         ctsio->kern_sg_entries = 0;
9662
9663         if (data_len < alloc_len) {
9664                 ctsio->residual = alloc_len - data_len;
9665                 ctsio->kern_data_len = data_len;
9666                 ctsio->kern_total_len = data_len;
9667         } else {
9668                 ctsio->residual = 0;
9669                 ctsio->kern_data_len = alloc_len;
9670                 ctsio->kern_total_len = alloc_len;
9671         }
9672         ctsio->kern_data_resid = 0;
9673         ctsio->kern_rel_offset = 0;
9674         ctsio->kern_sg_entries = 0;
9675
9676         /*
9677          * The control device is always connected.  The disk device, on the
9678          * other hand, may not be online all the time.
9679          */
9680         if (lun != NULL)
9681                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9682                                      lun->be_lun->lun_type;
9683         else
9684                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9685         devid_ptr->page_code = SVPD_DEVICE_ID;
9686         scsi_ulto2b(data_len - 4, devid_ptr->length);
9687
9688         if (port && port->port_type == CTL_PORT_FC)
9689                 proto = SCSI_PROTO_FC << 4;
9690         else if (port && port->port_type == CTL_PORT_ISCSI)
9691                 proto = SCSI_PROTO_ISCSI << 4;
9692         else
9693                 proto = SCSI_PROTO_SPI << 4;
9694         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9695
9696         /*
9697          * We're using a LUN association here.  i.e., this device ID is a
9698          * per-LUN identifier.
9699          */
9700         if (lun && lun->lun_devid) {
9701                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9702                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9703                     lun->lun_devid->len);
9704         }
9705
9706         /*
9707          * This is for the WWPN which is a port association.
9708          */
9709         if (port && port->port_devid) {
9710                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9711                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9712                     port->port_devid->len);
9713         }
9714
9715         /*
9716          * This is for the Relative Target Port(type 4h) identifier
9717          */
9718         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9719         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9720             SVPD_ID_TYPE_RELTARG;
9721         desc->length = 4;
9722         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9723         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9724             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9725
9726         /*
9727          * This is for the Target Port Group(type 5h) identifier
9728          */
9729         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9730         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9731             SVPD_ID_TYPE_TPORTGRP;
9732         desc->length = 4;
9733         if (softc->is_single ||
9734             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9735                 g = 1;
9736         else
9737                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9738         scsi_ulto2b(g, &desc->identifier[2]);
9739         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9740             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9741
9742         /*
9743          * This is for the Target identifier
9744          */
9745         if (port && port->target_devid) {
9746                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9747         }
9748
9749         ctl_set_success(ctsio);
9750         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9751         ctsio->be_move_done = ctl_config_move_done;
9752         ctl_datamove((union ctl_io *)ctsio);
9753         return (CTL_RETVAL_COMPLETE);
9754 }
9755
9756 static int
9757 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9758 {
9759         struct ctl_softc *softc = control_softc;
9760         struct scsi_vpd_scsi_ports *sp;
9761         struct scsi_vpd_port_designation *pd;
9762         struct scsi_vpd_port_designation_cont *pdc;
9763         struct ctl_lun *lun;
9764         struct ctl_port *port;
9765         int data_len, num_target_ports, iid_len, id_len;
9766
9767         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9768
9769         num_target_ports = 0;
9770         iid_len = 0;
9771         id_len = 0;
9772         mtx_lock(&softc->ctl_lock);
9773         STAILQ_FOREACH(port, &softc->port_list, links) {
9774                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9775                         continue;
9776                 if (lun != NULL &&
9777                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9778                         continue;
9779                 num_target_ports++;
9780                 if (port->init_devid)
9781                         iid_len += port->init_devid->len;
9782                 if (port->port_devid)
9783                         id_len += port->port_devid->len;
9784         }
9785         mtx_unlock(&softc->ctl_lock);
9786
9787         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9788             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9789              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9790         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9791         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9792         ctsio->kern_sg_entries = 0;
9793
9794         if (data_len < alloc_len) {
9795                 ctsio->residual = alloc_len - data_len;
9796                 ctsio->kern_data_len = data_len;
9797                 ctsio->kern_total_len = data_len;
9798         } else {
9799                 ctsio->residual = 0;
9800                 ctsio->kern_data_len = alloc_len;
9801                 ctsio->kern_total_len = alloc_len;
9802         }
9803         ctsio->kern_data_resid = 0;
9804         ctsio->kern_rel_offset = 0;
9805         ctsio->kern_sg_entries = 0;
9806
9807         /*
9808          * The control device is always connected.  The disk device, on the
9809          * other hand, may not be online all the time.  Need to change this
9810          * to figure out whether the disk device is actually online or not.
9811          */
9812         if (lun != NULL)
9813                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9814                                   lun->be_lun->lun_type;
9815         else
9816                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9817
9818         sp->page_code = SVPD_SCSI_PORTS;
9819         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9820             sp->page_length);
9821         pd = &sp->design[0];
9822
9823         mtx_lock(&softc->ctl_lock);
9824         STAILQ_FOREACH(port, &softc->port_list, links) {
9825                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9826                         continue;
9827                 if (lun != NULL &&
9828                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9829                         continue;
9830                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9831                 if (port->init_devid) {
9832                         iid_len = port->init_devid->len;
9833                         memcpy(pd->initiator_transportid,
9834                             port->init_devid->data, port->init_devid->len);
9835                 } else
9836                         iid_len = 0;
9837                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9838                 pdc = (struct scsi_vpd_port_designation_cont *)
9839                     (&pd->initiator_transportid[iid_len]);
9840                 if (port->port_devid) {
9841                         id_len = port->port_devid->len;
9842                         memcpy(pdc->target_port_descriptors,
9843                             port->port_devid->data, port->port_devid->len);
9844                 } else
9845                         id_len = 0;
9846                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9847                 pd = (struct scsi_vpd_port_designation *)
9848                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9849         }
9850         mtx_unlock(&softc->ctl_lock);
9851
9852         ctl_set_success(ctsio);
9853         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9854         ctsio->be_move_done = ctl_config_move_done;
9855         ctl_datamove((union ctl_io *)ctsio);
9856         return (CTL_RETVAL_COMPLETE);
9857 }
9858
9859 static int
9860 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9861 {
9862         struct scsi_vpd_block_limits *bl_ptr;
9863         struct ctl_lun *lun;
9864         uint64_t ival;
9865
9866         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9867
9868         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9869         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9870         ctsio->kern_sg_entries = 0;
9871
9872         if (sizeof(*bl_ptr) < alloc_len) {
9873                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9874                 ctsio->kern_data_len = sizeof(*bl_ptr);
9875                 ctsio->kern_total_len = sizeof(*bl_ptr);
9876         } else {
9877                 ctsio->residual = 0;
9878                 ctsio->kern_data_len = alloc_len;
9879                 ctsio->kern_total_len = alloc_len;
9880         }
9881         ctsio->kern_data_resid = 0;
9882         ctsio->kern_rel_offset = 0;
9883         ctsio->kern_sg_entries = 0;
9884
9885         /*
9886          * The control device is always connected.  The disk device, on the
9887          * other hand, may not be online all the time.  Need to change this
9888          * to figure out whether the disk device is actually online or not.
9889          */
9890         if (lun != NULL)
9891                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9892                                   lun->be_lun->lun_type;
9893         else
9894                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9895
9896         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9897         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9898         bl_ptr->max_cmp_write_len = 0xff;
9899         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9900         if (lun != NULL) {
9901                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9902                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9903                         ival = 0xffffffff;
9904                         ctl_get_opt_number(&lun->be_lun->options,
9905                             "unmap_max_lba", &ival);
9906                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9907                         ival = 0xffffffff;
9908                         ctl_get_opt_number(&lun->be_lun->options,
9909                             "unmap_max_descr", &ival);
9910                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9911                         if (lun->be_lun->ublockexp != 0) {
9912                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9913                                     bl_ptr->opt_unmap_grain);
9914                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9915                                     bl_ptr->unmap_grain_align);
9916                         }
9917                 }
9918                 scsi_ulto4b(lun->be_lun->atomicblock,
9919                     bl_ptr->max_atomic_transfer_length);
9920                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9921                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9922                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9923                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9924                 ival = UINT64_MAX;
9925                 ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9926                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9927         }
9928
9929         ctl_set_success(ctsio);
9930         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9931         ctsio->be_move_done = ctl_config_move_done;
9932         ctl_datamove((union ctl_io *)ctsio);
9933         return (CTL_RETVAL_COMPLETE);
9934 }
9935
9936 static int
9937 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9938 {
9939         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9940         struct ctl_lun *lun;
9941         const char *value;
9942         u_int i;
9943
9944         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9945
9946         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9947         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9948         ctsio->kern_sg_entries = 0;
9949
9950         if (sizeof(*bdc_ptr) < alloc_len) {
9951                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9952                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9953                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9954         } else {
9955                 ctsio->residual = 0;
9956                 ctsio->kern_data_len = alloc_len;
9957                 ctsio->kern_total_len = alloc_len;
9958         }
9959         ctsio->kern_data_resid = 0;
9960         ctsio->kern_rel_offset = 0;
9961         ctsio->kern_sg_entries = 0;
9962
9963         /*
9964          * The control device is always connected.  The disk device, on the
9965          * other hand, may not be online all the time.  Need to change this
9966          * to figure out whether the disk device is actually online or not.
9967          */
9968         if (lun != NULL)
9969                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9970                                   lun->be_lun->lun_type;
9971         else
9972                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9973         bdc_ptr->page_code = SVPD_BDC;
9974         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9975         if (lun != NULL &&
9976             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9977                 i = strtol(value, NULL, 0);
9978         else
9979                 i = CTL_DEFAULT_ROTATION_RATE;
9980         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9981         if (lun != NULL &&
9982             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9983                 i = strtol(value, NULL, 0);
9984         else
9985                 i = 0;
9986         bdc_ptr->wab_wac_ff = (i & 0x0f);
9987         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9988
9989         ctl_set_success(ctsio);
9990         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9991         ctsio->be_move_done = ctl_config_move_done;
9992         ctl_datamove((union ctl_io *)ctsio);
9993         return (CTL_RETVAL_COMPLETE);
9994 }
9995
9996 static int
9997 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9998 {
9999         struct scsi_vpd_logical_block_prov *lbp_ptr;
10000         struct ctl_lun *lun;
10001         const char *value;
10002
10003         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10004
10005         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10006         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10007         ctsio->kern_sg_entries = 0;
10008
10009         if (sizeof(*lbp_ptr) < alloc_len) {
10010                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10011                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10012                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10013         } else {
10014                 ctsio->residual = 0;
10015                 ctsio->kern_data_len = alloc_len;
10016                 ctsio->kern_total_len = alloc_len;
10017         }
10018         ctsio->kern_data_resid = 0;
10019         ctsio->kern_rel_offset = 0;
10020         ctsio->kern_sg_entries = 0;
10021
10022         /*
10023          * The control device is always connected.  The disk device, on the
10024          * other hand, may not be online all the time.  Need to change this
10025          * to figure out whether the disk device is actually online or not.
10026          */
10027         if (lun != NULL)
10028                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10029                                   lun->be_lun->lun_type;
10030         else
10031                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10032
10033         lbp_ptr->page_code = SVPD_LBP;
10034         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10035         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10036         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10037                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10038                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10039                 value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10040                 if (value != NULL) {
10041                         if (strcmp(value, "resource") == 0)
10042                                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10043                         else if (strcmp(value, "thin") == 0)
10044                                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10045                 } else
10046                         lbp_ptr->prov_type = SVPD_LBP_THIN;
10047         }
10048
10049         ctl_set_success(ctsio);
10050         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10051         ctsio->be_move_done = ctl_config_move_done;
10052         ctl_datamove((union ctl_io *)ctsio);
10053         return (CTL_RETVAL_COMPLETE);
10054 }
10055
10056 /*
10057  * INQUIRY with the EVPD bit set.
10058  */
10059 static int
10060 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10061 {
10062         struct ctl_lun *lun;
10063         struct scsi_inquiry *cdb;
10064         int alloc_len, retval;
10065
10066         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10067         cdb = (struct scsi_inquiry *)ctsio->cdb;
10068         alloc_len = scsi_2btoul(cdb->length);
10069
10070         switch (cdb->page_code) {
10071         case SVPD_SUPPORTED_PAGES:
10072                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10073                 break;
10074         case SVPD_UNIT_SERIAL_NUMBER:
10075                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10076                 break;
10077         case SVPD_DEVICE_ID:
10078                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10079                 break;
10080         case SVPD_EXTENDED_INQUIRY_DATA:
10081                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10082                 break;
10083         case SVPD_MODE_PAGE_POLICY:
10084                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10085                 break;
10086         case SVPD_SCSI_PORTS:
10087                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10088                 break;
10089         case SVPD_SCSI_TPC:
10090                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10091                 break;
10092         case SVPD_BLOCK_LIMITS:
10093                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10094                         goto err;
10095                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10096                 break;
10097         case SVPD_BDC:
10098                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10099                         goto err;
10100                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10101                 break;
10102         case SVPD_LBP:
10103                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10104                         goto err;
10105                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10106                 break;
10107         default:
10108 err:
10109                 ctl_set_invalid_field(ctsio,
10110                                       /*sks_valid*/ 1,
10111                                       /*command*/ 1,
10112                                       /*field*/ 2,
10113                                       /*bit_valid*/ 0,
10114                                       /*bit*/ 0);
10115                 ctl_done((union ctl_io *)ctsio);
10116                 retval = CTL_RETVAL_COMPLETE;
10117                 break;
10118         }
10119
10120         return (retval);
10121 }
10122
10123 /*
10124  * Standard INQUIRY data.
10125  */
10126 static int
10127 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10128 {
10129         struct scsi_inquiry_data *inq_ptr;
10130         struct scsi_inquiry *cdb;
10131         struct ctl_softc *softc = control_softc;
10132         struct ctl_port *port;
10133         struct ctl_lun *lun;
10134         char *val;
10135         uint32_t alloc_len, data_len;
10136         ctl_port_type port_type;
10137
10138         port = ctl_io_port(&ctsio->io_hdr);
10139         port_type = port->port_type;
10140         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10141                 port_type = CTL_PORT_SCSI;
10142
10143         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10144         cdb = (struct scsi_inquiry *)ctsio->cdb;
10145         alloc_len = scsi_2btoul(cdb->length);
10146
10147         /*
10148          * We malloc the full inquiry data size here and fill it
10149          * in.  If the user only asks for less, we'll give him
10150          * that much.
10151          */
10152         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10153         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10154         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10155         ctsio->kern_sg_entries = 0;
10156         ctsio->kern_data_resid = 0;
10157         ctsio->kern_rel_offset = 0;
10158
10159         if (data_len < alloc_len) {
10160                 ctsio->residual = alloc_len - data_len;
10161                 ctsio->kern_data_len = data_len;
10162                 ctsio->kern_total_len = data_len;
10163         } else {
10164                 ctsio->residual = 0;
10165                 ctsio->kern_data_len = alloc_len;
10166                 ctsio->kern_total_len = alloc_len;
10167         }
10168
10169         if (lun != NULL) {
10170                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10171                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10172                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10173                             lun->be_lun->lun_type;
10174                 } else {
10175                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10176                             lun->be_lun->lun_type;
10177                 }
10178                 if (lun->flags & CTL_LUN_REMOVABLE)
10179                         inq_ptr->dev_qual2 |= SID_RMB;
10180         } else
10181                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10182
10183         /* RMB in byte 2 is 0 */
10184         inq_ptr->version = SCSI_REV_SPC5;
10185
10186         /*
10187          * According to SAM-3, even if a device only supports a single
10188          * level of LUN addressing, it should still set the HISUP bit:
10189          *
10190          * 4.9.1 Logical unit numbers overview
10191          *
10192          * All logical unit number formats described in this standard are
10193          * hierarchical in structure even when only a single level in that
10194          * hierarchy is used. The HISUP bit shall be set to one in the
10195          * standard INQUIRY data (see SPC-2) when any logical unit number
10196          * format described in this standard is used.  Non-hierarchical
10197          * formats are outside the scope of this standard.
10198          *
10199          * Therefore we set the HiSup bit here.
10200          *
10201          * The response format is 2, per SPC-3.
10202          */
10203         inq_ptr->response_format = SID_HiSup | 2;
10204
10205         inq_ptr->additional_length = data_len -
10206             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10207         CTL_DEBUG_PRINT(("additional_length = %d\n",
10208                          inq_ptr->additional_length));
10209
10210         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10211         if (port_type == CTL_PORT_SCSI)
10212                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10213         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10214         inq_ptr->flags = SID_CmdQue;
10215         if (port_type == CTL_PORT_SCSI)
10216                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10217
10218         /*
10219          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10220          * We have 8 bytes for the vendor name, and 16 bytes for the device
10221          * name and 4 bytes for the revision.
10222          */
10223         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10224             "vendor")) == NULL) {
10225                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10226         } else {
10227                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10228                 strncpy(inq_ptr->vendor, val,
10229                     min(sizeof(inq_ptr->vendor), strlen(val)));
10230         }
10231         if (lun == NULL) {
10232                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10233                     sizeof(inq_ptr->product));
10234         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10235                 switch (lun->be_lun->lun_type) {
10236                 case T_DIRECT:
10237                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10238                             sizeof(inq_ptr->product));
10239                         break;
10240                 case T_PROCESSOR:
10241                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10242                             sizeof(inq_ptr->product));
10243                         break;
10244                 case T_CDROM:
10245                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10246                             sizeof(inq_ptr->product));
10247                         break;
10248                 default:
10249                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10250                             sizeof(inq_ptr->product));
10251                         break;
10252                 }
10253         } else {
10254                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10255                 strncpy(inq_ptr->product, val,
10256                     min(sizeof(inq_ptr->product), strlen(val)));
10257         }
10258
10259         /*
10260          * XXX make this a macro somewhere so it automatically gets
10261          * incremented when we make changes.
10262          */
10263         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10264             "revision")) == NULL) {
10265                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10266         } else {
10267                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10268                 strncpy(inq_ptr->revision, val,
10269                     min(sizeof(inq_ptr->revision), strlen(val)));
10270         }
10271
10272         /*
10273          * For parallel SCSI, we support double transition and single
10274          * transition clocking.  We also support QAS (Quick Arbitration
10275          * and Selection) and Information Unit transfers on both the
10276          * control and array devices.
10277          */
10278         if (port_type == CTL_PORT_SCSI)
10279                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10280                                     SID_SPI_IUS;
10281
10282         /* SAM-6 (no version claimed) */
10283         scsi_ulto2b(0x00C0, inq_ptr->version1);
10284         /* SPC-5 (no version claimed) */
10285         scsi_ulto2b(0x05C0, inq_ptr->version2);
10286         if (port_type == CTL_PORT_FC) {
10287                 /* FCP-2 ANSI INCITS.350:2003 */
10288                 scsi_ulto2b(0x0917, inq_ptr->version3);
10289         } else if (port_type == CTL_PORT_SCSI) {
10290                 /* SPI-4 ANSI INCITS.362:200x */
10291                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10292         } else if (port_type == CTL_PORT_ISCSI) {
10293                 /* iSCSI (no version claimed) */
10294                 scsi_ulto2b(0x0960, inq_ptr->version3);
10295         } else if (port_type == CTL_PORT_SAS) {
10296                 /* SAS (no version claimed) */
10297                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10298         }
10299
10300         if (lun == NULL) {
10301                 /* SBC-4 (no version claimed) */
10302                 scsi_ulto2b(0x0600, inq_ptr->version4);
10303         } else {
10304                 switch (lun->be_lun->lun_type) {
10305                 case T_DIRECT:
10306                         /* SBC-4 (no version claimed) */
10307                         scsi_ulto2b(0x0600, inq_ptr->version4);
10308                         break;
10309                 case T_PROCESSOR:
10310                         break;
10311                 case T_CDROM:
10312                         /* MMC-6 (no version claimed) */
10313                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10314                         break;
10315                 default:
10316                         break;
10317                 }
10318         }
10319
10320         ctl_set_success(ctsio);
10321         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10322         ctsio->be_move_done = ctl_config_move_done;
10323         ctl_datamove((union ctl_io *)ctsio);
10324         return (CTL_RETVAL_COMPLETE);
10325 }
10326
10327 int
10328 ctl_inquiry(struct ctl_scsiio *ctsio)
10329 {
10330         struct scsi_inquiry *cdb;
10331         int retval;
10332
10333         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10334
10335         cdb = (struct scsi_inquiry *)ctsio->cdb;
10336         if (cdb->byte2 & SI_EVPD)
10337                 retval = ctl_inquiry_evpd(ctsio);
10338         else if (cdb->page_code == 0)
10339                 retval = ctl_inquiry_std(ctsio);
10340         else {
10341                 ctl_set_invalid_field(ctsio,
10342                                       /*sks_valid*/ 1,
10343                                       /*command*/ 1,
10344                                       /*field*/ 2,
10345                                       /*bit_valid*/ 0,
10346                                       /*bit*/ 0);
10347                 ctl_done((union ctl_io *)ctsio);
10348                 return (CTL_RETVAL_COMPLETE);
10349         }
10350
10351         return (retval);
10352 }
10353
10354 int
10355 ctl_get_config(struct ctl_scsiio *ctsio)
10356 {
10357         struct scsi_get_config_header *hdr;
10358         struct scsi_get_config_feature *feature;
10359         struct scsi_get_config *cdb;
10360         struct ctl_lun *lun;
10361         uint32_t alloc_len, data_len;
10362         int rt, starting;
10363
10364         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10365         cdb = (struct scsi_get_config *)ctsio->cdb;
10366         rt = (cdb->rt & SGC_RT_MASK);
10367         starting = scsi_2btoul(cdb->starting_feature);
10368         alloc_len = scsi_2btoul(cdb->length);
10369
10370         data_len = sizeof(struct scsi_get_config_header) +
10371             sizeof(struct scsi_get_config_feature) + 8 +
10372             sizeof(struct scsi_get_config_feature) + 8 +
10373             sizeof(struct scsi_get_config_feature) + 4 +
10374             sizeof(struct scsi_get_config_feature) + 4 +
10375             sizeof(struct scsi_get_config_feature) + 8 +
10376             sizeof(struct scsi_get_config_feature) +
10377             sizeof(struct scsi_get_config_feature) + 4 +
10378             sizeof(struct scsi_get_config_feature) + 4 +
10379             sizeof(struct scsi_get_config_feature) + 4 +
10380             sizeof(struct scsi_get_config_feature) + 4 +
10381             sizeof(struct scsi_get_config_feature) + 4 +
10382             sizeof(struct scsi_get_config_feature) + 4;
10383         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10384         ctsio->kern_sg_entries = 0;
10385         ctsio->kern_data_resid = 0;
10386         ctsio->kern_rel_offset = 0;
10387
10388         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10389         if (lun->flags & CTL_LUN_NO_MEDIA)
10390                 scsi_ulto2b(0x0000, hdr->current_profile);
10391         else
10392                 scsi_ulto2b(0x0010, hdr->current_profile);
10393         feature = (struct scsi_get_config_feature *)(hdr + 1);
10394
10395         if (starting > 0x003b)
10396                 goto done;
10397         if (starting > 0x003a)
10398                 goto f3b;
10399         if (starting > 0x002b)
10400                 goto f3a;
10401         if (starting > 0x002a)
10402                 goto f2b;
10403         if (starting > 0x001f)
10404                 goto f2a;
10405         if (starting > 0x001e)
10406                 goto f1f;
10407         if (starting > 0x001d)
10408                 goto f1e;
10409         if (starting > 0x0010)
10410                 goto f1d;
10411         if (starting > 0x0003)
10412                 goto f10;
10413         if (starting > 0x0002)
10414                 goto f3;
10415         if (starting > 0x0001)
10416                 goto f2;
10417         if (starting > 0x0000)
10418                 goto f1;
10419
10420         /* Profile List */
10421         scsi_ulto2b(0x0000, feature->feature_code);
10422         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10423         feature->add_length = 8;
10424         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10425         feature->feature_data[2] = 0x00;
10426         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10427         feature->feature_data[6] = 0x01;
10428         feature = (struct scsi_get_config_feature *)
10429             &feature->feature_data[feature->add_length];
10430
10431 f1:     /* Core */
10432         scsi_ulto2b(0x0001, feature->feature_code);
10433         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10434         feature->add_length = 8;
10435         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10436         feature->feature_data[4] = 0x03;
10437         feature = (struct scsi_get_config_feature *)
10438             &feature->feature_data[feature->add_length];
10439
10440 f2:     /* Morphing */
10441         scsi_ulto2b(0x0002, feature->feature_code);
10442         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10443         feature->add_length = 4;
10444         feature->feature_data[0] = 0x02;
10445         feature = (struct scsi_get_config_feature *)
10446             &feature->feature_data[feature->add_length];
10447
10448 f3:     /* Removable Medium */
10449         scsi_ulto2b(0x0003, feature->feature_code);
10450         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10451         feature->add_length = 4;
10452         feature->feature_data[0] = 0x39;
10453         feature = (struct scsi_get_config_feature *)
10454             &feature->feature_data[feature->add_length];
10455
10456         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10457                 goto done;
10458
10459 f10:    /* Random Read */
10460         scsi_ulto2b(0x0010, feature->feature_code);
10461         feature->flags = 0x00;
10462         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10463                 feature->flags |= SGC_F_CURRENT;
10464         feature->add_length = 8;
10465         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10466         scsi_ulto2b(1, &feature->feature_data[4]);
10467         feature->feature_data[6] = 0x00;
10468         feature = (struct scsi_get_config_feature *)
10469             &feature->feature_data[feature->add_length];
10470
10471 f1d:    /* Multi-Read */
10472         scsi_ulto2b(0x001D, feature->feature_code);
10473         feature->flags = 0x00;
10474         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10475                 feature->flags |= SGC_F_CURRENT;
10476         feature->add_length = 0;
10477         feature = (struct scsi_get_config_feature *)
10478             &feature->feature_data[feature->add_length];
10479
10480 f1e:    /* CD Read */
10481         scsi_ulto2b(0x001E, feature->feature_code);
10482         feature->flags = 0x00;
10483         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10484                 feature->flags |= SGC_F_CURRENT;
10485         feature->add_length = 4;
10486         feature->feature_data[0] = 0x00;
10487         feature = (struct scsi_get_config_feature *)
10488             &feature->feature_data[feature->add_length];
10489
10490 f1f:    /* DVD Read */
10491         scsi_ulto2b(0x001F, feature->feature_code);
10492         feature->flags = 0x08;
10493         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10494                 feature->flags |= SGC_F_CURRENT;
10495         feature->add_length = 4;
10496         feature->feature_data[0] = 0x01;
10497         feature->feature_data[2] = 0x03;
10498         feature = (struct scsi_get_config_feature *)
10499             &feature->feature_data[feature->add_length];
10500
10501 f2a:    /* DVD+RW */
10502         scsi_ulto2b(0x002A, feature->feature_code);
10503         feature->flags = 0x04;
10504         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10505                 feature->flags |= SGC_F_CURRENT;
10506         feature->add_length = 4;
10507         feature->feature_data[0] = 0x00;
10508         feature->feature_data[1] = 0x00;
10509         feature = (struct scsi_get_config_feature *)
10510             &feature->feature_data[feature->add_length];
10511
10512 f2b:    /* DVD+R */
10513         scsi_ulto2b(0x002B, feature->feature_code);
10514         feature->flags = 0x00;
10515         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10516                 feature->flags |= SGC_F_CURRENT;
10517         feature->add_length = 4;
10518         feature->feature_data[0] = 0x00;
10519         feature = (struct scsi_get_config_feature *)
10520             &feature->feature_data[feature->add_length];
10521
10522 f3a:    /* DVD+RW Dual Layer */
10523         scsi_ulto2b(0x003A, feature->feature_code);
10524         feature->flags = 0x00;
10525         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10526                 feature->flags |= SGC_F_CURRENT;
10527         feature->add_length = 4;
10528         feature->feature_data[0] = 0x00;
10529         feature->feature_data[1] = 0x00;
10530         feature = (struct scsi_get_config_feature *)
10531             &feature->feature_data[feature->add_length];
10532
10533 f3b:    /* DVD+R Dual Layer */
10534         scsi_ulto2b(0x003B, feature->feature_code);
10535         feature->flags = 0x00;
10536         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10537                 feature->flags |= SGC_F_CURRENT;
10538         feature->add_length = 4;
10539         feature->feature_data[0] = 0x00;
10540         feature = (struct scsi_get_config_feature *)
10541             &feature->feature_data[feature->add_length];
10542
10543 done:
10544         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10545         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10546                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10547                 if (scsi_2btoul(feature->feature_code) == starting)
10548                         feature = (struct scsi_get_config_feature *)
10549                             &feature->feature_data[feature->add_length];
10550                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10551         }
10552         scsi_ulto4b(data_len - 4, hdr->data_length);
10553         if (data_len < alloc_len) {
10554                 ctsio->residual = alloc_len - data_len;
10555                 ctsio->kern_data_len = data_len;
10556                 ctsio->kern_total_len = data_len;
10557         } else {
10558                 ctsio->residual = 0;
10559                 ctsio->kern_data_len = alloc_len;
10560                 ctsio->kern_total_len = alloc_len;
10561         }
10562
10563         ctl_set_success(ctsio);
10564         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10565         ctsio->be_move_done = ctl_config_move_done;
10566         ctl_datamove((union ctl_io *)ctsio);
10567         return (CTL_RETVAL_COMPLETE);
10568 }
10569
10570 int
10571 ctl_get_event_status(struct ctl_scsiio *ctsio)
10572 {
10573         struct scsi_get_event_status_header *hdr;
10574         struct scsi_get_event_status *cdb;
10575         struct ctl_lun *lun;
10576         uint32_t alloc_len, data_len;
10577         int notif_class;
10578
10579         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10580         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10581         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10582                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10583                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10584                 ctl_done((union ctl_io *)ctsio);
10585                 return (CTL_RETVAL_COMPLETE);
10586         }
10587         notif_class = cdb->notif_class;
10588         alloc_len = scsi_2btoul(cdb->length);
10589
10590         data_len = sizeof(struct scsi_get_event_status_header);
10591         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10592         ctsio->kern_sg_entries = 0;
10593         ctsio->kern_data_resid = 0;
10594         ctsio->kern_rel_offset = 0;
10595
10596         if (data_len < alloc_len) {
10597                 ctsio->residual = alloc_len - data_len;
10598                 ctsio->kern_data_len = data_len;
10599                 ctsio->kern_total_len = data_len;
10600         } else {
10601                 ctsio->residual = 0;
10602                 ctsio->kern_data_len = alloc_len;
10603                 ctsio->kern_total_len = alloc_len;
10604         }
10605
10606         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10607         scsi_ulto2b(0, hdr->descr_length);
10608         hdr->nea_class = SGESN_NEA;
10609         hdr->supported_class = 0;
10610
10611         ctl_set_success(ctsio);
10612         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10613         ctsio->be_move_done = ctl_config_move_done;
10614         ctl_datamove((union ctl_io *)ctsio);
10615         return (CTL_RETVAL_COMPLETE);
10616 }
10617
10618 int
10619 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10620 {
10621         struct scsi_mechanism_status_header *hdr;
10622         struct scsi_mechanism_status *cdb;
10623         struct ctl_lun *lun;
10624         uint32_t alloc_len, data_len;
10625
10626         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10627         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10628         alloc_len = scsi_2btoul(cdb->length);
10629
10630         data_len = sizeof(struct scsi_mechanism_status_header);
10631         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10632         ctsio->kern_sg_entries = 0;
10633         ctsio->kern_data_resid = 0;
10634         ctsio->kern_rel_offset = 0;
10635
10636         if (data_len < alloc_len) {
10637                 ctsio->residual = alloc_len - data_len;
10638                 ctsio->kern_data_len = data_len;
10639                 ctsio->kern_total_len = data_len;
10640         } else {
10641                 ctsio->residual = 0;
10642                 ctsio->kern_data_len = alloc_len;
10643                 ctsio->kern_total_len = alloc_len;
10644         }
10645
10646         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10647         hdr->state1 = 0x00;
10648         hdr->state2 = 0xe0;
10649         scsi_ulto3b(0, hdr->lba);
10650         hdr->slots_num = 0;
10651         scsi_ulto2b(0, hdr->slots_length);
10652
10653         ctl_set_success(ctsio);
10654         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10655         ctsio->be_move_done = ctl_config_move_done;
10656         ctl_datamove((union ctl_io *)ctsio);
10657         return (CTL_RETVAL_COMPLETE);
10658 }
10659
10660 static void
10661 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10662 {
10663
10664         lba += 150;
10665         buf[0] = 0;
10666         buf[1] = bin2bcd((lba / 75) / 60);
10667         buf[2] = bin2bcd((lba / 75) % 60);
10668         buf[3] = bin2bcd(lba % 75);
10669 }
10670
10671 int
10672 ctl_read_toc(struct ctl_scsiio *ctsio)
10673 {
10674         struct scsi_read_toc_hdr *hdr;
10675         struct scsi_read_toc_type01_descr *descr;
10676         struct scsi_read_toc *cdb;
10677         struct ctl_lun *lun;
10678         uint32_t alloc_len, data_len;
10679         int format, msf;
10680
10681         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10682         cdb = (struct scsi_read_toc *)ctsio->cdb;
10683         msf = (cdb->byte2 & CD_MSF) != 0;
10684         format = cdb->format;
10685         alloc_len = scsi_2btoul(cdb->data_len);
10686
10687         data_len = sizeof(struct scsi_read_toc_hdr);
10688         if (format == 0)
10689                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10690         else
10691                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10692         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10693         ctsio->kern_sg_entries = 0;
10694         ctsio->kern_data_resid = 0;
10695         ctsio->kern_rel_offset = 0;
10696
10697         if (data_len < alloc_len) {
10698                 ctsio->residual = alloc_len - data_len;
10699                 ctsio->kern_data_len = data_len;
10700                 ctsio->kern_total_len = data_len;
10701         } else {
10702                 ctsio->residual = 0;
10703                 ctsio->kern_data_len = alloc_len;
10704                 ctsio->kern_total_len = alloc_len;
10705         }
10706
10707         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10708         if (format == 0) {
10709                 scsi_ulto2b(0x12, hdr->data_length);
10710                 hdr->first = 1;
10711                 hdr->last = 1;
10712                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10713                 descr->addr_ctl = 0x14;
10714                 descr->track_number = 1;
10715                 if (msf)
10716                         ctl_ultomsf(0, descr->track_start);
10717                 else
10718                         scsi_ulto4b(0, descr->track_start);
10719                 descr++;
10720                 descr->addr_ctl = 0x14;
10721                 descr->track_number = 0xaa;
10722                 if (msf)
10723                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10724                 else
10725                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10726         } else {
10727                 scsi_ulto2b(0x0a, hdr->data_length);
10728                 hdr->first = 1;
10729                 hdr->last = 1;
10730                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10731                 descr->addr_ctl = 0x14;
10732                 descr->track_number = 1;
10733                 if (msf)
10734                         ctl_ultomsf(0, descr->track_start);
10735                 else
10736                         scsi_ulto4b(0, descr->track_start);
10737         }
10738
10739         ctl_set_success(ctsio);
10740         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10741         ctsio->be_move_done = ctl_config_move_done;
10742         ctl_datamove((union ctl_io *)ctsio);
10743         return (CTL_RETVAL_COMPLETE);
10744 }
10745
10746 /*
10747  * For known CDB types, parse the LBA and length.
10748  */
10749 static int
10750 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10751 {
10752         if (io->io_hdr.io_type != CTL_IO_SCSI)
10753                 return (1);
10754
10755         switch (io->scsiio.cdb[0]) {
10756         case COMPARE_AND_WRITE: {
10757                 struct scsi_compare_and_write *cdb;
10758
10759                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10760
10761                 *lba = scsi_8btou64(cdb->addr);
10762                 *len = cdb->length;
10763                 break;
10764         }
10765         case READ_6:
10766         case WRITE_6: {
10767                 struct scsi_rw_6 *cdb;
10768
10769                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10770
10771                 *lba = scsi_3btoul(cdb->addr);
10772                 /* only 5 bits are valid in the most significant address byte */
10773                 *lba &= 0x1fffff;
10774                 *len = cdb->length;
10775                 break;
10776         }
10777         case READ_10:
10778         case WRITE_10: {
10779                 struct scsi_rw_10 *cdb;
10780
10781                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10782
10783                 *lba = scsi_4btoul(cdb->addr);
10784                 *len = scsi_2btoul(cdb->length);
10785                 break;
10786         }
10787         case WRITE_VERIFY_10: {
10788                 struct scsi_write_verify_10 *cdb;
10789
10790                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10791
10792                 *lba = scsi_4btoul(cdb->addr);
10793                 *len = scsi_2btoul(cdb->length);
10794                 break;
10795         }
10796         case READ_12:
10797         case WRITE_12: {
10798                 struct scsi_rw_12 *cdb;
10799
10800                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10801
10802                 *lba = scsi_4btoul(cdb->addr);
10803                 *len = scsi_4btoul(cdb->length);
10804                 break;
10805         }
10806         case WRITE_VERIFY_12: {
10807                 struct scsi_write_verify_12 *cdb;
10808
10809                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10810
10811                 *lba = scsi_4btoul(cdb->addr);
10812                 *len = scsi_4btoul(cdb->length);
10813                 break;
10814         }
10815         case READ_16:
10816         case WRITE_16: {
10817                 struct scsi_rw_16 *cdb;
10818
10819                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10820
10821                 *lba = scsi_8btou64(cdb->addr);
10822                 *len = scsi_4btoul(cdb->length);
10823                 break;
10824         }
10825         case WRITE_ATOMIC_16: {
10826                 struct scsi_write_atomic_16 *cdb;
10827
10828                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10829
10830                 *lba = scsi_8btou64(cdb->addr);
10831                 *len = scsi_2btoul(cdb->length);
10832                 break;
10833         }
10834         case WRITE_VERIFY_16: {
10835                 struct scsi_write_verify_16 *cdb;
10836
10837                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10838
10839                 *lba = scsi_8btou64(cdb->addr);
10840                 *len = scsi_4btoul(cdb->length);
10841                 break;
10842         }
10843         case WRITE_SAME_10: {
10844                 struct scsi_write_same_10 *cdb;
10845
10846                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10847
10848                 *lba = scsi_4btoul(cdb->addr);
10849                 *len = scsi_2btoul(cdb->length);
10850                 break;
10851         }
10852         case WRITE_SAME_16: {
10853                 struct scsi_write_same_16 *cdb;
10854
10855                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10856
10857                 *lba = scsi_8btou64(cdb->addr);
10858                 *len = scsi_4btoul(cdb->length);
10859                 break;
10860         }
10861         case VERIFY_10: {
10862                 struct scsi_verify_10 *cdb;
10863
10864                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10865
10866                 *lba = scsi_4btoul(cdb->addr);
10867                 *len = scsi_2btoul(cdb->length);
10868                 break;
10869         }
10870         case VERIFY_12: {
10871                 struct scsi_verify_12 *cdb;
10872
10873                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10874
10875                 *lba = scsi_4btoul(cdb->addr);
10876                 *len = scsi_4btoul(cdb->length);
10877                 break;
10878         }
10879         case VERIFY_16: {
10880                 struct scsi_verify_16 *cdb;
10881
10882                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10883
10884                 *lba = scsi_8btou64(cdb->addr);
10885                 *len = scsi_4btoul(cdb->length);
10886                 break;
10887         }
10888         case UNMAP: {
10889                 *lba = 0;
10890                 *len = UINT64_MAX;
10891                 break;
10892         }
10893         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10894                 struct scsi_get_lba_status *cdb;
10895
10896                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10897                 *lba = scsi_8btou64(cdb->addr);
10898                 *len = UINT32_MAX;
10899                 break;
10900         }
10901         default:
10902                 return (1);
10903                 break; /* NOTREACHED */
10904         }
10905
10906         return (0);
10907 }
10908
10909 static ctl_action
10910 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10911     bool seq)
10912 {
10913         uint64_t endlba1, endlba2;
10914
10915         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10916         endlba2 = lba2 + len2 - 1;
10917
10918         if ((endlba1 < lba2) || (endlba2 < lba1))
10919                 return (CTL_ACTION_PASS);
10920         else
10921                 return (CTL_ACTION_BLOCK);
10922 }
10923
10924 static int
10925 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10926 {
10927         struct ctl_ptr_len_flags *ptrlen;
10928         struct scsi_unmap_desc *buf, *end, *range;
10929         uint64_t lba;
10930         uint32_t len;
10931
10932         /* If not UNMAP -- go other way. */
10933         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10934             io->scsiio.cdb[0] != UNMAP)
10935                 return (CTL_ACTION_ERROR);
10936
10937         /* If UNMAP without data -- block and wait for data. */
10938         ptrlen = (struct ctl_ptr_len_flags *)
10939             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10940         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10941             ptrlen->ptr == NULL)
10942                 return (CTL_ACTION_BLOCK);
10943
10944         /* UNMAP with data -- check for collision. */
10945         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10946         end = buf + ptrlen->len / sizeof(*buf);
10947         for (range = buf; range < end; range++) {
10948                 lba = scsi_8btou64(range->lba);
10949                 len = scsi_4btoul(range->length);
10950                 if ((lba < lba2 + len2) && (lba + len > lba2))
10951                         return (CTL_ACTION_BLOCK);
10952         }
10953         return (CTL_ACTION_PASS);
10954 }
10955
10956 static ctl_action
10957 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10958 {
10959         uint64_t lba1, lba2;
10960         uint64_t len1, len2;
10961         int retval;
10962
10963         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10964                 return (CTL_ACTION_ERROR);
10965
10966         retval = ctl_extent_check_unmap(io1, lba2, len2);
10967         if (retval != CTL_ACTION_ERROR)
10968                 return (retval);
10969
10970         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10971                 return (CTL_ACTION_ERROR);
10972
10973         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10974                 seq = FALSE;
10975         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10976 }
10977
10978 static ctl_action
10979 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10980 {
10981         uint64_t lba1, lba2;
10982         uint64_t len1, len2;
10983
10984         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10985                 return (CTL_ACTION_PASS);
10986         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10987                 return (CTL_ACTION_ERROR);
10988         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10989                 return (CTL_ACTION_ERROR);
10990
10991         if (lba1 + len1 == lba2)
10992                 return (CTL_ACTION_BLOCK);
10993         return (CTL_ACTION_PASS);
10994 }
10995
10996 static ctl_action
10997 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10998     union ctl_io *ooa_io)
10999 {
11000         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11001         const ctl_serialize_action *serialize_row;
11002
11003         /*
11004          * The initiator attempted multiple untagged commands at the same
11005          * time.  Can't do that.
11006          */
11007         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11008          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11009          && ((pending_io->io_hdr.nexus.targ_port ==
11010               ooa_io->io_hdr.nexus.targ_port)
11011           && (pending_io->io_hdr.nexus.initid ==
11012               ooa_io->io_hdr.nexus.initid))
11013          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11014               CTL_FLAG_STATUS_SENT)) == 0))
11015                 return (CTL_ACTION_OVERLAP);
11016
11017         /*
11018          * The initiator attempted to send multiple tagged commands with
11019          * the same ID.  (It's fine if different initiators have the same
11020          * tag ID.)
11021          *
11022          * Even if all of those conditions are true, we don't kill the I/O
11023          * if the command ahead of us has been aborted.  We won't end up
11024          * sending it to the FETD, and it's perfectly legal to resend a
11025          * command with the same tag number as long as the previous
11026          * instance of this tag number has been aborted somehow.
11027          */
11028         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11029          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11030          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11031          && ((pending_io->io_hdr.nexus.targ_port ==
11032               ooa_io->io_hdr.nexus.targ_port)
11033           && (pending_io->io_hdr.nexus.initid ==
11034               ooa_io->io_hdr.nexus.initid))
11035          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11036               CTL_FLAG_STATUS_SENT)) == 0))
11037                 return (CTL_ACTION_OVERLAP_TAG);
11038
11039         /*
11040          * If we get a head of queue tag, SAM-3 says that we should
11041          * immediately execute it.
11042          *
11043          * What happens if this command would normally block for some other
11044          * reason?  e.g. a request sense with a head of queue tag
11045          * immediately after a write.  Normally that would block, but this
11046          * will result in its getting executed immediately...
11047          *
11048          * We currently return "pass" instead of "skip", so we'll end up
11049          * going through the rest of the queue to check for overlapped tags.
11050          *
11051          * XXX KDM check for other types of blockage first??
11052          */
11053         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11054                 return (CTL_ACTION_PASS);
11055
11056         /*
11057          * Ordered tags have to block until all items ahead of them
11058          * have completed.  If we get called with an ordered tag, we always
11059          * block, if something else is ahead of us in the queue.
11060          */
11061         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11062                 return (CTL_ACTION_BLOCK);
11063
11064         /*
11065          * Simple tags get blocked until all head of queue and ordered tags
11066          * ahead of them have completed.  I'm lumping untagged commands in
11067          * with simple tags here.  XXX KDM is that the right thing to do?
11068          */
11069         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11070           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11071          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11072           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11073                 return (CTL_ACTION_BLOCK);
11074
11075         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11076         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11077             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11078              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11079              pending_io->scsiio.cdb[1], pending_io));
11080         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11081         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11082                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11083         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11084             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11085              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11086              ooa_io->scsiio.cdb[1], ooa_io));
11087
11088         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11089
11090         switch (serialize_row[pending_entry->seridx]) {
11091         case CTL_SER_BLOCK:
11092                 return (CTL_ACTION_BLOCK);
11093         case CTL_SER_EXTENT:
11094                 return (ctl_extent_check(ooa_io, pending_io,
11095                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11096         case CTL_SER_EXTENTOPT:
11097                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11098                     SCP_QUEUE_ALG_UNRESTRICTED)
11099                         return (ctl_extent_check(ooa_io, pending_io,
11100                             (lun->be_lun &&
11101                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11102                 return (CTL_ACTION_PASS);
11103         case CTL_SER_EXTENTSEQ:
11104                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11105                         return (ctl_extent_check_seq(ooa_io, pending_io));
11106                 return (CTL_ACTION_PASS);
11107         case CTL_SER_PASS:
11108                 return (CTL_ACTION_PASS);
11109         case CTL_SER_BLOCKOPT:
11110                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11111                     SCP_QUEUE_ALG_UNRESTRICTED)
11112                         return (CTL_ACTION_BLOCK);
11113                 return (CTL_ACTION_PASS);
11114         case CTL_SER_SKIP:
11115                 return (CTL_ACTION_SKIP);
11116         default:
11117                 panic("%s: Invalid serialization value %d for %d => %d",
11118                     __func__, serialize_row[pending_entry->seridx],
11119                     pending_entry->seridx, ooa_entry->seridx);
11120         }
11121
11122         return (CTL_ACTION_ERROR);
11123 }
11124
11125 /*
11126  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11127  * Assumptions:
11128  * - pending_io is generally either incoming, or on the blocked queue
11129  * - starting I/O is the I/O we want to start the check with.
11130  */
11131 static ctl_action
11132 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11133               union ctl_io *starting_io)
11134 {
11135         union ctl_io *ooa_io;
11136         ctl_action action;
11137
11138         mtx_assert(&lun->lun_lock, MA_OWNED);
11139
11140         /*
11141          * Run back along the OOA queue, starting with the current
11142          * blocked I/O and going through every I/O before it on the
11143          * queue.  If starting_io is NULL, we'll just end up returning
11144          * CTL_ACTION_PASS.
11145          */
11146         for (ooa_io = starting_io; ooa_io != NULL;
11147              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11148              ooa_links)){
11149
11150                 /*
11151                  * This routine just checks to see whether
11152                  * cur_blocked is blocked by ooa_io, which is ahead
11153                  * of it in the queue.  It doesn't queue/dequeue
11154                  * cur_blocked.
11155                  */
11156                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11157                 switch (action) {
11158                 case CTL_ACTION_BLOCK:
11159                 case CTL_ACTION_OVERLAP:
11160                 case CTL_ACTION_OVERLAP_TAG:
11161                 case CTL_ACTION_SKIP:
11162                 case CTL_ACTION_ERROR:
11163                         return (action);
11164                         break; /* NOTREACHED */
11165                 case CTL_ACTION_PASS:
11166                         break;
11167                 default:
11168                         panic("%s: Invalid action %d\n", __func__, action);
11169                 }
11170         }
11171
11172         return (CTL_ACTION_PASS);
11173 }
11174
11175 /*
11176  * Assumptions:
11177  * - An I/O has just completed, and has been removed from the per-LUN OOA
11178  *   queue, so some items on the blocked queue may now be unblocked.
11179  */
11180 static int
11181 ctl_check_blocked(struct ctl_lun *lun)
11182 {
11183         struct ctl_softc *softc = lun->ctl_softc;
11184         union ctl_io *cur_blocked, *next_blocked;
11185
11186         mtx_assert(&lun->lun_lock, MA_OWNED);
11187
11188         /*
11189          * Run forward from the head of the blocked queue, checking each
11190          * entry against the I/Os prior to it on the OOA queue to see if
11191          * there is still any blockage.
11192          *
11193          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11194          * with our removing a variable on it while it is traversing the
11195          * list.
11196          */
11197         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11198              cur_blocked != NULL; cur_blocked = next_blocked) {
11199                 union ctl_io *prev_ooa;
11200                 ctl_action action;
11201
11202                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11203                                                           blocked_links);
11204
11205                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11206                                                       ctl_ooaq, ooa_links);
11207
11208                 /*
11209                  * If cur_blocked happens to be the first item in the OOA
11210                  * queue now, prev_ooa will be NULL, and the action
11211                  * returned will just be CTL_ACTION_PASS.
11212                  */
11213                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11214
11215                 switch (action) {
11216                 case CTL_ACTION_BLOCK:
11217                         /* Nothing to do here, still blocked */
11218                         break;
11219                 case CTL_ACTION_OVERLAP:
11220                 case CTL_ACTION_OVERLAP_TAG:
11221                         /*
11222                          * This shouldn't happen!  In theory we've already
11223                          * checked this command for overlap...
11224                          */
11225                         break;
11226                 case CTL_ACTION_PASS:
11227                 case CTL_ACTION_SKIP: {
11228                         const struct ctl_cmd_entry *entry;
11229
11230                         /*
11231                          * The skip case shouldn't happen, this transaction
11232                          * should have never made it onto the blocked queue.
11233                          */
11234                         /*
11235                          * This I/O is no longer blocked, we can remove it
11236                          * from the blocked queue.  Since this is a TAILQ
11237                          * (doubly linked list), we can do O(1) removals
11238                          * from any place on the list.
11239                          */
11240                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11241                                      blocked_links);
11242                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11243
11244                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11245                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11246                                 /*
11247                                  * Need to send IO back to original side to
11248                                  * run
11249                                  */
11250                                 union ctl_ha_msg msg_info;
11251
11252                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11253                                 msg_info.hdr.original_sc =
11254                                         cur_blocked->io_hdr.original_sc;
11255                                 msg_info.hdr.serializing_sc = cur_blocked;
11256                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11257                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11258                                     sizeof(msg_info.hdr), M_NOWAIT);
11259                                 break;
11260                         }
11261                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11262
11263                         /*
11264                          * Check this I/O for LUN state changes that may
11265                          * have happened while this command was blocked.
11266                          * The LUN state may have been changed by a command
11267                          * ahead of us in the queue, so we need to re-check
11268                          * for any states that can be caused by SCSI
11269                          * commands.
11270                          */
11271                         if (ctl_scsiio_lun_check(lun, entry,
11272                                                  &cur_blocked->scsiio) == 0) {
11273                                 cur_blocked->io_hdr.flags |=
11274                                                       CTL_FLAG_IS_WAS_ON_RTR;
11275                                 ctl_enqueue_rtr(cur_blocked);
11276                         } else
11277                                 ctl_done(cur_blocked);
11278                         break;
11279                 }
11280                 default:
11281                         /*
11282                          * This probably shouldn't happen -- we shouldn't
11283                          * get CTL_ACTION_ERROR, or anything else.
11284                          */
11285                         break;
11286                 }
11287         }
11288
11289         return (CTL_RETVAL_COMPLETE);
11290 }
11291
11292 /*
11293  * This routine (with one exception) checks LUN flags that can be set by
11294  * commands ahead of us in the OOA queue.  These flags have to be checked
11295  * when a command initially comes in, and when we pull a command off the
11296  * blocked queue and are preparing to execute it.  The reason we have to
11297  * check these flags for commands on the blocked queue is that the LUN
11298  * state may have been changed by a command ahead of us while we're on the
11299  * blocked queue.
11300  *
11301  * Ordering is somewhat important with these checks, so please pay
11302  * careful attention to the placement of any new checks.
11303  */
11304 static int
11305 ctl_scsiio_lun_check(struct ctl_lun *lun,
11306     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11307 {
11308         struct ctl_softc *softc = lun->ctl_softc;
11309         int retval;
11310         uint32_t residx;
11311
11312         retval = 0;
11313
11314         mtx_assert(&lun->lun_lock, MA_OWNED);
11315
11316         /*
11317          * If this shelf is a secondary shelf controller, we may have to
11318          * reject some commands disallowed by HA mode and link state.
11319          */
11320         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11321                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11322                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11323                         ctl_set_lun_unavail(ctsio);
11324                         retval = 1;
11325                         goto bailout;
11326                 }
11327                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11328                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11329                         ctl_set_lun_transit(ctsio);
11330                         retval = 1;
11331                         goto bailout;
11332                 }
11333                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11334                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11335                         ctl_set_lun_standby(ctsio);
11336                         retval = 1;
11337                         goto bailout;
11338                 }
11339
11340                 /* The rest of checks are only done on executing side */
11341                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11342                         goto bailout;
11343         }
11344
11345         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11346                 if (lun->be_lun &&
11347                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11348                         ctl_set_hw_write_protected(ctsio);
11349                         retval = 1;
11350                         goto bailout;
11351                 }
11352                 if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11353                         ctl_set_sense(ctsio, /*current_error*/ 1,
11354                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11355                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11356                         retval = 1;
11357                         goto bailout;
11358                 }
11359         }
11360
11361         /*
11362          * Check for a reservation conflict.  If this command isn't allowed
11363          * even on reserved LUNs, and if this initiator isn't the one who
11364          * reserved us, reject the command with a reservation conflict.
11365          */
11366         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11367         if ((lun->flags & CTL_LUN_RESERVED)
11368          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11369                 if (lun->res_idx != residx) {
11370                         ctl_set_reservation_conflict(ctsio);
11371                         retval = 1;
11372                         goto bailout;
11373                 }
11374         }
11375
11376         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11377             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11378                 /* No reservation or command is allowed. */;
11379         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11380             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11381              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11382              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11383                 /* The command is allowed for Write Exclusive resv. */;
11384         } else {
11385                 /*
11386                  * if we aren't registered or it's a res holder type
11387                  * reservation and this isn't the res holder then set a
11388                  * conflict.
11389                  */
11390                 if (ctl_get_prkey(lun, residx) == 0 ||
11391                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11392                         ctl_set_reservation_conflict(ctsio);
11393                         retval = 1;
11394                         goto bailout;
11395                 }
11396         }
11397
11398         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11399                 if (lun->flags & CTL_LUN_EJECTED)
11400                         ctl_set_lun_ejected(ctsio);
11401                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11402                         if (lun->flags & CTL_LUN_REMOVABLE)
11403                                 ctl_set_lun_no_media(ctsio);
11404                         else
11405                                 ctl_set_lun_int_reqd(ctsio);
11406                 } else if (lun->flags & CTL_LUN_STOPPED)
11407                         ctl_set_lun_stopped(ctsio);
11408                 else
11409                         goto bailout;
11410                 retval = 1;
11411                 goto bailout;
11412         }
11413
11414 bailout:
11415         return (retval);
11416 }
11417
11418 static void
11419 ctl_failover_io(union ctl_io *io, int have_lock)
11420 {
11421         ctl_set_busy(&io->scsiio);
11422         ctl_done(io);
11423 }
11424
11425 static void
11426 ctl_failover_lun(union ctl_io *rio)
11427 {
11428         struct ctl_softc *softc = control_softc;
11429         struct ctl_lun *lun;
11430         struct ctl_io_hdr *io, *next_io;
11431         uint32_t targ_lun;
11432
11433         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11434         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11435
11436         /* Find and lock the LUN. */
11437         mtx_lock(&softc->ctl_lock);
11438         if ((targ_lun < CTL_MAX_LUNS) &&
11439             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11440                 mtx_lock(&lun->lun_lock);
11441                 mtx_unlock(&softc->ctl_lock);
11442                 if (lun->flags & CTL_LUN_DISABLED) {
11443                         mtx_unlock(&lun->lun_lock);
11444                         return;
11445                 }
11446         } else {
11447                 mtx_unlock(&softc->ctl_lock);
11448                 return;
11449         }
11450
11451         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11452                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11453                         /* We are master */
11454                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11455                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11456                                         io->flags |= CTL_FLAG_ABORT;
11457                                         io->flags |= CTL_FLAG_FAILOVER;
11458                                 } else { /* This can be only due to DATAMOVE */
11459                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11460                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11461                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11462                                         io->port_status = 31340;
11463                                         ctl_enqueue_isc((union ctl_io *)io);
11464                                 }
11465                         }
11466                         /* We are slave */
11467                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11468                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11469                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11470                                         io->flags |= CTL_FLAG_FAILOVER;
11471                                 } else {
11472                                         ctl_set_busy(&((union ctl_io *)io)->
11473                                             scsiio);
11474                                         ctl_done((union ctl_io *)io);
11475                                 }
11476                         }
11477                 }
11478         } else { /* SERIALIZE modes */
11479                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11480                     next_io) {
11481                         /* We are master */
11482                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11483                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11484                                     blocked_links);
11485                                 io->flags &= ~CTL_FLAG_BLOCKED;
11486                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11487                                 ctl_free_io((union ctl_io *)io);
11488                         }
11489                 }
11490                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11491                         /* We are master */
11492                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11493                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11494                                 ctl_free_io((union ctl_io *)io);
11495                         }
11496                         /* We are slave */
11497                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11498                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11499                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11500                                         ctl_set_busy(&((union ctl_io *)io)->
11501                                             scsiio);
11502                                         ctl_done((union ctl_io *)io);
11503                                 }
11504                         }
11505                 }
11506                 ctl_check_blocked(lun);
11507         }
11508         mtx_unlock(&lun->lun_lock);
11509 }
11510
11511 static int
11512 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11513 {
11514         struct ctl_lun *lun;
11515         const struct ctl_cmd_entry *entry;
11516         uint32_t initidx, targ_lun;
11517         int retval;
11518
11519         retval = 0;
11520
11521         lun = NULL;
11522
11523         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11524         if ((targ_lun < CTL_MAX_LUNS)
11525          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11526                 /*
11527                  * If the LUN is invalid, pretend that it doesn't exist.
11528                  * It will go away as soon as all pending I/O has been
11529                  * completed.
11530                  */
11531                 mtx_lock(&lun->lun_lock);
11532                 if (lun->flags & CTL_LUN_DISABLED) {
11533                         mtx_unlock(&lun->lun_lock);
11534                         lun = NULL;
11535                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11536                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11537                 } else {
11538                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11539                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11540                                 lun->be_lun;
11541
11542                         /*
11543                          * Every I/O goes into the OOA queue for a
11544                          * particular LUN, and stays there until completion.
11545                          */
11546 #ifdef CTL_TIME_IO
11547                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11548                                 lun->idle_time += getsbinuptime() -
11549                                     lun->last_busy;
11550                         }
11551 #endif
11552                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11553                             ooa_links);
11554                 }
11555         } else {
11556                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11557                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11558         }
11559
11560         /* Get command entry and return error if it is unsuppotyed. */
11561         entry = ctl_validate_command(ctsio);
11562         if (entry == NULL) {
11563                 if (lun)
11564                         mtx_unlock(&lun->lun_lock);
11565                 return (retval);
11566         }
11567
11568         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11569         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11570
11571         /*
11572          * Check to see whether we can send this command to LUNs that don't
11573          * exist.  This should pretty much only be the case for inquiry
11574          * and request sense.  Further checks, below, really require having
11575          * a LUN, so we can't really check the command anymore.  Just put
11576          * it on the rtr queue.
11577          */
11578         if (lun == NULL) {
11579                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11580                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11581                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11582                         return (retval);
11583                 }
11584
11585                 ctl_set_unsupported_lun(ctsio);
11586                 ctl_done((union ctl_io *)ctsio);
11587                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11588                 return (retval);
11589         } else {
11590                 /*
11591                  * Make sure we support this particular command on this LUN.
11592                  * e.g., we don't support writes to the control LUN.
11593                  */
11594                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11595                         mtx_unlock(&lun->lun_lock);
11596                         ctl_set_invalid_opcode(ctsio);
11597                         ctl_done((union ctl_io *)ctsio);
11598                         return (retval);
11599                 }
11600         }
11601
11602         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11603
11604 #ifdef CTL_WITH_CA
11605         /*
11606          * If we've got a request sense, it'll clear the contingent
11607          * allegiance condition.  Otherwise, if we have a CA condition for
11608          * this initiator, clear it, because it sent down a command other
11609          * than request sense.
11610          */
11611         if ((ctsio->cdb[0] != REQUEST_SENSE)
11612          && (ctl_is_set(lun->have_ca, initidx)))
11613                 ctl_clear_mask(lun->have_ca, initidx);
11614 #endif
11615
11616         /*
11617          * If the command has this flag set, it handles its own unit
11618          * attention reporting, we shouldn't do anything.  Otherwise we
11619          * check for any pending unit attentions, and send them back to the
11620          * initiator.  We only do this when a command initially comes in,
11621          * not when we pull it off the blocked queue.
11622          *
11623          * According to SAM-3, section 5.3.2, the order that things get
11624          * presented back to the host is basically unit attentions caused
11625          * by some sort of reset event, busy status, reservation conflicts
11626          * or task set full, and finally any other status.
11627          *
11628          * One issue here is that some of the unit attentions we report
11629          * don't fall into the "reset" category (e.g. "reported luns data
11630          * has changed").  So reporting it here, before the reservation
11631          * check, may be technically wrong.  I guess the only thing to do
11632          * would be to check for and report the reset events here, and then
11633          * check for the other unit attention types after we check for a
11634          * reservation conflict.
11635          *
11636          * XXX KDM need to fix this
11637          */
11638         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11639                 ctl_ua_type ua_type;
11640
11641                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11642                     SSD_TYPE_NONE);
11643                 if (ua_type != CTL_UA_NONE) {
11644                         mtx_unlock(&lun->lun_lock);
11645                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11646                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11647                         ctsio->sense_len = SSD_FULL_SIZE;
11648                         ctl_done((union ctl_io *)ctsio);
11649                         return (retval);
11650                 }
11651         }
11652
11653
11654         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11655                 mtx_unlock(&lun->lun_lock);
11656                 ctl_done((union ctl_io *)ctsio);
11657                 return (retval);
11658         }
11659
11660         /*
11661          * XXX CHD this is where we want to send IO to other side if
11662          * this LUN is secondary on this SC. We will need to make a copy
11663          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11664          * the copy we send as FROM_OTHER.
11665          * We also need to stuff the address of the original IO so we can
11666          * find it easily. Something similar will need be done on the other
11667          * side so when we are done we can find the copy.
11668          */
11669         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11670             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11671             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11672                 union ctl_ha_msg msg_info;
11673                 int isc_retval;
11674
11675                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11676                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11677                 mtx_unlock(&lun->lun_lock);
11678
11679                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11680                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11681                 msg_info.hdr.serializing_sc = NULL;
11682                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11683                 msg_info.scsi.tag_num = ctsio->tag_num;
11684                 msg_info.scsi.tag_type = ctsio->tag_type;
11685                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11686                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11687
11688                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11689                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11690                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11691                         ctl_set_busy(ctsio);
11692                         ctl_done((union ctl_io *)ctsio);
11693                         return (retval);
11694                 }
11695                 return (retval);
11696         }
11697
11698         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11699                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11700                               ctl_ooaq, ooa_links))) {
11701         case CTL_ACTION_BLOCK:
11702                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11703                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11704                                   blocked_links);
11705                 mtx_unlock(&lun->lun_lock);
11706                 return (retval);
11707         case CTL_ACTION_PASS:
11708         case CTL_ACTION_SKIP:
11709                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11710                 mtx_unlock(&lun->lun_lock);
11711                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11712                 break;
11713         case CTL_ACTION_OVERLAP:
11714                 mtx_unlock(&lun->lun_lock);
11715                 ctl_set_overlapped_cmd(ctsio);
11716                 ctl_done((union ctl_io *)ctsio);
11717                 break;
11718         case CTL_ACTION_OVERLAP_TAG:
11719                 mtx_unlock(&lun->lun_lock);
11720                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11721                 ctl_done((union ctl_io *)ctsio);
11722                 break;
11723         case CTL_ACTION_ERROR:
11724         default:
11725                 mtx_unlock(&lun->lun_lock);
11726                 ctl_set_internal_failure(ctsio,
11727                                          /*sks_valid*/ 0,
11728                                          /*retry_count*/ 0);
11729                 ctl_done((union ctl_io *)ctsio);
11730                 break;
11731         }
11732         return (retval);
11733 }
11734
11735 const struct ctl_cmd_entry *
11736 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11737 {
11738         const struct ctl_cmd_entry *entry;
11739         int service_action;
11740
11741         entry = &ctl_cmd_table[ctsio->cdb[0]];
11742         if (sa)
11743                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11744         if (entry->flags & CTL_CMD_FLAG_SA5) {
11745                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11746                 entry = &((const struct ctl_cmd_entry *)
11747                     entry->execute)[service_action];
11748         }
11749         return (entry);
11750 }
11751
11752 const struct ctl_cmd_entry *
11753 ctl_validate_command(struct ctl_scsiio *ctsio)
11754 {
11755         const struct ctl_cmd_entry *entry;
11756         int i, sa;
11757         uint8_t diff;
11758
11759         entry = ctl_get_cmd_entry(ctsio, &sa);
11760         if (entry->execute == NULL) {
11761                 if (sa)
11762                         ctl_set_invalid_field(ctsio,
11763                                               /*sks_valid*/ 1,
11764                                               /*command*/ 1,
11765                                               /*field*/ 1,
11766                                               /*bit_valid*/ 1,
11767                                               /*bit*/ 4);
11768                 else
11769                         ctl_set_invalid_opcode(ctsio);
11770                 ctl_done((union ctl_io *)ctsio);
11771                 return (NULL);
11772         }
11773         KASSERT(entry->length > 0,
11774             ("Not defined length for command 0x%02x/0x%02x",
11775              ctsio->cdb[0], ctsio->cdb[1]));
11776         for (i = 1; i < entry->length; i++) {
11777                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11778                 if (diff == 0)
11779                         continue;
11780                 ctl_set_invalid_field(ctsio,
11781                                       /*sks_valid*/ 1,
11782                                       /*command*/ 1,
11783                                       /*field*/ i,
11784                                       /*bit_valid*/ 1,
11785                                       /*bit*/ fls(diff) - 1);
11786                 ctl_done((union ctl_io *)ctsio);
11787                 return (NULL);
11788         }
11789         return (entry);
11790 }
11791
11792 static int
11793 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11794 {
11795
11796         switch (lun_type) {
11797         case T_DIRECT:
11798                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11799                         return (0);
11800                 break;
11801         case T_PROCESSOR:
11802                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11803                         return (0);
11804                 break;
11805         case T_CDROM:
11806                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11807                         return (0);
11808                 break;
11809         default:
11810                 return (0);
11811         }
11812         return (1);
11813 }
11814
11815 static int
11816 ctl_scsiio(struct ctl_scsiio *ctsio)
11817 {
11818         int retval;
11819         const struct ctl_cmd_entry *entry;
11820
11821         retval = CTL_RETVAL_COMPLETE;
11822
11823         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11824
11825         entry = ctl_get_cmd_entry(ctsio, NULL);
11826
11827         /*
11828          * If this I/O has been aborted, just send it straight to
11829          * ctl_done() without executing it.
11830          */
11831         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11832                 ctl_done((union ctl_io *)ctsio);
11833                 goto bailout;
11834         }
11835
11836         /*
11837          * All the checks should have been handled by ctl_scsiio_precheck().
11838          * We should be clear now to just execute the I/O.
11839          */
11840         retval = entry->execute(ctsio);
11841
11842 bailout:
11843         return (retval);
11844 }
11845
11846 /*
11847  * Since we only implement one target right now, a bus reset simply resets
11848  * our single target.
11849  */
11850 static int
11851 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11852 {
11853         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11854 }
11855
11856 static int
11857 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11858                  ctl_ua_type ua_type)
11859 {
11860         struct ctl_port *port;
11861         struct ctl_lun *lun;
11862         int retval;
11863
11864         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11865                 union ctl_ha_msg msg_info;
11866
11867                 msg_info.hdr.nexus = io->io_hdr.nexus;
11868                 if (ua_type==CTL_UA_TARG_RESET)
11869                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11870                 else
11871                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11872                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11873                 msg_info.hdr.original_sc = NULL;
11874                 msg_info.hdr.serializing_sc = NULL;
11875                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11876                     sizeof(msg_info.task), M_WAITOK);
11877         }
11878         retval = 0;
11879
11880         mtx_lock(&softc->ctl_lock);
11881         port = ctl_io_port(&io->io_hdr);
11882         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11883                 if (port != NULL &&
11884                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11885                         continue;
11886                 retval += ctl_do_lun_reset(lun, io, ua_type);
11887         }
11888         mtx_unlock(&softc->ctl_lock);
11889         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11890         return (retval);
11891 }
11892
11893 /*
11894  * The LUN should always be set.  The I/O is optional, and is used to
11895  * distinguish between I/Os sent by this initiator, and by other
11896  * initiators.  We set unit attention for initiators other than this one.
11897  * SAM-3 is vague on this point.  It does say that a unit attention should
11898  * be established for other initiators when a LUN is reset (see section
11899  * 5.7.3), but it doesn't specifically say that the unit attention should
11900  * be established for this particular initiator when a LUN is reset.  Here
11901  * is the relevant text, from SAM-3 rev 8:
11902  *
11903  * 5.7.2 When a SCSI initiator port aborts its own tasks
11904  *
11905  * When a SCSI initiator port causes its own task(s) to be aborted, no
11906  * notification that the task(s) have been aborted shall be returned to
11907  * the SCSI initiator port other than the completion response for the
11908  * command or task management function action that caused the task(s) to
11909  * be aborted and notification(s) associated with related effects of the
11910  * action (e.g., a reset unit attention condition).
11911  *
11912  * XXX KDM for now, we're setting unit attention for all initiators.
11913  */
11914 static int
11915 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11916 {
11917         union ctl_io *xio;
11918 #if 0
11919         uint32_t initidx;
11920 #endif
11921         int i;
11922
11923         mtx_lock(&lun->lun_lock);
11924         /*
11925          * Run through the OOA queue and abort each I/O.
11926          */
11927         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11928              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11929                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11930         }
11931
11932         /*
11933          * This version sets unit attention for every
11934          */
11935 #if 0
11936         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11937         ctl_est_ua_all(lun, initidx, ua_type);
11938 #else
11939         ctl_est_ua_all(lun, -1, ua_type);
11940 #endif
11941
11942         /*
11943          * A reset (any kind, really) clears reservations established with
11944          * RESERVE/RELEASE.  It does not clear reservations established
11945          * with PERSISTENT RESERVE OUT, but we don't support that at the
11946          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11947          * reservations made with the RESERVE/RELEASE commands, because
11948          * those commands are obsolete in SPC-3.
11949          */
11950         lun->flags &= ~CTL_LUN_RESERVED;
11951
11952 #ifdef CTL_WITH_CA
11953         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11954                 ctl_clear_mask(lun->have_ca, i);
11955 #endif
11956         lun->prevent_count = 0;
11957         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11958                 ctl_clear_mask(lun->prevent, i);
11959         mtx_unlock(&lun->lun_lock);
11960
11961         return (0);
11962 }
11963
11964 static int
11965 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11966 {
11967         struct ctl_lun *lun;
11968         uint32_t targ_lun;
11969         int retval;
11970
11971         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11972         mtx_lock(&softc->ctl_lock);
11973         if ((targ_lun >= CTL_MAX_LUNS) ||
11974             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11975                 mtx_unlock(&softc->ctl_lock);
11976                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11977                 return (1);
11978         }
11979         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11980         mtx_unlock(&softc->ctl_lock);
11981         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11982
11983         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11984                 union ctl_ha_msg msg_info;
11985
11986                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11987                 msg_info.hdr.nexus = io->io_hdr.nexus;
11988                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11989                 msg_info.hdr.original_sc = NULL;
11990                 msg_info.hdr.serializing_sc = NULL;
11991                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11992                     sizeof(msg_info.task), M_WAITOK);
11993         }
11994         return (retval);
11995 }
11996
11997 static void
11998 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11999     int other_sc)
12000 {
12001         union ctl_io *xio;
12002
12003         mtx_assert(&lun->lun_lock, MA_OWNED);
12004
12005         /*
12006          * Run through the OOA queue and attempt to find the given I/O.
12007          * The target port, initiator ID, tag type and tag number have to
12008          * match the values that we got from the initiator.  If we have an
12009          * untagged command to abort, simply abort the first untagged command
12010          * we come to.  We only allow one untagged command at a time of course.
12011          */
12012         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12013              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12014
12015                 if ((targ_port == UINT32_MAX ||
12016                      targ_port == xio->io_hdr.nexus.targ_port) &&
12017                     (init_id == UINT32_MAX ||
12018                      init_id == xio->io_hdr.nexus.initid)) {
12019                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12020                             init_id != xio->io_hdr.nexus.initid)
12021                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12022                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12023                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12024                                 union ctl_ha_msg msg_info;
12025
12026                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12027                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12028                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12029                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12030                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12031                                 msg_info.hdr.original_sc = NULL;
12032                                 msg_info.hdr.serializing_sc = NULL;
12033                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12034                                     sizeof(msg_info.task), M_NOWAIT);
12035                         }
12036                 }
12037         }
12038 }
12039
12040 static int
12041 ctl_abort_task_set(union ctl_io *io)
12042 {
12043         struct ctl_softc *softc = control_softc;
12044         struct ctl_lun *lun;
12045         uint32_t targ_lun;
12046
12047         /*
12048          * Look up the LUN.
12049          */
12050         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12051         mtx_lock(&softc->ctl_lock);
12052         if ((targ_lun >= CTL_MAX_LUNS) ||
12053             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12054                 mtx_unlock(&softc->ctl_lock);
12055                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12056                 return (1);
12057         }
12058
12059         mtx_lock(&lun->lun_lock);
12060         mtx_unlock(&softc->ctl_lock);
12061         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12062                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12063                     io->io_hdr.nexus.initid,
12064                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12065         } else { /* CTL_TASK_CLEAR_TASK_SET */
12066                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12067                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12068         }
12069         mtx_unlock(&lun->lun_lock);
12070         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12071         return (0);
12072 }
12073
12074 static int
12075 ctl_i_t_nexus_reset(union ctl_io *io)
12076 {
12077         struct ctl_softc *softc = control_softc;
12078         struct ctl_lun *lun;
12079         uint32_t initidx;
12080
12081         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12082                 union ctl_ha_msg msg_info;
12083
12084                 msg_info.hdr.nexus = io->io_hdr.nexus;
12085                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12086                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12087                 msg_info.hdr.original_sc = NULL;
12088                 msg_info.hdr.serializing_sc = NULL;
12089                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12090                     sizeof(msg_info.task), M_WAITOK);
12091         }
12092
12093         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12094         mtx_lock(&softc->ctl_lock);
12095         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12096                 mtx_lock(&lun->lun_lock);
12097                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12098                     io->io_hdr.nexus.initid, 1);
12099 #ifdef CTL_WITH_CA
12100                 ctl_clear_mask(lun->have_ca, initidx);
12101 #endif
12102                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12103                         lun->flags &= ~CTL_LUN_RESERVED;
12104                 if (ctl_is_set(lun->prevent, initidx)) {
12105                         ctl_clear_mask(lun->prevent, initidx);
12106                         lun->prevent_count--;
12107                 }
12108                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12109                 mtx_unlock(&lun->lun_lock);
12110         }
12111         mtx_unlock(&softc->ctl_lock);
12112         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12113         return (0);
12114 }
12115
12116 static int
12117 ctl_abort_task(union ctl_io *io)
12118 {
12119         union ctl_io *xio;
12120         struct ctl_lun *lun;
12121         struct ctl_softc *softc;
12122 #if 0
12123         struct sbuf sb;
12124         char printbuf[128];
12125 #endif
12126         int found;
12127         uint32_t targ_lun;
12128
12129         softc = control_softc;
12130         found = 0;
12131
12132         /*
12133          * Look up the LUN.
12134          */
12135         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12136         mtx_lock(&softc->ctl_lock);
12137         if ((targ_lun >= CTL_MAX_LUNS) ||
12138             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12139                 mtx_unlock(&softc->ctl_lock);
12140                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12141                 return (1);
12142         }
12143
12144 #if 0
12145         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12146                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12147 #endif
12148
12149         mtx_lock(&lun->lun_lock);
12150         mtx_unlock(&softc->ctl_lock);
12151         /*
12152          * Run through the OOA queue and attempt to find the given I/O.
12153          * The target port, initiator ID, tag type and tag number have to
12154          * match the values that we got from the initiator.  If we have an
12155          * untagged command to abort, simply abort the first untagged command
12156          * we come to.  We only allow one untagged command at a time of course.
12157          */
12158         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12159              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12160 #if 0
12161                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12162
12163                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12164                             lun->lun, xio->scsiio.tag_num,
12165                             xio->scsiio.tag_type,
12166                             (xio->io_hdr.blocked_links.tqe_prev
12167                             == NULL) ? "" : " BLOCKED",
12168                             (xio->io_hdr.flags &
12169                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12170                             (xio->io_hdr.flags &
12171                             CTL_FLAG_ABORT) ? " ABORT" : "",
12172                             (xio->io_hdr.flags &
12173                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12174                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12175                 sbuf_finish(&sb);
12176                 printf("%s\n", sbuf_data(&sb));
12177 #endif
12178
12179                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12180                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12181                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12182                         continue;
12183
12184                 /*
12185                  * If the abort says that the task is untagged, the
12186                  * task in the queue must be untagged.  Otherwise,
12187                  * we just check to see whether the tag numbers
12188                  * match.  This is because the QLogic firmware
12189                  * doesn't pass back the tag type in an abort
12190                  * request.
12191                  */
12192 #if 0
12193                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12194                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12195                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12196 #endif
12197                 /*
12198                  * XXX KDM we've got problems with FC, because it
12199                  * doesn't send down a tag type with aborts.  So we
12200                  * can only really go by the tag number...
12201                  * This may cause problems with parallel SCSI.
12202                  * Need to figure that out!!
12203                  */
12204                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12205                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12206                         found = 1;
12207                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12208                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12209                                 union ctl_ha_msg msg_info;
12210
12211                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12212                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12213                                 msg_info.task.tag_num = io->taskio.tag_num;
12214                                 msg_info.task.tag_type = io->taskio.tag_type;
12215                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12216                                 msg_info.hdr.original_sc = NULL;
12217                                 msg_info.hdr.serializing_sc = NULL;
12218 #if 0
12219                                 printf("Sent Abort to other side\n");
12220 #endif
12221                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12222                                     sizeof(msg_info.task), M_NOWAIT);
12223                         }
12224 #if 0
12225                         printf("ctl_abort_task: found I/O to abort\n");
12226 #endif
12227                 }
12228         }
12229         mtx_unlock(&lun->lun_lock);
12230
12231         if (found == 0) {
12232                 /*
12233                  * This isn't really an error.  It's entirely possible for
12234                  * the abort and command completion to cross on the wire.
12235                  * This is more of an informative/diagnostic error.
12236                  */
12237 #if 0
12238                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12239                        "%u:%u:%u tag %d type %d\n",
12240                        io->io_hdr.nexus.initid,
12241                        io->io_hdr.nexus.targ_port,
12242                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12243                        io->taskio.tag_type);
12244 #endif
12245         }
12246         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12247         return (0);
12248 }
12249
12250 static int
12251 ctl_query_task(union ctl_io *io, int task_set)
12252 {
12253         union ctl_io *xio;
12254         struct ctl_lun *lun;
12255         struct ctl_softc *softc;
12256         int found = 0;
12257         uint32_t targ_lun;
12258
12259         softc = control_softc;
12260         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12261         mtx_lock(&softc->ctl_lock);
12262         if ((targ_lun >= CTL_MAX_LUNS) ||
12263             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12264                 mtx_unlock(&softc->ctl_lock);
12265                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12266                 return (1);
12267         }
12268         mtx_lock(&lun->lun_lock);
12269         mtx_unlock(&softc->ctl_lock);
12270         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12271              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12272
12273                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12274                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12275                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12276                         continue;
12277
12278                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12279                         found = 1;
12280                         break;
12281                 }
12282         }
12283         mtx_unlock(&lun->lun_lock);
12284         if (found)
12285                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12286         else
12287                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12288         return (0);
12289 }
12290
12291 static int
12292 ctl_query_async_event(union ctl_io *io)
12293 {
12294         struct ctl_lun *lun;
12295         struct ctl_softc *softc;
12296         ctl_ua_type ua;
12297         uint32_t targ_lun, initidx;
12298
12299         softc = control_softc;
12300         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12301         mtx_lock(&softc->ctl_lock);
12302         if ((targ_lun >= CTL_MAX_LUNS) ||
12303             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12304                 mtx_unlock(&softc->ctl_lock);
12305                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12306                 return (1);
12307         }
12308         mtx_lock(&lun->lun_lock);
12309         mtx_unlock(&softc->ctl_lock);
12310         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12311         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12312         mtx_unlock(&lun->lun_lock);
12313         if (ua != CTL_UA_NONE)
12314                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12315         else
12316                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12317         return (0);
12318 }
12319
12320 static void
12321 ctl_run_task(union ctl_io *io)
12322 {
12323         struct ctl_softc *softc = control_softc;
12324         int retval = 1;
12325
12326         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12327         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12328             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12329         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12330         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12331         switch (io->taskio.task_action) {
12332         case CTL_TASK_ABORT_TASK:
12333                 retval = ctl_abort_task(io);
12334                 break;
12335         case CTL_TASK_ABORT_TASK_SET:
12336         case CTL_TASK_CLEAR_TASK_SET:
12337                 retval = ctl_abort_task_set(io);
12338                 break;
12339         case CTL_TASK_CLEAR_ACA:
12340                 break;
12341         case CTL_TASK_I_T_NEXUS_RESET:
12342                 retval = ctl_i_t_nexus_reset(io);
12343                 break;
12344         case CTL_TASK_LUN_RESET:
12345                 retval = ctl_lun_reset(softc, io);
12346                 break;
12347         case CTL_TASK_TARGET_RESET:
12348                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12349                 break;
12350         case CTL_TASK_BUS_RESET:
12351                 retval = ctl_bus_reset(softc, io);
12352                 break;
12353         case CTL_TASK_PORT_LOGIN:
12354                 break;
12355         case CTL_TASK_PORT_LOGOUT:
12356                 break;
12357         case CTL_TASK_QUERY_TASK:
12358                 retval = ctl_query_task(io, 0);
12359                 break;
12360         case CTL_TASK_QUERY_TASK_SET:
12361                 retval = ctl_query_task(io, 1);
12362                 break;
12363         case CTL_TASK_QUERY_ASYNC_EVENT:
12364                 retval = ctl_query_async_event(io);
12365                 break;
12366         default:
12367                 printf("%s: got unknown task management event %d\n",
12368                        __func__, io->taskio.task_action);
12369                 break;
12370         }
12371         if (retval == 0)
12372                 io->io_hdr.status = CTL_SUCCESS;
12373         else
12374                 io->io_hdr.status = CTL_ERROR;
12375         ctl_done(io);
12376 }
12377
12378 /*
12379  * For HA operation.  Handle commands that come in from the other
12380  * controller.
12381  */
12382 static void
12383 ctl_handle_isc(union ctl_io *io)
12384 {
12385         int free_io;
12386         struct ctl_lun *lun;
12387         struct ctl_softc *softc = control_softc;
12388         uint32_t targ_lun;
12389
12390         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12391         lun = softc->ctl_luns[targ_lun];
12392
12393         switch (io->io_hdr.msg_type) {
12394         case CTL_MSG_SERIALIZE:
12395                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12396                 break;
12397         case CTL_MSG_R2R: {
12398                 const struct ctl_cmd_entry *entry;
12399
12400                 /*
12401                  * This is only used in SER_ONLY mode.
12402                  */
12403                 free_io = 0;
12404                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12405                 mtx_lock(&lun->lun_lock);
12406                 if (ctl_scsiio_lun_check(lun,
12407                     entry, (struct ctl_scsiio *)io) != 0) {
12408                         mtx_unlock(&lun->lun_lock);
12409                         ctl_done(io);
12410                         break;
12411                 }
12412                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12413                 mtx_unlock(&lun->lun_lock);
12414                 ctl_enqueue_rtr(io);
12415                 break;
12416         }
12417         case CTL_MSG_FINISH_IO:
12418                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12419                         free_io = 0;
12420                         ctl_done(io);
12421                 } else {
12422                         free_io = 1;
12423                         mtx_lock(&lun->lun_lock);
12424                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12425                                      ooa_links);
12426                         ctl_check_blocked(lun);
12427                         mtx_unlock(&lun->lun_lock);
12428                 }
12429                 break;
12430         case CTL_MSG_PERS_ACTION:
12431                 ctl_hndl_per_res_out_on_other_sc(
12432                         (union ctl_ha_msg *)&io->presio.pr_msg);
12433                 free_io = 1;
12434                 break;
12435         case CTL_MSG_BAD_JUJU:
12436                 free_io = 0;
12437                 ctl_done(io);
12438                 break;
12439         case CTL_MSG_DATAMOVE:
12440                 /* Only used in XFER mode */
12441                 free_io = 0;
12442                 ctl_datamove_remote(io);
12443                 break;
12444         case CTL_MSG_DATAMOVE_DONE:
12445                 /* Only used in XFER mode */
12446                 free_io = 0;
12447                 io->scsiio.be_move_done(io);
12448                 break;
12449         case CTL_MSG_FAILOVER:
12450                 ctl_failover_lun(io);
12451                 free_io = 1;
12452                 break;
12453         default:
12454                 free_io = 1;
12455                 printf("%s: Invalid message type %d\n",
12456                        __func__, io->io_hdr.msg_type);
12457                 break;
12458         }
12459         if (free_io)
12460                 ctl_free_io(io);
12461
12462 }
12463
12464
12465 /*
12466  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12467  * there is no match.
12468  */
12469 static ctl_lun_error_pattern
12470 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12471 {
12472         const struct ctl_cmd_entry *entry;
12473         ctl_lun_error_pattern filtered_pattern, pattern;
12474
12475         pattern = desc->error_pattern;
12476
12477         /*
12478          * XXX KDM we need more data passed into this function to match a
12479          * custom pattern, and we actually need to implement custom pattern
12480          * matching.
12481          */
12482         if (pattern & CTL_LUN_PAT_CMD)
12483                 return (CTL_LUN_PAT_CMD);
12484
12485         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12486                 return (CTL_LUN_PAT_ANY);
12487
12488         entry = ctl_get_cmd_entry(ctsio, NULL);
12489
12490         filtered_pattern = entry->pattern & pattern;
12491
12492         /*
12493          * If the user requested specific flags in the pattern (e.g.
12494          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12495          * flags.
12496          *
12497          * If the user did not specify any flags, it doesn't matter whether
12498          * or not the command supports the flags.
12499          */
12500         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12501              (pattern & ~CTL_LUN_PAT_MASK))
12502                 return (CTL_LUN_PAT_NONE);
12503
12504         /*
12505          * If the user asked for a range check, see if the requested LBA
12506          * range overlaps with this command's LBA range.
12507          */
12508         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12509                 uint64_t lba1;
12510                 uint64_t len1;
12511                 ctl_action action;
12512                 int retval;
12513
12514                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12515                 if (retval != 0)
12516                         return (CTL_LUN_PAT_NONE);
12517
12518                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12519                                               desc->lba_range.len, FALSE);
12520                 /*
12521                  * A "pass" means that the LBA ranges don't overlap, so
12522                  * this doesn't match the user's range criteria.
12523                  */
12524                 if (action == CTL_ACTION_PASS)
12525                         return (CTL_LUN_PAT_NONE);
12526         }
12527
12528         return (filtered_pattern);
12529 }
12530
12531 static void
12532 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12533 {
12534         struct ctl_error_desc *desc, *desc2;
12535
12536         mtx_assert(&lun->lun_lock, MA_OWNED);
12537
12538         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12539                 ctl_lun_error_pattern pattern;
12540                 /*
12541                  * Check to see whether this particular command matches
12542                  * the pattern in the descriptor.
12543                  */
12544                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12545                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12546                         continue;
12547
12548                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12549                 case CTL_LUN_INJ_ABORTED:
12550                         ctl_set_aborted(&io->scsiio);
12551                         break;
12552                 case CTL_LUN_INJ_MEDIUM_ERR:
12553                         ctl_set_medium_error(&io->scsiio,
12554                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12555                              CTL_FLAG_DATA_OUT);
12556                         break;
12557                 case CTL_LUN_INJ_UA:
12558                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12559                          * OCCURRED */
12560                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12561                         break;
12562                 case CTL_LUN_INJ_CUSTOM:
12563                         /*
12564                          * We're assuming the user knows what he is doing.
12565                          * Just copy the sense information without doing
12566                          * checks.
12567                          */
12568                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12569                               MIN(sizeof(desc->custom_sense),
12570                                   sizeof(io->scsiio.sense_data)));
12571                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12572                         io->scsiio.sense_len = SSD_FULL_SIZE;
12573                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12574                         break;
12575                 case CTL_LUN_INJ_NONE:
12576                 default:
12577                         /*
12578                          * If this is an error injection type we don't know
12579                          * about, clear the continuous flag (if it is set)
12580                          * so it will get deleted below.
12581                          */
12582                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12583                         break;
12584                 }
12585                 /*
12586                  * By default, each error injection action is a one-shot
12587                  */
12588                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12589                         continue;
12590
12591                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12592
12593                 free(desc, M_CTL);
12594         }
12595 }
12596
12597 #ifdef CTL_IO_DELAY
12598 static void
12599 ctl_datamove_timer_wakeup(void *arg)
12600 {
12601         union ctl_io *io;
12602
12603         io = (union ctl_io *)arg;
12604
12605         ctl_datamove(io);
12606 }
12607 #endif /* CTL_IO_DELAY */
12608
12609 void
12610 ctl_datamove(union ctl_io *io)
12611 {
12612         struct ctl_lun *lun;
12613         void (*fe_datamove)(union ctl_io *io);
12614
12615         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12616
12617         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12618
12619         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12620 #ifdef CTL_TIME_IO
12621         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12622                 char str[256];
12623                 char path_str[64];
12624                 struct sbuf sb;
12625
12626                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12627                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12628
12629                 sbuf_cat(&sb, path_str);
12630                 switch (io->io_hdr.io_type) {
12631                 case CTL_IO_SCSI:
12632                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12633                         sbuf_printf(&sb, "\n");
12634                         sbuf_cat(&sb, path_str);
12635                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12636                                     io->scsiio.tag_num, io->scsiio.tag_type);
12637                         break;
12638                 case CTL_IO_TASK:
12639                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12640                                     "Tag Type: %d\n", io->taskio.task_action,
12641                                     io->taskio.tag_num, io->taskio.tag_type);
12642                         break;
12643                 default:
12644                         panic("%s: Invalid CTL I/O type %d\n",
12645                             __func__, io->io_hdr.io_type);
12646                 }
12647                 sbuf_cat(&sb, path_str);
12648                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12649                             (intmax_t)time_uptime - io->io_hdr.start_time);
12650                 sbuf_finish(&sb);
12651                 printf("%s", sbuf_data(&sb));
12652         }
12653 #endif /* CTL_TIME_IO */
12654
12655 #ifdef CTL_IO_DELAY
12656         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12657                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12658         } else {
12659                 if ((lun != NULL)
12660                  && (lun->delay_info.datamove_delay > 0)) {
12661
12662                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12663                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12664                         callout_reset(&io->io_hdr.delay_callout,
12665                                       lun->delay_info.datamove_delay * hz,
12666                                       ctl_datamove_timer_wakeup, io);
12667                         if (lun->delay_info.datamove_type ==
12668                             CTL_DELAY_TYPE_ONESHOT)
12669                                 lun->delay_info.datamove_delay = 0;
12670                         return;
12671                 }
12672         }
12673 #endif
12674
12675         /*
12676          * This command has been aborted.  Set the port status, so we fail
12677          * the data move.
12678          */
12679         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12680                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12681                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12682                        io->io_hdr.nexus.targ_port,
12683                        io->io_hdr.nexus.targ_lun);
12684                 io->io_hdr.port_status = 31337;
12685                 /*
12686                  * Note that the backend, in this case, will get the
12687                  * callback in its context.  In other cases it may get
12688                  * called in the frontend's interrupt thread context.
12689                  */
12690                 io->scsiio.be_move_done(io);
12691                 return;
12692         }
12693
12694         /* Don't confuse frontend with zero length data move. */
12695         if (io->scsiio.kern_data_len == 0) {
12696                 io->scsiio.be_move_done(io);
12697                 return;
12698         }
12699
12700         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12701         fe_datamove(io);
12702 }
12703
12704 static void
12705 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12706 {
12707         union ctl_ha_msg msg;
12708 #ifdef CTL_TIME_IO
12709         struct bintime cur_bt;
12710 #endif
12711
12712         memset(&msg, 0, sizeof(msg));
12713         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12714         msg.hdr.original_sc = io;
12715         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12716         msg.hdr.nexus = io->io_hdr.nexus;
12717         msg.hdr.status = io->io_hdr.status;
12718         msg.scsi.tag_num = io->scsiio.tag_num;
12719         msg.scsi.tag_type = io->scsiio.tag_type;
12720         msg.scsi.scsi_status = io->scsiio.scsi_status;
12721         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12722                io->scsiio.sense_len);
12723         msg.scsi.sense_len = io->scsiio.sense_len;
12724         msg.scsi.sense_residual = io->scsiio.sense_residual;
12725         msg.scsi.fetd_status = io->io_hdr.port_status;
12726         msg.scsi.residual = io->scsiio.residual;
12727         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12728         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12729                 ctl_failover_io(io, /*have_lock*/ have_lock);
12730                 return;
12731         }
12732         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12733             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12734             msg.scsi.sense_len, M_WAITOK);
12735
12736 #ifdef CTL_TIME_IO
12737         getbinuptime(&cur_bt);
12738         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12739         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12740 #endif
12741         io->io_hdr.num_dmas++;
12742 }
12743
12744 /*
12745  * The DMA to the remote side is done, now we need to tell the other side
12746  * we're done so it can continue with its data movement.
12747  */
12748 static void
12749 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12750 {
12751         union ctl_io *io;
12752         uint32_t i;
12753
12754         io = rq->context;
12755
12756         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12757                 printf("%s: ISC DMA write failed with error %d", __func__,
12758                        rq->ret);
12759                 ctl_set_internal_failure(&io->scsiio,
12760                                          /*sks_valid*/ 1,
12761                                          /*retry_count*/ rq->ret);
12762         }
12763
12764         ctl_dt_req_free(rq);
12765
12766         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12767                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12768         free(io->io_hdr.remote_sglist, M_CTL);
12769         io->io_hdr.remote_sglist = NULL;
12770         io->io_hdr.local_sglist = NULL;
12771
12772         /*
12773          * The data is in local and remote memory, so now we need to send
12774          * status (good or back) back to the other side.
12775          */
12776         ctl_send_datamove_done(io, /*have_lock*/ 0);
12777 }
12778
12779 /*
12780  * We've moved the data from the host/controller into local memory.  Now we
12781  * need to push it over to the remote controller's memory.
12782  */
12783 static int
12784 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12785 {
12786         int retval;
12787
12788         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12789                                           ctl_datamove_remote_write_cb);
12790         return (retval);
12791 }
12792
12793 static void
12794 ctl_datamove_remote_write(union ctl_io *io)
12795 {
12796         int retval;
12797         void (*fe_datamove)(union ctl_io *io);
12798
12799         /*
12800          * - Get the data from the host/HBA into local memory.
12801          * - DMA memory from the local controller to the remote controller.
12802          * - Send status back to the remote controller.
12803          */
12804
12805         retval = ctl_datamove_remote_sgl_setup(io);
12806         if (retval != 0)
12807                 return;
12808
12809         /* Switch the pointer over so the FETD knows what to do */
12810         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12811
12812         /*
12813          * Use a custom move done callback, since we need to send completion
12814          * back to the other controller, not to the backend on this side.
12815          */
12816         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12817
12818         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12819         fe_datamove(io);
12820 }
12821
12822 static int
12823 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12824 {
12825 #if 0
12826         char str[256];
12827         char path_str[64];
12828         struct sbuf sb;
12829 #endif
12830         uint32_t i;
12831
12832         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12833                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12834         free(io->io_hdr.remote_sglist, M_CTL);
12835         io->io_hdr.remote_sglist = NULL;
12836         io->io_hdr.local_sglist = NULL;
12837
12838 #if 0
12839         scsi_path_string(io, path_str, sizeof(path_str));
12840         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12841         sbuf_cat(&sb, path_str);
12842         scsi_command_string(&io->scsiio, NULL, &sb);
12843         sbuf_printf(&sb, "\n");
12844         sbuf_cat(&sb, path_str);
12845         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12846                     io->scsiio.tag_num, io->scsiio.tag_type);
12847         sbuf_cat(&sb, path_str);
12848         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12849                     io->io_hdr.flags, io->io_hdr.status);
12850         sbuf_finish(&sb);
12851         printk("%s", sbuf_data(&sb));
12852 #endif
12853
12854
12855         /*
12856          * The read is done, now we need to send status (good or bad) back
12857          * to the other side.
12858          */
12859         ctl_send_datamove_done(io, /*have_lock*/ 0);
12860
12861         return (0);
12862 }
12863
12864 static void
12865 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12866 {
12867         union ctl_io *io;
12868         void (*fe_datamove)(union ctl_io *io);
12869
12870         io = rq->context;
12871
12872         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12873                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12874                        rq->ret);
12875                 ctl_set_internal_failure(&io->scsiio,
12876                                          /*sks_valid*/ 1,
12877                                          /*retry_count*/ rq->ret);
12878         }
12879
12880         ctl_dt_req_free(rq);
12881
12882         /* Switch the pointer over so the FETD knows what to do */
12883         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12884
12885         /*
12886          * Use a custom move done callback, since we need to send completion
12887          * back to the other controller, not to the backend on this side.
12888          */
12889         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12890
12891         /* XXX KDM add checks like the ones in ctl_datamove? */
12892
12893         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12894         fe_datamove(io);
12895 }
12896
12897 static int
12898 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12899 {
12900         struct ctl_sg_entry *local_sglist;
12901         uint32_t len_to_go;
12902         int retval;
12903         int i;
12904
12905         retval = 0;
12906         local_sglist = io->io_hdr.local_sglist;
12907         len_to_go = io->scsiio.kern_data_len;
12908
12909         /*
12910          * The difficult thing here is that the size of the various
12911          * S/G segments may be different than the size from the
12912          * remote controller.  That'll make it harder when DMAing
12913          * the data back to the other side.
12914          */
12915         for (i = 0; len_to_go > 0; i++) {
12916                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12917                 local_sglist[i].addr =
12918                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12919
12920                 len_to_go -= local_sglist[i].len;
12921         }
12922         /*
12923          * Reset the number of S/G entries accordingly.  The original
12924          * number of S/G entries is available in rem_sg_entries.
12925          */
12926         io->scsiio.kern_sg_entries = i;
12927
12928 #if 0
12929         printf("%s: kern_sg_entries = %d\n", __func__,
12930                io->scsiio.kern_sg_entries);
12931         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12932                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12933                        local_sglist[i].addr, local_sglist[i].len);
12934 #endif
12935
12936         return (retval);
12937 }
12938
12939 static int
12940 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12941                          ctl_ha_dt_cb callback)
12942 {
12943         struct ctl_ha_dt_req *rq;
12944         struct ctl_sg_entry *remote_sglist, *local_sglist;
12945         uint32_t local_used, remote_used, total_used;
12946         int i, j, isc_ret;
12947
12948         rq = ctl_dt_req_alloc();
12949
12950         /*
12951          * If we failed to allocate the request, and if the DMA didn't fail
12952          * anyway, set busy status.  This is just a resource allocation
12953          * failure.
12954          */
12955         if ((rq == NULL)
12956          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12957              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12958                 ctl_set_busy(&io->scsiio);
12959
12960         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12961             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12962
12963                 if (rq != NULL)
12964                         ctl_dt_req_free(rq);
12965
12966                 /*
12967                  * The data move failed.  We need to return status back
12968                  * to the other controller.  No point in trying to DMA
12969                  * data to the remote controller.
12970                  */
12971
12972                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12973
12974                 return (1);
12975         }
12976
12977         local_sglist = io->io_hdr.local_sglist;
12978         remote_sglist = io->io_hdr.remote_sglist;
12979         local_used = 0;
12980         remote_used = 0;
12981         total_used = 0;
12982
12983         /*
12984          * Pull/push the data over the wire from/to the other controller.
12985          * This takes into account the possibility that the local and
12986          * remote sglists may not be identical in terms of the size of
12987          * the elements and the number of elements.
12988          *
12989          * One fundamental assumption here is that the length allocated for
12990          * both the local and remote sglists is identical.  Otherwise, we've
12991          * essentially got a coding error of some sort.
12992          */
12993         isc_ret = CTL_HA_STATUS_SUCCESS;
12994         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12995                 uint32_t cur_len;
12996                 uint8_t *tmp_ptr;
12997
12998                 rq->command = command;
12999                 rq->context = io;
13000
13001                 /*
13002                  * Both pointers should be aligned.  But it is possible
13003                  * that the allocation length is not.  They should both
13004                  * also have enough slack left over at the end, though,
13005                  * to round up to the next 8 byte boundary.
13006                  */
13007                 cur_len = MIN(local_sglist[i].len - local_used,
13008                               remote_sglist[j].len - remote_used);
13009                 rq->size = cur_len;
13010
13011                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13012                 tmp_ptr += local_used;
13013
13014 #if 0
13015                 /* Use physical addresses when talking to ISC hardware */
13016                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13017                         /* XXX KDM use busdma */
13018                         rq->local = vtophys(tmp_ptr);
13019                 } else
13020                         rq->local = tmp_ptr;
13021 #else
13022                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13023                     ("HA does not support BUS_ADDR"));
13024                 rq->local = tmp_ptr;
13025 #endif
13026
13027                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13028                 tmp_ptr += remote_used;
13029                 rq->remote = tmp_ptr;
13030
13031                 rq->callback = NULL;
13032
13033                 local_used += cur_len;
13034                 if (local_used >= local_sglist[i].len) {
13035                         i++;
13036                         local_used = 0;
13037                 }
13038
13039                 remote_used += cur_len;
13040                 if (remote_used >= remote_sglist[j].len) {
13041                         j++;
13042                         remote_used = 0;
13043                 }
13044                 total_used += cur_len;
13045
13046                 if (total_used >= io->scsiio.kern_data_len)
13047                         rq->callback = callback;
13048
13049 #if 0
13050                 printf("%s: %s: local %p remote %p size %d\n", __func__,
13051                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13052                        rq->local, rq->remote, rq->size);
13053 #endif
13054
13055                 isc_ret = ctl_dt_single(rq);
13056                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
13057                         break;
13058         }
13059         if (isc_ret != CTL_HA_STATUS_WAIT) {
13060                 rq->ret = isc_ret;
13061                 callback(rq);
13062         }
13063
13064         return (0);
13065 }
13066
13067 static void
13068 ctl_datamove_remote_read(union ctl_io *io)
13069 {
13070         int retval;
13071         uint32_t i;
13072
13073         /*
13074          * This will send an error to the other controller in the case of a
13075          * failure.
13076          */
13077         retval = ctl_datamove_remote_sgl_setup(io);
13078         if (retval != 0)
13079                 return;
13080
13081         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13082                                           ctl_datamove_remote_read_cb);
13083         if (retval != 0) {
13084                 /*
13085                  * Make sure we free memory if there was an error..  The
13086                  * ctl_datamove_remote_xfer() function will send the
13087                  * datamove done message, or call the callback with an
13088                  * error if there is a problem.
13089                  */
13090                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13091                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13092                 free(io->io_hdr.remote_sglist, M_CTL);
13093                 io->io_hdr.remote_sglist = NULL;
13094                 io->io_hdr.local_sglist = NULL;
13095         }
13096 }
13097
13098 /*
13099  * Process a datamove request from the other controller.  This is used for
13100  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13101  * first.  Once that is complete, the data gets DMAed into the remote
13102  * controller's memory.  For reads, we DMA from the remote controller's
13103  * memory into our memory first, and then move it out to the FETD.
13104  */
13105 static void
13106 ctl_datamove_remote(union ctl_io *io)
13107 {
13108
13109         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13110
13111         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13112                 ctl_failover_io(io, /*have_lock*/ 0);
13113                 return;
13114         }
13115
13116         /*
13117          * Note that we look for an aborted I/O here, but don't do some of
13118          * the other checks that ctl_datamove() normally does.
13119          * We don't need to run the datamove delay code, since that should
13120          * have been done if need be on the other controller.
13121          */
13122         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13123                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13124                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13125                        io->io_hdr.nexus.targ_port,
13126                        io->io_hdr.nexus.targ_lun);
13127                 io->io_hdr.port_status = 31338;
13128                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13129                 return;
13130         }
13131
13132         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13133                 ctl_datamove_remote_write(io);
13134         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13135                 ctl_datamove_remote_read(io);
13136         else {
13137                 io->io_hdr.port_status = 31339;
13138                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13139         }
13140 }
13141
13142 static void
13143 ctl_process_done(union ctl_io *io)
13144 {
13145         struct ctl_lun *lun;
13146         struct ctl_softc *softc = control_softc;
13147         void (*fe_done)(union ctl_io *io);
13148         union ctl_ha_msg msg;
13149         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13150
13151         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13152         fe_done = softc->ctl_ports[targ_port]->fe_done;
13153
13154 #ifdef CTL_TIME_IO
13155         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13156                 char str[256];
13157                 char path_str[64];
13158                 struct sbuf sb;
13159
13160                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13161                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13162
13163                 sbuf_cat(&sb, path_str);
13164                 switch (io->io_hdr.io_type) {
13165                 case CTL_IO_SCSI:
13166                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13167                         sbuf_printf(&sb, "\n");
13168                         sbuf_cat(&sb, path_str);
13169                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13170                                     io->scsiio.tag_num, io->scsiio.tag_type);
13171                         break;
13172                 case CTL_IO_TASK:
13173                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13174                                     "Tag Type: %d\n", io->taskio.task_action,
13175                                     io->taskio.tag_num, io->taskio.tag_type);
13176                         break;
13177                 default:
13178                         panic("%s: Invalid CTL I/O type %d\n",
13179                             __func__, io->io_hdr.io_type);
13180                 }
13181                 sbuf_cat(&sb, path_str);
13182                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13183                             (intmax_t)time_uptime - io->io_hdr.start_time);
13184                 sbuf_finish(&sb);
13185                 printf("%s", sbuf_data(&sb));
13186         }
13187 #endif /* CTL_TIME_IO */
13188
13189         switch (io->io_hdr.io_type) {
13190         case CTL_IO_SCSI:
13191                 break;
13192         case CTL_IO_TASK:
13193                 if (ctl_debug & CTL_DEBUG_INFO)
13194                         ctl_io_error_print(io, NULL);
13195                 fe_done(io);
13196                 return;
13197         default:
13198                 panic("%s: Invalid CTL I/O type %d\n",
13199                     __func__, io->io_hdr.io_type);
13200         }
13201
13202         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13203         if (lun == NULL) {
13204                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13205                                  io->io_hdr.nexus.targ_mapped_lun));
13206                 goto bailout;
13207         }
13208
13209         mtx_lock(&lun->lun_lock);
13210
13211         /*
13212          * Check to see if we have any informational exception and status
13213          * of this command can be modified to report it in form of either
13214          * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13215          */
13216         if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13217             io->io_hdr.status == CTL_SUCCESS &&
13218             (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13219                 uint8_t mrie = lun->MODE_IE.mrie;
13220                 uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13221                     (lun->MODE_VER.byte3 & SMS_VER_PER));
13222                 if (((mrie == SIEP_MRIE_REC_COND && per) ||
13223                      mrie == SIEP_MRIE_REC_UNCOND ||
13224                      mrie == SIEP_MRIE_NO_SENSE) &&
13225                     (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13226                      CTL_CMD_FLAG_NO_SENSE) == 0) {
13227                         ctl_set_sense(&io->scsiio,
13228                               /*current_error*/ 1,
13229                               /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13230                                 SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13231                               /*asc*/ lun->ie_asc,
13232                               /*ascq*/ lun->ie_ascq,
13233                               SSD_ELEM_NONE);
13234                         lun->ie_reported = 1;
13235                 }
13236         } else if (lun->ie_reported < 0)
13237                 lun->ie_reported = 0;
13238
13239         /*
13240          * Check to see if we have any errors to inject here.  We only
13241          * inject errors for commands that don't already have errors set.
13242          */
13243         if (!STAILQ_EMPTY(&lun->error_list) &&
13244             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13245             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13246                 ctl_inject_error(lun, io);
13247
13248         /*
13249          * XXX KDM how do we treat commands that aren't completed
13250          * successfully?
13251          *
13252          * XXX KDM should we also track I/O latency?
13253          */
13254         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13255             io->io_hdr.io_type == CTL_IO_SCSI) {
13256 #ifdef CTL_TIME_IO
13257                 struct bintime cur_bt;
13258 #endif
13259                 int type;
13260
13261                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13262                     CTL_FLAG_DATA_IN)
13263                         type = CTL_STATS_READ;
13264                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13265                     CTL_FLAG_DATA_OUT)
13266                         type = CTL_STATS_WRITE;
13267                 else
13268                         type = CTL_STATS_NO_IO;
13269
13270                 lun->stats.ports[targ_port].bytes[type] +=
13271                     io->scsiio.kern_total_len;
13272                 lun->stats.ports[targ_port].operations[type]++;
13273 #ifdef CTL_TIME_IO
13274                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13275                    &io->io_hdr.dma_bt);
13276                 getbinuptime(&cur_bt);
13277                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13278                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13279 #endif
13280                 lun->stats.ports[targ_port].num_dmas[type] +=
13281                     io->io_hdr.num_dmas;
13282         }
13283
13284         /*
13285          * Remove this from the OOA queue.
13286          */
13287         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13288 #ifdef CTL_TIME_IO
13289         if (TAILQ_EMPTY(&lun->ooa_queue))
13290                 lun->last_busy = getsbinuptime();
13291 #endif
13292
13293         /*
13294          * Run through the blocked queue on this LUN and see if anything
13295          * has become unblocked, now that this transaction is done.
13296          */
13297         ctl_check_blocked(lun);
13298
13299         /*
13300          * If the LUN has been invalidated, free it if there is nothing
13301          * left on its OOA queue.
13302          */
13303         if ((lun->flags & CTL_LUN_INVALID)
13304          && TAILQ_EMPTY(&lun->ooa_queue)) {
13305                 mtx_unlock(&lun->lun_lock);
13306                 mtx_lock(&softc->ctl_lock);
13307                 ctl_free_lun(lun);
13308                 mtx_unlock(&softc->ctl_lock);
13309         } else
13310                 mtx_unlock(&lun->lun_lock);
13311
13312 bailout:
13313
13314         /*
13315          * If this command has been aborted, make sure we set the status
13316          * properly.  The FETD is responsible for freeing the I/O and doing
13317          * whatever it needs to do to clean up its state.
13318          */
13319         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13320                 ctl_set_task_aborted(&io->scsiio);
13321
13322         /*
13323          * If enabled, print command error status.
13324          */
13325         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13326             (ctl_debug & CTL_DEBUG_INFO) != 0)
13327                 ctl_io_error_print(io, NULL);
13328
13329         /*
13330          * Tell the FETD or the other shelf controller we're done with this
13331          * command.  Note that only SCSI commands get to this point.  Task
13332          * management commands are completed above.
13333          */
13334         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13335             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13336                 memset(&msg, 0, sizeof(msg));
13337                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13338                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13339                 msg.hdr.nexus = io->io_hdr.nexus;
13340                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13341                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13342                     M_WAITOK);
13343         }
13344
13345         fe_done(io);
13346 }
13347
13348 #ifdef CTL_WITH_CA
13349 /*
13350  * Front end should call this if it doesn't do autosense.  When the request
13351  * sense comes back in from the initiator, we'll dequeue this and send it.
13352  */
13353 int
13354 ctl_queue_sense(union ctl_io *io)
13355 {
13356         struct ctl_lun *lun;
13357         struct ctl_port *port;
13358         struct ctl_softc *softc;
13359         uint32_t initidx, targ_lun;
13360
13361         softc = control_softc;
13362
13363         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13364
13365         /*
13366          * LUN lookup will likely move to the ctl_work_thread() once we
13367          * have our new queueing infrastructure (that doesn't put things on
13368          * a per-LUN queue initially).  That is so that we can handle
13369          * things like an INQUIRY to a LUN that we don't have enabled.  We
13370          * can't deal with that right now.
13371          */
13372         mtx_lock(&softc->ctl_lock);
13373
13374         /*
13375          * If we don't have a LUN for this, just toss the sense
13376          * information.
13377          */
13378         port = ctl_io_port(&ctsio->io_hdr);
13379         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13380         if ((targ_lun < CTL_MAX_LUNS)
13381          && (softc->ctl_luns[targ_lun] != NULL))
13382                 lun = softc->ctl_luns[targ_lun];
13383         else
13384                 goto bailout;
13385
13386         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13387
13388         mtx_lock(&lun->lun_lock);
13389         /*
13390          * Already have CA set for this LUN...toss the sense information.
13391          */
13392         if (ctl_is_set(lun->have_ca, initidx)) {
13393                 mtx_unlock(&lun->lun_lock);
13394                 goto bailout;
13395         }
13396
13397         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13398                MIN(sizeof(lun->pending_sense[initidx]),
13399                sizeof(io->scsiio.sense_data)));
13400         ctl_set_mask(lun->have_ca, initidx);
13401         mtx_unlock(&lun->lun_lock);
13402
13403 bailout:
13404         mtx_unlock(&softc->ctl_lock);
13405
13406         ctl_free_io(io);
13407
13408         return (CTL_RETVAL_COMPLETE);
13409 }
13410 #endif
13411
13412 /*
13413  * Primary command inlet from frontend ports.  All SCSI and task I/O
13414  * requests must go through this function.
13415  */
13416 int
13417 ctl_queue(union ctl_io *io)
13418 {
13419         struct ctl_port *port;
13420
13421         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13422
13423 #ifdef CTL_TIME_IO
13424         io->io_hdr.start_time = time_uptime;
13425         getbinuptime(&io->io_hdr.start_bt);
13426 #endif /* CTL_TIME_IO */
13427
13428         /* Map FE-specific LUN ID into global one. */
13429         port = ctl_io_port(&io->io_hdr);
13430         io->io_hdr.nexus.targ_mapped_lun =
13431             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13432
13433         switch (io->io_hdr.io_type) {
13434         case CTL_IO_SCSI:
13435         case CTL_IO_TASK:
13436                 if (ctl_debug & CTL_DEBUG_CDB)
13437                         ctl_io_print(io);
13438                 ctl_enqueue_incoming(io);
13439                 break;
13440         default:
13441                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13442                 return (EINVAL);
13443         }
13444
13445         return (CTL_RETVAL_COMPLETE);
13446 }
13447
13448 #ifdef CTL_IO_DELAY
13449 static void
13450 ctl_done_timer_wakeup(void *arg)
13451 {
13452         union ctl_io *io;
13453
13454         io = (union ctl_io *)arg;
13455         ctl_done(io);
13456 }
13457 #endif /* CTL_IO_DELAY */
13458
13459 void
13460 ctl_serseq_done(union ctl_io *io)
13461 {
13462         struct ctl_lun *lun;
13463
13464         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13465         if (lun->be_lun == NULL ||
13466             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13467                 return;
13468         mtx_lock(&lun->lun_lock);
13469         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13470         ctl_check_blocked(lun);
13471         mtx_unlock(&lun->lun_lock);
13472 }
13473
13474 void
13475 ctl_done(union ctl_io *io)
13476 {
13477
13478         /*
13479          * Enable this to catch duplicate completion issues.
13480          */
13481 #if 0
13482         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13483                 printf("%s: type %d msg %d cdb %x iptl: "
13484                        "%u:%u:%u tag 0x%04x "
13485                        "flag %#x status %x\n",
13486                         __func__,
13487                         io->io_hdr.io_type,
13488                         io->io_hdr.msg_type,
13489                         io->scsiio.cdb[0],
13490                         io->io_hdr.nexus.initid,
13491                         io->io_hdr.nexus.targ_port,
13492                         io->io_hdr.nexus.targ_lun,
13493                         (io->io_hdr.io_type ==
13494                         CTL_IO_TASK) ?
13495                         io->taskio.tag_num :
13496                         io->scsiio.tag_num,
13497                         io->io_hdr.flags,
13498                         io->io_hdr.status);
13499         } else
13500                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13501 #endif
13502
13503         /*
13504          * This is an internal copy of an I/O, and should not go through
13505          * the normal done processing logic.
13506          */
13507         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13508                 return;
13509
13510 #ifdef CTL_IO_DELAY
13511         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13512                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13513         } else {
13514                 struct ctl_lun *lun;
13515
13516                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13517
13518                 if ((lun != NULL)
13519                  && (lun->delay_info.done_delay > 0)) {
13520
13521                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13522                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13523                         callout_reset(&io->io_hdr.delay_callout,
13524                                       lun->delay_info.done_delay * hz,
13525                                       ctl_done_timer_wakeup, io);
13526                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13527                                 lun->delay_info.done_delay = 0;
13528                         return;
13529                 }
13530         }
13531 #endif /* CTL_IO_DELAY */
13532
13533         ctl_enqueue_done(io);
13534 }
13535
13536 static void
13537 ctl_work_thread(void *arg)
13538 {
13539         struct ctl_thread *thr = (struct ctl_thread *)arg;
13540         struct ctl_softc *softc = thr->ctl_softc;
13541         union ctl_io *io;
13542         int retval;
13543
13544         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13545
13546         for (;;) {
13547                 /*
13548                  * We handle the queues in this order:
13549                  * - ISC
13550                  * - done queue (to free up resources, unblock other commands)
13551                  * - RtR queue
13552                  * - incoming queue
13553                  *
13554                  * If those queues are empty, we break out of the loop and
13555                  * go to sleep.
13556                  */
13557                 mtx_lock(&thr->queue_lock);
13558                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13559                 if (io != NULL) {
13560                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13561                         mtx_unlock(&thr->queue_lock);
13562                         ctl_handle_isc(io);
13563                         continue;
13564                 }
13565                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13566                 if (io != NULL) {
13567                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13568                         /* clear any blocked commands, call fe_done */
13569                         mtx_unlock(&thr->queue_lock);
13570                         ctl_process_done(io);
13571                         continue;
13572                 }
13573                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13574                 if (io != NULL) {
13575                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13576                         mtx_unlock(&thr->queue_lock);
13577                         if (io->io_hdr.io_type == CTL_IO_TASK)
13578                                 ctl_run_task(io);
13579                         else
13580                                 ctl_scsiio_precheck(softc, &io->scsiio);
13581                         continue;
13582                 }
13583                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13584                 if (io != NULL) {
13585                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13586                         mtx_unlock(&thr->queue_lock);
13587                         retval = ctl_scsiio(&io->scsiio);
13588                         if (retval != CTL_RETVAL_COMPLETE)
13589                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13590                         continue;
13591                 }
13592
13593                 /* Sleep until we have something to do. */
13594                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13595         }
13596 }
13597
13598 static void
13599 ctl_lun_thread(void *arg)
13600 {
13601         struct ctl_softc *softc = (struct ctl_softc *)arg;
13602         struct ctl_be_lun *be_lun;
13603
13604         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13605
13606         for (;;) {
13607                 mtx_lock(&softc->ctl_lock);
13608                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13609                 if (be_lun != NULL) {
13610                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13611                         mtx_unlock(&softc->ctl_lock);
13612                         ctl_create_lun(be_lun);
13613                         continue;
13614                 }
13615
13616                 /* Sleep until we have something to do. */
13617                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13618                     PDROP | PRIBIO, "-", 0);
13619         }
13620 }
13621
13622 static void
13623 ctl_thresh_thread(void *arg)
13624 {
13625         struct ctl_softc *softc = (struct ctl_softc *)arg;
13626         struct ctl_lun *lun;
13627         struct ctl_logical_block_provisioning_page *page;
13628         const char *attr;
13629         union ctl_ha_msg msg;
13630         uint64_t thres, val;
13631         int i, e, set;
13632
13633         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13634
13635         for (;;) {
13636                 mtx_lock(&softc->ctl_lock);
13637                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13638                         if ((lun->flags & CTL_LUN_DISABLED) ||
13639                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13640                             lun->backend->lun_attr == NULL)
13641                                 continue;
13642                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13643                             softc->ha_mode == CTL_HA_MODE_XFER)
13644                                 continue;
13645                         if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13646                                 continue;
13647                         e = 0;
13648                         page = &lun->MODE_LBP;
13649                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13650                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13651                                         continue;
13652                                 thres = scsi_4btoul(page->descr[i].count);
13653                                 thres <<= CTL_LBP_EXPONENT;
13654                                 switch (page->descr[i].resource) {
13655                                 case 0x01:
13656                                         attr = "blocksavail";
13657                                         break;
13658                                 case 0x02:
13659                                         attr = "blocksused";
13660                                         break;
13661                                 case 0xf1:
13662                                         attr = "poolblocksavail";
13663                                         break;
13664                                 case 0xf2:
13665                                         attr = "poolblocksused";
13666                                         break;
13667                                 default:
13668                                         continue;
13669                                 }
13670                                 mtx_unlock(&softc->ctl_lock); // XXX
13671                                 val = lun->backend->lun_attr(
13672                                     lun->be_lun->be_lun, attr);
13673                                 mtx_lock(&softc->ctl_lock);
13674                                 if (val == UINT64_MAX)
13675                                         continue;
13676                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13677                                     == SLBPPD_ARMING_INC)
13678                                         e = (val >= thres);
13679                                 else
13680                                         e = (val <= thres);
13681                                 if (e)
13682                                         break;
13683                         }
13684                         mtx_lock(&lun->lun_lock);
13685                         if (e) {
13686                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13687                                     (uint8_t *)page, lun->ua_tpt_info);
13688                                 if (lun->lasttpt == 0 ||
13689                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13690                                         lun->lasttpt = time_uptime;
13691                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13692                                         set = 1;
13693                                 } else
13694                                         set = 0;
13695                         } else {
13696                                 lun->lasttpt = 0;
13697                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13698                                 set = -1;
13699                         }
13700                         mtx_unlock(&lun->lun_lock);
13701                         if (set != 0 &&
13702                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13703                                 /* Send msg to other side. */
13704                                 bzero(&msg.ua, sizeof(msg.ua));
13705                                 msg.hdr.msg_type = CTL_MSG_UA;
13706                                 msg.hdr.nexus.initid = -1;
13707                                 msg.hdr.nexus.targ_port = -1;
13708                                 msg.hdr.nexus.targ_lun = lun->lun;
13709                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13710                                 msg.ua.ua_all = 1;
13711                                 msg.ua.ua_set = (set > 0);
13712                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13713                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13714                                 mtx_unlock(&softc->ctl_lock); // XXX
13715                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13716                                     sizeof(msg.ua), M_WAITOK);
13717                                 mtx_lock(&softc->ctl_lock);
13718                         }
13719                 }
13720                 mtx_unlock(&softc->ctl_lock);
13721                 pause("-", CTL_LBP_PERIOD * hz);
13722         }
13723 }
13724
13725 static void
13726 ctl_enqueue_incoming(union ctl_io *io)
13727 {
13728         struct ctl_softc *softc = control_softc;
13729         struct ctl_thread *thr;
13730         u_int idx;
13731
13732         idx = (io->io_hdr.nexus.targ_port * 127 +
13733                io->io_hdr.nexus.initid) % worker_threads;
13734         thr = &softc->threads[idx];
13735         mtx_lock(&thr->queue_lock);
13736         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13737         mtx_unlock(&thr->queue_lock);
13738         wakeup(thr);
13739 }
13740
13741 static void
13742 ctl_enqueue_rtr(union ctl_io *io)
13743 {
13744         struct ctl_softc *softc = control_softc;
13745         struct ctl_thread *thr;
13746
13747         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13748         mtx_lock(&thr->queue_lock);
13749         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13750         mtx_unlock(&thr->queue_lock);
13751         wakeup(thr);
13752 }
13753
13754 static void
13755 ctl_enqueue_done(union ctl_io *io)
13756 {
13757         struct ctl_softc *softc = control_softc;
13758         struct ctl_thread *thr;
13759
13760         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13761         mtx_lock(&thr->queue_lock);
13762         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13763         mtx_unlock(&thr->queue_lock);
13764         wakeup(thr);
13765 }
13766
13767 static void
13768 ctl_enqueue_isc(union ctl_io *io)
13769 {
13770         struct ctl_softc *softc = control_softc;
13771         struct ctl_thread *thr;
13772
13773         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13774         mtx_lock(&thr->queue_lock);
13775         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13776         mtx_unlock(&thr->queue_lock);
13777         wakeup(thr);
13778 }
13779
13780 /*
13781  *  vim: ts=8
13782  */