]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r310555: Some random code cleaning.
[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*/0xff
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*/SLBPP_SITUA,
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 void 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_unlock(&softc->ctl_lock);
1032                 return;
1033         }
1034         mtx_lock(&lun->lun_lock);
1035         mtx_unlock(&softc->ctl_lock);
1036         if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1037                 memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1038         if (msg->ua.ua_all) {
1039                 if (msg->ua.ua_set)
1040                         ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1041                 else
1042                         ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1043         } else {
1044                 if (msg->ua.ua_set)
1045                         ctl_est_ua(lun, iid, msg->ua.ua_type);
1046                 else
1047                         ctl_clr_ua(lun, iid, msg->ua.ua_type);
1048         }
1049         mtx_unlock(&lun->lun_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) == UINT32_MAX)
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 void
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         uint32_t targ_lun;
2209
2210         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2211         mtx_lock(&softc->ctl_lock);
2212
2213         /* Make sure that we know about this port. */
2214         port = ctl_io_port(&ctsio->io_hdr);
2215         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2216                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2217                                          /*retry_count*/ 1);
2218                 goto badjuju;
2219         }
2220
2221         /* Make sure that we know about this LUN. */
2222         if (targ_lun >= CTL_MAX_LUNS ||
2223             (lun = softc->ctl_luns[targ_lun]) == NULL) {
2224                 mtx_unlock(&softc->ctl_lock);
2225
2226                 /*
2227                  * The other node would not send this request to us unless
2228                  * received announce that we are primary node for this LUN.
2229                  * If this LUN does not exist now, it is probably result of
2230                  * a race, so respond to initiator in the most opaque way.
2231                  */
2232                 ctl_set_busy(ctsio);
2233                 goto badjuju;
2234         }
2235         mtx_lock(&lun->lun_lock);
2236         mtx_unlock(&softc->ctl_lock);
2237
2238         /*
2239          * If the LUN is invalid, pretend that it doesn't exist.
2240          * It will go away as soon as all pending I/Os completed.
2241          */
2242         if (lun->flags & CTL_LUN_DISABLED) {
2243                 mtx_unlock(&lun->lun_lock);
2244                 ctl_set_busy(ctsio);
2245                 goto badjuju;
2246         }
2247
2248         entry = ctl_get_cmd_entry(ctsio, NULL);
2249         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2250                 mtx_unlock(&lun->lun_lock);
2251                 goto badjuju;
2252         }
2253
2254         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2255         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2256
2257         /*
2258          * Every I/O goes into the OOA queue for a
2259          * particular LUN, and stays there until completion.
2260          */
2261 #ifdef CTL_TIME_IO
2262         if (TAILQ_EMPTY(&lun->ooa_queue))
2263                 lun->idle_time += getsbinuptime() - lun->last_busy;
2264 #endif
2265         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2266
2267         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2268                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2269                  ooa_links))) {
2270         case CTL_ACTION_BLOCK:
2271                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2272                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2273                                   blocked_links);
2274                 mtx_unlock(&lun->lun_lock);
2275                 break;
2276         case CTL_ACTION_PASS:
2277         case CTL_ACTION_SKIP:
2278                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2279                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2280                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2281                         mtx_unlock(&lun->lun_lock);
2282                 } else {
2283                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2284                         mtx_unlock(&lun->lun_lock);
2285
2286                         /* send msg back to other side */
2287                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2288                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2289                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2290                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2291                             sizeof(msg_info.hdr), M_WAITOK);
2292                 }
2293                 break;
2294         case CTL_ACTION_OVERLAP:
2295                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2296                 mtx_unlock(&lun->lun_lock);
2297                 ctl_set_overlapped_cmd(ctsio);
2298                 goto badjuju;
2299         case CTL_ACTION_OVERLAP_TAG:
2300                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2301                 mtx_unlock(&lun->lun_lock);
2302                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2303                 goto badjuju;
2304         case CTL_ACTION_ERROR:
2305         default:
2306                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2307                 mtx_unlock(&lun->lun_lock);
2308
2309                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2310                                          /*retry_count*/ 0);
2311 badjuju:
2312                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2313                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2314                 msg_info.hdr.serializing_sc = NULL;
2315                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2316                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2317                     sizeof(msg_info.scsi), M_WAITOK);
2318                 ctl_free_io((union ctl_io *)ctsio);
2319                 break;
2320         }
2321 }
2322
2323 /*
2324  * Returns 0 for success, errno for failure.
2325  */
2326 static void
2327 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2328                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2329 {
2330         union ctl_io *io;
2331
2332         mtx_lock(&lun->lun_lock);
2333         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2334              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2335              ooa_links)) {
2336                 struct ctl_ooa_entry *entry;
2337
2338                 /*
2339                  * If we've got more than we can fit, just count the
2340                  * remaining entries.
2341                  */
2342                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2343                         continue;
2344
2345                 entry = &kern_entries[*cur_fill_num];
2346
2347                 entry->tag_num = io->scsiio.tag_num;
2348                 entry->lun_num = lun->lun;
2349 #ifdef CTL_TIME_IO
2350                 entry->start_bt = io->io_hdr.start_bt;
2351 #endif
2352                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2353                 entry->cdb_len = io->scsiio.cdb_len;
2354                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2355                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2356
2357                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2358                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2359
2360                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2361                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2362
2363                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2364                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2365
2366                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2367                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2368         }
2369         mtx_unlock(&lun->lun_lock);
2370 }
2371
2372 static void *
2373 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2374                  size_t error_str_len)
2375 {
2376         void *kptr;
2377
2378         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2379
2380         if (copyin(user_addr, kptr, len) != 0) {
2381                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2382                          "from user address %p to kernel address %p", len,
2383                          user_addr, kptr);
2384                 free(kptr, M_CTL);
2385                 return (NULL);
2386         }
2387
2388         return (kptr);
2389 }
2390
2391 static void
2392 ctl_free_args(int num_args, struct ctl_be_arg *args)
2393 {
2394         int i;
2395
2396         if (args == NULL)
2397                 return;
2398
2399         for (i = 0; i < num_args; i++) {
2400                 free(args[i].kname, M_CTL);
2401                 free(args[i].kvalue, M_CTL);
2402         }
2403
2404         free(args, M_CTL);
2405 }
2406
2407 static struct ctl_be_arg *
2408 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2409                 char *error_str, size_t error_str_len)
2410 {
2411         struct ctl_be_arg *args;
2412         int i;
2413
2414         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2415                                 error_str, error_str_len);
2416
2417         if (args == NULL)
2418                 goto bailout;
2419
2420         for (i = 0; i < num_args; i++) {
2421                 args[i].kname = NULL;
2422                 args[i].kvalue = NULL;
2423         }
2424
2425         for (i = 0; i < num_args; i++) {
2426                 uint8_t *tmpptr;
2427
2428                 args[i].kname = ctl_copyin_alloc(args[i].name,
2429                         args[i].namelen, error_str, error_str_len);
2430                 if (args[i].kname == NULL)
2431                         goto bailout;
2432
2433                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2434                         snprintf(error_str, error_str_len, "Argument %d "
2435                                  "name is not NUL-terminated", i);
2436                         goto bailout;
2437                 }
2438
2439                 if (args[i].flags & CTL_BEARG_RD) {
2440                         tmpptr = ctl_copyin_alloc(args[i].value,
2441                                 args[i].vallen, error_str, error_str_len);
2442                         if (tmpptr == NULL)
2443                                 goto bailout;
2444                         if ((args[i].flags & CTL_BEARG_ASCII)
2445                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2446                                 snprintf(error_str, error_str_len, "Argument "
2447                                     "%d value is not NUL-terminated", i);
2448                                 free(tmpptr, M_CTL);
2449                                 goto bailout;
2450                         }
2451                         args[i].kvalue = tmpptr;
2452                 } else {
2453                         args[i].kvalue = malloc(args[i].vallen,
2454                             M_CTL, M_WAITOK | M_ZERO);
2455                 }
2456         }
2457
2458         return (args);
2459 bailout:
2460
2461         ctl_free_args(num_args, args);
2462
2463         return (NULL);
2464 }
2465
2466 static void
2467 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2468 {
2469         int i;
2470
2471         for (i = 0; i < num_args; i++) {
2472                 if (args[i].flags & CTL_BEARG_WR)
2473                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2474         }
2475 }
2476
2477 /*
2478  * Escape characters that are illegal or not recommended in XML.
2479  */
2480 int
2481 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2482 {
2483         char *end = str + size;
2484         int retval;
2485
2486         retval = 0;
2487
2488         for (; *str && str < end; str++) {
2489                 switch (*str) {
2490                 case '&':
2491                         retval = sbuf_printf(sb, "&amp;");
2492                         break;
2493                 case '>':
2494                         retval = sbuf_printf(sb, "&gt;");
2495                         break;
2496                 case '<':
2497                         retval = sbuf_printf(sb, "&lt;");
2498                         break;
2499                 default:
2500                         retval = sbuf_putc(sb, *str);
2501                         break;
2502                 }
2503
2504                 if (retval != 0)
2505                         break;
2506
2507         }
2508
2509         return (retval);
2510 }
2511
2512 static void
2513 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2514 {
2515         struct scsi_vpd_id_descriptor *desc;
2516         int i;
2517
2518         if (id == NULL || id->len < 4)
2519                 return;
2520         desc = (struct scsi_vpd_id_descriptor *)id->data;
2521         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2522         case SVPD_ID_TYPE_T10:
2523                 sbuf_printf(sb, "t10.");
2524                 break;
2525         case SVPD_ID_TYPE_EUI64:
2526                 sbuf_printf(sb, "eui.");
2527                 break;
2528         case SVPD_ID_TYPE_NAA:
2529                 sbuf_printf(sb, "naa.");
2530                 break;
2531         case SVPD_ID_TYPE_SCSI_NAME:
2532                 break;
2533         }
2534         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2535         case SVPD_ID_CODESET_BINARY:
2536                 for (i = 0; i < desc->length; i++)
2537                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2538                 break;
2539         case SVPD_ID_CODESET_ASCII:
2540                 sbuf_printf(sb, "%.*s", (int)desc->length,
2541                     (char *)desc->identifier);
2542                 break;
2543         case SVPD_ID_CODESET_UTF8:
2544                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2545                 break;
2546         }
2547 }
2548
2549 static int
2550 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2551           struct thread *td)
2552 {
2553         struct ctl_softc *softc = dev->si_drv1;
2554         struct ctl_lun *lun;
2555         int retval;
2556
2557         retval = 0;
2558
2559         switch (cmd) {
2560         case CTL_IO:
2561                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2562                 break;
2563         case CTL_ENABLE_PORT:
2564         case CTL_DISABLE_PORT:
2565         case CTL_SET_PORT_WWNS: {
2566                 struct ctl_port *port;
2567                 struct ctl_port_entry *entry;
2568
2569                 entry = (struct ctl_port_entry *)addr;
2570                 
2571                 mtx_lock(&softc->ctl_lock);
2572                 STAILQ_FOREACH(port, &softc->port_list, links) {
2573                         int action, done;
2574
2575                         if (port->targ_port < softc->port_min ||
2576                             port->targ_port >= softc->port_max)
2577                                 continue;
2578
2579                         action = 0;
2580                         done = 0;
2581                         if ((entry->port_type == CTL_PORT_NONE)
2582                          && (entry->targ_port == port->targ_port)) {
2583                                 /*
2584                                  * If the user only wants to enable or
2585                                  * disable or set WWNs on a specific port,
2586                                  * do the operation and we're done.
2587                                  */
2588                                 action = 1;
2589                                 done = 1;
2590                         } else if (entry->port_type & port->port_type) {
2591                                 /*
2592                                  * Compare the user's type mask with the
2593                                  * particular frontend type to see if we
2594                                  * have a match.
2595                                  */
2596                                 action = 1;
2597                                 done = 0;
2598
2599                                 /*
2600                                  * Make sure the user isn't trying to set
2601                                  * WWNs on multiple ports at the same time.
2602                                  */
2603                                 if (cmd == CTL_SET_PORT_WWNS) {
2604                                         printf("%s: Can't set WWNs on "
2605                                                "multiple ports\n", __func__);
2606                                         retval = EINVAL;
2607                                         break;
2608                                 }
2609                         }
2610                         if (action == 0)
2611                                 continue;
2612
2613                         /*
2614                          * XXX KDM we have to drop the lock here, because
2615                          * the online/offline operations can potentially
2616                          * block.  We need to reference count the frontends
2617                          * so they can't go away,
2618                          */
2619                         if (cmd == CTL_ENABLE_PORT) {
2620                                 mtx_unlock(&softc->ctl_lock);
2621                                 ctl_port_online(port);
2622                                 mtx_lock(&softc->ctl_lock);
2623                         } else if (cmd == CTL_DISABLE_PORT) {
2624                                 mtx_unlock(&softc->ctl_lock);
2625                                 ctl_port_offline(port);
2626                                 mtx_lock(&softc->ctl_lock);
2627                         } else if (cmd == CTL_SET_PORT_WWNS) {
2628                                 ctl_port_set_wwns(port,
2629                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2630                                     1 : 0, entry->wwnn,
2631                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2632                                     1 : 0, entry->wwpn);
2633                         }
2634                         if (done != 0)
2635                                 break;
2636                 }
2637                 mtx_unlock(&softc->ctl_lock);
2638                 break;
2639         }
2640         case CTL_GET_OOA: {
2641                 struct ctl_ooa *ooa_hdr;
2642                 struct ctl_ooa_entry *entries;
2643                 uint32_t cur_fill_num;
2644
2645                 ooa_hdr = (struct ctl_ooa *)addr;
2646
2647                 if ((ooa_hdr->alloc_len == 0)
2648                  || (ooa_hdr->alloc_num == 0)) {
2649                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2650                                "must be non-zero\n", __func__,
2651                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2652                         retval = EINVAL;
2653                         break;
2654                 }
2655
2656                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2657                     sizeof(struct ctl_ooa_entry))) {
2658                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2659                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2660                                __func__, ooa_hdr->alloc_len,
2661                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2662                         retval = EINVAL;
2663                         break;
2664                 }
2665
2666                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2667                 if (entries == NULL) {
2668                         printf("%s: could not allocate %d bytes for OOA "
2669                                "dump\n", __func__, ooa_hdr->alloc_len);
2670                         retval = ENOMEM;
2671                         break;
2672                 }
2673
2674                 mtx_lock(&softc->ctl_lock);
2675                 if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2676                     (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2677                      softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2678                         mtx_unlock(&softc->ctl_lock);
2679                         free(entries, M_CTL);
2680                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2681                                __func__, (uintmax_t)ooa_hdr->lun_num);
2682                         retval = EINVAL;
2683                         break;
2684                 }
2685
2686                 cur_fill_num = 0;
2687
2688                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2689                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2690                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2691                                     ooa_hdr, entries);
2692                         }
2693                 } else {
2694                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2695                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2696                             entries);
2697                 }
2698                 mtx_unlock(&softc->ctl_lock);
2699
2700                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2701                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2702                         sizeof(struct ctl_ooa_entry);
2703                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2704                 if (retval != 0) {
2705                         printf("%s: error copying out %d bytes for OOA dump\n", 
2706                                __func__, ooa_hdr->fill_len);
2707                 }
2708
2709                 getbinuptime(&ooa_hdr->cur_bt);
2710
2711                 if (cur_fill_num > ooa_hdr->alloc_num) {
2712                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2713                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2714                 } else {
2715                         ooa_hdr->dropped_num = 0;
2716                         ooa_hdr->status = CTL_OOA_OK;
2717                 }
2718
2719                 free(entries, M_CTL);
2720                 break;
2721         }
2722         case CTL_DELAY_IO: {
2723                 struct ctl_io_delay_info *delay_info;
2724
2725                 delay_info = (struct ctl_io_delay_info *)addr;
2726
2727 #ifdef CTL_IO_DELAY
2728                 mtx_lock(&softc->ctl_lock);
2729                 if (delay_info->lun_id >= CTL_MAX_LUNS ||
2730                     (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2731                         mtx_unlock(&softc->ctl_lock);
2732                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2733                         break;
2734                 }
2735                 mtx_lock(&lun->lun_lock);
2736                 mtx_unlock(&softc->ctl_lock);
2737                 delay_info->status = CTL_DELAY_STATUS_OK;
2738                 switch (delay_info->delay_type) {
2739                 case CTL_DELAY_TYPE_CONT:
2740                 case CTL_DELAY_TYPE_ONESHOT:
2741                         break;
2742                 default:
2743                         delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2744                         break;
2745                 }
2746                 switch (delay_info->delay_loc) {
2747                 case CTL_DELAY_LOC_DATAMOVE:
2748                         lun->delay_info.datamove_type = delay_info->delay_type;
2749                         lun->delay_info.datamove_delay = delay_info->delay_secs;
2750                         break;
2751                 case CTL_DELAY_LOC_DONE:
2752                         lun->delay_info.done_type = delay_info->delay_type;
2753                         lun->delay_info.done_delay = delay_info->delay_secs;
2754                         break;
2755                 default:
2756                         delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2757                         break;
2758                 }
2759                 mtx_unlock(&lun->lun_lock);
2760 #else
2761                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2762 #endif /* CTL_IO_DELAY */
2763                 break;
2764         }
2765         case CTL_GETSTATS: {
2766                 struct ctl_stats *stats;
2767                 int i;
2768
2769                 stats = (struct ctl_stats *)addr;
2770
2771                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2772                      stats->alloc_len) {
2773                         stats->status = CTL_SS_NEED_MORE_SPACE;
2774                         stats->num_luns = softc->num_luns;
2775                         break;
2776                 }
2777                 /*
2778                  * XXX KDM no locking here.  If the LUN list changes,
2779                  * things can blow up.
2780                  */
2781                 i = 0;
2782                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2783                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2784                                          sizeof(lun->stats));
2785                         if (retval != 0)
2786                                 break;
2787                 }
2788                 stats->num_luns = softc->num_luns;
2789                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2790                                  softc->num_luns;
2791                 stats->status = CTL_SS_OK;
2792 #ifdef CTL_TIME_IO
2793                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2794 #else
2795                 stats->flags = CTL_STATS_FLAG_NONE;
2796 #endif
2797                 getnanouptime(&stats->timestamp);
2798                 break;
2799         }
2800         case CTL_ERROR_INJECT: {
2801                 struct ctl_error_desc *err_desc, *new_err_desc;
2802
2803                 err_desc = (struct ctl_error_desc *)addr;
2804
2805                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2806                                       M_WAITOK | M_ZERO);
2807                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2808
2809                 mtx_lock(&softc->ctl_lock);
2810                 if (err_desc->lun_id >= CTL_MAX_LUNS ||
2811                     (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2812                         mtx_unlock(&softc->ctl_lock);
2813                         free(new_err_desc, M_CTL);
2814                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2815                                __func__, (uintmax_t)err_desc->lun_id);
2816                         retval = EINVAL;
2817                         break;
2818                 }
2819                 mtx_lock(&lun->lun_lock);
2820                 mtx_unlock(&softc->ctl_lock);
2821
2822                 /*
2823                  * We could do some checking here to verify the validity
2824                  * of the request, but given the complexity of error
2825                  * injection requests, the checking logic would be fairly
2826                  * complex.
2827                  *
2828                  * For now, if the request is invalid, it just won't get
2829                  * executed and might get deleted.
2830                  */
2831                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2832
2833                 /*
2834                  * XXX KDM check to make sure the serial number is unique,
2835                  * in case we somehow manage to wrap.  That shouldn't
2836                  * happen for a very long time, but it's the right thing to
2837                  * do.
2838                  */
2839                 new_err_desc->serial = lun->error_serial;
2840                 err_desc->serial = lun->error_serial;
2841                 lun->error_serial++;
2842
2843                 mtx_unlock(&lun->lun_lock);
2844                 break;
2845         }
2846         case CTL_ERROR_INJECT_DELETE: {
2847                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2848                 int delete_done;
2849
2850                 delete_desc = (struct ctl_error_desc *)addr;
2851                 delete_done = 0;
2852
2853                 mtx_lock(&softc->ctl_lock);
2854                 if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2855                     (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2856                         mtx_unlock(&softc->ctl_lock);
2857                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2858                                __func__, (uintmax_t)delete_desc->lun_id);
2859                         retval = EINVAL;
2860                         break;
2861                 }
2862                 mtx_lock(&lun->lun_lock);
2863                 mtx_unlock(&softc->ctl_lock);
2864                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2865                         if (desc->serial != delete_desc->serial)
2866                                 continue;
2867
2868                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2869                                       links);
2870                         free(desc, M_CTL);
2871                         delete_done = 1;
2872                 }
2873                 mtx_unlock(&lun->lun_lock);
2874                 if (delete_done == 0) {
2875                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2876                                "error serial %ju on LUN %u\n", __func__, 
2877                                delete_desc->serial, delete_desc->lun_id);
2878                         retval = EINVAL;
2879                         break;
2880                 }
2881                 break;
2882         }
2883         case CTL_DUMP_STRUCTS: {
2884                 int j, k;
2885                 struct ctl_port *port;
2886                 struct ctl_frontend *fe;
2887
2888                 mtx_lock(&softc->ctl_lock);
2889                 printf("CTL Persistent Reservation information start:\n");
2890                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2891                         mtx_lock(&lun->lun_lock);
2892                         if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2893                                 mtx_unlock(&lun->lun_lock);
2894                                 continue;
2895                         }
2896
2897                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2898                                 if (lun->pr_keys[j] == NULL)
2899                                         continue;
2900                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2901                                         if (lun->pr_keys[j][k] == 0)
2902                                                 continue;
2903                                         printf("  LUN %ju port %d iid %d key "
2904                                                "%#jx\n", lun->lun, j, k,
2905                                                (uintmax_t)lun->pr_keys[j][k]);
2906                                 }
2907                         }
2908                         mtx_unlock(&lun->lun_lock);
2909                 }
2910                 printf("CTL Persistent Reservation information end\n");
2911                 printf("CTL Ports:\n");
2912                 STAILQ_FOREACH(port, &softc->port_list, links) {
2913                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2914                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2915                                port->frontend->name, port->port_type,
2916                                port->physical_port, port->virtual_port,
2917                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2918                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2919                                 if (port->wwpn_iid[j].in_use == 0 &&
2920                                     port->wwpn_iid[j].wwpn == 0 &&
2921                                     port->wwpn_iid[j].name == NULL)
2922                                         continue;
2923
2924                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2925                                     j, port->wwpn_iid[j].in_use,
2926                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2927                                     port->wwpn_iid[j].name);
2928                         }
2929                 }
2930                 printf("CTL Port information end\n");
2931                 mtx_unlock(&softc->ctl_lock);
2932                 /*
2933                  * XXX KDM calling this without a lock.  We'd likely want
2934                  * to drop the lock before calling the frontend's dump
2935                  * routine anyway.
2936                  */
2937                 printf("CTL Frontends:\n");
2938                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2939                         printf("  Frontend '%s'\n", fe->name);
2940                         if (fe->fe_dump != NULL)
2941                                 fe->fe_dump();
2942                 }
2943                 printf("CTL Frontend information end\n");
2944                 break;
2945         }
2946         case CTL_LUN_REQ: {
2947                 struct ctl_lun_req *lun_req;
2948                 struct ctl_backend_driver *backend;
2949
2950                 lun_req = (struct ctl_lun_req *)addr;
2951
2952                 backend = ctl_backend_find(lun_req->backend);
2953                 if (backend == NULL) {
2954                         lun_req->status = CTL_LUN_ERROR;
2955                         snprintf(lun_req->error_str,
2956                                  sizeof(lun_req->error_str),
2957                                  "Backend \"%s\" not found.",
2958                                  lun_req->backend);
2959                         break;
2960                 }
2961                 if (lun_req->num_be_args > 0) {
2962                         lun_req->kern_be_args = ctl_copyin_args(
2963                                 lun_req->num_be_args,
2964                                 lun_req->be_args,
2965                                 lun_req->error_str,
2966                                 sizeof(lun_req->error_str));
2967                         if (lun_req->kern_be_args == NULL) {
2968                                 lun_req->status = CTL_LUN_ERROR;
2969                                 break;
2970                         }
2971                 }
2972
2973                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2974
2975                 if (lun_req->num_be_args > 0) {
2976                         ctl_copyout_args(lun_req->num_be_args,
2977                                       lun_req->kern_be_args);
2978                         ctl_free_args(lun_req->num_be_args,
2979                                       lun_req->kern_be_args);
2980                 }
2981                 break;
2982         }
2983         case CTL_LUN_LIST: {
2984                 struct sbuf *sb;
2985                 struct ctl_lun_list *list;
2986                 struct ctl_option *opt;
2987
2988                 list = (struct ctl_lun_list *)addr;
2989
2990                 /*
2991                  * Allocate a fixed length sbuf here, based on the length
2992                  * of the user's buffer.  We could allocate an auto-extending
2993                  * buffer, and then tell the user how much larger our
2994                  * amount of data is than his buffer, but that presents
2995                  * some problems:
2996                  *
2997                  * 1.  The sbuf(9) routines use a blocking malloc, and so
2998                  *     we can't hold a lock while calling them with an
2999                  *     auto-extending buffer.
3000                  *
3001                  * 2.  There is not currently a LUN reference counting
3002                  *     mechanism, outside of outstanding transactions on
3003                  *     the LUN's OOA queue.  So a LUN could go away on us
3004                  *     while we're getting the LUN number, backend-specific
3005                  *     information, etc.  Thus, given the way things
3006                  *     currently work, we need to hold the CTL lock while
3007                  *     grabbing LUN information.
3008                  *
3009                  * So, from the user's standpoint, the best thing to do is
3010                  * allocate what he thinks is a reasonable buffer length,
3011                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3012                  * double the buffer length and try again.  (And repeat
3013                  * that until he succeeds.)
3014                  */
3015                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3016                 if (sb == NULL) {
3017                         list->status = CTL_LUN_LIST_ERROR;
3018                         snprintf(list->error_str, sizeof(list->error_str),
3019                                  "Unable to allocate %d bytes for LUN list",
3020                                  list->alloc_len);
3021                         break;
3022                 }
3023
3024                 sbuf_printf(sb, "<ctllunlist>\n");
3025
3026                 mtx_lock(&softc->ctl_lock);
3027                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3028                         mtx_lock(&lun->lun_lock);
3029                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3030                                              (uintmax_t)lun->lun);
3031
3032                         /*
3033                          * Bail out as soon as we see that we've overfilled
3034                          * the buffer.
3035                          */
3036                         if (retval != 0)
3037                                 break;
3038
3039                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3040                                              "</backend_type>\n",
3041                                              (lun->backend == NULL) ?  "none" :
3042                                              lun->backend->name);
3043
3044                         if (retval != 0)
3045                                 break;
3046
3047                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3048                                              lun->be_lun->lun_type);
3049
3050                         if (retval != 0)
3051                                 break;
3052
3053                         if (lun->backend == NULL) {
3054                                 retval = sbuf_printf(sb, "</lun>\n");
3055                                 if (retval != 0)
3056                                         break;
3057                                 continue;
3058                         }
3059
3060                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3061                                              (lun->be_lun->maxlba > 0) ?
3062                                              lun->be_lun->maxlba + 1 : 0);
3063
3064                         if (retval != 0)
3065                                 break;
3066
3067                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3068                                              lun->be_lun->blocksize);
3069
3070                         if (retval != 0)
3071                                 break;
3072
3073                         retval = sbuf_printf(sb, "\t<serial_number>");
3074
3075                         if (retval != 0)
3076                                 break;
3077
3078                         retval = ctl_sbuf_printf_esc(sb,
3079                             lun->be_lun->serial_num,
3080                             sizeof(lun->be_lun->serial_num));
3081
3082                         if (retval != 0)
3083                                 break;
3084
3085                         retval = sbuf_printf(sb, "</serial_number>\n");
3086                 
3087                         if (retval != 0)
3088                                 break;
3089
3090                         retval = sbuf_printf(sb, "\t<device_id>");
3091
3092                         if (retval != 0)
3093                                 break;
3094
3095                         retval = ctl_sbuf_printf_esc(sb,
3096                             lun->be_lun->device_id,
3097                             sizeof(lun->be_lun->device_id));
3098
3099                         if (retval != 0)
3100                                 break;
3101
3102                         retval = sbuf_printf(sb, "</device_id>\n");
3103
3104                         if (retval != 0)
3105                                 break;
3106
3107                         if (lun->backend->lun_info != NULL) {
3108                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3109                                 if (retval != 0)
3110                                         break;
3111                         }
3112                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3113                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3114                                     opt->name, opt->value, opt->name);
3115                                 if (retval != 0)
3116                                         break;
3117                         }
3118
3119                         retval = sbuf_printf(sb, "</lun>\n");
3120
3121                         if (retval != 0)
3122                                 break;
3123                         mtx_unlock(&lun->lun_lock);
3124                 }
3125                 if (lun != NULL)
3126                         mtx_unlock(&lun->lun_lock);
3127                 mtx_unlock(&softc->ctl_lock);
3128
3129                 if ((retval != 0)
3130                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3131                         retval = 0;
3132                         sbuf_delete(sb);
3133                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3134                         snprintf(list->error_str, sizeof(list->error_str),
3135                                  "Out of space, %d bytes is too small",
3136                                  list->alloc_len);
3137                         break;
3138                 }
3139
3140                 sbuf_finish(sb);
3141
3142                 retval = copyout(sbuf_data(sb), list->lun_xml,
3143                                  sbuf_len(sb) + 1);
3144
3145                 list->fill_len = sbuf_len(sb) + 1;
3146                 list->status = CTL_LUN_LIST_OK;
3147                 sbuf_delete(sb);
3148                 break;
3149         }
3150         case CTL_ISCSI: {
3151                 struct ctl_iscsi *ci;
3152                 struct ctl_frontend *fe;
3153
3154                 ci = (struct ctl_iscsi *)addr;
3155
3156                 fe = ctl_frontend_find("iscsi");
3157                 if (fe == NULL) {
3158                         ci->status = CTL_ISCSI_ERROR;
3159                         snprintf(ci->error_str, sizeof(ci->error_str),
3160                             "Frontend \"iscsi\" not found.");
3161                         break;
3162                 }
3163
3164                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3165                 break;
3166         }
3167         case CTL_PORT_REQ: {
3168                 struct ctl_req *req;
3169                 struct ctl_frontend *fe;
3170
3171                 req = (struct ctl_req *)addr;
3172
3173                 fe = ctl_frontend_find(req->driver);
3174                 if (fe == NULL) {
3175                         req->status = CTL_LUN_ERROR;
3176                         snprintf(req->error_str, sizeof(req->error_str),
3177                             "Frontend \"%s\" not found.", req->driver);
3178                         break;
3179                 }
3180                 if (req->num_args > 0) {
3181                         req->kern_args = ctl_copyin_args(req->num_args,
3182                             req->args, req->error_str, sizeof(req->error_str));
3183                         if (req->kern_args == NULL) {
3184                                 req->status = CTL_LUN_ERROR;
3185                                 break;
3186                         }
3187                 }
3188
3189                 if (fe->ioctl)
3190                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3191                 else
3192                         retval = ENODEV;
3193
3194                 if (req->num_args > 0) {
3195                         ctl_copyout_args(req->num_args, req->kern_args);
3196                         ctl_free_args(req->num_args, req->kern_args);
3197                 }
3198                 break;
3199         }
3200         case CTL_PORT_LIST: {
3201                 struct sbuf *sb;
3202                 struct ctl_port *port;
3203                 struct ctl_lun_list *list;
3204                 struct ctl_option *opt;
3205                 int j;
3206                 uint32_t plun;
3207
3208                 list = (struct ctl_lun_list *)addr;
3209
3210                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3211                 if (sb == NULL) {
3212                         list->status = CTL_LUN_LIST_ERROR;
3213                         snprintf(list->error_str, sizeof(list->error_str),
3214                                  "Unable to allocate %d bytes for LUN list",
3215                                  list->alloc_len);
3216                         break;
3217                 }
3218
3219                 sbuf_printf(sb, "<ctlportlist>\n");
3220
3221                 mtx_lock(&softc->ctl_lock);
3222                 STAILQ_FOREACH(port, &softc->port_list, links) {
3223                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3224                                              (uintmax_t)port->targ_port);
3225
3226                         /*
3227                          * Bail out as soon as we see that we've overfilled
3228                          * the buffer.
3229                          */
3230                         if (retval != 0)
3231                                 break;
3232
3233                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3234                             "</frontend_type>\n", port->frontend->name);
3235                         if (retval != 0)
3236                                 break;
3237
3238                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3239                                              port->port_type);
3240                         if (retval != 0)
3241                                 break;
3242
3243                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3244                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3245                         if (retval != 0)
3246                                 break;
3247
3248                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3249                             port->port_name);
3250                         if (retval != 0)
3251                                 break;
3252
3253                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3254                             port->physical_port);
3255                         if (retval != 0)
3256                                 break;
3257
3258                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3259                             port->virtual_port);
3260                         if (retval != 0)
3261                                 break;
3262
3263                         if (port->target_devid != NULL) {
3264                                 sbuf_printf(sb, "\t<target>");
3265                                 ctl_id_sbuf(port->target_devid, sb);
3266                                 sbuf_printf(sb, "</target>\n");
3267                         }
3268
3269                         if (port->port_devid != NULL) {
3270                                 sbuf_printf(sb, "\t<port>");
3271                                 ctl_id_sbuf(port->port_devid, sb);
3272                                 sbuf_printf(sb, "</port>\n");
3273                         }
3274
3275                         if (port->port_info != NULL) {
3276                                 retval = port->port_info(port->onoff_arg, sb);
3277                                 if (retval != 0)
3278                                         break;
3279                         }
3280                         STAILQ_FOREACH(opt, &port->options, links) {
3281                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3282                                     opt->name, opt->value, opt->name);
3283                                 if (retval != 0)
3284                                         break;
3285                         }
3286
3287                         if (port->lun_map != NULL) {
3288                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3289                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3290                                         plun = ctl_lun_map_from_port(port, j);
3291                                         if (plun == UINT32_MAX)
3292                                                 continue;
3293                                         sbuf_printf(sb,
3294                                             "\t<lun id=\"%u\">%u</lun>\n",
3295                                             j, plun);
3296                                 }
3297                         }
3298
3299                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3300                                 if (port->wwpn_iid[j].in_use == 0 ||
3301                                     (port->wwpn_iid[j].wwpn == 0 &&
3302                                      port->wwpn_iid[j].name == NULL))
3303                                         continue;
3304
3305                                 if (port->wwpn_iid[j].name != NULL)
3306                                         retval = sbuf_printf(sb,
3307                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3308                                             j, port->wwpn_iid[j].name);
3309                                 else
3310                                         retval = sbuf_printf(sb,
3311                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3312                                             j, port->wwpn_iid[j].wwpn);
3313                                 if (retval != 0)
3314                                         break;
3315                         }
3316                         if (retval != 0)
3317                                 break;
3318
3319                         retval = sbuf_printf(sb, "</targ_port>\n");
3320                         if (retval != 0)
3321                                 break;
3322                 }
3323                 mtx_unlock(&softc->ctl_lock);
3324
3325                 if ((retval != 0)
3326                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3327                         retval = 0;
3328                         sbuf_delete(sb);
3329                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3330                         snprintf(list->error_str, sizeof(list->error_str),
3331                                  "Out of space, %d bytes is too small",
3332                                  list->alloc_len);
3333                         break;
3334                 }
3335
3336                 sbuf_finish(sb);
3337
3338                 retval = copyout(sbuf_data(sb), list->lun_xml,
3339                                  sbuf_len(sb) + 1);
3340
3341                 list->fill_len = sbuf_len(sb) + 1;
3342                 list->status = CTL_LUN_LIST_OK;
3343                 sbuf_delete(sb);
3344                 break;
3345         }
3346         case CTL_LUN_MAP: {
3347                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3348                 struct ctl_port *port;
3349
3350                 mtx_lock(&softc->ctl_lock);
3351                 if (lm->port < softc->port_min ||
3352                     lm->port >= softc->port_max ||
3353                     (port = softc->ctl_ports[lm->port]) == NULL) {
3354                         mtx_unlock(&softc->ctl_lock);
3355                         return (ENXIO);
3356                 }
3357                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3358                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3359                                 if (ctl_lun_map_to_port(port, lun->lun) ==
3360                                     UINT32_MAX)
3361                                         continue;
3362                                 mtx_lock(&lun->lun_lock);
3363                                 ctl_est_ua_port(lun, lm->port, -1,
3364                                     CTL_UA_LUN_CHANGE);
3365                                 mtx_unlock(&lun->lun_lock);
3366                         }
3367                 }
3368                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3369                 if (lm->plun < CTL_MAX_LUNS) {
3370                         if (lm->lun == UINT32_MAX)
3371                                 retval = ctl_lun_map_unset(port, lm->plun);
3372                         else if (lm->lun < CTL_MAX_LUNS &&
3373                             softc->ctl_luns[lm->lun] != NULL)
3374                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3375                         else
3376                                 return (ENXIO);
3377                 } else if (lm->plun == UINT32_MAX) {
3378                         if (lm->lun == UINT32_MAX)
3379                                 retval = ctl_lun_map_deinit(port);
3380                         else
3381                                 retval = ctl_lun_map_init(port);
3382                 } else
3383                         return (ENXIO);
3384                 if (port->status & CTL_PORT_STATUS_ONLINE)
3385                         ctl_isc_announce_port(port);
3386                 break;
3387         }
3388         default: {
3389                 /* XXX KDM should we fix this? */
3390 #if 0
3391                 struct ctl_backend_driver *backend;
3392                 unsigned int type;
3393                 int found;
3394
3395                 found = 0;
3396
3397                 /*
3398                  * We encode the backend type as the ioctl type for backend
3399                  * ioctls.  So parse it out here, and then search for a
3400                  * backend of this type.
3401                  */
3402                 type = _IOC_TYPE(cmd);
3403
3404                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3405                         if (backend->type == type) {
3406                                 found = 1;
3407                                 break;
3408                         }
3409                 }
3410                 if (found == 0) {
3411                         printf("ctl: unknown ioctl command %#lx or backend "
3412                                "%d\n", cmd, type);
3413                         retval = EINVAL;
3414                         break;
3415                 }
3416                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3417 #endif
3418                 retval = ENOTTY;
3419                 break;
3420         }
3421         }
3422         return (retval);
3423 }
3424
3425 uint32_t
3426 ctl_get_initindex(struct ctl_nexus *nexus)
3427 {
3428         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3429 }
3430
3431 int
3432 ctl_lun_map_init(struct ctl_port *port)
3433 {
3434         struct ctl_softc *softc = port->ctl_softc;
3435         struct ctl_lun *lun;
3436         uint32_t i;
3437
3438         if (port->lun_map == NULL)
3439                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3440                     M_CTL, M_NOWAIT);
3441         if (port->lun_map == NULL)
3442                 return (ENOMEM);
3443         for (i = 0; i < CTL_MAX_LUNS; i++)
3444                 port->lun_map[i] = UINT32_MAX;
3445         if (port->status & CTL_PORT_STATUS_ONLINE) {
3446                 if (port->lun_disable != NULL) {
3447                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3448                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3449                 }
3450                 ctl_isc_announce_port(port);
3451         }
3452         return (0);
3453 }
3454
3455 int
3456 ctl_lun_map_deinit(struct ctl_port *port)
3457 {
3458         struct ctl_softc *softc = port->ctl_softc;
3459         struct ctl_lun *lun;
3460
3461         if (port->lun_map == NULL)
3462                 return (0);
3463         free(port->lun_map, M_CTL);
3464         port->lun_map = NULL;
3465         if (port->status & CTL_PORT_STATUS_ONLINE) {
3466                 if (port->lun_enable != NULL) {
3467                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3468                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3469                 }
3470                 ctl_isc_announce_port(port);
3471         }
3472         return (0);
3473 }
3474
3475 int
3476 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3477 {
3478         int status;
3479         uint32_t old;
3480
3481         if (port->lun_map == NULL) {
3482                 status = ctl_lun_map_init(port);
3483                 if (status != 0)
3484                         return (status);
3485         }
3486         old = port->lun_map[plun];
3487         port->lun_map[plun] = glun;
3488         if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3489                 if (port->lun_enable != NULL)
3490                         port->lun_enable(port->targ_lun_arg, plun);
3491                 ctl_isc_announce_port(port);
3492         }
3493         return (0);
3494 }
3495
3496 int
3497 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3498 {
3499         uint32_t old;
3500
3501         if (port->lun_map == NULL)
3502                 return (0);
3503         old = port->lun_map[plun];
3504         port->lun_map[plun] = UINT32_MAX;
3505         if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3506                 if (port->lun_disable != NULL)
3507                         port->lun_disable(port->targ_lun_arg, plun);
3508                 ctl_isc_announce_port(port);
3509         }
3510         return (0);
3511 }
3512
3513 uint32_t
3514 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3515 {
3516
3517         if (port == NULL)
3518                 return (UINT32_MAX);
3519         if (port->lun_map == NULL || lun_id == UINT32_MAX)
3520                 return (lun_id);
3521         return (port->lun_map[lun_id]);
3522 }
3523
3524 uint32_t
3525 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3526 {
3527         uint32_t i;
3528
3529         if (port == NULL)
3530                 return (UINT32_MAX);
3531         if (port->lun_map == NULL)
3532                 return (lun_id);
3533         for (i = 0; i < CTL_MAX_LUNS; i++) {
3534                 if (port->lun_map[i] == lun_id)
3535                         return (i);
3536         }
3537         return (UINT32_MAX);
3538 }
3539
3540 uint32_t
3541 ctl_decode_lun(uint64_t encoded)
3542 {
3543         uint8_t lun[8];
3544         uint32_t result = 0xffffffff;
3545
3546         be64enc(lun, encoded);
3547         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3548         case RPL_LUNDATA_ATYP_PERIPH:
3549                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3550                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3551                         result = lun[1];
3552                 break;
3553         case RPL_LUNDATA_ATYP_FLAT:
3554                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3555                     lun[6] == 0 && lun[7] == 0)
3556                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3557                 break;
3558         case RPL_LUNDATA_ATYP_EXTLUN:
3559                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3560                 case 0x02:
3561                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3562                         case 0x00:
3563                                 result = lun[1];
3564                                 break;
3565                         case 0x10:
3566                                 result = (lun[1] << 16) + (lun[2] << 8) +
3567                                     lun[3];
3568                                 break;
3569                         case 0x20:
3570                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3571                                         result = (lun[2] << 24) +
3572                                             (lun[3] << 16) + (lun[4] << 8) +
3573                                             lun[5];
3574                                 break;
3575                         }
3576                         break;
3577                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3578                         result = 0xffffffff;
3579                         break;
3580                 }
3581                 break;
3582         }
3583         return (result);
3584 }
3585
3586 uint64_t
3587 ctl_encode_lun(uint32_t decoded)
3588 {
3589         uint64_t l = decoded;
3590
3591         if (l <= 0xff)
3592                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3593         if (l <= 0x3fff)
3594                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3595         if (l <= 0xffffff)
3596                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3597                     (l << 32));
3598         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3599 }
3600
3601 static struct ctl_port *
3602 ctl_io_port(struct ctl_io_hdr *io_hdr)
3603 {
3604
3605         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3606 }
3607
3608 int
3609 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3610 {
3611         int i;
3612
3613         for (i = first; i < last; i++) {
3614                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3615                         return (i);
3616         }
3617         return (-1);
3618 }
3619
3620 int
3621 ctl_set_mask(uint32_t *mask, uint32_t bit)
3622 {
3623         uint32_t chunk, piece;
3624
3625         chunk = bit >> 5;
3626         piece = bit % (sizeof(uint32_t) * 8);
3627
3628         if ((mask[chunk] & (1 << piece)) != 0)
3629                 return (-1);
3630         else
3631                 mask[chunk] |= (1 << piece);
3632
3633         return (0);
3634 }
3635
3636 int
3637 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3638 {
3639         uint32_t chunk, piece;
3640
3641         chunk = bit >> 5;
3642         piece = bit % (sizeof(uint32_t) * 8);
3643
3644         if ((mask[chunk] & (1 << piece)) == 0)
3645                 return (-1);
3646         else
3647                 mask[chunk] &= ~(1 << piece);
3648
3649         return (0);
3650 }
3651
3652 int
3653 ctl_is_set(uint32_t *mask, uint32_t bit)
3654 {
3655         uint32_t chunk, piece;
3656
3657         chunk = bit >> 5;
3658         piece = bit % (sizeof(uint32_t) * 8);
3659
3660         if ((mask[chunk] & (1 << piece)) == 0)
3661                 return (0);
3662         else
3663                 return (1);
3664 }
3665
3666 static uint64_t
3667 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3668 {
3669         uint64_t *t;
3670
3671         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3672         if (t == NULL)
3673                 return (0);
3674         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3675 }
3676
3677 static void
3678 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3679 {
3680         uint64_t *t;
3681
3682         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3683         if (t == NULL)
3684                 return;
3685         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3686 }
3687
3688 static void
3689 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3690 {
3691         uint64_t *p;
3692         u_int i;
3693
3694         i = residx/CTL_MAX_INIT_PER_PORT;
3695         if (lun->pr_keys[i] != NULL)
3696                 return;
3697         mtx_unlock(&lun->lun_lock);
3698         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3699             M_WAITOK | M_ZERO);
3700         mtx_lock(&lun->lun_lock);
3701         if (lun->pr_keys[i] == NULL)
3702                 lun->pr_keys[i] = p;
3703         else
3704                 free(p, M_CTL);
3705 }
3706
3707 static void
3708 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3709 {
3710         uint64_t *t;
3711
3712         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3713         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3714         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3715 }
3716
3717 /*
3718  * ctl_softc, pool_name, total_ctl_io are passed in.
3719  * npool is passed out.
3720  */
3721 int
3722 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3723                 uint32_t total_ctl_io, void **npool)
3724 {
3725 #ifdef IO_POOLS
3726         struct ctl_io_pool *pool;
3727
3728         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3729                                             M_NOWAIT | M_ZERO);
3730         if (pool == NULL)
3731                 return (ENOMEM);
3732
3733         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3734         pool->ctl_softc = ctl_softc;
3735         pool->zone = uma_zsecond_create(pool->name, NULL,
3736             NULL, NULL, NULL, ctl_softc->io_zone);
3737         /* uma_prealloc(pool->zone, total_ctl_io); */
3738
3739         *npool = pool;
3740 #else
3741         *npool = ctl_softc->io_zone;
3742 #endif
3743         return (0);
3744 }
3745
3746 void
3747 ctl_pool_free(struct ctl_io_pool *pool)
3748 {
3749
3750         if (pool == NULL)
3751                 return;
3752
3753 #ifdef IO_POOLS
3754         uma_zdestroy(pool->zone);
3755         free(pool, M_CTL);
3756 #endif
3757 }
3758
3759 union ctl_io *
3760 ctl_alloc_io(void *pool_ref)
3761 {
3762         union ctl_io *io;
3763 #ifdef IO_POOLS
3764         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3765
3766         io = uma_zalloc(pool->zone, M_WAITOK);
3767 #else
3768         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3769 #endif
3770         if (io != NULL)
3771                 io->io_hdr.pool = pool_ref;
3772         return (io);
3773 }
3774
3775 union ctl_io *
3776 ctl_alloc_io_nowait(void *pool_ref)
3777 {
3778         union ctl_io *io;
3779 #ifdef IO_POOLS
3780         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3781
3782         io = uma_zalloc(pool->zone, M_NOWAIT);
3783 #else
3784         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3785 #endif
3786         if (io != NULL)
3787                 io->io_hdr.pool = pool_ref;
3788         return (io);
3789 }
3790
3791 void
3792 ctl_free_io(union ctl_io *io)
3793 {
3794 #ifdef IO_POOLS
3795         struct ctl_io_pool *pool;
3796 #endif
3797
3798         if (io == NULL)
3799                 return;
3800
3801 #ifdef IO_POOLS
3802         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3803         uma_zfree(pool->zone, io);
3804 #else
3805         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3806 #endif
3807 }
3808
3809 void
3810 ctl_zero_io(union ctl_io *io)
3811 {
3812         void *pool_ref;
3813
3814         if (io == NULL)
3815                 return;
3816
3817         /*
3818          * May need to preserve linked list pointers at some point too.
3819          */
3820         pool_ref = io->io_hdr.pool;
3821         memset(io, 0, sizeof(*io));
3822         io->io_hdr.pool = pool_ref;
3823 }
3824
3825 int
3826 ctl_expand_number(const char *buf, uint64_t *num)
3827 {
3828         char *endptr;
3829         uint64_t number;
3830         unsigned shift;
3831
3832         number = strtoq(buf, &endptr, 0);
3833
3834         switch (tolower((unsigned char)*endptr)) {
3835         case 'e':
3836                 shift = 60;
3837                 break;
3838         case 'p':
3839                 shift = 50;
3840                 break;
3841         case 't':
3842                 shift = 40;
3843                 break;
3844         case 'g':
3845                 shift = 30;
3846                 break;
3847         case 'm':
3848                 shift = 20;
3849                 break;
3850         case 'k':
3851                 shift = 10;
3852                 break;
3853         case 'b':
3854         case '\0': /* No unit. */
3855                 *num = number;
3856                 return (0);
3857         default:
3858                 /* Unrecognized unit. */
3859                 return (-1);
3860         }
3861
3862         if ((number << shift) >> shift != number) {
3863                 /* Overflow */
3864                 return (-1);
3865         }
3866         *num = number << shift;
3867         return (0);
3868 }
3869
3870
3871 /*
3872  * This routine could be used in the future to load default and/or saved
3873  * mode page parameters for a particuar lun.
3874  */
3875 static int
3876 ctl_init_page_index(struct ctl_lun *lun)
3877 {
3878         int i, page_code;
3879         struct ctl_page_index *page_index;
3880         const char *value;
3881         uint64_t ival;
3882
3883         memcpy(&lun->mode_pages.index, page_index_template,
3884                sizeof(page_index_template));
3885
3886         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3887
3888                 page_index = &lun->mode_pages.index[i];
3889                 if (lun->be_lun->lun_type == T_DIRECT &&
3890                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3891                         continue;
3892                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3893                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3894                         continue;
3895                 if (lun->be_lun->lun_type == T_CDROM &&
3896                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3897                         continue;
3898
3899                 page_code = page_index->page_code & SMPH_PC_MASK;
3900                 switch (page_code) {
3901                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3902                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3903                             ("subpage %#x for page %#x is incorrect!",
3904                             page_index->subpage, page_code));
3905                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3906                                &rw_er_page_default,
3907                                sizeof(rw_er_page_default));
3908                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3909                                &rw_er_page_changeable,
3910                                sizeof(rw_er_page_changeable));
3911                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3912                                &rw_er_page_default,
3913                                sizeof(rw_er_page_default));
3914                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3915                                &rw_er_page_default,
3916                                sizeof(rw_er_page_default));
3917                         page_index->page_data =
3918                                 (uint8_t *)lun->mode_pages.rw_er_page;
3919                         break;
3920                 }
3921                 case SMS_FORMAT_DEVICE_PAGE: {
3922                         struct scsi_format_page *format_page;
3923
3924                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3925                             ("subpage %#x for page %#x is incorrect!",
3926                             page_index->subpage, page_code));
3927
3928                         /*
3929                          * Sectors per track are set above.  Bytes per
3930                          * sector need to be set here on a per-LUN basis.
3931                          */
3932                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3933                                &format_page_default,
3934                                sizeof(format_page_default));
3935                         memcpy(&lun->mode_pages.format_page[
3936                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3937                                sizeof(format_page_changeable));
3938                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3939                                &format_page_default,
3940                                sizeof(format_page_default));
3941                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3942                                &format_page_default,
3943                                sizeof(format_page_default));
3944
3945                         format_page = &lun->mode_pages.format_page[
3946                                 CTL_PAGE_CURRENT];
3947                         scsi_ulto2b(lun->be_lun->blocksize,
3948                                     format_page->bytes_per_sector);
3949
3950                         format_page = &lun->mode_pages.format_page[
3951                                 CTL_PAGE_DEFAULT];
3952                         scsi_ulto2b(lun->be_lun->blocksize,
3953                                     format_page->bytes_per_sector);
3954
3955                         format_page = &lun->mode_pages.format_page[
3956                                 CTL_PAGE_SAVED];
3957                         scsi_ulto2b(lun->be_lun->blocksize,
3958                                     format_page->bytes_per_sector);
3959
3960                         page_index->page_data =
3961                                 (uint8_t *)lun->mode_pages.format_page;
3962                         break;
3963                 }
3964                 case SMS_RIGID_DISK_PAGE: {
3965                         struct scsi_rigid_disk_page *rigid_disk_page;
3966                         uint32_t sectors_per_cylinder;
3967                         uint64_t cylinders;
3968 #ifndef __XSCALE__
3969                         int shift;
3970 #endif /* !__XSCALE__ */
3971
3972                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3973                             ("subpage %#x for page %#x is incorrect!",
3974                             page_index->subpage, page_code));
3975
3976                         /*
3977                          * Rotation rate and sectors per track are set
3978                          * above.  We calculate the cylinders here based on
3979                          * capacity.  Due to the number of heads and
3980                          * sectors per track we're using, smaller arrays
3981                          * may turn out to have 0 cylinders.  Linux and
3982                          * FreeBSD don't pay attention to these mode pages
3983                          * to figure out capacity, but Solaris does.  It
3984                          * seems to deal with 0 cylinders just fine, and
3985                          * works out a fake geometry based on the capacity.
3986                          */
3987                         memcpy(&lun->mode_pages.rigid_disk_page[
3988                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3989                                sizeof(rigid_disk_page_default));
3990                         memcpy(&lun->mode_pages.rigid_disk_page[
3991                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3992                                sizeof(rigid_disk_page_changeable));
3993
3994                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3995                                 CTL_DEFAULT_HEADS;
3996
3997                         /*
3998                          * The divide method here will be more accurate,
3999                          * probably, but results in floating point being
4000                          * used in the kernel on i386 (__udivdi3()).  On the
4001                          * XScale, though, __udivdi3() is implemented in
4002                          * software.
4003                          *
4004                          * The shift method for cylinder calculation is
4005                          * accurate if sectors_per_cylinder is a power of
4006                          * 2.  Otherwise it might be slightly off -- you
4007                          * might have a bit of a truncation problem.
4008                          */
4009 #ifdef  __XSCALE__
4010                         cylinders = (lun->be_lun->maxlba + 1) /
4011                                 sectors_per_cylinder;
4012 #else
4013                         for (shift = 31; shift > 0; shift--) {
4014                                 if (sectors_per_cylinder & (1 << shift))
4015                                         break;
4016                         }
4017                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4018 #endif
4019
4020                         /*
4021                          * We've basically got 3 bytes, or 24 bits for the
4022                          * cylinder size in the mode page.  If we're over,
4023                          * just round down to 2^24.
4024                          */
4025                         if (cylinders > 0xffffff)
4026                                 cylinders = 0xffffff;
4027
4028                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4029                                 CTL_PAGE_DEFAULT];
4030                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4031
4032                         if ((value = ctl_get_opt(&lun->be_lun->options,
4033                             "rpm")) != NULL) {
4034                                 scsi_ulto2b(strtol(value, NULL, 0),
4035                                      rigid_disk_page->rotation_rate);
4036                         }
4037
4038                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4039                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4040                                sizeof(rigid_disk_page_default));
4041                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4042                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4043                                sizeof(rigid_disk_page_default));
4044
4045                         page_index->page_data =
4046                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4047                         break;
4048                 }
4049                 case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4050                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4051                             ("subpage %#x for page %#x is incorrect!",
4052                             page_index->subpage, page_code));
4053                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4054                                &verify_er_page_default,
4055                                sizeof(verify_er_page_default));
4056                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4057                                &verify_er_page_changeable,
4058                                sizeof(verify_er_page_changeable));
4059                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4060                                &verify_er_page_default,
4061                                sizeof(verify_er_page_default));
4062                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4063                                &verify_er_page_default,
4064                                sizeof(verify_er_page_default));
4065                         page_index->page_data =
4066                                 (uint8_t *)lun->mode_pages.verify_er_page;
4067                         break;
4068                 }
4069                 case SMS_CACHING_PAGE: {
4070                         struct scsi_caching_page *caching_page;
4071
4072                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4073                             ("subpage %#x for page %#x is incorrect!",
4074                             page_index->subpage, page_code));
4075                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4076                                &caching_page_default,
4077                                sizeof(caching_page_default));
4078                         memcpy(&lun->mode_pages.caching_page[
4079                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4080                                sizeof(caching_page_changeable));
4081                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4082                                &caching_page_default,
4083                                sizeof(caching_page_default));
4084                         caching_page = &lun->mode_pages.caching_page[
4085                             CTL_PAGE_SAVED];
4086                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4087                         if (value != NULL && strcmp(value, "off") == 0)
4088                                 caching_page->flags1 &= ~SCP_WCE;
4089                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4090                         if (value != NULL && strcmp(value, "off") == 0)
4091                                 caching_page->flags1 |= SCP_RCD;
4092                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4093                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4094                                sizeof(caching_page_default));
4095                         page_index->page_data =
4096                                 (uint8_t *)lun->mode_pages.caching_page;
4097                         break;
4098                 }
4099                 case SMS_CONTROL_MODE_PAGE: {
4100                         switch (page_index->subpage) {
4101                         case SMS_SUBPAGE_PAGE_0: {
4102                                 struct scsi_control_page *control_page;
4103
4104                                 memcpy(&lun->mode_pages.control_page[
4105                                     CTL_PAGE_DEFAULT],
4106                                        &control_page_default,
4107                                        sizeof(control_page_default));
4108                                 memcpy(&lun->mode_pages.control_page[
4109                                     CTL_PAGE_CHANGEABLE],
4110                                        &control_page_changeable,
4111                                        sizeof(control_page_changeable));
4112                                 memcpy(&lun->mode_pages.control_page[
4113                                     CTL_PAGE_SAVED],
4114                                        &control_page_default,
4115                                        sizeof(control_page_default));
4116                                 control_page = &lun->mode_pages.control_page[
4117                                     CTL_PAGE_SAVED];
4118                                 value = ctl_get_opt(&lun->be_lun->options,
4119                                     "reordering");
4120                                 if (value != NULL &&
4121                                     strcmp(value, "unrestricted") == 0) {
4122                                         control_page->queue_flags &=
4123                                             ~SCP_QUEUE_ALG_MASK;
4124                                         control_page->queue_flags |=
4125                                             SCP_QUEUE_ALG_UNRESTRICTED;
4126                                 }
4127                                 memcpy(&lun->mode_pages.control_page[
4128                                     CTL_PAGE_CURRENT],
4129                                        &lun->mode_pages.control_page[
4130                                     CTL_PAGE_SAVED],
4131                                        sizeof(control_page_default));
4132                                 page_index->page_data =
4133                                     (uint8_t *)lun->mode_pages.control_page;
4134                                 break;
4135                         }
4136                         case 0x01:
4137                                 memcpy(&lun->mode_pages.control_ext_page[
4138                                     CTL_PAGE_DEFAULT],
4139                                        &control_ext_page_default,
4140                                        sizeof(control_ext_page_default));
4141                                 memcpy(&lun->mode_pages.control_ext_page[
4142                                     CTL_PAGE_CHANGEABLE],
4143                                        &control_ext_page_changeable,
4144                                        sizeof(control_ext_page_changeable));
4145                                 memcpy(&lun->mode_pages.control_ext_page[
4146                                     CTL_PAGE_SAVED],
4147                                        &control_ext_page_default,
4148                                        sizeof(control_ext_page_default));
4149                                 memcpy(&lun->mode_pages.control_ext_page[
4150                                     CTL_PAGE_CURRENT],
4151                                        &lun->mode_pages.control_ext_page[
4152                                     CTL_PAGE_SAVED],
4153                                        sizeof(control_ext_page_default));
4154                                 page_index->page_data =
4155                                     (uint8_t *)lun->mode_pages.control_ext_page;
4156                                 break;
4157                         default:
4158                                 panic("subpage %#x for page %#x is incorrect!",
4159                                       page_index->subpage, page_code);
4160                         }
4161                         break;
4162                 }
4163                 case SMS_INFO_EXCEPTIONS_PAGE: {
4164                         switch (page_index->subpage) {
4165                         case SMS_SUBPAGE_PAGE_0:
4166                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4167                                        &ie_page_default,
4168                                        sizeof(ie_page_default));
4169                                 memcpy(&lun->mode_pages.ie_page[
4170                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4171                                        sizeof(ie_page_changeable));
4172                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4173                                        &ie_page_default,
4174                                        sizeof(ie_page_default));
4175                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4176                                        &ie_page_default,
4177                                        sizeof(ie_page_default));
4178                                 page_index->page_data =
4179                                         (uint8_t *)lun->mode_pages.ie_page;
4180                                 break;
4181                         case 0x02: {
4182                                 struct ctl_logical_block_provisioning_page *page;
4183
4184                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4185                                        &lbp_page_default,
4186                                        sizeof(lbp_page_default));
4187                                 memcpy(&lun->mode_pages.lbp_page[
4188                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4189                                        sizeof(lbp_page_changeable));
4190                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4191                                        &lbp_page_default,
4192                                        sizeof(lbp_page_default));
4193                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4194                                 value = ctl_get_opt(&lun->be_lun->options,
4195                                     "avail-threshold");
4196                                 if (value != NULL &&
4197                                     ctl_expand_number(value, &ival) == 0) {
4198                                         page->descr[0].flags |= SLBPPD_ENABLED |
4199                                             SLBPPD_ARMING_DEC;
4200                                         if (lun->be_lun->blocksize)
4201                                                 ival /= lun->be_lun->blocksize;
4202                                         else
4203                                                 ival /= 512;
4204                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4205                                             page->descr[0].count);
4206                                 }
4207                                 value = ctl_get_opt(&lun->be_lun->options,
4208                                     "used-threshold");
4209                                 if (value != NULL &&
4210                                     ctl_expand_number(value, &ival) == 0) {
4211                                         page->descr[1].flags |= SLBPPD_ENABLED |
4212                                             SLBPPD_ARMING_INC;
4213                                         if (lun->be_lun->blocksize)
4214                                                 ival /= lun->be_lun->blocksize;
4215                                         else
4216                                                 ival /= 512;
4217                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4218                                             page->descr[1].count);
4219                                 }
4220                                 value = ctl_get_opt(&lun->be_lun->options,
4221                                     "pool-avail-threshold");
4222                                 if (value != NULL &&
4223                                     ctl_expand_number(value, &ival) == 0) {
4224                                         page->descr[2].flags |= SLBPPD_ENABLED |
4225                                             SLBPPD_ARMING_DEC;
4226                                         if (lun->be_lun->blocksize)
4227                                                 ival /= lun->be_lun->blocksize;
4228                                         else
4229                                                 ival /= 512;
4230                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4231                                             page->descr[2].count);
4232                                 }
4233                                 value = ctl_get_opt(&lun->be_lun->options,
4234                                     "pool-used-threshold");
4235                                 if (value != NULL &&
4236                                     ctl_expand_number(value, &ival) == 0) {
4237                                         page->descr[3].flags |= SLBPPD_ENABLED |
4238                                             SLBPPD_ARMING_INC;
4239                                         if (lun->be_lun->blocksize)
4240                                                 ival /= lun->be_lun->blocksize;
4241                                         else
4242                                                 ival /= 512;
4243                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4244                                             page->descr[3].count);
4245                                 }
4246                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4247                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4248                                        sizeof(lbp_page_default));
4249                                 page_index->page_data =
4250                                         (uint8_t *)lun->mode_pages.lbp_page;
4251                                 break;
4252                         }
4253                         default:
4254                                 panic("subpage %#x for page %#x is incorrect!",
4255                                       page_index->subpage, page_code);
4256                         }
4257                         break;
4258                 }
4259                 case SMS_CDDVD_CAPS_PAGE:{
4260                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4261                             ("subpage %#x for page %#x is incorrect!",
4262                             page_index->subpage, page_code));
4263                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4264                                &cddvd_page_default,
4265                                sizeof(cddvd_page_default));
4266                         memcpy(&lun->mode_pages.cddvd_page[
4267                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4268                                sizeof(cddvd_page_changeable));
4269                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4270                                &cddvd_page_default,
4271                                sizeof(cddvd_page_default));
4272                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4273                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4274                                sizeof(cddvd_page_default));
4275                         page_index->page_data =
4276                                 (uint8_t *)lun->mode_pages.cddvd_page;
4277                         break;
4278                 }
4279                 default:
4280                         panic("invalid page code value %#x", page_code);
4281                 }
4282         }
4283
4284         return (CTL_RETVAL_COMPLETE);
4285 }
4286
4287 static int
4288 ctl_init_log_page_index(struct ctl_lun *lun)
4289 {
4290         struct ctl_page_index *page_index;
4291         int i, j, k, prev;
4292
4293         memcpy(&lun->log_pages.index, log_page_index_template,
4294                sizeof(log_page_index_template));
4295
4296         prev = -1;
4297         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4298
4299                 page_index = &lun->log_pages.index[i];
4300                 if (lun->be_lun->lun_type == T_DIRECT &&
4301                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4302                         continue;
4303                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4304                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4305                         continue;
4306                 if (lun->be_lun->lun_type == T_CDROM &&
4307                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4308                         continue;
4309
4310                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4311                     lun->backend->lun_attr == NULL)
4312                         continue;
4313
4314                 if (page_index->page_code != prev) {
4315                         lun->log_pages.pages_page[j] = page_index->page_code;
4316                         prev = page_index->page_code;
4317                         j++;
4318                 }
4319                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4320                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4321                 k++;
4322         }
4323         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4324         lun->log_pages.index[0].page_len = j;
4325         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4326         lun->log_pages.index[1].page_len = k * 2;
4327         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4328         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4329         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4330         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4331         lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4332         lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4333
4334         return (CTL_RETVAL_COMPLETE);
4335 }
4336
4337 static int
4338 hex2bin(const char *str, uint8_t *buf, int buf_size)
4339 {
4340         int i;
4341         u_char c;
4342
4343         memset(buf, 0, buf_size);
4344         while (isspace(str[0]))
4345                 str++;
4346         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4347                 str += 2;
4348         buf_size *= 2;
4349         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4350                 while (str[i] == '-')   /* Skip dashes in UUIDs. */
4351                         str++;
4352                 c = str[i];
4353                 if (isdigit(c))
4354                         c -= '0';
4355                 else if (isalpha(c))
4356                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4357                 else
4358                         break;
4359                 if (c >= 16)
4360                         break;
4361                 if ((i & 1) == 0)
4362                         buf[i / 2] |= (c << 4);
4363                 else
4364                         buf[i / 2] |= c;
4365         }
4366         return ((i + 1) / 2);
4367 }
4368
4369 /*
4370  * LUN allocation.
4371  *
4372  * Requirements:
4373  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4374  *   wants us to allocate the LUN and he can block.
4375  * - ctl_softc is always set
4376  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4377  *
4378  * Returns 0 for success, non-zero (errno) for failure.
4379  */
4380 static int
4381 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4382               struct ctl_be_lun *const be_lun)
4383 {
4384         struct ctl_lun *nlun, *lun;
4385         struct scsi_vpd_id_descriptor *desc;
4386         struct scsi_vpd_id_t10 *t10id;
4387         const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4388         int lun_number, i, lun_malloced;
4389         int devidlen, idlen1, idlen2 = 0, len;
4390
4391         if (be_lun == NULL)
4392                 return (EINVAL);
4393
4394         /*
4395          * We currently only support Direct Access or Processor LUN types.
4396          */
4397         switch (be_lun->lun_type) {
4398         case T_DIRECT:
4399         case T_PROCESSOR:
4400         case T_CDROM:
4401                 break;
4402         case T_SEQUENTIAL:
4403         case T_CHANGER:
4404         default:
4405                 be_lun->lun_config_status(be_lun->be_lun,
4406                                           CTL_LUN_CONFIG_FAILURE);
4407                 break;
4408         }
4409         if (ctl_lun == NULL) {
4410                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4411                 lun_malloced = 1;
4412         } else {
4413                 lun_malloced = 0;
4414                 lun = ctl_lun;
4415         }
4416
4417         memset(lun, 0, sizeof(*lun));
4418         if (lun_malloced)
4419                 lun->flags = CTL_LUN_MALLOCED;
4420
4421         /* Generate LUN ID. */
4422         devidlen = max(CTL_DEVID_MIN_LEN,
4423             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4424         idlen1 = sizeof(*t10id) + devidlen;
4425         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4426         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4427         if (scsiname != NULL) {
4428                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4429                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4430         }
4431         eui = ctl_get_opt(&be_lun->options, "eui");
4432         if (eui != NULL) {
4433                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4434         }
4435         naa = ctl_get_opt(&be_lun->options, "naa");
4436         if (naa != NULL) {
4437                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4438         }
4439         uuid = ctl_get_opt(&be_lun->options, "uuid");
4440         if (uuid != NULL) {
4441                 len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4442         }
4443         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4444             M_CTL, M_WAITOK | M_ZERO);
4445         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4446         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4447         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4448         desc->length = idlen1;
4449         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4450         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4451         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4452                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4453         } else {
4454                 strncpy(t10id->vendor, vendor,
4455                     min(sizeof(t10id->vendor), strlen(vendor)));
4456         }
4457         strncpy((char *)t10id->vendor_spec_id,
4458             (char *)be_lun->device_id, devidlen);
4459         if (scsiname != NULL) {
4460                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4461                     desc->length);
4462                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4463                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4464                     SVPD_ID_TYPE_SCSI_NAME;
4465                 desc->length = idlen2;
4466                 strlcpy(desc->identifier, scsiname, idlen2);
4467         }
4468         if (eui != NULL) {
4469                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4470                     desc->length);
4471                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4472                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4473                     SVPD_ID_TYPE_EUI64;
4474                 desc->length = hex2bin(eui, desc->identifier, 16);
4475                 desc->length = desc->length > 12 ? 16 :
4476                     (desc->length > 8 ? 12 : 8);
4477                 len -= 16 - desc->length;
4478         }
4479         if (naa != NULL) {
4480                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4481                     desc->length);
4482                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4483                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4484                     SVPD_ID_TYPE_NAA;
4485                 desc->length = hex2bin(naa, desc->identifier, 16);
4486                 desc->length = desc->length > 8 ? 16 : 8;
4487                 len -= 16 - desc->length;
4488         }
4489         if (uuid != NULL) {
4490                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4491                     desc->length);
4492                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4493                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4494                     SVPD_ID_TYPE_UUID;
4495                 desc->identifier[0] = 0x10;
4496                 hex2bin(uuid, &desc->identifier[2], 16);
4497                 desc->length = 18;
4498         }
4499         lun->lun_devid->len = len;
4500
4501         mtx_lock(&ctl_softc->ctl_lock);
4502         /*
4503          * See if the caller requested a particular LUN number.  If so, see
4504          * if it is available.  Otherwise, allocate the first available LUN.
4505          */
4506         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4507                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4508                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4509                         mtx_unlock(&ctl_softc->ctl_lock);
4510                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4511                                 printf("ctl: requested LUN ID %d is higher "
4512                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4513                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4514                         } else {
4515                                 /*
4516                                  * XXX KDM return an error, or just assign
4517                                  * another LUN ID in this case??
4518                                  */
4519                                 printf("ctl: requested LUN ID %d is already "
4520                                        "in use\n", be_lun->req_lun_id);
4521                         }
4522                         if (lun->flags & CTL_LUN_MALLOCED)
4523                                 free(lun, M_CTL);
4524                         be_lun->lun_config_status(be_lun->be_lun,
4525                                                   CTL_LUN_CONFIG_FAILURE);
4526                         return (ENOSPC);
4527                 }
4528                 lun_number = be_lun->req_lun_id;
4529         } else {
4530                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4531                 if (lun_number == -1) {
4532                         mtx_unlock(&ctl_softc->ctl_lock);
4533                         printf("ctl: can't allocate LUN, out of LUNs\n");
4534                         if (lun->flags & CTL_LUN_MALLOCED)
4535                                 free(lun, M_CTL);
4536                         be_lun->lun_config_status(be_lun->be_lun,
4537                                                   CTL_LUN_CONFIG_FAILURE);
4538                         return (ENOSPC);
4539                 }
4540         }
4541         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4542
4543         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4544         lun->lun = lun_number;
4545         lun->be_lun = be_lun;
4546         /*
4547          * The processor LUN is always enabled.  Disk LUNs come on line
4548          * disabled, and must be enabled by the backend.
4549          */
4550         lun->flags |= CTL_LUN_DISABLED;
4551         lun->backend = be_lun->be;
4552         be_lun->ctl_lun = lun;
4553         be_lun->lun_id = lun_number;
4554         atomic_add_int(&be_lun->be->num_luns, 1);
4555         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4556                 lun->flags |= CTL_LUN_EJECTED;
4557         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4558                 lun->flags |= CTL_LUN_NO_MEDIA;
4559         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4560                 lun->flags |= CTL_LUN_STOPPED;
4561
4562         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4563                 lun->flags |= CTL_LUN_PRIMARY_SC;
4564
4565         value = ctl_get_opt(&be_lun->options, "removable");
4566         if (value != NULL) {
4567                 if (strcmp(value, "on") == 0)
4568                         lun->flags |= CTL_LUN_REMOVABLE;
4569         } else if (be_lun->lun_type == T_CDROM)
4570                 lun->flags |= CTL_LUN_REMOVABLE;
4571
4572         lun->ctl_softc = ctl_softc;
4573 #ifdef CTL_TIME_IO
4574         lun->last_busy = getsbinuptime();
4575 #endif
4576         TAILQ_INIT(&lun->ooa_queue);
4577         TAILQ_INIT(&lun->blocked_queue);
4578         STAILQ_INIT(&lun->error_list);
4579         lun->ie_reported = 1;
4580         callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4581         ctl_tpc_lun_init(lun);
4582
4583         /*
4584          * Initialize the mode and log page index.
4585          */
4586         ctl_init_page_index(lun);
4587         ctl_init_log_page_index(lun);
4588
4589         /*
4590          * Now, before we insert this lun on the lun list, set the lun
4591          * inventory changed UA for all other luns.
4592          */
4593         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4594                 mtx_lock(&nlun->lun_lock);
4595                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4596                 mtx_unlock(&nlun->lun_lock);
4597         }
4598
4599         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4600
4601         ctl_softc->ctl_luns[lun_number] = lun;
4602
4603         ctl_softc->num_luns++;
4604
4605         /* Setup statistics gathering */
4606         lun->stats.device_type = be_lun->lun_type;
4607         lun->stats.lun_number = lun_number;
4608         lun->stats.blocksize = be_lun->blocksize;
4609         if (be_lun->blocksize == 0)
4610                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4611         for (i = 0;i < CTL_MAX_PORTS;i++)
4612                 lun->stats.ports[i].targ_port = i;
4613
4614         mtx_unlock(&ctl_softc->ctl_lock);
4615
4616         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4617         return (0);
4618 }
4619
4620 /*
4621  * Delete a LUN.
4622  * Assumptions:
4623  * - LUN has already been marked invalid and any pending I/O has been taken
4624  *   care of.
4625  */
4626 static int
4627 ctl_free_lun(struct ctl_lun *lun)
4628 {
4629         struct ctl_softc *softc;
4630         struct ctl_lun *nlun;
4631         int i;
4632
4633         softc = lun->ctl_softc;
4634
4635         mtx_assert(&softc->ctl_lock, MA_OWNED);
4636
4637         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4638
4639         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4640
4641         softc->ctl_luns[lun->lun] = NULL;
4642
4643         if (!TAILQ_EMPTY(&lun->ooa_queue))
4644                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4645
4646         softc->num_luns--;
4647
4648         /*
4649          * Tell the backend to free resources, if this LUN has a backend.
4650          */
4651         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4652         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4653
4654         lun->ie_reportcnt = UINT32_MAX;
4655         callout_drain(&lun->ie_callout);
4656
4657         ctl_tpc_lun_shutdown(lun);
4658         mtx_destroy(&lun->lun_lock);
4659         free(lun->lun_devid, M_CTL);
4660         for (i = 0; i < CTL_MAX_PORTS; i++)
4661                 free(lun->pending_ua[i], M_CTL);
4662         for (i = 0; i < CTL_MAX_PORTS; i++)
4663                 free(lun->pr_keys[i], M_CTL);
4664         free(lun->write_buffer, M_CTL);
4665         if (lun->flags & CTL_LUN_MALLOCED)
4666                 free(lun, M_CTL);
4667
4668         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4669                 mtx_lock(&nlun->lun_lock);
4670                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4671                 mtx_unlock(&nlun->lun_lock);
4672         }
4673
4674         return (0);
4675 }
4676
4677 static void
4678 ctl_create_lun(struct ctl_be_lun *be_lun)
4679 {
4680
4681         /*
4682          * ctl_alloc_lun() should handle all potential failure cases.
4683          */
4684         ctl_alloc_lun(control_softc, NULL, be_lun);
4685 }
4686
4687 int
4688 ctl_add_lun(struct ctl_be_lun *be_lun)
4689 {
4690         struct ctl_softc *softc = control_softc;
4691
4692         mtx_lock(&softc->ctl_lock);
4693         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4694         mtx_unlock(&softc->ctl_lock);
4695         wakeup(&softc->pending_lun_queue);
4696
4697         return (0);
4698 }
4699
4700 int
4701 ctl_enable_lun(struct ctl_be_lun *be_lun)
4702 {
4703         struct ctl_softc *softc;
4704         struct ctl_port *port, *nport;
4705         struct ctl_lun *lun;
4706         int retval;
4707
4708         lun = (struct ctl_lun *)be_lun->ctl_lun;
4709         softc = lun->ctl_softc;
4710
4711         mtx_lock(&softc->ctl_lock);
4712         mtx_lock(&lun->lun_lock);
4713         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4714                 /*
4715                  * eh?  Why did we get called if the LUN is already
4716                  * enabled?
4717                  */
4718                 mtx_unlock(&lun->lun_lock);
4719                 mtx_unlock(&softc->ctl_lock);
4720                 return (0);
4721         }
4722         lun->flags &= ~CTL_LUN_DISABLED;
4723         mtx_unlock(&lun->lun_lock);
4724
4725         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4726                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4727                     port->lun_map != NULL || port->lun_enable == NULL)
4728                         continue;
4729
4730                 /*
4731                  * Drop the lock while we call the FETD's enable routine.
4732                  * This can lead to a callback into CTL (at least in the
4733                  * case of the internal initiator frontend.
4734                  */
4735                 mtx_unlock(&softc->ctl_lock);
4736                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4737                 mtx_lock(&softc->ctl_lock);
4738                 if (retval != 0) {
4739                         printf("%s: FETD %s port %d returned error "
4740                                "%d for lun_enable on lun %jd\n",
4741                                __func__, port->port_name, port->targ_port,
4742                                retval, (intmax_t)lun->lun);
4743                 }
4744         }
4745
4746         mtx_unlock(&softc->ctl_lock);
4747         ctl_isc_announce_lun(lun);
4748
4749         return (0);
4750 }
4751
4752 int
4753 ctl_disable_lun(struct ctl_be_lun *be_lun)
4754 {
4755         struct ctl_softc *softc;
4756         struct ctl_port *port;
4757         struct ctl_lun *lun;
4758         int retval;
4759
4760         lun = (struct ctl_lun *)be_lun->ctl_lun;
4761         softc = lun->ctl_softc;
4762
4763         mtx_lock(&softc->ctl_lock);
4764         mtx_lock(&lun->lun_lock);
4765         if (lun->flags & CTL_LUN_DISABLED) {
4766                 mtx_unlock(&lun->lun_lock);
4767                 mtx_unlock(&softc->ctl_lock);
4768                 return (0);
4769         }
4770         lun->flags |= CTL_LUN_DISABLED;
4771         mtx_unlock(&lun->lun_lock);
4772
4773         STAILQ_FOREACH(port, &softc->port_list, links) {
4774                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4775                     port->lun_map != NULL || port->lun_disable == NULL)
4776                         continue;
4777
4778                 /*
4779                  * Drop the lock before we call the frontend's disable
4780                  * routine, to avoid lock order reversals.
4781                  *
4782                  * XXX KDM what happens if the frontend list changes while
4783                  * we're traversing it?  It's unlikely, but should be handled.
4784                  */
4785                 mtx_unlock(&softc->ctl_lock);
4786                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4787                 mtx_lock(&softc->ctl_lock);
4788                 if (retval != 0) {
4789                         printf("%s: FETD %s port %d returned error "
4790                                "%d for lun_disable on lun %jd\n",
4791                                __func__, port->port_name, port->targ_port,
4792                                retval, (intmax_t)lun->lun);
4793                 }
4794         }
4795
4796         mtx_unlock(&softc->ctl_lock);
4797         ctl_isc_announce_lun(lun);
4798
4799         return (0);
4800 }
4801
4802 int
4803 ctl_start_lun(struct ctl_be_lun *be_lun)
4804 {
4805         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4806
4807         mtx_lock(&lun->lun_lock);
4808         lun->flags &= ~CTL_LUN_STOPPED;
4809         mtx_unlock(&lun->lun_lock);
4810         return (0);
4811 }
4812
4813 int
4814 ctl_stop_lun(struct ctl_be_lun *be_lun)
4815 {
4816         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4817
4818         mtx_lock(&lun->lun_lock);
4819         lun->flags |= CTL_LUN_STOPPED;
4820         mtx_unlock(&lun->lun_lock);
4821         return (0);
4822 }
4823
4824 int
4825 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4826 {
4827         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4828
4829         mtx_lock(&lun->lun_lock);
4830         lun->flags |= CTL_LUN_NO_MEDIA;
4831         mtx_unlock(&lun->lun_lock);
4832         return (0);
4833 }
4834
4835 int
4836 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4837 {
4838         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4839         union ctl_ha_msg msg;
4840
4841         mtx_lock(&lun->lun_lock);
4842         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4843         if (lun->flags & CTL_LUN_REMOVABLE)
4844                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4845         mtx_unlock(&lun->lun_lock);
4846         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4847             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4848                 bzero(&msg.ua, sizeof(msg.ua));
4849                 msg.hdr.msg_type = CTL_MSG_UA;
4850                 msg.hdr.nexus.initid = -1;
4851                 msg.hdr.nexus.targ_port = -1;
4852                 msg.hdr.nexus.targ_lun = lun->lun;
4853                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4854                 msg.ua.ua_all = 1;
4855                 msg.ua.ua_set = 1;
4856                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4857                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4858                     M_WAITOK);
4859         }
4860         return (0);
4861 }
4862
4863 int
4864 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4865 {
4866         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4867
4868         mtx_lock(&lun->lun_lock);
4869         lun->flags |= CTL_LUN_EJECTED;
4870         mtx_unlock(&lun->lun_lock);
4871         return (0);
4872 }
4873
4874 int
4875 ctl_lun_primary(struct ctl_be_lun *be_lun)
4876 {
4877         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4878
4879         mtx_lock(&lun->lun_lock);
4880         lun->flags |= CTL_LUN_PRIMARY_SC;
4881         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4882         mtx_unlock(&lun->lun_lock);
4883         ctl_isc_announce_lun(lun);
4884         return (0);
4885 }
4886
4887 int
4888 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4889 {
4890         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4891
4892         mtx_lock(&lun->lun_lock);
4893         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4894         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4895         mtx_unlock(&lun->lun_lock);
4896         ctl_isc_announce_lun(lun);
4897         return (0);
4898 }
4899
4900 int
4901 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4902 {
4903         struct ctl_softc *softc;
4904         struct ctl_lun *lun;
4905
4906         lun = (struct ctl_lun *)be_lun->ctl_lun;
4907         softc = lun->ctl_softc;
4908
4909         mtx_lock(&lun->lun_lock);
4910
4911         /*
4912          * The LUN needs to be disabled before it can be marked invalid.
4913          */
4914         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4915                 mtx_unlock(&lun->lun_lock);
4916                 return (-1);
4917         }
4918         /*
4919          * Mark the LUN invalid.
4920          */
4921         lun->flags |= CTL_LUN_INVALID;
4922
4923         /*
4924          * If there is nothing in the OOA queue, go ahead and free the LUN.
4925          * If we have something in the OOA queue, we'll free it when the
4926          * last I/O completes.
4927          */
4928         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4929                 mtx_unlock(&lun->lun_lock);
4930                 mtx_lock(&softc->ctl_lock);
4931                 ctl_free_lun(lun);
4932                 mtx_unlock(&softc->ctl_lock);
4933         } else
4934                 mtx_unlock(&lun->lun_lock);
4935
4936         return (0);
4937 }
4938
4939 void
4940 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4941 {
4942         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4943         union ctl_ha_msg msg;
4944
4945         mtx_lock(&lun->lun_lock);
4946         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4947         mtx_unlock(&lun->lun_lock);
4948         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4949                 /* Send msg to other side. */
4950                 bzero(&msg.ua, sizeof(msg.ua));
4951                 msg.hdr.msg_type = CTL_MSG_UA;
4952                 msg.hdr.nexus.initid = -1;
4953                 msg.hdr.nexus.targ_port = -1;
4954                 msg.hdr.nexus.targ_lun = lun->lun;
4955                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4956                 msg.ua.ua_all = 1;
4957                 msg.ua.ua_set = 1;
4958                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4959                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4960                     M_WAITOK);
4961         }
4962 }
4963
4964 /*
4965  * Backend "memory move is complete" callback for requests that never
4966  * make it down to say RAIDCore's configuration code.
4967  */
4968 int
4969 ctl_config_move_done(union ctl_io *io)
4970 {
4971         int retval;
4972
4973         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4974         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4975             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4976
4977         if ((io->io_hdr.port_status != 0) &&
4978             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4979              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4980                 /*
4981                  * For hardware error sense keys, the sense key
4982                  * specific value is defined to be a retry count,
4983                  * but we use it to pass back an internal FETD
4984                  * error code.  XXX KDM  Hopefully the FETD is only
4985                  * using 16 bits for an error code, since that's
4986                  * all the space we have in the sks field.
4987                  */
4988                 ctl_set_internal_failure(&io->scsiio,
4989                                          /*sks_valid*/ 1,
4990                                          /*retry_count*/
4991                                          io->io_hdr.port_status);
4992         }
4993
4994         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4995                 ctl_data_print(io);
4996         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4997             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4998              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4999             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5000                 /*
5001                  * XXX KDM just assuming a single pointer here, and not a
5002                  * S/G list.  If we start using S/G lists for config data,
5003                  * we'll need to know how to clean them up here as well.
5004                  */
5005                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5006                         free(io->scsiio.kern_data_ptr, M_CTL);
5007                 ctl_done(io);
5008                 retval = CTL_RETVAL_COMPLETE;
5009         } else {
5010                 /*
5011                  * XXX KDM now we need to continue data movement.  Some
5012                  * options:
5013                  * - call ctl_scsiio() again?  We don't do this for data
5014                  *   writes, because for those at least we know ahead of
5015                  *   time where the write will go and how long it is.  For
5016                  *   config writes, though, that information is largely
5017                  *   contained within the write itself, thus we need to
5018                  *   parse out the data again.
5019                  *
5020                  * - Call some other function once the data is in?
5021                  */
5022
5023                 /*
5024                  * XXX KDM call ctl_scsiio() again for now, and check flag
5025                  * bits to see whether we're allocated or not.
5026                  */
5027                 retval = ctl_scsiio(&io->scsiio);
5028         }
5029         return (retval);
5030 }
5031
5032 /*
5033  * This gets called by a backend driver when it is done with a
5034  * data_submit method.
5035  */
5036 void
5037 ctl_data_submit_done(union ctl_io *io)
5038 {
5039         /*
5040          * If the IO_CONT flag is set, we need to call the supplied
5041          * function to continue processing the I/O, instead of completing
5042          * the I/O just yet.
5043          *
5044          * If there is an error, though, we don't want to keep processing.
5045          * Instead, just send status back to the initiator.
5046          */
5047         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5048             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5049             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5050              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5051                 io->scsiio.io_cont(io);
5052                 return;
5053         }
5054         ctl_done(io);
5055 }
5056
5057 /*
5058  * This gets called by a backend driver when it is done with a
5059  * configuration write.
5060  */
5061 void
5062 ctl_config_write_done(union ctl_io *io)
5063 {
5064         uint8_t *buf;
5065
5066         /*
5067          * If the IO_CONT flag is set, we need to call the supplied
5068          * function to continue processing the I/O, instead of completing
5069          * the I/O just yet.
5070          *
5071          * If there is an error, though, we don't want to keep processing.
5072          * Instead, just send status back to the initiator.
5073          */
5074         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5075             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5076             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5077              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5078                 io->scsiio.io_cont(io);
5079                 return;
5080         }
5081         /*
5082          * Since a configuration write can be done for commands that actually
5083          * have data allocated, like write buffer, and commands that have
5084          * no data, like start/stop unit, we need to check here.
5085          */
5086         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5087                 buf = io->scsiio.kern_data_ptr;
5088         else
5089                 buf = NULL;
5090         ctl_done(io);
5091         if (buf)
5092                 free(buf, M_CTL);
5093 }
5094
5095 void
5096 ctl_config_read_done(union ctl_io *io)
5097 {
5098         uint8_t *buf;
5099
5100         /*
5101          * If there is some error -- we are done, skip data transfer.
5102          */
5103         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5104             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5105              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5106                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5107                         buf = io->scsiio.kern_data_ptr;
5108                 else
5109                         buf = NULL;
5110                 ctl_done(io);
5111                 if (buf)
5112                         free(buf, M_CTL);
5113                 return;
5114         }
5115
5116         /*
5117          * If the IO_CONT flag is set, we need to call the supplied
5118          * function to continue processing the I/O, instead of completing
5119          * the I/O just yet.
5120          */
5121         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5122                 io->scsiio.io_cont(io);
5123                 return;
5124         }
5125
5126         ctl_datamove(io);
5127 }
5128
5129 /*
5130  * SCSI release command.
5131  */
5132 int
5133 ctl_scsi_release(struct ctl_scsiio *ctsio)
5134 {
5135         struct ctl_lun *lun;
5136         uint32_t residx;
5137
5138         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5139
5140         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5141         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5142
5143         /*
5144          * XXX KDM right now, we only support LUN reservation.  We don't
5145          * support 3rd party reservations, or extent reservations, which
5146          * might actually need the parameter list.  If we've gotten this
5147          * far, we've got a LUN reservation.  Anything else got kicked out
5148          * above.  So, according to SPC, ignore the length.
5149          */
5150
5151         mtx_lock(&lun->lun_lock);
5152
5153         /*
5154          * According to SPC, it is not an error for an intiator to attempt
5155          * to release a reservation on a LUN that isn't reserved, or that
5156          * is reserved by another initiator.  The reservation can only be
5157          * released, though, by the initiator who made it or by one of
5158          * several reset type events.
5159          */
5160         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5161                         lun->flags &= ~CTL_LUN_RESERVED;
5162
5163         mtx_unlock(&lun->lun_lock);
5164
5165         ctl_set_success(ctsio);
5166         ctl_done((union ctl_io *)ctsio);
5167         return (CTL_RETVAL_COMPLETE);
5168 }
5169
5170 int
5171 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5172 {
5173         struct ctl_lun *lun;
5174         uint32_t residx;
5175
5176         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5177
5178         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5179         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5180
5181         /*
5182          * XXX KDM right now, we only support LUN reservation.  We don't
5183          * support 3rd party reservations, or extent reservations, which
5184          * might actually need the parameter list.  If we've gotten this
5185          * far, we've got a LUN reservation.  Anything else got kicked out
5186          * above.  So, according to SPC, ignore the length.
5187          */
5188
5189         mtx_lock(&lun->lun_lock);
5190         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5191                 ctl_set_reservation_conflict(ctsio);
5192                 goto bailout;
5193         }
5194
5195         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5196         if (lun->flags & CTL_LUN_PR_RESERVED) {
5197                 ctl_set_success(ctsio);
5198                 goto bailout;
5199         }
5200
5201         lun->flags |= CTL_LUN_RESERVED;
5202         lun->res_idx = residx;
5203         ctl_set_success(ctsio);
5204
5205 bailout:
5206         mtx_unlock(&lun->lun_lock);
5207         ctl_done((union ctl_io *)ctsio);
5208         return (CTL_RETVAL_COMPLETE);
5209 }
5210
5211 int
5212 ctl_start_stop(struct ctl_scsiio *ctsio)
5213 {
5214         struct scsi_start_stop_unit *cdb;
5215         struct ctl_lun *lun;
5216         int retval;
5217
5218         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5219
5220         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5221         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5222
5223         if ((cdb->how & SSS_PC_MASK) == 0) {
5224                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5225                     (cdb->how & SSS_START) == 0) {
5226                         uint32_t residx;
5227
5228                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5229                         if (ctl_get_prkey(lun, residx) == 0 ||
5230                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5231
5232                                 ctl_set_reservation_conflict(ctsio);
5233                                 ctl_done((union ctl_io *)ctsio);
5234                                 return (CTL_RETVAL_COMPLETE);
5235                         }
5236                 }
5237
5238                 if ((cdb->how & SSS_LOEJ) &&
5239                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5240                         ctl_set_invalid_field(ctsio,
5241                                               /*sks_valid*/ 1,
5242                                               /*command*/ 1,
5243                                               /*field*/ 4,
5244                                               /*bit_valid*/ 1,
5245                                               /*bit*/ 1);
5246                         ctl_done((union ctl_io *)ctsio);
5247                         return (CTL_RETVAL_COMPLETE);
5248                 }
5249
5250                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5251                     lun->prevent_count > 0) {
5252                         /* "Medium removal prevented" */
5253                         ctl_set_sense(ctsio, /*current_error*/ 1,
5254                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5255                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5256                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5257                         ctl_done((union ctl_io *)ctsio);
5258                         return (CTL_RETVAL_COMPLETE);
5259                 }
5260         }
5261
5262         retval = lun->backend->config_write((union ctl_io *)ctsio);
5263         return (retval);
5264 }
5265
5266 int
5267 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5268 {
5269         struct ctl_lun *lun;
5270         struct scsi_prevent *cdb;
5271         int retval;
5272         uint32_t initidx;
5273
5274         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5275
5276         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5277         cdb = (struct scsi_prevent *)ctsio->cdb;
5278
5279         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5280                 ctl_set_invalid_opcode(ctsio);
5281                 ctl_done((union ctl_io *)ctsio);
5282                 return (CTL_RETVAL_COMPLETE);
5283         }
5284
5285         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5286         mtx_lock(&lun->lun_lock);
5287         if ((cdb->how & PR_PREVENT) &&
5288             ctl_is_set(lun->prevent, initidx) == 0) {
5289                 ctl_set_mask(lun->prevent, initidx);
5290                 lun->prevent_count++;
5291         } else if ((cdb->how & PR_PREVENT) == 0 &&
5292             ctl_is_set(lun->prevent, initidx)) {
5293                 ctl_clear_mask(lun->prevent, initidx);
5294                 lun->prevent_count--;
5295         }
5296         mtx_unlock(&lun->lun_lock);
5297         retval = lun->backend->config_write((union ctl_io *)ctsio);
5298         return (retval);
5299 }
5300
5301 /*
5302  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5303  * we don't really do anything with the LBA and length fields if the user
5304  * passes them in.  Instead we'll just flush out the cache for the entire
5305  * LUN.
5306  */
5307 int
5308 ctl_sync_cache(struct ctl_scsiio *ctsio)
5309 {
5310         struct ctl_lun *lun;
5311         struct ctl_softc *softc;
5312         struct ctl_lba_len_flags *lbalen;
5313         uint64_t starting_lba;
5314         uint32_t block_count;
5315         int retval;
5316         uint8_t byte2;
5317
5318         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5319
5320         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5321         softc = lun->ctl_softc;
5322         retval = 0;
5323
5324         switch (ctsio->cdb[0]) {
5325         case SYNCHRONIZE_CACHE: {
5326                 struct scsi_sync_cache *cdb;
5327                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5328
5329                 starting_lba = scsi_4btoul(cdb->begin_lba);
5330                 block_count = scsi_2btoul(cdb->lb_count);
5331                 byte2 = cdb->byte2;
5332                 break;
5333         }
5334         case SYNCHRONIZE_CACHE_16: {
5335                 struct scsi_sync_cache_16 *cdb;
5336                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5337
5338                 starting_lba = scsi_8btou64(cdb->begin_lba);
5339                 block_count = scsi_4btoul(cdb->lb_count);
5340                 byte2 = cdb->byte2;
5341                 break;
5342         }
5343         default:
5344                 ctl_set_invalid_opcode(ctsio);
5345                 ctl_done((union ctl_io *)ctsio);
5346                 goto bailout;
5347                 break; /* NOTREACHED */
5348         }
5349
5350         /*
5351          * We check the LBA and length, but don't do anything with them.
5352          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5353          * get flushed.  This check will just help satisfy anyone who wants
5354          * to see an error for an out of range LBA.
5355          */
5356         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5357                 ctl_set_lba_out_of_range(ctsio,
5358                     MAX(starting_lba, lun->be_lun->maxlba + 1));
5359                 ctl_done((union ctl_io *)ctsio);
5360                 goto bailout;
5361         }
5362
5363         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5364         lbalen->lba = starting_lba;
5365         lbalen->len = block_count;
5366         lbalen->flags = byte2;
5367         retval = lun->backend->config_write((union ctl_io *)ctsio);
5368
5369 bailout:
5370         return (retval);
5371 }
5372
5373 int
5374 ctl_format(struct ctl_scsiio *ctsio)
5375 {
5376         struct scsi_format *cdb;
5377         struct ctl_lun *lun;
5378         int length, defect_list_len;
5379
5380         CTL_DEBUG_PRINT(("ctl_format\n"));
5381
5382         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5383
5384         cdb = (struct scsi_format *)ctsio->cdb;
5385
5386         length = 0;
5387         if (cdb->byte2 & SF_FMTDATA) {
5388                 if (cdb->byte2 & SF_LONGLIST)
5389                         length = sizeof(struct scsi_format_header_long);
5390                 else
5391                         length = sizeof(struct scsi_format_header_short);
5392         }
5393
5394         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5395          && (length > 0)) {
5396                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5397                 ctsio->kern_data_len = length;
5398                 ctsio->kern_total_len = length;
5399                 ctsio->kern_data_resid = 0;
5400                 ctsio->kern_rel_offset = 0;
5401                 ctsio->kern_sg_entries = 0;
5402                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5403                 ctsio->be_move_done = ctl_config_move_done;
5404                 ctl_datamove((union ctl_io *)ctsio);
5405
5406                 return (CTL_RETVAL_COMPLETE);
5407         }
5408
5409         defect_list_len = 0;
5410
5411         if (cdb->byte2 & SF_FMTDATA) {
5412                 if (cdb->byte2 & SF_LONGLIST) {
5413                         struct scsi_format_header_long *header;
5414
5415                         header = (struct scsi_format_header_long *)
5416                                 ctsio->kern_data_ptr;
5417
5418                         defect_list_len = scsi_4btoul(header->defect_list_len);
5419                         if (defect_list_len != 0) {
5420                                 ctl_set_invalid_field(ctsio,
5421                                                       /*sks_valid*/ 1,
5422                                                       /*command*/ 0,
5423                                                       /*field*/ 2,
5424                                                       /*bit_valid*/ 0,
5425                                                       /*bit*/ 0);
5426                                 goto bailout;
5427                         }
5428                 } else {
5429                         struct scsi_format_header_short *header;
5430
5431                         header = (struct scsi_format_header_short *)
5432                                 ctsio->kern_data_ptr;
5433
5434                         defect_list_len = scsi_2btoul(header->defect_list_len);
5435                         if (defect_list_len != 0) {
5436                                 ctl_set_invalid_field(ctsio,
5437                                                       /*sks_valid*/ 1,
5438                                                       /*command*/ 0,
5439                                                       /*field*/ 2,
5440                                                       /*bit_valid*/ 0,
5441                                                       /*bit*/ 0);
5442                                 goto bailout;
5443                         }
5444                 }
5445         }
5446
5447         ctl_set_success(ctsio);
5448 bailout:
5449
5450         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5451                 free(ctsio->kern_data_ptr, M_CTL);
5452                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5453         }
5454
5455         ctl_done((union ctl_io *)ctsio);
5456         return (CTL_RETVAL_COMPLETE);
5457 }
5458
5459 int
5460 ctl_read_buffer(struct ctl_scsiio *ctsio)
5461 {
5462         struct ctl_lun *lun;
5463         uint64_t buffer_offset;
5464         uint32_t len;
5465         uint8_t byte2;
5466         static uint8_t descr[4];
5467         static uint8_t echo_descr[4] = { 0 };
5468
5469         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5470         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5471         switch (ctsio->cdb[0]) {
5472         case READ_BUFFER: {
5473                 struct scsi_read_buffer *cdb;
5474
5475                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5476                 buffer_offset = scsi_3btoul(cdb->offset);
5477                 len = scsi_3btoul(cdb->length);
5478                 byte2 = cdb->byte2;
5479                 break;
5480         }
5481         case READ_BUFFER_16: {
5482                 struct scsi_read_buffer_16 *cdb;
5483
5484                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5485                 buffer_offset = scsi_8btou64(cdb->offset);
5486                 len = scsi_4btoul(cdb->length);
5487                 byte2 = cdb->byte2;
5488                 break;
5489         }
5490         default: /* This shouldn't happen. */
5491                 ctl_set_invalid_opcode(ctsio);
5492                 ctl_done((union ctl_io *)ctsio);
5493                 return (CTL_RETVAL_COMPLETE);
5494         }
5495
5496         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5497             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5498                 ctl_set_invalid_field(ctsio,
5499                                       /*sks_valid*/ 1,
5500                                       /*command*/ 1,
5501                                       /*field*/ 6,
5502                                       /*bit_valid*/ 0,
5503                                       /*bit*/ 0);
5504                 ctl_done((union ctl_io *)ctsio);
5505                 return (CTL_RETVAL_COMPLETE);
5506         }
5507
5508         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5509                 descr[0] = 0;
5510                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5511                 ctsio->kern_data_ptr = descr;
5512                 len = min(len, sizeof(descr));
5513         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5514                 ctsio->kern_data_ptr = echo_descr;
5515                 len = min(len, sizeof(echo_descr));
5516         } else {
5517                 if (lun->write_buffer == NULL) {
5518                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5519                             M_CTL, M_WAITOK);
5520                 }
5521                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5522         }
5523         ctsio->kern_data_len = len;
5524         ctsio->kern_total_len = len;
5525         ctsio->kern_data_resid = 0;
5526         ctsio->kern_rel_offset = 0;
5527         ctsio->kern_sg_entries = 0;
5528         ctl_set_success(ctsio);
5529         ctsio->be_move_done = ctl_config_move_done;
5530         ctl_datamove((union ctl_io *)ctsio);
5531         return (CTL_RETVAL_COMPLETE);
5532 }
5533
5534 int
5535 ctl_write_buffer(struct ctl_scsiio *ctsio)
5536 {
5537         struct scsi_write_buffer *cdb;
5538         struct ctl_lun *lun;
5539         int buffer_offset, len;
5540
5541         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5542
5543         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5544         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5545
5546         len = scsi_3btoul(cdb->length);
5547         buffer_offset = scsi_3btoul(cdb->offset);
5548
5549         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5550                 ctl_set_invalid_field(ctsio,
5551                                       /*sks_valid*/ 1,
5552                                       /*command*/ 1,
5553                                       /*field*/ 6,
5554                                       /*bit_valid*/ 0,
5555                                       /*bit*/ 0);
5556                 ctl_done((union ctl_io *)ctsio);
5557                 return (CTL_RETVAL_COMPLETE);
5558         }
5559
5560         /*
5561          * If we've got a kernel request that hasn't been malloced yet,
5562          * malloc it and tell the caller the data buffer is here.
5563          */
5564         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5565                 if (lun->write_buffer == NULL) {
5566                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5567                             M_CTL, M_WAITOK);
5568                 }
5569                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5570                 ctsio->kern_data_len = len;
5571                 ctsio->kern_total_len = len;
5572                 ctsio->kern_data_resid = 0;
5573                 ctsio->kern_rel_offset = 0;
5574                 ctsio->kern_sg_entries = 0;
5575                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5576                 ctsio->be_move_done = ctl_config_move_done;
5577                 ctl_datamove((union ctl_io *)ctsio);
5578
5579                 return (CTL_RETVAL_COMPLETE);
5580         }
5581
5582         ctl_set_success(ctsio);
5583         ctl_done((union ctl_io *)ctsio);
5584         return (CTL_RETVAL_COMPLETE);
5585 }
5586
5587 int
5588 ctl_write_same(struct ctl_scsiio *ctsio)
5589 {
5590         struct ctl_lun *lun;
5591         struct ctl_lba_len_flags *lbalen;
5592         uint64_t lba;
5593         uint32_t num_blocks;
5594         int len, retval;
5595         uint8_t byte2;
5596
5597         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5598
5599         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5600
5601         switch (ctsio->cdb[0]) {
5602         case WRITE_SAME_10: {
5603                 struct scsi_write_same_10 *cdb;
5604
5605                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5606
5607                 lba = scsi_4btoul(cdb->addr);
5608                 num_blocks = scsi_2btoul(cdb->length);
5609                 byte2 = cdb->byte2;
5610                 break;
5611         }
5612         case WRITE_SAME_16: {
5613                 struct scsi_write_same_16 *cdb;
5614
5615                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5616
5617                 lba = scsi_8btou64(cdb->addr);
5618                 num_blocks = scsi_4btoul(cdb->length);
5619                 byte2 = cdb->byte2;
5620                 break;
5621         }
5622         default:
5623                 /*
5624                  * We got a command we don't support.  This shouldn't
5625                  * happen, commands should be filtered out above us.
5626                  */
5627                 ctl_set_invalid_opcode(ctsio);
5628                 ctl_done((union ctl_io *)ctsio);
5629
5630                 return (CTL_RETVAL_COMPLETE);
5631                 break; /* NOTREACHED */
5632         }
5633
5634         /* ANCHOR flag can be used only together with UNMAP */
5635         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5636                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5637                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5638                 ctl_done((union ctl_io *)ctsio);
5639                 return (CTL_RETVAL_COMPLETE);
5640         }
5641
5642         /*
5643          * The first check is to make sure we're in bounds, the second
5644          * check is to catch wrap-around problems.  If the lba + num blocks
5645          * is less than the lba, then we've wrapped around and the block
5646          * range is invalid anyway.
5647          */
5648         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5649          || ((lba + num_blocks) < lba)) {
5650                 ctl_set_lba_out_of_range(ctsio,
5651                     MAX(lba, lun->be_lun->maxlba + 1));
5652                 ctl_done((union ctl_io *)ctsio);
5653                 return (CTL_RETVAL_COMPLETE);
5654         }
5655
5656         /* Zero number of blocks means "to the last logical block" */
5657         if (num_blocks == 0) {
5658                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5659                         ctl_set_invalid_field(ctsio,
5660                                               /*sks_valid*/ 0,
5661                                               /*command*/ 1,
5662                                               /*field*/ 0,
5663                                               /*bit_valid*/ 0,
5664                                               /*bit*/ 0);
5665                         ctl_done((union ctl_io *)ctsio);
5666                         return (CTL_RETVAL_COMPLETE);
5667                 }
5668                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5669         }
5670
5671         len = lun->be_lun->blocksize;
5672
5673         /*
5674          * If we've got a kernel request that hasn't been malloced yet,
5675          * malloc it and tell the caller the data buffer is here.
5676          */
5677         if ((byte2 & SWS_NDOB) == 0 &&
5678             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5679                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5680                 ctsio->kern_data_len = len;
5681                 ctsio->kern_total_len = len;
5682                 ctsio->kern_data_resid = 0;
5683                 ctsio->kern_rel_offset = 0;
5684                 ctsio->kern_sg_entries = 0;
5685                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5686                 ctsio->be_move_done = ctl_config_move_done;
5687                 ctl_datamove((union ctl_io *)ctsio);
5688
5689                 return (CTL_RETVAL_COMPLETE);
5690         }
5691
5692         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5693         lbalen->lba = lba;
5694         lbalen->len = num_blocks;
5695         lbalen->flags = byte2;
5696         retval = lun->backend->config_write((union ctl_io *)ctsio);
5697
5698         return (retval);
5699 }
5700
5701 int
5702 ctl_unmap(struct ctl_scsiio *ctsio)
5703 {
5704         struct ctl_lun *lun;
5705         struct scsi_unmap *cdb;
5706         struct ctl_ptr_len_flags *ptrlen;
5707         struct scsi_unmap_header *hdr;
5708         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5709         uint64_t lba;
5710         uint32_t num_blocks;
5711         int len, retval;
5712         uint8_t byte2;
5713
5714         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5715
5716         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5717         cdb = (struct scsi_unmap *)ctsio->cdb;
5718
5719         len = scsi_2btoul(cdb->length);
5720         byte2 = cdb->byte2;
5721
5722         /*
5723          * If we've got a kernel request that hasn't been malloced yet,
5724          * malloc it and tell the caller the data buffer is here.
5725          */
5726         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5727                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5728                 ctsio->kern_data_len = len;
5729                 ctsio->kern_total_len = len;
5730                 ctsio->kern_data_resid = 0;
5731                 ctsio->kern_rel_offset = 0;
5732                 ctsio->kern_sg_entries = 0;
5733                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5734                 ctsio->be_move_done = ctl_config_move_done;
5735                 ctl_datamove((union ctl_io *)ctsio);
5736
5737                 return (CTL_RETVAL_COMPLETE);
5738         }
5739
5740         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5741         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5742         if (len < sizeof (*hdr) ||
5743             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5744             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5745             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5746                 ctl_set_invalid_field(ctsio,
5747                                       /*sks_valid*/ 0,
5748                                       /*command*/ 0,
5749                                       /*field*/ 0,
5750                                       /*bit_valid*/ 0,
5751                                       /*bit*/ 0);
5752                 goto done;
5753         }
5754         len = scsi_2btoul(hdr->desc_length);
5755         buf = (struct scsi_unmap_desc *)(hdr + 1);
5756         end = buf + len / sizeof(*buf);
5757
5758         endnz = buf;
5759         for (range = buf; range < end; range++) {
5760                 lba = scsi_8btou64(range->lba);
5761                 num_blocks = scsi_4btoul(range->length);
5762                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5763                  || ((lba + num_blocks) < lba)) {
5764                         ctl_set_lba_out_of_range(ctsio,
5765                             MAX(lba, lun->be_lun->maxlba + 1));
5766                         ctl_done((union ctl_io *)ctsio);
5767                         return (CTL_RETVAL_COMPLETE);
5768                 }
5769                 if (num_blocks != 0)
5770                         endnz = range + 1;
5771         }
5772
5773         /*
5774          * Block backend can not handle zero last range.
5775          * Filter it out and return if there is nothing left.
5776          */
5777         len = (uint8_t *)endnz - (uint8_t *)buf;
5778         if (len == 0) {
5779                 ctl_set_success(ctsio);
5780                 goto done;
5781         }
5782
5783         mtx_lock(&lun->lun_lock);
5784         ptrlen = (struct ctl_ptr_len_flags *)
5785             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5786         ptrlen->ptr = (void *)buf;
5787         ptrlen->len = len;
5788         ptrlen->flags = byte2;
5789         ctl_check_blocked(lun);
5790         mtx_unlock(&lun->lun_lock);
5791
5792         retval = lun->backend->config_write((union ctl_io *)ctsio);
5793         return (retval);
5794
5795 done:
5796         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5797                 free(ctsio->kern_data_ptr, M_CTL);
5798                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5799         }
5800         ctl_done((union ctl_io *)ctsio);
5801         return (CTL_RETVAL_COMPLETE);
5802 }
5803
5804 int
5805 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5806                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5807 {
5808         struct ctl_lun *lun;
5809         uint8_t *current_cp, *saved_cp;
5810         int set_ua;
5811         uint32_t initidx;
5812
5813         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5814         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5815         set_ua = 0;
5816
5817         current_cp = (page_index->page_data + (page_index->page_len *
5818             CTL_PAGE_CURRENT));
5819         saved_cp = (page_index->page_data + (page_index->page_len *
5820             CTL_PAGE_SAVED));
5821
5822         mtx_lock(&lun->lun_lock);
5823         if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5824                 memcpy(current_cp, page_ptr, page_index->page_len);
5825                 memcpy(saved_cp, page_ptr, page_index->page_len);
5826                 set_ua = 1;
5827         }
5828         if (set_ua != 0)
5829                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5830         mtx_unlock(&lun->lun_lock);
5831         if (set_ua) {
5832                 ctl_isc_announce_mode(lun,
5833                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5834                     page_index->page_code, page_index->subpage);
5835         }
5836         return (CTL_RETVAL_COMPLETE);
5837 }
5838
5839 static void
5840 ctl_ie_timer(void *arg)
5841 {
5842         struct ctl_lun *lun = arg;
5843         uint64_t t;
5844
5845         if (lun->ie_asc == 0)
5846                 return;
5847
5848         if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5849                 ctl_est_ua_all(lun, -1, CTL_UA_IE);
5850         else
5851                 lun->ie_reported = 0;
5852
5853         if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5854                 lun->ie_reportcnt++;
5855                 t = scsi_4btoul(lun->MODE_IE.interval_timer);
5856                 if (t == 0 || t == UINT32_MAX)
5857                         t = 3000;  /* 5 min */
5858                 callout_schedule(&lun->ie_callout, t * hz / 10);
5859         }
5860 }
5861
5862 int
5863 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5864                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5865 {
5866         struct scsi_info_exceptions_page *pg;
5867         struct ctl_lun *lun;
5868         uint64_t t;
5869
5870         (void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5871
5872         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5873         pg = (struct scsi_info_exceptions_page *)page_ptr;
5874         mtx_lock(&lun->lun_lock);
5875         if (pg->info_flags & SIEP_FLAGS_TEST) {
5876                 lun->ie_asc = 0x5d;
5877                 lun->ie_ascq = 0xff;
5878                 if (pg->mrie == SIEP_MRIE_UA) {
5879                         ctl_est_ua_all(lun, -1, CTL_UA_IE);
5880                         lun->ie_reported = 1;
5881                 } else {
5882                         ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5883                         lun->ie_reported = -1;
5884                 }
5885                 lun->ie_reportcnt = 1;
5886                 if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5887                         lun->ie_reportcnt++;
5888                         t = scsi_4btoul(pg->interval_timer);
5889                         if (t == 0 || t == UINT32_MAX)
5890                                 t = 3000;  /* 5 min */
5891                         callout_reset(&lun->ie_callout, t * hz / 10,
5892                             ctl_ie_timer, lun);
5893                 }
5894         } else {
5895                 lun->ie_asc = 0;
5896                 lun->ie_ascq = 0;
5897                 lun->ie_reported = 1;
5898                 ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5899                 lun->ie_reportcnt = UINT32_MAX;
5900                 callout_stop(&lun->ie_callout);
5901         }
5902         mtx_unlock(&lun->lun_lock);
5903         return (CTL_RETVAL_COMPLETE);
5904 }
5905
5906 static int
5907 ctl_do_mode_select(union ctl_io *io)
5908 {
5909         struct scsi_mode_page_header *page_header;
5910         struct ctl_page_index *page_index;
5911         struct ctl_scsiio *ctsio;
5912         int page_len, page_len_offset, page_len_size;
5913         union ctl_modepage_info *modepage_info;
5914         struct ctl_lun *lun;
5915         int *len_left, *len_used;
5916         int retval, i;
5917
5918         ctsio = &io->scsiio;
5919         page_index = NULL;
5920         page_len = 0;
5921         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5922
5923         modepage_info = (union ctl_modepage_info *)
5924                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5925         len_left = &modepage_info->header.len_left;
5926         len_used = &modepage_info->header.len_used;
5927
5928 do_next_page:
5929
5930         page_header = (struct scsi_mode_page_header *)
5931                 (ctsio->kern_data_ptr + *len_used);
5932
5933         if (*len_left == 0) {
5934                 free(ctsio->kern_data_ptr, M_CTL);
5935                 ctl_set_success(ctsio);
5936                 ctl_done((union ctl_io *)ctsio);
5937                 return (CTL_RETVAL_COMPLETE);
5938         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5939
5940                 free(ctsio->kern_data_ptr, M_CTL);
5941                 ctl_set_param_len_error(ctsio);
5942                 ctl_done((union ctl_io *)ctsio);
5943                 return (CTL_RETVAL_COMPLETE);
5944
5945         } else if ((page_header->page_code & SMPH_SPF)
5946                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5947
5948                 free(ctsio->kern_data_ptr, M_CTL);
5949                 ctl_set_param_len_error(ctsio);
5950                 ctl_done((union ctl_io *)ctsio);
5951                 return (CTL_RETVAL_COMPLETE);
5952         }
5953
5954
5955         /*
5956          * XXX KDM should we do something with the block descriptor?
5957          */
5958         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5959                 page_index = &lun->mode_pages.index[i];
5960                 if (lun->be_lun->lun_type == T_DIRECT &&
5961                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5962                         continue;
5963                 if (lun->be_lun->lun_type == T_PROCESSOR &&
5964                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5965                         continue;
5966                 if (lun->be_lun->lun_type == T_CDROM &&
5967                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5968                         continue;
5969
5970                 if ((page_index->page_code & SMPH_PC_MASK) !=
5971                     (page_header->page_code & SMPH_PC_MASK))
5972                         continue;
5973
5974                 /*
5975                  * If neither page has a subpage code, then we've got a
5976                  * match.
5977                  */
5978                 if (((page_index->page_code & SMPH_SPF) == 0)
5979                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5980                         page_len = page_header->page_length;
5981                         break;
5982                 }
5983
5984                 /*
5985                  * If both pages have subpages, then the subpage numbers
5986                  * have to match.
5987                  */
5988                 if ((page_index->page_code & SMPH_SPF)
5989                   && (page_header->page_code & SMPH_SPF)) {
5990                         struct scsi_mode_page_header_sp *sph;
5991
5992                         sph = (struct scsi_mode_page_header_sp *)page_header;
5993                         if (page_index->subpage == sph->subpage) {
5994                                 page_len = scsi_2btoul(sph->page_length);
5995                                 break;
5996                         }
5997                 }
5998         }
5999
6000         /*
6001          * If we couldn't find the page, or if we don't have a mode select
6002          * handler for it, send back an error to the user.
6003          */
6004         if ((i >= CTL_NUM_MODE_PAGES)
6005          || (page_index->select_handler == NULL)) {
6006                 ctl_set_invalid_field(ctsio,
6007                                       /*sks_valid*/ 1,
6008                                       /*command*/ 0,
6009                                       /*field*/ *len_used,
6010                                       /*bit_valid*/ 0,
6011                                       /*bit*/ 0);
6012                 free(ctsio->kern_data_ptr, M_CTL);
6013                 ctl_done((union ctl_io *)ctsio);
6014                 return (CTL_RETVAL_COMPLETE);
6015         }
6016
6017         if (page_index->page_code & SMPH_SPF) {
6018                 page_len_offset = 2;
6019                 page_len_size = 2;
6020         } else {
6021                 page_len_size = 1;
6022                 page_len_offset = 1;
6023         }
6024
6025         /*
6026          * If the length the initiator gives us isn't the one we specify in
6027          * the mode page header, or if they didn't specify enough data in
6028          * the CDB to avoid truncating this page, kick out the request.
6029          */
6030         if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6031                 ctl_set_invalid_field(ctsio,
6032                                       /*sks_valid*/ 1,
6033                                       /*command*/ 0,
6034                                       /*field*/ *len_used + page_len_offset,
6035                                       /*bit_valid*/ 0,
6036                                       /*bit*/ 0);
6037                 free(ctsio->kern_data_ptr, M_CTL);
6038                 ctl_done((union ctl_io *)ctsio);
6039                 return (CTL_RETVAL_COMPLETE);
6040         }
6041         if (*len_left < page_index->page_len) {
6042                 free(ctsio->kern_data_ptr, M_CTL);
6043                 ctl_set_param_len_error(ctsio);
6044                 ctl_done((union ctl_io *)ctsio);
6045                 return (CTL_RETVAL_COMPLETE);
6046         }
6047
6048         /*
6049          * Run through the mode page, checking to make sure that the bits
6050          * the user changed are actually legal for him to change.
6051          */
6052         for (i = 0; i < page_index->page_len; i++) {
6053                 uint8_t *user_byte, *change_mask, *current_byte;
6054                 int bad_bit;
6055                 int j;
6056
6057                 user_byte = (uint8_t *)page_header + i;
6058                 change_mask = page_index->page_data +
6059                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6060                 current_byte = page_index->page_data +
6061                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6062
6063                 /*
6064                  * Check to see whether the user set any bits in this byte
6065                  * that he is not allowed to set.
6066                  */
6067                 if ((*user_byte & ~(*change_mask)) ==
6068                     (*current_byte & ~(*change_mask)))
6069                         continue;
6070
6071                 /*
6072                  * Go through bit by bit to determine which one is illegal.
6073                  */
6074                 bad_bit = 0;
6075                 for (j = 7; j >= 0; j--) {
6076                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6077                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6078                                 bad_bit = i;
6079                                 break;
6080                         }
6081                 }
6082                 ctl_set_invalid_field(ctsio,
6083                                       /*sks_valid*/ 1,
6084                                       /*command*/ 0,
6085                                       /*field*/ *len_used + i,
6086                                       /*bit_valid*/ 1,
6087                                       /*bit*/ bad_bit);
6088                 free(ctsio->kern_data_ptr, M_CTL);
6089                 ctl_done((union ctl_io *)ctsio);
6090                 return (CTL_RETVAL_COMPLETE);
6091         }
6092
6093         /*
6094          * Decrement these before we call the page handler, since we may
6095          * end up getting called back one way or another before the handler
6096          * returns to this context.
6097          */
6098         *len_left -= page_index->page_len;
6099         *len_used += page_index->page_len;
6100
6101         retval = page_index->select_handler(ctsio, page_index,
6102                                             (uint8_t *)page_header);
6103
6104         /*
6105          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6106          * wait until this queued command completes to finish processing
6107          * the mode page.  If it returns anything other than
6108          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6109          * already set the sense information, freed the data pointer, and
6110          * completed the io for us.
6111          */
6112         if (retval != CTL_RETVAL_COMPLETE)
6113                 goto bailout_no_done;
6114
6115         /*
6116          * If the initiator sent us more than one page, parse the next one.
6117          */
6118         if (*len_left > 0)
6119                 goto do_next_page;
6120
6121         ctl_set_success(ctsio);
6122         free(ctsio->kern_data_ptr, M_CTL);
6123         ctl_done((union ctl_io *)ctsio);
6124
6125 bailout_no_done:
6126
6127         return (CTL_RETVAL_COMPLETE);
6128
6129 }
6130
6131 int
6132 ctl_mode_select(struct ctl_scsiio *ctsio)
6133 {
6134         int param_len, pf, sp;
6135         int header_size, bd_len;
6136         union ctl_modepage_info *modepage_info;
6137
6138         switch (ctsio->cdb[0]) {
6139         case MODE_SELECT_6: {
6140                 struct scsi_mode_select_6 *cdb;
6141
6142                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6143
6144                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6145                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6146                 param_len = cdb->length;
6147                 header_size = sizeof(struct scsi_mode_header_6);
6148                 break;
6149         }
6150         case MODE_SELECT_10: {
6151                 struct scsi_mode_select_10 *cdb;
6152
6153                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6154
6155                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6156                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6157                 param_len = scsi_2btoul(cdb->length);
6158                 header_size = sizeof(struct scsi_mode_header_10);
6159                 break;
6160         }
6161         default:
6162                 ctl_set_invalid_opcode(ctsio);
6163                 ctl_done((union ctl_io *)ctsio);
6164                 return (CTL_RETVAL_COMPLETE);
6165         }
6166
6167         /*
6168          * From SPC-3:
6169          * "A parameter list length of zero indicates that the Data-Out Buffer
6170          * shall be empty. This condition shall not be considered as an error."
6171          */
6172         if (param_len == 0) {
6173                 ctl_set_success(ctsio);
6174                 ctl_done((union ctl_io *)ctsio);
6175                 return (CTL_RETVAL_COMPLETE);
6176         }
6177
6178         /*
6179          * Since we'll hit this the first time through, prior to
6180          * allocation, we don't need to free a data buffer here.
6181          */
6182         if (param_len < header_size) {
6183                 ctl_set_param_len_error(ctsio);
6184                 ctl_done((union ctl_io *)ctsio);
6185                 return (CTL_RETVAL_COMPLETE);
6186         }
6187
6188         /*
6189          * Allocate the data buffer and grab the user's data.  In theory,
6190          * we shouldn't have to sanity check the parameter list length here
6191          * because the maximum size is 64K.  We should be able to malloc
6192          * that much without too many problems.
6193          */
6194         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6195                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6196                 ctsio->kern_data_len = param_len;
6197                 ctsio->kern_total_len = param_len;
6198                 ctsio->kern_data_resid = 0;
6199                 ctsio->kern_rel_offset = 0;
6200                 ctsio->kern_sg_entries = 0;
6201                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6202                 ctsio->be_move_done = ctl_config_move_done;
6203                 ctl_datamove((union ctl_io *)ctsio);
6204
6205                 return (CTL_RETVAL_COMPLETE);
6206         }
6207
6208         switch (ctsio->cdb[0]) {
6209         case MODE_SELECT_6: {
6210                 struct scsi_mode_header_6 *mh6;
6211
6212                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6213                 bd_len = mh6->blk_desc_len;
6214                 break;
6215         }
6216         case MODE_SELECT_10: {
6217                 struct scsi_mode_header_10 *mh10;
6218
6219                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6220                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6221                 break;
6222         }
6223         default:
6224                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6225         }
6226
6227         if (param_len < (header_size + bd_len)) {
6228                 free(ctsio->kern_data_ptr, M_CTL);
6229                 ctl_set_param_len_error(ctsio);
6230                 ctl_done((union ctl_io *)ctsio);
6231                 return (CTL_RETVAL_COMPLETE);
6232         }
6233
6234         /*
6235          * Set the IO_CONT flag, so that if this I/O gets passed to
6236          * ctl_config_write_done(), it'll get passed back to
6237          * ctl_do_mode_select() for further processing, or completion if
6238          * we're all done.
6239          */
6240         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6241         ctsio->io_cont = ctl_do_mode_select;
6242
6243         modepage_info = (union ctl_modepage_info *)
6244                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6245         memset(modepage_info, 0, sizeof(*modepage_info));
6246         modepage_info->header.len_left = param_len - header_size - bd_len;
6247         modepage_info->header.len_used = header_size + bd_len;
6248
6249         return (ctl_do_mode_select((union ctl_io *)ctsio));
6250 }
6251
6252 int
6253 ctl_mode_sense(struct ctl_scsiio *ctsio)
6254 {
6255         struct ctl_lun *lun;
6256         int pc, page_code, dbd, llba, subpage;
6257         int alloc_len, page_len, header_len, total_len;
6258         struct scsi_mode_block_descr *block_desc;
6259         struct ctl_page_index *page_index;
6260
6261         dbd = 0;
6262         llba = 0;
6263         block_desc = NULL;
6264
6265         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6266
6267         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6268         switch (ctsio->cdb[0]) {
6269         case MODE_SENSE_6: {
6270                 struct scsi_mode_sense_6 *cdb;
6271
6272                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6273
6274                 header_len = sizeof(struct scsi_mode_hdr_6);
6275                 if (cdb->byte2 & SMS_DBD)
6276                         dbd = 1;
6277                 else
6278                         header_len += sizeof(struct scsi_mode_block_descr);
6279
6280                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6281                 page_code = cdb->page & SMS_PAGE_CODE;
6282                 subpage = cdb->subpage;
6283                 alloc_len = cdb->length;
6284                 break;
6285         }
6286         case MODE_SENSE_10: {
6287                 struct scsi_mode_sense_10 *cdb;
6288
6289                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6290
6291                 header_len = sizeof(struct scsi_mode_hdr_10);
6292
6293                 if (cdb->byte2 & SMS_DBD)
6294                         dbd = 1;
6295                 else
6296                         header_len += sizeof(struct scsi_mode_block_descr);
6297                 if (cdb->byte2 & SMS10_LLBAA)
6298                         llba = 1;
6299                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6300                 page_code = cdb->page & SMS_PAGE_CODE;
6301                 subpage = cdb->subpage;
6302                 alloc_len = scsi_2btoul(cdb->length);
6303                 break;
6304         }
6305         default:
6306                 ctl_set_invalid_opcode(ctsio);
6307                 ctl_done((union ctl_io *)ctsio);
6308                 return (CTL_RETVAL_COMPLETE);
6309                 break; /* NOTREACHED */
6310         }
6311
6312         /*
6313          * We have to make a first pass through to calculate the size of
6314          * the pages that match the user's query.  Then we allocate enough
6315          * memory to hold it, and actually copy the data into the buffer.
6316          */
6317         switch (page_code) {
6318         case SMS_ALL_PAGES_PAGE: {
6319                 u_int i;
6320
6321                 page_len = 0;
6322
6323                 /*
6324                  * At the moment, values other than 0 and 0xff here are
6325                  * reserved according to SPC-3.
6326                  */
6327                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6328                  && (subpage != SMS_SUBPAGE_ALL)) {
6329                         ctl_set_invalid_field(ctsio,
6330                                               /*sks_valid*/ 1,
6331                                               /*command*/ 1,
6332                                               /*field*/ 3,
6333                                               /*bit_valid*/ 0,
6334                                               /*bit*/ 0);
6335                         ctl_done((union ctl_io *)ctsio);
6336                         return (CTL_RETVAL_COMPLETE);
6337                 }
6338
6339                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6340                         page_index = &lun->mode_pages.index[i];
6341
6342                         /* Make sure the page is supported for this dev type */
6343                         if (lun->be_lun->lun_type == T_DIRECT &&
6344                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6345                                 continue;
6346                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6347                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6348                                 continue;
6349                         if (lun->be_lun->lun_type == T_CDROM &&
6350                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6351                                 continue;
6352
6353                         /*
6354                          * We don't use this subpage if the user didn't
6355                          * request all subpages.
6356                          */
6357                         if ((page_index->subpage != 0)
6358                          && (subpage == SMS_SUBPAGE_PAGE_0))
6359                                 continue;
6360
6361 #if 0
6362                         printf("found page %#x len %d\n",
6363                                page_index->page_code & SMPH_PC_MASK,
6364                                page_index->page_len);
6365 #endif
6366                         page_len += page_index->page_len;
6367                 }
6368                 break;
6369         }
6370         default: {
6371                 u_int i;
6372
6373                 page_len = 0;
6374
6375                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6376                         page_index = &lun->mode_pages.index[i];
6377
6378                         /* Make sure the page is supported for this dev type */
6379                         if (lun->be_lun->lun_type == T_DIRECT &&
6380                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6381                                 continue;
6382                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6383                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6384                                 continue;
6385                         if (lun->be_lun->lun_type == T_CDROM &&
6386                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6387                                 continue;
6388
6389                         /* Look for the right page code */
6390                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6391                                 continue;
6392
6393                         /* Look for the right subpage or the subpage wildcard*/
6394                         if ((page_index->subpage != subpage)
6395                          && (subpage != SMS_SUBPAGE_ALL))
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
6404                         page_len += page_index->page_len;
6405                 }
6406
6407                 if (page_len == 0) {
6408                         ctl_set_invalid_field(ctsio,
6409                                               /*sks_valid*/ 1,
6410                                               /*command*/ 1,
6411                                               /*field*/ 2,
6412                                               /*bit_valid*/ 1,
6413                                               /*bit*/ 5);
6414                         ctl_done((union ctl_io *)ctsio);
6415                         return (CTL_RETVAL_COMPLETE);
6416                 }
6417                 break;
6418         }
6419         }
6420
6421         total_len = header_len + page_len;
6422 #if 0
6423         printf("header_len = %d, page_len = %d, total_len = %d\n",
6424                header_len, page_len, total_len);
6425 #endif
6426
6427         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6428         ctsio->kern_sg_entries = 0;
6429         ctsio->kern_data_resid = 0;
6430         ctsio->kern_rel_offset = 0;
6431         if (total_len < alloc_len) {
6432                 ctsio->residual = alloc_len - total_len;
6433                 ctsio->kern_data_len = total_len;
6434                 ctsio->kern_total_len = total_len;
6435         } else {
6436                 ctsio->residual = 0;
6437                 ctsio->kern_data_len = alloc_len;
6438                 ctsio->kern_total_len = alloc_len;
6439         }
6440
6441         switch (ctsio->cdb[0]) {
6442         case MODE_SENSE_6: {
6443                 struct scsi_mode_hdr_6 *header;
6444
6445                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6446
6447                 header->datalen = MIN(total_len - 1, 254);
6448                 if (lun->be_lun->lun_type == T_DIRECT) {
6449                         header->dev_specific = 0x10; /* DPOFUA */
6450                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6451                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6452                                 header->dev_specific |= 0x80; /* WP */
6453                 }
6454                 if (dbd)
6455                         header->block_descr_len = 0;
6456                 else
6457                         header->block_descr_len =
6458                                 sizeof(struct scsi_mode_block_descr);
6459                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6460                 break;
6461         }
6462         case MODE_SENSE_10: {
6463                 struct scsi_mode_hdr_10 *header;
6464                 int datalen;
6465
6466                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6467
6468                 datalen = MIN(total_len - 2, 65533);
6469                 scsi_ulto2b(datalen, header->datalen);
6470                 if (lun->be_lun->lun_type == T_DIRECT) {
6471                         header->dev_specific = 0x10; /* DPOFUA */
6472                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6473                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6474                                 header->dev_specific |= 0x80; /* WP */
6475                 }
6476                 if (dbd)
6477                         scsi_ulto2b(0, header->block_descr_len);
6478                 else
6479                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6480                                     header->block_descr_len);
6481                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6482                 break;
6483         }
6484         default:
6485                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6486         }
6487
6488         /*
6489          * If we've got a disk, use its blocksize in the block
6490          * descriptor.  Otherwise, just set it to 0.
6491          */
6492         if (dbd == 0) {
6493                 if (lun->be_lun->lun_type == T_DIRECT)
6494                         scsi_ulto3b(lun->be_lun->blocksize,
6495                                     block_desc->block_len);
6496                 else
6497                         scsi_ulto3b(0, block_desc->block_len);
6498         }
6499
6500         switch (page_code) {
6501         case SMS_ALL_PAGES_PAGE: {
6502                 int i, data_used;
6503
6504                 data_used = header_len;
6505                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6506                         struct ctl_page_index *page_index;
6507
6508                         page_index = &lun->mode_pages.index[i];
6509                         if (lun->be_lun->lun_type == T_DIRECT &&
6510                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6511                                 continue;
6512                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6513                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6514                                 continue;
6515                         if (lun->be_lun->lun_type == T_CDROM &&
6516                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6517                                 continue;
6518
6519                         /*
6520                          * We don't use this subpage if the user didn't
6521                          * request all subpages.  We already checked (above)
6522                          * to make sure the user only specified a subpage
6523                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6524                          */
6525                         if ((page_index->subpage != 0)
6526                          && (subpage == SMS_SUBPAGE_PAGE_0))
6527                                 continue;
6528
6529                         /*
6530                          * Call the handler, if it exists, to update the
6531                          * page to the latest values.
6532                          */
6533                         if (page_index->sense_handler != NULL)
6534                                 page_index->sense_handler(ctsio, page_index,pc);
6535
6536                         memcpy(ctsio->kern_data_ptr + data_used,
6537                                page_index->page_data +
6538                                (page_index->page_len * pc),
6539                                page_index->page_len);
6540                         data_used += page_index->page_len;
6541                 }
6542                 break;
6543         }
6544         default: {
6545                 int i, data_used;
6546
6547                 data_used = header_len;
6548
6549                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6550                         struct ctl_page_index *page_index;
6551
6552                         page_index = &lun->mode_pages.index[i];
6553
6554                         /* Look for the right page code */
6555                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6556                                 continue;
6557
6558                         /* Look for the right subpage or the subpage wildcard*/
6559                         if ((page_index->subpage != subpage)
6560                          && (subpage != SMS_SUBPAGE_ALL))
6561                                 continue;
6562
6563                         /* Make sure the page is supported for this dev type */
6564                         if (lun->be_lun->lun_type == T_DIRECT &&
6565                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6566                                 continue;
6567                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6568                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6569                                 continue;
6570                         if (lun->be_lun->lun_type == T_CDROM &&
6571                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6572                                 continue;
6573
6574                         /*
6575                          * Call the handler, if it exists, to update the
6576                          * page to the latest values.
6577                          */
6578                         if (page_index->sense_handler != NULL)
6579                                 page_index->sense_handler(ctsio, page_index,pc);
6580
6581                         memcpy(ctsio->kern_data_ptr + data_used,
6582                                page_index->page_data +
6583                                (page_index->page_len * pc),
6584                                page_index->page_len);
6585                         data_used += page_index->page_len;
6586                 }
6587                 break;
6588         }
6589         }
6590
6591         ctl_set_success(ctsio);
6592         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6593         ctsio->be_move_done = ctl_config_move_done;
6594         ctl_datamove((union ctl_io *)ctsio);
6595         return (CTL_RETVAL_COMPLETE);
6596 }
6597
6598 int
6599 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6600                                struct ctl_page_index *page_index,
6601                                int pc)
6602 {
6603         struct ctl_lun *lun;
6604         struct scsi_log_param_header *phdr;
6605         uint8_t *data;
6606         uint64_t val;
6607
6608         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6609         data = page_index->page_data;
6610
6611         if (lun->backend->lun_attr != NULL &&
6612             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6613              != UINT64_MAX) {
6614                 phdr = (struct scsi_log_param_header *)data;
6615                 scsi_ulto2b(0x0001, phdr->param_code);
6616                 phdr->param_control = SLP_LBIN | SLP_LP;
6617                 phdr->param_len = 8;
6618                 data = (uint8_t *)(phdr + 1);
6619                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6620                 data[4] = 0x02; /* per-pool */
6621                 data += phdr->param_len;
6622         }
6623
6624         if (lun->backend->lun_attr != NULL &&
6625             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6626              != UINT64_MAX) {
6627                 phdr = (struct scsi_log_param_header *)data;
6628                 scsi_ulto2b(0x0002, phdr->param_code);
6629                 phdr->param_control = SLP_LBIN | SLP_LP;
6630                 phdr->param_len = 8;
6631                 data = (uint8_t *)(phdr + 1);
6632                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6633                 data[4] = 0x01; /* per-LUN */
6634                 data += phdr->param_len;
6635         }
6636
6637         if (lun->backend->lun_attr != NULL &&
6638             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6639              != UINT64_MAX) {
6640                 phdr = (struct scsi_log_param_header *)data;
6641                 scsi_ulto2b(0x00f1, phdr->param_code);
6642                 phdr->param_control = SLP_LBIN | SLP_LP;
6643                 phdr->param_len = 8;
6644                 data = (uint8_t *)(phdr + 1);
6645                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6646                 data[4] = 0x02; /* per-pool */
6647                 data += phdr->param_len;
6648         }
6649
6650         if (lun->backend->lun_attr != NULL &&
6651             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6652              != UINT64_MAX) {
6653                 phdr = (struct scsi_log_param_header *)data;
6654                 scsi_ulto2b(0x00f2, phdr->param_code);
6655                 phdr->param_control = SLP_LBIN | SLP_LP;
6656                 phdr->param_len = 8;
6657                 data = (uint8_t *)(phdr + 1);
6658                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6659                 data[4] = 0x02; /* per-pool */
6660                 data += phdr->param_len;
6661         }
6662
6663         page_index->page_len = data - page_index->page_data;
6664         return (0);
6665 }
6666
6667 int
6668 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6669                                struct ctl_page_index *page_index,
6670                                int pc)
6671 {
6672         struct ctl_lun *lun;
6673         struct stat_page *data;
6674         uint64_t rn, wn, rb, wb;
6675         struct bintime rt, wt;
6676         int i;
6677
6678         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6679         data = (struct stat_page *)page_index->page_data;
6680
6681         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6682         data->sap.hdr.param_control = SLP_LBIN;
6683         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6684             sizeof(struct scsi_log_param_header);
6685         rn = wn = rb = wb = 0;
6686         bintime_clear(&rt);
6687         bintime_clear(&wt);
6688         for (i = 0; i < CTL_MAX_PORTS; i++) {
6689                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6690                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6691                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6692                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6693                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6694                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6695         }
6696         scsi_u64to8b(rn, data->sap.read_num);
6697         scsi_u64to8b(wn, data->sap.write_num);
6698         if (lun->stats.blocksize > 0) {
6699                 scsi_u64to8b(wb / lun->stats.blocksize,
6700                     data->sap.recvieved_lba);
6701                 scsi_u64to8b(rb / lun->stats.blocksize,
6702                     data->sap.transmitted_lba);
6703         }
6704         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6705             data->sap.read_int);
6706         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6707             data->sap.write_int);
6708         scsi_u64to8b(0, data->sap.weighted_num);
6709         scsi_u64to8b(0, data->sap.weighted_int);
6710         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6711         data->it.hdr.param_control = SLP_LBIN;
6712         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6713             sizeof(struct scsi_log_param_header);
6714 #ifdef CTL_TIME_IO
6715         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6716 #endif
6717         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6718         data->it.hdr.param_control = SLP_LBIN;
6719         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6720             sizeof(struct scsi_log_param_header);
6721         scsi_ulto4b(3, data->ti.exponent);
6722         scsi_ulto4b(1, data->ti.integer);
6723         return (0);
6724 }
6725
6726 int
6727 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6728                                struct ctl_page_index *page_index,
6729                                int pc)
6730 {
6731         struct ctl_lun *lun;
6732         struct scsi_log_informational_exceptions *data;
6733
6734         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6735         data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6736
6737         scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6738         data->hdr.param_control = SLP_LBIN;
6739         data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6740             sizeof(struct scsi_log_param_header);
6741         data->ie_asc = lun->ie_asc;
6742         data->ie_ascq = lun->ie_ascq;
6743         data->temperature = 0xff;
6744         return (0);
6745 }
6746
6747 int
6748 ctl_log_sense(struct ctl_scsiio *ctsio)
6749 {
6750         struct ctl_lun *lun;
6751         int i, pc, page_code, subpage;
6752         int alloc_len, total_len;
6753         struct ctl_page_index *page_index;
6754         struct scsi_log_sense *cdb;
6755         struct scsi_log_header *header;
6756
6757         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6758
6759         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6760         cdb = (struct scsi_log_sense *)ctsio->cdb;
6761         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6762         page_code = cdb->page & SLS_PAGE_CODE;
6763         subpage = cdb->subpage;
6764         alloc_len = scsi_2btoul(cdb->length);
6765
6766         page_index = NULL;
6767         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6768                 page_index = &lun->log_pages.index[i];
6769
6770                 /* Look for the right page code */
6771                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6772                         continue;
6773
6774                 /* Look for the right subpage or the subpage wildcard*/
6775                 if (page_index->subpage != subpage)
6776                         continue;
6777
6778                 break;
6779         }
6780         if (i >= CTL_NUM_LOG_PAGES) {
6781                 ctl_set_invalid_field(ctsio,
6782                                       /*sks_valid*/ 1,
6783                                       /*command*/ 1,
6784                                       /*field*/ 2,
6785                                       /*bit_valid*/ 0,
6786                                       /*bit*/ 0);
6787                 ctl_done((union ctl_io *)ctsio);
6788                 return (CTL_RETVAL_COMPLETE);
6789         }
6790
6791         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6792
6793         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6794         ctsio->kern_sg_entries = 0;
6795         ctsio->kern_data_resid = 0;
6796         ctsio->kern_rel_offset = 0;
6797         if (total_len < alloc_len) {
6798                 ctsio->residual = alloc_len - total_len;
6799                 ctsio->kern_data_len = total_len;
6800                 ctsio->kern_total_len = total_len;
6801         } else {
6802                 ctsio->residual = 0;
6803                 ctsio->kern_data_len = alloc_len;
6804                 ctsio->kern_total_len = alloc_len;
6805         }
6806
6807         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6808         header->page = page_index->page_code;
6809         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6810                 header->page |= SL_DS;
6811         if (page_index->subpage) {
6812                 header->page |= SL_SPF;
6813                 header->subpage = page_index->subpage;
6814         }
6815         scsi_ulto2b(page_index->page_len, header->datalen);
6816
6817         /*
6818          * Call the handler, if it exists, to update the
6819          * page to the latest values.
6820          */
6821         if (page_index->sense_handler != NULL)
6822                 page_index->sense_handler(ctsio, page_index, pc);
6823
6824         memcpy(header + 1, page_index->page_data, page_index->page_len);
6825
6826         ctl_set_success(ctsio);
6827         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6828         ctsio->be_move_done = ctl_config_move_done;
6829         ctl_datamove((union ctl_io *)ctsio);
6830         return (CTL_RETVAL_COMPLETE);
6831 }
6832
6833 int
6834 ctl_read_capacity(struct ctl_scsiio *ctsio)
6835 {
6836         struct scsi_read_capacity *cdb;
6837         struct scsi_read_capacity_data *data;
6838         struct ctl_lun *lun;
6839         uint32_t lba;
6840
6841         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6842
6843         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6844
6845         lba = scsi_4btoul(cdb->addr);
6846         if (((cdb->pmi & SRC_PMI) == 0)
6847          && (lba != 0)) {
6848                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6849                                       /*sks_valid*/ 1,
6850                                       /*command*/ 1,
6851                                       /*field*/ 2,
6852                                       /*bit_valid*/ 0,
6853                                       /*bit*/ 0);
6854                 ctl_done((union ctl_io *)ctsio);
6855                 return (CTL_RETVAL_COMPLETE);
6856         }
6857
6858         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6859
6860         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6861         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6862         ctsio->residual = 0;
6863         ctsio->kern_data_len = sizeof(*data);
6864         ctsio->kern_total_len = sizeof(*data);
6865         ctsio->kern_data_resid = 0;
6866         ctsio->kern_rel_offset = 0;
6867         ctsio->kern_sg_entries = 0;
6868
6869         /*
6870          * If the maximum LBA is greater than 0xfffffffe, the user must
6871          * issue a SERVICE ACTION IN (16) command, with the read capacity
6872          * serivce action set.
6873          */
6874         if (lun->be_lun->maxlba > 0xfffffffe)
6875                 scsi_ulto4b(0xffffffff, data->addr);
6876         else
6877                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6878
6879         /*
6880          * XXX KDM this may not be 512 bytes...
6881          */
6882         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6883
6884         ctl_set_success(ctsio);
6885         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6886         ctsio->be_move_done = ctl_config_move_done;
6887         ctl_datamove((union ctl_io *)ctsio);
6888         return (CTL_RETVAL_COMPLETE);
6889 }
6890
6891 int
6892 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6893 {
6894         struct scsi_read_capacity_16 *cdb;
6895         struct scsi_read_capacity_data_long *data;
6896         struct ctl_lun *lun;
6897         uint64_t lba;
6898         uint32_t alloc_len;
6899
6900         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6901
6902         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6903
6904         alloc_len = scsi_4btoul(cdb->alloc_len);
6905         lba = scsi_8btou64(cdb->addr);
6906
6907         if ((cdb->reladr & SRC16_PMI)
6908          && (lba != 0)) {
6909                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6910                                       /*sks_valid*/ 1,
6911                                       /*command*/ 1,
6912                                       /*field*/ 2,
6913                                       /*bit_valid*/ 0,
6914                                       /*bit*/ 0);
6915                 ctl_done((union ctl_io *)ctsio);
6916                 return (CTL_RETVAL_COMPLETE);
6917         }
6918
6919         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6920
6921         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6922         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6923
6924         if (sizeof(*data) < alloc_len) {
6925                 ctsio->residual = alloc_len - sizeof(*data);
6926                 ctsio->kern_data_len = sizeof(*data);
6927                 ctsio->kern_total_len = sizeof(*data);
6928         } else {
6929                 ctsio->residual = 0;
6930                 ctsio->kern_data_len = alloc_len;
6931                 ctsio->kern_total_len = alloc_len;
6932         }
6933         ctsio->kern_data_resid = 0;
6934         ctsio->kern_rel_offset = 0;
6935         ctsio->kern_sg_entries = 0;
6936
6937         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6938         /* XXX KDM this may not be 512 bytes... */
6939         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6940         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6941         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6942         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6943                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6944
6945         ctl_set_success(ctsio);
6946         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6947         ctsio->be_move_done = ctl_config_move_done;
6948         ctl_datamove((union ctl_io *)ctsio);
6949         return (CTL_RETVAL_COMPLETE);
6950 }
6951
6952 int
6953 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6954 {
6955         struct scsi_get_lba_status *cdb;
6956         struct scsi_get_lba_status_data *data;
6957         struct ctl_lun *lun;
6958         struct ctl_lba_len_flags *lbalen;
6959         uint64_t lba;
6960         uint32_t alloc_len, total_len;
6961         int retval;
6962
6963         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6964
6965         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6966         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6967         lba = scsi_8btou64(cdb->addr);
6968         alloc_len = scsi_4btoul(cdb->alloc_len);
6969
6970         if (lba > lun->be_lun->maxlba) {
6971                 ctl_set_lba_out_of_range(ctsio, lba);
6972                 ctl_done((union ctl_io *)ctsio);
6973                 return (CTL_RETVAL_COMPLETE);
6974         }
6975
6976         total_len = sizeof(*data) + sizeof(data->descr[0]);
6977         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6978         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6979
6980         if (total_len < alloc_len) {
6981                 ctsio->residual = alloc_len - total_len;
6982                 ctsio->kern_data_len = total_len;
6983                 ctsio->kern_total_len = total_len;
6984         } else {
6985                 ctsio->residual = 0;
6986                 ctsio->kern_data_len = alloc_len;
6987                 ctsio->kern_total_len = alloc_len;
6988         }
6989         ctsio->kern_data_resid = 0;
6990         ctsio->kern_rel_offset = 0;
6991         ctsio->kern_sg_entries = 0;
6992
6993         /* Fill dummy data in case backend can't tell anything. */
6994         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6995         scsi_u64to8b(lba, data->descr[0].addr);
6996         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6997             data->descr[0].length);
6998         data->descr[0].status = 0; /* Mapped or unknown. */
6999
7000         ctl_set_success(ctsio);
7001         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7002         ctsio->be_move_done = ctl_config_move_done;
7003
7004         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7005         lbalen->lba = lba;
7006         lbalen->len = total_len;
7007         lbalen->flags = 0;
7008         retval = lun->backend->config_read((union ctl_io *)ctsio);
7009         return (CTL_RETVAL_COMPLETE);
7010 }
7011
7012 int
7013 ctl_read_defect(struct ctl_scsiio *ctsio)
7014 {
7015         struct scsi_read_defect_data_10 *ccb10;
7016         struct scsi_read_defect_data_12 *ccb12;
7017         struct scsi_read_defect_data_hdr_10 *data10;
7018         struct scsi_read_defect_data_hdr_12 *data12;
7019         uint32_t alloc_len, data_len;
7020         uint8_t format;
7021
7022         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7023
7024         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7025                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7026                 format = ccb10->format;
7027                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7028                 data_len = sizeof(*data10);
7029         } else {
7030                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7031                 format = ccb12->format;
7032                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7033                 data_len = sizeof(*data12);
7034         }
7035         if (alloc_len == 0) {
7036                 ctl_set_success(ctsio);
7037                 ctl_done((union ctl_io *)ctsio);
7038                 return (CTL_RETVAL_COMPLETE);
7039         }
7040
7041         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7042         if (data_len < alloc_len) {
7043                 ctsio->residual = alloc_len - data_len;
7044                 ctsio->kern_data_len = data_len;
7045                 ctsio->kern_total_len = data_len;
7046         } else {
7047                 ctsio->residual = 0;
7048                 ctsio->kern_data_len = alloc_len;
7049                 ctsio->kern_total_len = alloc_len;
7050         }
7051         ctsio->kern_data_resid = 0;
7052         ctsio->kern_rel_offset = 0;
7053         ctsio->kern_sg_entries = 0;
7054
7055         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7056                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7057                     ctsio->kern_data_ptr;
7058                 data10->format = format;
7059                 scsi_ulto2b(0, data10->length);
7060         } else {
7061                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7062                     ctsio->kern_data_ptr;
7063                 data12->format = format;
7064                 scsi_ulto2b(0, data12->generation);
7065                 scsi_ulto4b(0, data12->length);
7066         }
7067
7068         ctl_set_success(ctsio);
7069         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7070         ctsio->be_move_done = ctl_config_move_done;
7071         ctl_datamove((union ctl_io *)ctsio);
7072         return (CTL_RETVAL_COMPLETE);
7073 }
7074
7075 int
7076 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7077 {
7078         struct scsi_maintenance_in *cdb;
7079         int retval;
7080         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7081         int num_ha_groups, num_target_ports, shared_group;
7082         struct ctl_lun *lun;
7083         struct ctl_softc *softc;
7084         struct ctl_port *port;
7085         struct scsi_target_group_data *rtg_ptr;
7086         struct scsi_target_group_data_extended *rtg_ext_ptr;
7087         struct scsi_target_port_group_descriptor *tpg_desc;
7088
7089         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7090
7091         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7092         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7093         softc = lun->ctl_softc;
7094
7095         retval = CTL_RETVAL_COMPLETE;
7096
7097         switch (cdb->byte2 & STG_PDF_MASK) {
7098         case STG_PDF_LENGTH:
7099                 ext = 0;
7100                 break;
7101         case STG_PDF_EXTENDED:
7102                 ext = 1;
7103                 break;
7104         default:
7105                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7106                                       /*sks_valid*/ 1,
7107                                       /*command*/ 1,
7108                                       /*field*/ 2,
7109                                       /*bit_valid*/ 1,
7110                                       /*bit*/ 5);
7111                 ctl_done((union ctl_io *)ctsio);
7112                 return(retval);
7113         }
7114
7115         num_target_ports = 0;
7116         shared_group = (softc->is_single != 0);
7117         mtx_lock(&softc->ctl_lock);
7118         STAILQ_FOREACH(port, &softc->port_list, links) {
7119                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7120                         continue;
7121                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7122                         continue;
7123                 num_target_ports++;
7124                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7125                         shared_group = 1;
7126         }
7127         mtx_unlock(&softc->ctl_lock);
7128         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7129
7130         if (ext)
7131                 total_len = sizeof(struct scsi_target_group_data_extended);
7132         else
7133                 total_len = sizeof(struct scsi_target_group_data);
7134         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7135                 (shared_group + num_ha_groups) +
7136             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7137
7138         alloc_len = scsi_4btoul(cdb->length);
7139
7140         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7141
7142         ctsio->kern_sg_entries = 0;
7143
7144         if (total_len < alloc_len) {
7145                 ctsio->residual = alloc_len - total_len;
7146                 ctsio->kern_data_len = total_len;
7147                 ctsio->kern_total_len = total_len;
7148         } else {
7149                 ctsio->residual = 0;
7150                 ctsio->kern_data_len = alloc_len;
7151                 ctsio->kern_total_len = alloc_len;
7152         }
7153         ctsio->kern_data_resid = 0;
7154         ctsio->kern_rel_offset = 0;
7155
7156         if (ext) {
7157                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7158                     ctsio->kern_data_ptr;
7159                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7160                 rtg_ext_ptr->format_type = 0x10;
7161                 rtg_ext_ptr->implicit_transition_time = 0;
7162                 tpg_desc = &rtg_ext_ptr->groups[0];
7163         } else {
7164                 rtg_ptr = (struct scsi_target_group_data *)
7165                     ctsio->kern_data_ptr;
7166                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7167                 tpg_desc = &rtg_ptr->groups[0];
7168         }
7169
7170         mtx_lock(&softc->ctl_lock);
7171         pg = softc->port_min / softc->port_cnt;
7172         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7173                 /* Some shelf is known to be primary. */
7174                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7175                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7176                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7177                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7178                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7179                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7180                 else
7181                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7182                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7183                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7184                 } else {
7185                         ts = os;
7186                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7187                 }
7188         } else {
7189                 /* No known primary shelf. */
7190                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7191                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7192                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7193                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7194                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7195                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7196                 } else {
7197                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7198                 }
7199         }
7200         if (shared_group) {
7201                 tpg_desc->pref_state = ts;
7202                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7203                     TPG_U_SUP | TPG_T_SUP;
7204                 scsi_ulto2b(1, tpg_desc->target_port_group);
7205                 tpg_desc->status = TPG_IMPLICIT;
7206                 pc = 0;
7207                 STAILQ_FOREACH(port, &softc->port_list, links) {
7208                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7209                                 continue;
7210                         if (!softc->is_single &&
7211                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7212                                 continue;
7213                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7214                                 continue;
7215                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7216                             relative_target_port_identifier);
7217                         pc++;
7218                 }
7219                 tpg_desc->target_port_count = pc;
7220                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7221                     &tpg_desc->descriptors[pc];
7222         }
7223         for (g = 0; g < num_ha_groups; g++) {
7224                 tpg_desc->pref_state = (g == pg) ? ts : os;
7225                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7226                     TPG_U_SUP | TPG_T_SUP;
7227                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7228                 tpg_desc->status = TPG_IMPLICIT;
7229                 pc = 0;
7230                 STAILQ_FOREACH(port, &softc->port_list, links) {
7231                         if (port->targ_port < g * softc->port_cnt ||
7232                             port->targ_port >= (g + 1) * softc->port_cnt)
7233                                 continue;
7234                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7235                                 continue;
7236                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7237                                 continue;
7238                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7239                                 continue;
7240                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7241                             relative_target_port_identifier);
7242                         pc++;
7243                 }
7244                 tpg_desc->target_port_count = pc;
7245                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7246                     &tpg_desc->descriptors[pc];
7247         }
7248         mtx_unlock(&softc->ctl_lock);
7249
7250         ctl_set_success(ctsio);
7251         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7252         ctsio->be_move_done = ctl_config_move_done;
7253         ctl_datamove((union ctl_io *)ctsio);
7254         return(retval);
7255 }
7256
7257 int
7258 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7259 {
7260         struct ctl_lun *lun;
7261         struct scsi_report_supported_opcodes *cdb;
7262         const struct ctl_cmd_entry *entry, *sentry;
7263         struct scsi_report_supported_opcodes_all *all;
7264         struct scsi_report_supported_opcodes_descr *descr;
7265         struct scsi_report_supported_opcodes_one *one;
7266         int retval;
7267         int alloc_len, total_len;
7268         int opcode, service_action, i, j, num;
7269
7270         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7271
7272         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7273         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7274
7275         retval = CTL_RETVAL_COMPLETE;
7276
7277         opcode = cdb->requested_opcode;
7278         service_action = scsi_2btoul(cdb->requested_service_action);
7279         switch (cdb->options & RSO_OPTIONS_MASK) {
7280         case RSO_OPTIONS_ALL:
7281                 num = 0;
7282                 for (i = 0; i < 256; i++) {
7283                         entry = &ctl_cmd_table[i];
7284                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7285                                 for (j = 0; j < 32; j++) {
7286                                         sentry = &((const struct ctl_cmd_entry *)
7287                                             entry->execute)[j];
7288                                         if (ctl_cmd_applicable(
7289                                             lun->be_lun->lun_type, sentry))
7290                                                 num++;
7291                                 }
7292                         } else {
7293                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7294                                     entry))
7295                                         num++;
7296                         }
7297                 }
7298                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7299                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7300                 break;
7301         case RSO_OPTIONS_OC:
7302                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7303                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7304                                               /*sks_valid*/ 1,
7305                                               /*command*/ 1,
7306                                               /*field*/ 2,
7307                                               /*bit_valid*/ 1,
7308                                               /*bit*/ 2);
7309                         ctl_done((union ctl_io *)ctsio);
7310                         return (CTL_RETVAL_COMPLETE);
7311                 }
7312                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7313                 break;
7314         case RSO_OPTIONS_OC_SA:
7315                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7316                     service_action >= 32) {
7317                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7318                                               /*sks_valid*/ 1,
7319                                               /*command*/ 1,
7320                                               /*field*/ 2,
7321                                               /*bit_valid*/ 1,
7322                                               /*bit*/ 2);
7323                         ctl_done((union ctl_io *)ctsio);
7324                         return (CTL_RETVAL_COMPLETE);
7325                 }
7326                 /* FALLTHROUGH */
7327         case RSO_OPTIONS_OC_ASA:
7328                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7329                 break;
7330         default:
7331                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7332                                       /*sks_valid*/ 1,
7333                                       /*command*/ 1,
7334                                       /*field*/ 2,
7335                                       /*bit_valid*/ 1,
7336                                       /*bit*/ 2);
7337                 ctl_done((union ctl_io *)ctsio);
7338                 return (CTL_RETVAL_COMPLETE);
7339         }
7340
7341         alloc_len = scsi_4btoul(cdb->length);
7342
7343         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7344
7345         ctsio->kern_sg_entries = 0;
7346
7347         if (total_len < alloc_len) {
7348                 ctsio->residual = alloc_len - total_len;
7349                 ctsio->kern_data_len = total_len;
7350                 ctsio->kern_total_len = total_len;
7351         } else {
7352                 ctsio->residual = 0;
7353                 ctsio->kern_data_len = alloc_len;
7354                 ctsio->kern_total_len = alloc_len;
7355         }
7356         ctsio->kern_data_resid = 0;
7357         ctsio->kern_rel_offset = 0;
7358
7359         switch (cdb->options & RSO_OPTIONS_MASK) {
7360         case RSO_OPTIONS_ALL:
7361                 all = (struct scsi_report_supported_opcodes_all *)
7362                     ctsio->kern_data_ptr;
7363                 num = 0;
7364                 for (i = 0; i < 256; i++) {
7365                         entry = &ctl_cmd_table[i];
7366                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7367                                 for (j = 0; j < 32; j++) {
7368                                         sentry = &((const struct ctl_cmd_entry *)
7369                                             entry->execute)[j];
7370                                         if (!ctl_cmd_applicable(
7371                                             lun->be_lun->lun_type, sentry))
7372                                                 continue;
7373                                         descr = &all->descr[num++];
7374                                         descr->opcode = i;
7375                                         scsi_ulto2b(j, descr->service_action);
7376                                         descr->flags = RSO_SERVACTV;
7377                                         scsi_ulto2b(sentry->length,
7378                                             descr->cdb_length);
7379                                 }
7380                         } else {
7381                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7382                                     entry))
7383                                         continue;
7384                                 descr = &all->descr[num++];
7385                                 descr->opcode = i;
7386                                 scsi_ulto2b(0, descr->service_action);
7387                                 descr->flags = 0;
7388                                 scsi_ulto2b(entry->length, descr->cdb_length);
7389                         }
7390                 }
7391                 scsi_ulto4b(
7392                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7393                     all->length);
7394                 break;
7395         case RSO_OPTIONS_OC:
7396                 one = (struct scsi_report_supported_opcodes_one *)
7397                     ctsio->kern_data_ptr;
7398                 entry = &ctl_cmd_table[opcode];
7399                 goto fill_one;
7400         case RSO_OPTIONS_OC_SA:
7401                 one = (struct scsi_report_supported_opcodes_one *)
7402                     ctsio->kern_data_ptr;
7403                 entry = &ctl_cmd_table[opcode];
7404                 entry = &((const struct ctl_cmd_entry *)
7405                     entry->execute)[service_action];
7406 fill_one:
7407                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7408                         one->support = 3;
7409                         scsi_ulto2b(entry->length, one->cdb_length);
7410                         one->cdb_usage[0] = opcode;
7411                         memcpy(&one->cdb_usage[1], entry->usage,
7412                             entry->length - 1);
7413                 } else
7414                         one->support = 1;
7415                 break;
7416         case RSO_OPTIONS_OC_ASA:
7417                 one = (struct scsi_report_supported_opcodes_one *)
7418                     ctsio->kern_data_ptr;
7419                 entry = &ctl_cmd_table[opcode];
7420                 if (entry->flags & CTL_CMD_FLAG_SA5) {
7421                         entry = &((const struct ctl_cmd_entry *)
7422                             entry->execute)[service_action];
7423                 } else if (service_action != 0) {
7424                         one->support = 1;
7425                         break;
7426                 }
7427                 goto fill_one;
7428         }
7429
7430         ctl_set_success(ctsio);
7431         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7432         ctsio->be_move_done = ctl_config_move_done;
7433         ctl_datamove((union ctl_io *)ctsio);
7434         return(retval);
7435 }
7436
7437 int
7438 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7439 {
7440         struct scsi_report_supported_tmf *cdb;
7441         struct scsi_report_supported_tmf_ext_data *data;
7442         int retval;
7443         int alloc_len, total_len;
7444
7445         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7446
7447         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7448
7449         retval = CTL_RETVAL_COMPLETE;
7450
7451         if (cdb->options & RST_REPD)
7452                 total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7453         else
7454                 total_len = sizeof(struct scsi_report_supported_tmf_data);
7455         alloc_len = scsi_4btoul(cdb->length);
7456
7457         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7458
7459         ctsio->kern_sg_entries = 0;
7460
7461         if (total_len < alloc_len) {
7462                 ctsio->residual = alloc_len - total_len;
7463                 ctsio->kern_data_len = total_len;
7464                 ctsio->kern_total_len = total_len;
7465         } else {
7466                 ctsio->residual = 0;
7467                 ctsio->kern_data_len = alloc_len;
7468                 ctsio->kern_total_len = alloc_len;
7469         }
7470         ctsio->kern_data_resid = 0;
7471         ctsio->kern_rel_offset = 0;
7472
7473         data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7474         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7475             RST_TRS;
7476         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7477         data->length = total_len - 4;
7478
7479         ctl_set_success(ctsio);
7480         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7481         ctsio->be_move_done = ctl_config_move_done;
7482         ctl_datamove((union ctl_io *)ctsio);
7483         return (retval);
7484 }
7485
7486 int
7487 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7488 {
7489         struct scsi_report_timestamp *cdb;
7490         struct scsi_report_timestamp_data *data;
7491         struct timeval tv;
7492         int64_t timestamp;
7493         int retval;
7494         int alloc_len, total_len;
7495
7496         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7497
7498         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7499
7500         retval = CTL_RETVAL_COMPLETE;
7501
7502         total_len = sizeof(struct scsi_report_timestamp_data);
7503         alloc_len = scsi_4btoul(cdb->length);
7504
7505         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7506
7507         ctsio->kern_sg_entries = 0;
7508
7509         if (total_len < alloc_len) {
7510                 ctsio->residual = alloc_len - total_len;
7511                 ctsio->kern_data_len = total_len;
7512                 ctsio->kern_total_len = total_len;
7513         } else {
7514                 ctsio->residual = 0;
7515                 ctsio->kern_data_len = alloc_len;
7516                 ctsio->kern_total_len = alloc_len;
7517         }
7518         ctsio->kern_data_resid = 0;
7519         ctsio->kern_rel_offset = 0;
7520
7521         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7522         scsi_ulto2b(sizeof(*data) - 2, data->length);
7523         data->origin = RTS_ORIG_OUTSIDE;
7524         getmicrotime(&tv);
7525         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7526         scsi_ulto4b(timestamp >> 16, data->timestamp);
7527         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7528
7529         ctl_set_success(ctsio);
7530         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7531         ctsio->be_move_done = ctl_config_move_done;
7532         ctl_datamove((union ctl_io *)ctsio);
7533         return (retval);
7534 }
7535
7536 int
7537 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7538 {
7539         struct scsi_per_res_in *cdb;
7540         int alloc_len, total_len = 0;
7541         /* struct scsi_per_res_in_rsrv in_data; */
7542         struct ctl_lun *lun;
7543         struct ctl_softc *softc;
7544         uint64_t key;
7545
7546         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7547
7548         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7549
7550         alloc_len = scsi_2btoul(cdb->length);
7551
7552         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7553         softc = lun->ctl_softc;
7554
7555 retry:
7556         mtx_lock(&lun->lun_lock);
7557         switch (cdb->action) {
7558         case SPRI_RK: /* read keys */
7559                 total_len = sizeof(struct scsi_per_res_in_keys) +
7560                         lun->pr_key_count *
7561                         sizeof(struct scsi_per_res_key);
7562                 break;
7563         case SPRI_RR: /* read reservation */
7564                 if (lun->flags & CTL_LUN_PR_RESERVED)
7565                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7566                 else
7567                         total_len = sizeof(struct scsi_per_res_in_header);
7568                 break;
7569         case SPRI_RC: /* report capabilities */
7570                 total_len = sizeof(struct scsi_per_res_cap);
7571                 break;
7572         case SPRI_RS: /* read full status */
7573                 total_len = sizeof(struct scsi_per_res_in_header) +
7574                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7575                     lun->pr_key_count;
7576                 break;
7577         default:
7578                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7579         }
7580         mtx_unlock(&lun->lun_lock);
7581
7582         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7583
7584         if (total_len < alloc_len) {
7585                 ctsio->residual = alloc_len - total_len;
7586                 ctsio->kern_data_len = total_len;
7587                 ctsio->kern_total_len = total_len;
7588         } else {
7589                 ctsio->residual = 0;
7590                 ctsio->kern_data_len = alloc_len;
7591                 ctsio->kern_total_len = alloc_len;
7592         }
7593
7594         ctsio->kern_data_resid = 0;
7595         ctsio->kern_rel_offset = 0;
7596         ctsio->kern_sg_entries = 0;
7597
7598         mtx_lock(&lun->lun_lock);
7599         switch (cdb->action) {
7600         case SPRI_RK: { // read keys
7601         struct scsi_per_res_in_keys *res_keys;
7602                 int i, key_count;
7603
7604                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7605
7606                 /*
7607                  * We had to drop the lock to allocate our buffer, which
7608                  * leaves time for someone to come in with another
7609                  * persistent reservation.  (That is unlikely, though,
7610                  * since this should be the only persistent reservation
7611                  * command active right now.)
7612                  */
7613                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7614                     (lun->pr_key_count *
7615                      sizeof(struct scsi_per_res_key)))){
7616                         mtx_unlock(&lun->lun_lock);
7617                         free(ctsio->kern_data_ptr, M_CTL);
7618                         printf("%s: reservation length changed, retrying\n",
7619                                __func__);
7620                         goto retry;
7621                 }
7622
7623                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7624
7625                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7626                              lun->pr_key_count, res_keys->header.length);
7627
7628                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7629                         if ((key = ctl_get_prkey(lun, i)) == 0)
7630                                 continue;
7631
7632                         /*
7633                          * We used lun->pr_key_count to calculate the
7634                          * size to allocate.  If it turns out the number of
7635                          * initiators with the registered flag set is
7636                          * larger than that (i.e. they haven't been kept in
7637                          * sync), we've got a problem.
7638                          */
7639                         if (key_count >= lun->pr_key_count) {
7640                                 key_count++;
7641                                 continue;
7642                         }
7643                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7644                         key_count++;
7645                 }
7646                 break;
7647         }
7648         case SPRI_RR: { // read reservation
7649                 struct scsi_per_res_in_rsrv *res;
7650                 int tmp_len, header_only;
7651
7652                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7653
7654                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7655
7656                 if (lun->flags & CTL_LUN_PR_RESERVED)
7657                 {
7658                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7659                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7660                                     res->header.length);
7661                         header_only = 0;
7662                 } else {
7663                         tmp_len = sizeof(struct scsi_per_res_in_header);
7664                         scsi_ulto4b(0, res->header.length);
7665                         header_only = 1;
7666                 }
7667
7668                 /*
7669                  * We had to drop the lock to allocate our buffer, which
7670                  * leaves time for someone to come in with another
7671                  * persistent reservation.  (That is unlikely, though,
7672                  * since this should be the only persistent reservation
7673                  * command active right now.)
7674                  */
7675                 if (tmp_len != total_len) {
7676                         mtx_unlock(&lun->lun_lock);
7677                         free(ctsio->kern_data_ptr, M_CTL);
7678                         printf("%s: reservation status changed, retrying\n",
7679                                __func__);
7680                         goto retry;
7681                 }
7682
7683                 /*
7684                  * No reservation held, so we're done.
7685                  */
7686                 if (header_only != 0)
7687                         break;
7688
7689                 /*
7690                  * If the registration is an All Registrants type, the key
7691                  * is 0, since it doesn't really matter.
7692                  */
7693                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7694                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7695                             res->data.reservation);
7696                 }
7697                 res->data.scopetype = lun->pr_res_type;
7698                 break;
7699         }
7700         case SPRI_RC:     //report capabilities
7701         {
7702                 struct scsi_per_res_cap *res_cap;
7703                 uint16_t type_mask;
7704
7705                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7706                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7707                 res_cap->flags1 = SPRI_CRH;
7708                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7709                 type_mask = SPRI_TM_WR_EX_AR |
7710                             SPRI_TM_EX_AC_RO |
7711                             SPRI_TM_WR_EX_RO |
7712                             SPRI_TM_EX_AC |
7713                             SPRI_TM_WR_EX |
7714                             SPRI_TM_EX_AC_AR;
7715                 scsi_ulto2b(type_mask, res_cap->type_mask);
7716                 break;
7717         }
7718         case SPRI_RS: { // read full status
7719                 struct scsi_per_res_in_full *res_status;
7720                 struct scsi_per_res_in_full_desc *res_desc;
7721                 struct ctl_port *port;
7722                 int i, len;
7723
7724                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7725
7726                 /*
7727                  * We had to drop the lock to allocate our buffer, which
7728                  * leaves time for someone to come in with another
7729                  * persistent reservation.  (That is unlikely, though,
7730                  * since this should be the only persistent reservation
7731                  * command active right now.)
7732                  */
7733                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7734                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7735                      lun->pr_key_count)){
7736                         mtx_unlock(&lun->lun_lock);
7737                         free(ctsio->kern_data_ptr, M_CTL);
7738                         printf("%s: reservation length changed, retrying\n",
7739                                __func__);
7740                         goto retry;
7741                 }
7742
7743                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7744
7745                 res_desc = &res_status->desc[0];
7746                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7747                         if ((key = ctl_get_prkey(lun, i)) == 0)
7748                                 continue;
7749
7750                         scsi_u64to8b(key, res_desc->res_key.key);
7751                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7752                             (lun->pr_res_idx == i ||
7753                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7754                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7755                                 res_desc->scopetype = lun->pr_res_type;
7756                         }
7757                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7758                             res_desc->rel_trgt_port_id);
7759                         len = 0;
7760                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7761                         if (port != NULL)
7762                                 len = ctl_create_iid(port,
7763                                     i % CTL_MAX_INIT_PER_PORT,
7764                                     res_desc->transport_id);
7765                         scsi_ulto4b(len, res_desc->additional_length);
7766                         res_desc = (struct scsi_per_res_in_full_desc *)
7767                             &res_desc->transport_id[len];
7768                 }
7769                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7770                     res_status->header.length);
7771                 break;
7772         }
7773         default:
7774                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7775         }
7776         mtx_unlock(&lun->lun_lock);
7777
7778         ctl_set_success(ctsio);
7779         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7780         ctsio->be_move_done = ctl_config_move_done;
7781         ctl_datamove((union ctl_io *)ctsio);
7782         return (CTL_RETVAL_COMPLETE);
7783 }
7784
7785 /*
7786  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7787  * it should return.
7788  */
7789 static int
7790 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7791                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7792                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7793                 struct scsi_per_res_out_parms* param)
7794 {
7795         union ctl_ha_msg persis_io;
7796         int i;
7797
7798         mtx_lock(&lun->lun_lock);
7799         if (sa_res_key == 0) {
7800                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7801                         /* validate scope and type */
7802                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7803                              SPR_LU_SCOPE) {
7804                                 mtx_unlock(&lun->lun_lock);
7805                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7806                                                       /*sks_valid*/ 1,
7807                                                       /*command*/ 1,
7808                                                       /*field*/ 2,
7809                                                       /*bit_valid*/ 1,
7810                                                       /*bit*/ 4);
7811                                 ctl_done((union ctl_io *)ctsio);
7812                                 return (1);
7813                         }
7814
7815                         if (type>8 || type==2 || type==4 || type==0) {
7816                                 mtx_unlock(&lun->lun_lock);
7817                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7818                                                       /*sks_valid*/ 1,
7819                                                       /*command*/ 1,
7820                                                       /*field*/ 2,
7821                                                       /*bit_valid*/ 1,
7822                                                       /*bit*/ 0);
7823                                 ctl_done((union ctl_io *)ctsio);
7824                                 return (1);
7825                         }
7826
7827                         /*
7828                          * Unregister everybody else and build UA for
7829                          * them
7830                          */
7831                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7832                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7833                                         continue;
7834
7835                                 ctl_clr_prkey(lun, i);
7836                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7837                         }
7838                         lun->pr_key_count = 1;
7839                         lun->pr_res_type = type;
7840                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7841                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7842                                 lun->pr_res_idx = residx;
7843                         lun->pr_generation++;
7844                         mtx_unlock(&lun->lun_lock);
7845
7846                         /* send msg to other side */
7847                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7848                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7849                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7850                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7851                         persis_io.pr.pr_info.res_type = type;
7852                         memcpy(persis_io.pr.pr_info.sa_res_key,
7853                                param->serv_act_res_key,
7854                                sizeof(param->serv_act_res_key));
7855                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7856                             sizeof(persis_io.pr), M_WAITOK);
7857                 } else {
7858                         /* not all registrants */
7859                         mtx_unlock(&lun->lun_lock);
7860                         free(ctsio->kern_data_ptr, M_CTL);
7861                         ctl_set_invalid_field(ctsio,
7862                                               /*sks_valid*/ 1,
7863                                               /*command*/ 0,
7864                                               /*field*/ 8,
7865                                               /*bit_valid*/ 0,
7866                                               /*bit*/ 0);
7867                         ctl_done((union ctl_io *)ctsio);
7868                         return (1);
7869                 }
7870         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7871                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7872                 int found = 0;
7873
7874                 if (res_key == sa_res_key) {
7875                         /* special case */
7876                         /*
7877                          * The spec implies this is not good but doesn't
7878                          * say what to do. There are two choices either
7879                          * generate a res conflict or check condition
7880                          * with illegal field in parameter data. Since
7881                          * that is what is done when the sa_res_key is
7882                          * zero I'll take that approach since this has
7883                          * to do with the sa_res_key.
7884                          */
7885                         mtx_unlock(&lun->lun_lock);
7886                         free(ctsio->kern_data_ptr, M_CTL);
7887                         ctl_set_invalid_field(ctsio,
7888                                               /*sks_valid*/ 1,
7889                                               /*command*/ 0,
7890                                               /*field*/ 8,
7891                                               /*bit_valid*/ 0,
7892                                               /*bit*/ 0);
7893                         ctl_done((union ctl_io *)ctsio);
7894                         return (1);
7895                 }
7896
7897                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7898                         if (ctl_get_prkey(lun, i) != sa_res_key)
7899                                 continue;
7900
7901                         found = 1;
7902                         ctl_clr_prkey(lun, i);
7903                         lun->pr_key_count--;
7904                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7905                 }
7906                 if (!found) {
7907                         mtx_unlock(&lun->lun_lock);
7908                         free(ctsio->kern_data_ptr, M_CTL);
7909                         ctl_set_reservation_conflict(ctsio);
7910                         ctl_done((union ctl_io *)ctsio);
7911                         return (CTL_RETVAL_COMPLETE);
7912                 }
7913                 lun->pr_generation++;
7914                 mtx_unlock(&lun->lun_lock);
7915
7916                 /* send msg to other side */
7917                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7918                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7919                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7920                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7921                 persis_io.pr.pr_info.res_type = type;
7922                 memcpy(persis_io.pr.pr_info.sa_res_key,
7923                        param->serv_act_res_key,
7924                        sizeof(param->serv_act_res_key));
7925                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7926                     sizeof(persis_io.pr), M_WAITOK);
7927         } else {
7928                 /* Reserved but not all registrants */
7929                 /* sa_res_key is res holder */
7930                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7931                         /* validate scope and type */
7932                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7933                              SPR_LU_SCOPE) {
7934                                 mtx_unlock(&lun->lun_lock);
7935                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7936                                                       /*sks_valid*/ 1,
7937                                                       /*command*/ 1,
7938                                                       /*field*/ 2,
7939                                                       /*bit_valid*/ 1,
7940                                                       /*bit*/ 4);
7941                                 ctl_done((union ctl_io *)ctsio);
7942                                 return (1);
7943                         }
7944
7945                         if (type>8 || type==2 || type==4 || type==0) {
7946                                 mtx_unlock(&lun->lun_lock);
7947                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7948                                                       /*sks_valid*/ 1,
7949                                                       /*command*/ 1,
7950                                                       /*field*/ 2,
7951                                                       /*bit_valid*/ 1,
7952                                                       /*bit*/ 0);
7953                                 ctl_done((union ctl_io *)ctsio);
7954                                 return (1);
7955                         }
7956
7957                         /*
7958                          * Do the following:
7959                          * if sa_res_key != res_key remove all
7960                          * registrants w/sa_res_key and generate UA
7961                          * for these registrants(Registrations
7962                          * Preempted) if it wasn't an exclusive
7963                          * reservation generate UA(Reservations
7964                          * Preempted) for all other registered nexuses
7965                          * if the type has changed. Establish the new
7966                          * reservation and holder. If res_key and
7967                          * sa_res_key are the same do the above
7968                          * except don't unregister the res holder.
7969                          */
7970
7971                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7972                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7973                                         continue;
7974
7975                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7976                                         ctl_clr_prkey(lun, i);
7977                                         lun->pr_key_count--;
7978                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7979                                 } else if (type != lun->pr_res_type &&
7980                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7981                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7982                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7983                                 }
7984                         }
7985                         lun->pr_res_type = type;
7986                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7987                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7988                                 lun->pr_res_idx = residx;
7989                         else
7990                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7991                         lun->pr_generation++;
7992                         mtx_unlock(&lun->lun_lock);
7993
7994                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7995                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7996                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7997                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7998                         persis_io.pr.pr_info.res_type = type;
7999                         memcpy(persis_io.pr.pr_info.sa_res_key,
8000                                param->serv_act_res_key,
8001                                sizeof(param->serv_act_res_key));
8002                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8003                             sizeof(persis_io.pr), M_WAITOK);
8004                 } else {
8005                         /*
8006                          * sa_res_key is not the res holder just
8007                          * remove registrants
8008                          */
8009                         int found=0;
8010
8011                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8012                                 if (sa_res_key != ctl_get_prkey(lun, i))
8013                                         continue;
8014
8015                                 found = 1;
8016                                 ctl_clr_prkey(lun, i);
8017                                 lun->pr_key_count--;
8018                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8019                         }
8020
8021                         if (!found) {
8022                                 mtx_unlock(&lun->lun_lock);
8023                                 free(ctsio->kern_data_ptr, M_CTL);
8024                                 ctl_set_reservation_conflict(ctsio);
8025                                 ctl_done((union ctl_io *)ctsio);
8026                                 return (1);
8027                         }
8028                         lun->pr_generation++;
8029                         mtx_unlock(&lun->lun_lock);
8030
8031                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8032                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8033                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8034                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8035                         persis_io.pr.pr_info.res_type = type;
8036                         memcpy(persis_io.pr.pr_info.sa_res_key,
8037                                param->serv_act_res_key,
8038                                sizeof(param->serv_act_res_key));
8039                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8040                             sizeof(persis_io.pr), M_WAITOK);
8041                 }
8042         }
8043         return (0);
8044 }
8045
8046 static void
8047 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8048 {
8049         uint64_t sa_res_key;
8050         int i;
8051
8052         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8053
8054         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8055          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8056          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8057                 if (sa_res_key == 0) {
8058                         /*
8059                          * Unregister everybody else and build UA for
8060                          * them
8061                          */
8062                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8063                                 if (i == msg->pr.pr_info.residx ||
8064                                     ctl_get_prkey(lun, i) == 0)
8065                                         continue;
8066
8067                                 ctl_clr_prkey(lun, i);
8068                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8069                         }
8070
8071                         lun->pr_key_count = 1;
8072                         lun->pr_res_type = msg->pr.pr_info.res_type;
8073                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8074                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8075                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8076                 } else {
8077                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8078                                 if (sa_res_key == ctl_get_prkey(lun, i))
8079                                         continue;
8080
8081                                 ctl_clr_prkey(lun, i);
8082                                 lun->pr_key_count--;
8083                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8084                         }
8085                 }
8086         } else {
8087                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8088                         if (i == msg->pr.pr_info.residx ||
8089                             ctl_get_prkey(lun, i) == 0)
8090                                 continue;
8091
8092                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8093                                 ctl_clr_prkey(lun, i);
8094                                 lun->pr_key_count--;
8095                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8096                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8097                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8098                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8099                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8100                         }
8101                 }
8102                 lun->pr_res_type = msg->pr.pr_info.res_type;
8103                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8104                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8105                         lun->pr_res_idx = msg->pr.pr_info.residx;
8106                 else
8107                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8108         }
8109         lun->pr_generation++;
8110
8111 }
8112
8113
8114 int
8115 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8116 {
8117         int retval;
8118         u_int32_t param_len;
8119         struct scsi_per_res_out *cdb;
8120         struct ctl_lun *lun;
8121         struct scsi_per_res_out_parms* param;
8122         struct ctl_softc *softc;
8123         uint32_t residx;
8124         uint64_t res_key, sa_res_key, key;
8125         uint8_t type;
8126         union ctl_ha_msg persis_io;
8127         int    i;
8128
8129         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8130
8131         retval = CTL_RETVAL_COMPLETE;
8132
8133         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8134         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8135         softc = lun->ctl_softc;
8136
8137         /*
8138          * We only support whole-LUN scope.  The scope & type are ignored for
8139          * register, register and ignore existing key and clear.
8140          * We sometimes ignore scope and type on preempts too!!
8141          * Verify reservation type here as well.
8142          */
8143         type = cdb->scope_type & SPR_TYPE_MASK;
8144         if ((cdb->action == SPRO_RESERVE)
8145          || (cdb->action == SPRO_RELEASE)) {
8146                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8147                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8148                                               /*sks_valid*/ 1,
8149                                               /*command*/ 1,
8150                                               /*field*/ 2,
8151                                               /*bit_valid*/ 1,
8152                                               /*bit*/ 4);
8153                         ctl_done((union ctl_io *)ctsio);
8154                         return (CTL_RETVAL_COMPLETE);
8155                 }
8156
8157                 if (type>8 || type==2 || type==4 || type==0) {
8158                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8159                                               /*sks_valid*/ 1,
8160                                               /*command*/ 1,
8161                                               /*field*/ 2,
8162                                               /*bit_valid*/ 1,
8163                                               /*bit*/ 0);
8164                         ctl_done((union ctl_io *)ctsio);
8165                         return (CTL_RETVAL_COMPLETE);
8166                 }
8167         }
8168
8169         param_len = scsi_4btoul(cdb->length);
8170
8171         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8172                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8173                 ctsio->kern_data_len = param_len;
8174                 ctsio->kern_total_len = param_len;
8175                 ctsio->kern_data_resid = 0;
8176                 ctsio->kern_rel_offset = 0;
8177                 ctsio->kern_sg_entries = 0;
8178                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8179                 ctsio->be_move_done = ctl_config_move_done;
8180                 ctl_datamove((union ctl_io *)ctsio);
8181
8182                 return (CTL_RETVAL_COMPLETE);
8183         }
8184
8185         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8186
8187         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8188         res_key = scsi_8btou64(param->res_key.key);
8189         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8190
8191         /*
8192          * Validate the reservation key here except for SPRO_REG_IGNO
8193          * This must be done for all other service actions
8194          */
8195         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8196                 mtx_lock(&lun->lun_lock);
8197                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8198                         if (res_key != key) {
8199                                 /*
8200                                  * The current key passed in doesn't match
8201                                  * the one the initiator previously
8202                                  * registered.
8203                                  */
8204                                 mtx_unlock(&lun->lun_lock);
8205                                 free(ctsio->kern_data_ptr, M_CTL);
8206                                 ctl_set_reservation_conflict(ctsio);
8207                                 ctl_done((union ctl_io *)ctsio);
8208                                 return (CTL_RETVAL_COMPLETE);
8209                         }
8210                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8211                         /*
8212                          * We are not registered
8213                          */
8214                         mtx_unlock(&lun->lun_lock);
8215                         free(ctsio->kern_data_ptr, M_CTL);
8216                         ctl_set_reservation_conflict(ctsio);
8217                         ctl_done((union ctl_io *)ctsio);
8218                         return (CTL_RETVAL_COMPLETE);
8219                 } else if (res_key != 0) {
8220                         /*
8221                          * We are not registered and trying to register but
8222                          * the register key isn't zero.
8223                          */
8224                         mtx_unlock(&lun->lun_lock);
8225                         free(ctsio->kern_data_ptr, M_CTL);
8226                         ctl_set_reservation_conflict(ctsio);
8227                         ctl_done((union ctl_io *)ctsio);
8228                         return (CTL_RETVAL_COMPLETE);
8229                 }
8230                 mtx_unlock(&lun->lun_lock);
8231         }
8232
8233         switch (cdb->action & SPRO_ACTION_MASK) {
8234         case SPRO_REGISTER:
8235         case SPRO_REG_IGNO: {
8236
8237 #if 0
8238                 printf("Registration received\n");
8239 #endif
8240
8241                 /*
8242                  * We don't support any of these options, as we report in
8243                  * the read capabilities request (see
8244                  * ctl_persistent_reserve_in(), above).
8245                  */
8246                 if ((param->flags & SPR_SPEC_I_PT)
8247                  || (param->flags & SPR_ALL_TG_PT)
8248                  || (param->flags & SPR_APTPL)) {
8249                         int bit_ptr;
8250
8251                         if (param->flags & SPR_APTPL)
8252                                 bit_ptr = 0;
8253                         else if (param->flags & SPR_ALL_TG_PT)
8254                                 bit_ptr = 2;
8255                         else /* SPR_SPEC_I_PT */
8256                                 bit_ptr = 3;
8257
8258                         free(ctsio->kern_data_ptr, M_CTL);
8259                         ctl_set_invalid_field(ctsio,
8260                                               /*sks_valid*/ 1,
8261                                               /*command*/ 0,
8262                                               /*field*/ 20,
8263                                               /*bit_valid*/ 1,
8264                                               /*bit*/ bit_ptr);
8265                         ctl_done((union ctl_io *)ctsio);
8266                         return (CTL_RETVAL_COMPLETE);
8267                 }
8268
8269                 mtx_lock(&lun->lun_lock);
8270
8271                 /*
8272                  * The initiator wants to clear the
8273                  * key/unregister.
8274                  */
8275                 if (sa_res_key == 0) {
8276                         if ((res_key == 0
8277                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8278                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8279                           && ctl_get_prkey(lun, residx) == 0)) {
8280                                 mtx_unlock(&lun->lun_lock);
8281                                 goto done;
8282                         }
8283
8284                         ctl_clr_prkey(lun, residx);
8285                         lun->pr_key_count--;
8286
8287                         if (residx == lun->pr_res_idx) {
8288                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8289                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8290
8291                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8292                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8293                                     lun->pr_key_count) {
8294                                         /*
8295                                          * If the reservation is a registrants
8296                                          * only type we need to generate a UA
8297                                          * for other registered inits.  The
8298                                          * sense code should be RESERVATIONS
8299                                          * RELEASED
8300                                          */
8301
8302                                         for (i = softc->init_min; i < softc->init_max; i++){
8303                                                 if (ctl_get_prkey(lun, i) == 0)
8304                                                         continue;
8305                                                 ctl_est_ua(lun, i,
8306                                                     CTL_UA_RES_RELEASE);
8307                                         }
8308                                 }
8309                                 lun->pr_res_type = 0;
8310                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8311                                 if (lun->pr_key_count==0) {
8312                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8313                                         lun->pr_res_type = 0;
8314                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8315                                 }
8316                         }
8317                         lun->pr_generation++;
8318                         mtx_unlock(&lun->lun_lock);
8319
8320                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8321                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8322                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8323                         persis_io.pr.pr_info.residx = residx;
8324                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8325                             sizeof(persis_io.pr), M_WAITOK);
8326                 } else /* sa_res_key != 0 */ {
8327
8328                         /*
8329                          * If we aren't registered currently then increment
8330                          * the key count and set the registered flag.
8331                          */
8332                         ctl_alloc_prkey(lun, residx);
8333                         if (ctl_get_prkey(lun, residx) == 0)
8334                                 lun->pr_key_count++;
8335                         ctl_set_prkey(lun, residx, sa_res_key);
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_REG_KEY;
8342                         persis_io.pr.pr_info.residx = residx;
8343                         memcpy(persis_io.pr.pr_info.sa_res_key,
8344                                param->serv_act_res_key,
8345                                sizeof(param->serv_act_res_key));
8346                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8347                             sizeof(persis_io.pr), M_WAITOK);
8348                 }
8349
8350                 break;
8351         }
8352         case SPRO_RESERVE:
8353 #if 0
8354                 printf("Reserve executed type %d\n", type);
8355 #endif
8356                 mtx_lock(&lun->lun_lock);
8357                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8358                         /*
8359                          * if this isn't the reservation holder and it's
8360                          * not a "all registrants" type or if the type is
8361                          * different then we have a conflict
8362                          */
8363                         if ((lun->pr_res_idx != residx
8364                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8365                          || lun->pr_res_type != type) {
8366                                 mtx_unlock(&lun->lun_lock);
8367                                 free(ctsio->kern_data_ptr, M_CTL);
8368                                 ctl_set_reservation_conflict(ctsio);
8369                                 ctl_done((union ctl_io *)ctsio);
8370                                 return (CTL_RETVAL_COMPLETE);
8371                         }
8372                         mtx_unlock(&lun->lun_lock);
8373                 } else /* create a reservation */ {
8374                         /*
8375                          * If it's not an "all registrants" type record
8376                          * reservation holder
8377                          */
8378                         if (type != SPR_TYPE_WR_EX_AR
8379                          && type != SPR_TYPE_EX_AC_AR)
8380                                 lun->pr_res_idx = residx; /* Res holder */
8381                         else
8382                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8383
8384                         lun->flags |= CTL_LUN_PR_RESERVED;
8385                         lun->pr_res_type = type;
8386
8387                         mtx_unlock(&lun->lun_lock);
8388
8389                         /* send msg to other side */
8390                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8391                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8392                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8393                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8394                         persis_io.pr.pr_info.res_type = type;
8395                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8396                             sizeof(persis_io.pr), M_WAITOK);
8397                 }
8398                 break;
8399
8400         case SPRO_RELEASE:
8401                 mtx_lock(&lun->lun_lock);
8402                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8403                         /* No reservation exists return good status */
8404                         mtx_unlock(&lun->lun_lock);
8405                         goto done;
8406                 }
8407                 /*
8408                  * Is this nexus a reservation holder?
8409                  */
8410                 if (lun->pr_res_idx != residx
8411                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8412                         /*
8413                          * not a res holder return good status but
8414                          * do nothing
8415                          */
8416                         mtx_unlock(&lun->lun_lock);
8417                         goto done;
8418                 }
8419
8420                 if (lun->pr_res_type != type) {
8421                         mtx_unlock(&lun->lun_lock);
8422                         free(ctsio->kern_data_ptr, M_CTL);
8423                         ctl_set_illegal_pr_release(ctsio);
8424                         ctl_done((union ctl_io *)ctsio);
8425                         return (CTL_RETVAL_COMPLETE);
8426                 }
8427
8428                 /* okay to release */
8429                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8430                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8431                 lun->pr_res_type = 0;
8432
8433                 /*
8434                  * If this isn't an exclusive access reservation and NUAR
8435                  * is not set, generate UA for all other registrants.
8436                  */
8437                 if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8438                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8439                         for (i = softc->init_min; i < softc->init_max; i++) {
8440                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8441                                         continue;
8442                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8443                         }
8444                 }
8445                 mtx_unlock(&lun->lun_lock);
8446
8447                 /* Send msg to other side */
8448                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8449                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8450                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8451                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8452                      sizeof(persis_io.pr), M_WAITOK);
8453                 break;
8454
8455         case SPRO_CLEAR:
8456                 /* send msg to other side */
8457
8458                 mtx_lock(&lun->lun_lock);
8459                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8460                 lun->pr_res_type = 0;
8461                 lun->pr_key_count = 0;
8462                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8463
8464                 ctl_clr_prkey(lun, residx);
8465                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8466                         if (ctl_get_prkey(lun, i) != 0) {
8467                                 ctl_clr_prkey(lun, i);
8468                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8469                         }
8470                 lun->pr_generation++;
8471                 mtx_unlock(&lun->lun_lock);
8472
8473                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8474                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8475                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8476                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8477                      sizeof(persis_io.pr), M_WAITOK);
8478                 break;
8479
8480         case SPRO_PREEMPT:
8481         case SPRO_PRE_ABO: {
8482                 int nretval;
8483
8484                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8485                                           residx, ctsio, cdb, param);
8486                 if (nretval != 0)
8487                         return (CTL_RETVAL_COMPLETE);
8488                 break;
8489         }
8490         default:
8491                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8492         }
8493
8494 done:
8495         free(ctsio->kern_data_ptr, M_CTL);
8496         ctl_set_success(ctsio);
8497         ctl_done((union ctl_io *)ctsio);
8498
8499         return (retval);
8500 }
8501
8502 /*
8503  * This routine is for handling a message from the other SC pertaining to
8504  * persistent reserve out. All the error checking will have been done
8505  * so only perorming the action need be done here to keep the two
8506  * in sync.
8507  */
8508 static void
8509 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8510 {
8511         struct ctl_softc *softc = control_softc;
8512         struct ctl_lun *lun;
8513         int i;
8514         uint32_t residx, targ_lun;
8515
8516         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8517         mtx_lock(&softc->ctl_lock);
8518         if (targ_lun >= CTL_MAX_LUNS ||
8519             (lun = softc->ctl_luns[targ_lun]) == NULL) {
8520                 mtx_unlock(&softc->ctl_lock);
8521                 return;
8522         }
8523         mtx_lock(&lun->lun_lock);
8524         mtx_unlock(&softc->ctl_lock);
8525         if (lun->flags & CTL_LUN_DISABLED) {
8526                 mtx_unlock(&lun->lun_lock);
8527                 return;
8528         }
8529         residx = ctl_get_initindex(&msg->hdr.nexus);
8530         switch(msg->pr.pr_info.action) {
8531         case CTL_PR_REG_KEY:
8532                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8533                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8534                         lun->pr_key_count++;
8535                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8536                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8537                 lun->pr_generation++;
8538                 break;
8539
8540         case CTL_PR_UNREG_KEY:
8541                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8542                 lun->pr_key_count--;
8543
8544                 /* XXX Need to see if the reservation has been released */
8545                 /* if so do we need to generate UA? */
8546                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8547                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8548                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8549
8550                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8551                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8552                             lun->pr_key_count) {
8553                                 /*
8554                                  * If the reservation is a registrants
8555                                  * only type we need to generate a UA
8556                                  * for other registered inits.  The
8557                                  * sense code should be RESERVATIONS
8558                                  * RELEASED
8559                                  */
8560
8561                                 for (i = softc->init_min; i < softc->init_max; i++) {
8562                                         if (ctl_get_prkey(lun, i) == 0)
8563                                                 continue;
8564
8565                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8566                                 }
8567                         }
8568                         lun->pr_res_type = 0;
8569                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8570                         if (lun->pr_key_count==0) {
8571                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8572                                 lun->pr_res_type = 0;
8573                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8574                         }
8575                 }
8576                 lun->pr_generation++;
8577                 break;
8578
8579         case CTL_PR_RESERVE:
8580                 lun->flags |= CTL_LUN_PR_RESERVED;
8581                 lun->pr_res_type = msg->pr.pr_info.res_type;
8582                 lun->pr_res_idx = msg->pr.pr_info.residx;
8583
8584                 break;
8585
8586         case CTL_PR_RELEASE:
8587                 /*
8588                  * If this isn't an exclusive access reservation and NUAR
8589                  * is not set, generate UA for all other registrants.
8590                  */
8591                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8592                     lun->pr_res_type != SPR_TYPE_WR_EX &&
8593                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8594                         for (i = softc->init_min; i < softc->init_max; i++)
8595                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8596                                         continue;
8597                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8598                 }
8599
8600                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8601                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8602                 lun->pr_res_type = 0;
8603                 break;
8604
8605         case CTL_PR_PREEMPT:
8606                 ctl_pro_preempt_other(lun, msg);
8607                 break;
8608         case CTL_PR_CLEAR:
8609                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8610                 lun->pr_res_type = 0;
8611                 lun->pr_key_count = 0;
8612                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8613
8614                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8615                         if (ctl_get_prkey(lun, i) == 0)
8616                                 continue;
8617                         ctl_clr_prkey(lun, i);
8618                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8619                 }
8620                 lun->pr_generation++;
8621                 break;
8622         }
8623
8624         mtx_unlock(&lun->lun_lock);
8625 }
8626
8627 int
8628 ctl_read_write(struct ctl_scsiio *ctsio)
8629 {
8630         struct ctl_lun *lun;
8631         struct ctl_lba_len_flags *lbalen;
8632         uint64_t lba;
8633         uint32_t num_blocks;
8634         int flags, retval;
8635         int isread;
8636
8637         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8638
8639         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8640
8641         flags = 0;
8642         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8643               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8644         switch (ctsio->cdb[0]) {
8645         case READ_6:
8646         case WRITE_6: {
8647                 struct scsi_rw_6 *cdb;
8648
8649                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8650
8651                 lba = scsi_3btoul(cdb->addr);
8652                 /* only 5 bits are valid in the most significant address byte */
8653                 lba &= 0x1fffff;
8654                 num_blocks = cdb->length;
8655                 /*
8656                  * This is correct according to SBC-2.
8657                  */
8658                 if (num_blocks == 0)
8659                         num_blocks = 256;
8660                 break;
8661         }
8662         case READ_10:
8663         case WRITE_10: {
8664                 struct scsi_rw_10 *cdb;
8665
8666                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8667                 if (cdb->byte2 & SRW10_FUA)
8668                         flags |= CTL_LLF_FUA;
8669                 if (cdb->byte2 & SRW10_DPO)
8670                         flags |= CTL_LLF_DPO;
8671                 lba = scsi_4btoul(cdb->addr);
8672                 num_blocks = scsi_2btoul(cdb->length);
8673                 break;
8674         }
8675         case WRITE_VERIFY_10: {
8676                 struct scsi_write_verify_10 *cdb;
8677
8678                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8679                 flags |= CTL_LLF_FUA;
8680                 if (cdb->byte2 & SWV_DPO)
8681                         flags |= CTL_LLF_DPO;
8682                 lba = scsi_4btoul(cdb->addr);
8683                 num_blocks = scsi_2btoul(cdb->length);
8684                 break;
8685         }
8686         case READ_12:
8687         case WRITE_12: {
8688                 struct scsi_rw_12 *cdb;
8689
8690                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8691                 if (cdb->byte2 & SRW12_FUA)
8692                         flags |= CTL_LLF_FUA;
8693                 if (cdb->byte2 & SRW12_DPO)
8694                         flags |= CTL_LLF_DPO;
8695                 lba = scsi_4btoul(cdb->addr);
8696                 num_blocks = scsi_4btoul(cdb->length);
8697                 break;
8698         }
8699         case WRITE_VERIFY_12: {
8700                 struct scsi_write_verify_12 *cdb;
8701
8702                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8703                 flags |= CTL_LLF_FUA;
8704                 if (cdb->byte2 & SWV_DPO)
8705                         flags |= CTL_LLF_DPO;
8706                 lba = scsi_4btoul(cdb->addr);
8707                 num_blocks = scsi_4btoul(cdb->length);
8708                 break;
8709         }
8710         case READ_16:
8711         case WRITE_16: {
8712                 struct scsi_rw_16 *cdb;
8713
8714                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8715                 if (cdb->byte2 & SRW12_FUA)
8716                         flags |= CTL_LLF_FUA;
8717                 if (cdb->byte2 & SRW12_DPO)
8718                         flags |= CTL_LLF_DPO;
8719                 lba = scsi_8btou64(cdb->addr);
8720                 num_blocks = scsi_4btoul(cdb->length);
8721                 break;
8722         }
8723         case WRITE_ATOMIC_16: {
8724                 struct scsi_write_atomic_16 *cdb;
8725
8726                 if (lun->be_lun->atomicblock == 0) {
8727                         ctl_set_invalid_opcode(ctsio);
8728                         ctl_done((union ctl_io *)ctsio);
8729                         return (CTL_RETVAL_COMPLETE);
8730                 }
8731
8732                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8733                 if (cdb->byte2 & SRW12_FUA)
8734                         flags |= CTL_LLF_FUA;
8735                 if (cdb->byte2 & SRW12_DPO)
8736                         flags |= CTL_LLF_DPO;
8737                 lba = scsi_8btou64(cdb->addr);
8738                 num_blocks = scsi_2btoul(cdb->length);
8739                 if (num_blocks > lun->be_lun->atomicblock) {
8740                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8741                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8742                             /*bit*/ 0);
8743                         ctl_done((union ctl_io *)ctsio);
8744                         return (CTL_RETVAL_COMPLETE);
8745                 }
8746                 break;
8747         }
8748         case WRITE_VERIFY_16: {
8749                 struct scsi_write_verify_16 *cdb;
8750
8751                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8752                 flags |= CTL_LLF_FUA;
8753                 if (cdb->byte2 & SWV_DPO)
8754                         flags |= CTL_LLF_DPO;
8755                 lba = scsi_8btou64(cdb->addr);
8756                 num_blocks = scsi_4btoul(cdb->length);
8757                 break;
8758         }
8759         default:
8760                 /*
8761                  * We got a command we don't support.  This shouldn't
8762                  * happen, commands should be filtered out above us.
8763                  */
8764                 ctl_set_invalid_opcode(ctsio);
8765                 ctl_done((union ctl_io *)ctsio);
8766
8767                 return (CTL_RETVAL_COMPLETE);
8768                 break; /* NOTREACHED */
8769         }
8770
8771         /*
8772          * The first check is to make sure we're in bounds, the second
8773          * check is to catch wrap-around problems.  If the lba + num blocks
8774          * is less than the lba, then we've wrapped around and the block
8775          * range is invalid anyway.
8776          */
8777         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8778          || ((lba + num_blocks) < lba)) {
8779                 ctl_set_lba_out_of_range(ctsio,
8780                     MAX(lba, lun->be_lun->maxlba + 1));
8781                 ctl_done((union ctl_io *)ctsio);
8782                 return (CTL_RETVAL_COMPLETE);
8783         }
8784
8785         /*
8786          * According to SBC-3, a transfer length of 0 is not an error.
8787          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8788          * translates to 256 blocks for those commands.
8789          */
8790         if (num_blocks == 0) {
8791                 ctl_set_success(ctsio);
8792                 ctl_done((union ctl_io *)ctsio);
8793                 return (CTL_RETVAL_COMPLETE);
8794         }
8795
8796         /* Set FUA and/or DPO if caches are disabled. */
8797         if (isread) {
8798                 if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8799                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8800         } else {
8801                 if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8802                         flags |= CTL_LLF_FUA;
8803         }
8804
8805         lbalen = (struct ctl_lba_len_flags *)
8806             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8807         lbalen->lba = lba;
8808         lbalen->len = num_blocks;
8809         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8810
8811         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8812         ctsio->kern_rel_offset = 0;
8813
8814         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8815
8816         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8817         return (retval);
8818 }
8819
8820 static int
8821 ctl_cnw_cont(union ctl_io *io)
8822 {
8823         struct ctl_scsiio *ctsio;
8824         struct ctl_lun *lun;
8825         struct ctl_lba_len_flags *lbalen;
8826         int retval;
8827
8828         ctsio = &io->scsiio;
8829         ctsio->io_hdr.status = CTL_STATUS_NONE;
8830         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8831         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8832         lbalen = (struct ctl_lba_len_flags *)
8833             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8834         lbalen->flags &= ~CTL_LLF_COMPARE;
8835         lbalen->flags |= CTL_LLF_WRITE;
8836
8837         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8838         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8839         return (retval);
8840 }
8841
8842 int
8843 ctl_cnw(struct ctl_scsiio *ctsio)
8844 {
8845         struct ctl_lun *lun;
8846         struct ctl_lba_len_flags *lbalen;
8847         uint64_t lba;
8848         uint32_t num_blocks;
8849         int flags, retval;
8850
8851         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8852
8853         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8854
8855         flags = 0;
8856         switch (ctsio->cdb[0]) {
8857         case COMPARE_AND_WRITE: {
8858                 struct scsi_compare_and_write *cdb;
8859
8860                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8861                 if (cdb->byte2 & SRW10_FUA)
8862                         flags |= CTL_LLF_FUA;
8863                 if (cdb->byte2 & SRW10_DPO)
8864                         flags |= CTL_LLF_DPO;
8865                 lba = scsi_8btou64(cdb->addr);
8866                 num_blocks = cdb->length;
8867                 break;
8868         }
8869         default:
8870                 /*
8871                  * We got a command we don't support.  This shouldn't
8872                  * happen, commands should be filtered out above us.
8873                  */
8874                 ctl_set_invalid_opcode(ctsio);
8875                 ctl_done((union ctl_io *)ctsio);
8876
8877                 return (CTL_RETVAL_COMPLETE);
8878                 break; /* NOTREACHED */
8879         }
8880
8881         /*
8882          * The first check is to make sure we're in bounds, the second
8883          * check is to catch wrap-around problems.  If the lba + num blocks
8884          * is less than the lba, then we've wrapped around and the block
8885          * range is invalid anyway.
8886          */
8887         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8888          || ((lba + num_blocks) < lba)) {
8889                 ctl_set_lba_out_of_range(ctsio,
8890                     MAX(lba, lun->be_lun->maxlba + 1));
8891                 ctl_done((union ctl_io *)ctsio);
8892                 return (CTL_RETVAL_COMPLETE);
8893         }
8894
8895         /*
8896          * According to SBC-3, a transfer length of 0 is not an error.
8897          */
8898         if (num_blocks == 0) {
8899                 ctl_set_success(ctsio);
8900                 ctl_done((union ctl_io *)ctsio);
8901                 return (CTL_RETVAL_COMPLETE);
8902         }
8903
8904         /* Set FUA if write cache is disabled. */
8905         if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8906                 flags |= CTL_LLF_FUA;
8907
8908         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8909         ctsio->kern_rel_offset = 0;
8910
8911         /*
8912          * Set the IO_CONT flag, so that if this I/O gets passed to
8913          * ctl_data_submit_done(), it'll get passed back to
8914          * ctl_ctl_cnw_cont() for further processing.
8915          */
8916         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8917         ctsio->io_cont = ctl_cnw_cont;
8918
8919         lbalen = (struct ctl_lba_len_flags *)
8920             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8921         lbalen->lba = lba;
8922         lbalen->len = num_blocks;
8923         lbalen->flags = CTL_LLF_COMPARE | flags;
8924
8925         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8926         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8927         return (retval);
8928 }
8929
8930 int
8931 ctl_verify(struct ctl_scsiio *ctsio)
8932 {
8933         struct ctl_lun *lun;
8934         struct ctl_lba_len_flags *lbalen;
8935         uint64_t lba;
8936         uint32_t num_blocks;
8937         int bytchk, flags;
8938         int retval;
8939
8940         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8941
8942         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8943
8944         bytchk = 0;
8945         flags = CTL_LLF_FUA;
8946         switch (ctsio->cdb[0]) {
8947         case VERIFY_10: {
8948                 struct scsi_verify_10 *cdb;
8949
8950                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8951                 if (cdb->byte2 & SVFY_BYTCHK)
8952                         bytchk = 1;
8953                 if (cdb->byte2 & SVFY_DPO)
8954                         flags |= CTL_LLF_DPO;
8955                 lba = scsi_4btoul(cdb->addr);
8956                 num_blocks = scsi_2btoul(cdb->length);
8957                 break;
8958         }
8959         case VERIFY_12: {
8960                 struct scsi_verify_12 *cdb;
8961
8962                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8963                 if (cdb->byte2 & SVFY_BYTCHK)
8964                         bytchk = 1;
8965                 if (cdb->byte2 & SVFY_DPO)
8966                         flags |= CTL_LLF_DPO;
8967                 lba = scsi_4btoul(cdb->addr);
8968                 num_blocks = scsi_4btoul(cdb->length);
8969                 break;
8970         }
8971         case VERIFY_16: {
8972                 struct scsi_rw_16 *cdb;
8973
8974                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8975                 if (cdb->byte2 & SVFY_BYTCHK)
8976                         bytchk = 1;
8977                 if (cdb->byte2 & SVFY_DPO)
8978                         flags |= CTL_LLF_DPO;
8979                 lba = scsi_8btou64(cdb->addr);
8980                 num_blocks = scsi_4btoul(cdb->length);
8981                 break;
8982         }
8983         default:
8984                 /*
8985                  * We got a command we don't support.  This shouldn't
8986                  * happen, commands should be filtered out above us.
8987                  */
8988                 ctl_set_invalid_opcode(ctsio);
8989                 ctl_done((union ctl_io *)ctsio);
8990                 return (CTL_RETVAL_COMPLETE);
8991         }
8992
8993         /*
8994          * The first check is to make sure we're in bounds, the second
8995          * check is to catch wrap-around problems.  If the lba + num blocks
8996          * is less than the lba, then we've wrapped around and the block
8997          * range is invalid anyway.
8998          */
8999         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9000          || ((lba + num_blocks) < lba)) {
9001                 ctl_set_lba_out_of_range(ctsio,
9002                     MAX(lba, lun->be_lun->maxlba + 1));
9003                 ctl_done((union ctl_io *)ctsio);
9004                 return (CTL_RETVAL_COMPLETE);
9005         }
9006
9007         /*
9008          * According to SBC-3, a transfer length of 0 is not an error.
9009          */
9010         if (num_blocks == 0) {
9011                 ctl_set_success(ctsio);
9012                 ctl_done((union ctl_io *)ctsio);
9013                 return (CTL_RETVAL_COMPLETE);
9014         }
9015
9016         lbalen = (struct ctl_lba_len_flags *)
9017             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9018         lbalen->lba = lba;
9019         lbalen->len = num_blocks;
9020         if (bytchk) {
9021                 lbalen->flags = CTL_LLF_COMPARE | flags;
9022                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9023         } else {
9024                 lbalen->flags = CTL_LLF_VERIFY | flags;
9025                 ctsio->kern_total_len = 0;
9026         }
9027         ctsio->kern_rel_offset = 0;
9028
9029         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9030         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9031         return (retval);
9032 }
9033
9034 int
9035 ctl_report_luns(struct ctl_scsiio *ctsio)
9036 {
9037         struct ctl_softc *softc;
9038         struct scsi_report_luns *cdb;
9039         struct scsi_report_luns_data *lun_data;
9040         struct ctl_lun *lun, *request_lun;
9041         struct ctl_port *port;
9042         int num_luns, retval;
9043         uint32_t alloc_len, lun_datalen;
9044         int num_filled;
9045         uint32_t initidx, targ_lun_id, lun_id;
9046
9047         retval = CTL_RETVAL_COMPLETE;
9048         cdb = (struct scsi_report_luns *)ctsio->cdb;
9049         port = ctl_io_port(&ctsio->io_hdr);
9050         softc = port->ctl_softc;
9051
9052         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9053
9054         mtx_lock(&softc->ctl_lock);
9055         num_luns = 0;
9056         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9057                 if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9058                         num_luns++;
9059         }
9060         mtx_unlock(&softc->ctl_lock);
9061
9062         switch (cdb->select_report) {
9063         case RPL_REPORT_DEFAULT:
9064         case RPL_REPORT_ALL:
9065         case RPL_REPORT_NONSUBSID:
9066                 break;
9067         case RPL_REPORT_WELLKNOWN:
9068         case RPL_REPORT_ADMIN:
9069         case RPL_REPORT_CONGLOM:
9070                 num_luns = 0;
9071                 break;
9072         default:
9073                 ctl_set_invalid_field(ctsio,
9074                                       /*sks_valid*/ 1,
9075                                       /*command*/ 1,
9076                                       /*field*/ 2,
9077                                       /*bit_valid*/ 0,
9078                                       /*bit*/ 0);
9079                 ctl_done((union ctl_io *)ctsio);
9080                 return (retval);
9081                 break; /* NOTREACHED */
9082         }
9083
9084         alloc_len = scsi_4btoul(cdb->length);
9085         /*
9086          * The initiator has to allocate at least 16 bytes for this request,
9087          * so he can at least get the header and the first LUN.  Otherwise
9088          * we reject the request (per SPC-3 rev 14, section 6.21).
9089          */
9090         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9091             sizeof(struct scsi_report_luns_lundata))) {
9092                 ctl_set_invalid_field(ctsio,
9093                                       /*sks_valid*/ 1,
9094                                       /*command*/ 1,
9095                                       /*field*/ 6,
9096                                       /*bit_valid*/ 0,
9097                                       /*bit*/ 0);
9098                 ctl_done((union ctl_io *)ctsio);
9099                 return (retval);
9100         }
9101
9102         request_lun = (struct ctl_lun *)
9103                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9104
9105         lun_datalen = sizeof(*lun_data) +
9106                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9107
9108         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9109         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9110         ctsio->kern_sg_entries = 0;
9111
9112         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9113
9114         mtx_lock(&softc->ctl_lock);
9115         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9116                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9117                 if (lun_id == UINT32_MAX)
9118                         continue;
9119                 lun = softc->ctl_luns[lun_id];
9120                 if (lun == NULL)
9121                         continue;
9122
9123                 be64enc(lun_data->luns[num_filled++].lundata,
9124                     ctl_encode_lun(targ_lun_id));
9125
9126                 /*
9127                  * According to SPC-3, rev 14 section 6.21:
9128                  *
9129                  * "The execution of a REPORT LUNS command to any valid and
9130                  * installed logical unit shall clear the REPORTED LUNS DATA
9131                  * HAS CHANGED unit attention condition for all logical
9132                  * units of that target with respect to the requesting
9133                  * initiator. A valid and installed logical unit is one
9134                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9135                  * INQUIRY data (see 6.4.2)."
9136                  *
9137                  * If request_lun is NULL, the LUN this report luns command
9138                  * was issued to is either disabled or doesn't exist. In that
9139                  * case, we shouldn't clear any pending lun change unit
9140                  * attention.
9141                  */
9142                 if (request_lun != NULL) {
9143                         mtx_lock(&lun->lun_lock);
9144                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9145                         mtx_unlock(&lun->lun_lock);
9146                 }
9147         }
9148         mtx_unlock(&softc->ctl_lock);
9149
9150         /*
9151          * It's quite possible that we've returned fewer LUNs than we allocated
9152          * space for.  Trim it.
9153          */
9154         lun_datalen = sizeof(*lun_data) +
9155                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9156
9157         if (lun_datalen < alloc_len) {
9158                 ctsio->residual = alloc_len - lun_datalen;
9159                 ctsio->kern_data_len = lun_datalen;
9160                 ctsio->kern_total_len = lun_datalen;
9161         } else {
9162                 ctsio->residual = 0;
9163                 ctsio->kern_data_len = alloc_len;
9164                 ctsio->kern_total_len = alloc_len;
9165         }
9166         ctsio->kern_data_resid = 0;
9167         ctsio->kern_rel_offset = 0;
9168         ctsio->kern_sg_entries = 0;
9169
9170         /*
9171          * We set this to the actual data length, regardless of how much
9172          * space we actually have to return results.  If the user looks at
9173          * this value, he'll know whether or not he allocated enough space
9174          * and reissue the command if necessary.  We don't support well
9175          * known logical units, so if the user asks for that, return none.
9176          */
9177         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9178
9179         /*
9180          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9181          * this request.
9182          */
9183         ctl_set_success(ctsio);
9184         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9185         ctsio->be_move_done = ctl_config_move_done;
9186         ctl_datamove((union ctl_io *)ctsio);
9187         return (retval);
9188 }
9189
9190 int
9191 ctl_request_sense(struct ctl_scsiio *ctsio)
9192 {
9193         struct scsi_request_sense *cdb;
9194         struct scsi_sense_data *sense_ptr;
9195         struct ctl_softc *softc;
9196         struct ctl_lun *lun;
9197         uint32_t initidx;
9198         int have_error;
9199         u_int sense_len = SSD_FULL_SIZE;
9200         scsi_sense_data_type sense_format;
9201         ctl_ua_type ua_type;
9202         uint8_t asc = 0, ascq = 0;
9203
9204         cdb = (struct scsi_request_sense *)ctsio->cdb;
9205
9206         softc = control_softc;
9207         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9208
9209         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9210
9211         /*
9212          * Determine which sense format the user wants.
9213          */
9214         if (cdb->byte2 & SRS_DESC)
9215                 sense_format = SSD_TYPE_DESC;
9216         else
9217                 sense_format = SSD_TYPE_FIXED;
9218
9219         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9220         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9221         ctsio->kern_sg_entries = 0;
9222
9223         /*
9224          * struct scsi_sense_data, which is currently set to 256 bytes, is
9225          * larger than the largest allowed value for the length field in the
9226          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9227          */
9228         ctsio->residual = 0;
9229         ctsio->kern_data_len = cdb->length;
9230         ctsio->kern_total_len = cdb->length;
9231
9232         ctsio->kern_data_resid = 0;
9233         ctsio->kern_rel_offset = 0;
9234         ctsio->kern_sg_entries = 0;
9235
9236         /*
9237          * If we don't have a LUN, we don't have any pending sense.
9238          */
9239         if (lun == NULL ||
9240             ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9241              softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9242                 /* "Logical unit not supported" */
9243                 ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9244                     /*current_error*/ 1,
9245                     /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9246                     /*asc*/ 0x25,
9247                     /*ascq*/ 0x00,
9248                     SSD_ELEM_NONE);
9249                 goto send;
9250         }
9251
9252         have_error = 0;
9253         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9254         /*
9255          * Check for pending sense, and then for pending unit attentions.
9256          * Pending sense gets returned first, then pending unit attentions.
9257          */
9258         mtx_lock(&lun->lun_lock);
9259 #ifdef CTL_WITH_CA
9260         if (ctl_is_set(lun->have_ca, initidx)) {
9261                 scsi_sense_data_type stored_format;
9262
9263                 /*
9264                  * Check to see which sense format was used for the stored
9265                  * sense data.
9266                  */
9267                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9268
9269                 /*
9270                  * If the user requested a different sense format than the
9271                  * one we stored, then we need to convert it to the other
9272                  * format.  If we're going from descriptor to fixed format
9273                  * sense data, we may lose things in translation, depending
9274                  * on what options were used.
9275                  *
9276                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9277                  * for some reason we'll just copy it out as-is.
9278                  */
9279                 if ((stored_format == SSD_TYPE_FIXED)
9280                  && (sense_format == SSD_TYPE_DESC))
9281                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9282                             &lun->pending_sense[initidx],
9283                             (struct scsi_sense_data_desc *)sense_ptr);
9284                 else if ((stored_format == SSD_TYPE_DESC)
9285                       && (sense_format == SSD_TYPE_FIXED))
9286                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9287                             &lun->pending_sense[initidx],
9288                             (struct scsi_sense_data_fixed *)sense_ptr);
9289                 else
9290                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9291                                MIN(sizeof(*sense_ptr),
9292                                sizeof(lun->pending_sense[initidx])));
9293
9294                 ctl_clear_mask(lun->have_ca, initidx);
9295                 have_error = 1;
9296         } else
9297 #endif
9298         if (have_error == 0) {
9299                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9300                     sense_format);
9301                 if (ua_type != CTL_UA_NONE)
9302                         have_error = 1;
9303         }
9304         if (have_error == 0) {
9305                 /*
9306                  * Report informational exception if have one and allowed.
9307                  */
9308                 if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9309                         asc = lun->ie_asc;
9310                         ascq = lun->ie_ascq;
9311                 }
9312                 ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9313                     /*current_error*/ 1,
9314                     /*sense_key*/ SSD_KEY_NO_SENSE,
9315                     /*asc*/ asc,
9316                     /*ascq*/ ascq,
9317                     SSD_ELEM_NONE);
9318         }
9319         mtx_unlock(&lun->lun_lock);
9320
9321 send:
9322         /*
9323          * We report the SCSI status as OK, since the status of the command
9324          * itself is OK.  We're reporting sense as parameter data.
9325          */
9326         ctl_set_success(ctsio);
9327         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9328         ctsio->be_move_done = ctl_config_move_done;
9329         ctl_datamove((union ctl_io *)ctsio);
9330         return (CTL_RETVAL_COMPLETE);
9331 }
9332
9333 int
9334 ctl_tur(struct ctl_scsiio *ctsio)
9335 {
9336
9337         CTL_DEBUG_PRINT(("ctl_tur\n"));
9338
9339         ctl_set_success(ctsio);
9340         ctl_done((union ctl_io *)ctsio);
9341
9342         return (CTL_RETVAL_COMPLETE);
9343 }
9344
9345 /*
9346  * SCSI VPD page 0x00, the Supported VPD Pages page.
9347  */
9348 static int
9349 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9350 {
9351         struct scsi_vpd_supported_pages *pages;
9352         int sup_page_size;
9353         struct ctl_lun *lun;
9354         int p;
9355
9356         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9357
9358         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9359             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9360         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9361         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9362         ctsio->kern_sg_entries = 0;
9363
9364         if (sup_page_size < alloc_len) {
9365                 ctsio->residual = alloc_len - sup_page_size;
9366                 ctsio->kern_data_len = sup_page_size;
9367                 ctsio->kern_total_len = sup_page_size;
9368         } else {
9369                 ctsio->residual = 0;
9370                 ctsio->kern_data_len = alloc_len;
9371                 ctsio->kern_total_len = alloc_len;
9372         }
9373         ctsio->kern_data_resid = 0;
9374         ctsio->kern_rel_offset = 0;
9375         ctsio->kern_sg_entries = 0;
9376
9377         /*
9378          * The control device is always connected.  The disk device, on the
9379          * other hand, may not be online all the time.  Need to change this
9380          * to figure out whether the disk device is actually online or not.
9381          */
9382         if (lun != NULL)
9383                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9384                                 lun->be_lun->lun_type;
9385         else
9386                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9387
9388         p = 0;
9389         /* Supported VPD pages */
9390         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9391         /* Serial Number */
9392         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9393         /* Device Identification */
9394         pages->page_list[p++] = SVPD_DEVICE_ID;
9395         /* Extended INQUIRY Data */
9396         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9397         /* Mode Page Policy */
9398         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9399         /* SCSI Ports */
9400         pages->page_list[p++] = SVPD_SCSI_PORTS;
9401         /* Third-party Copy */
9402         pages->page_list[p++] = SVPD_SCSI_TPC;
9403         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9404                 /* Block limits */
9405                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9406                 /* Block Device Characteristics */
9407                 pages->page_list[p++] = SVPD_BDC;
9408                 /* Logical Block Provisioning */
9409                 pages->page_list[p++] = SVPD_LBP;
9410         }
9411         pages->length = p;
9412
9413         ctl_set_success(ctsio);
9414         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9415         ctsio->be_move_done = ctl_config_move_done;
9416         ctl_datamove((union ctl_io *)ctsio);
9417         return (CTL_RETVAL_COMPLETE);
9418 }
9419
9420 /*
9421  * SCSI VPD page 0x80, the Unit Serial Number page.
9422  */
9423 static int
9424 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9425 {
9426         struct scsi_vpd_unit_serial_number *sn_ptr;
9427         struct ctl_lun *lun;
9428         int data_len;
9429
9430         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9431
9432         data_len = 4 + CTL_SN_LEN;
9433         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9434         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9435         if (data_len < alloc_len) {
9436                 ctsio->residual = alloc_len - data_len;
9437                 ctsio->kern_data_len = data_len;
9438                 ctsio->kern_total_len = data_len;
9439         } else {
9440                 ctsio->residual = 0;
9441                 ctsio->kern_data_len = alloc_len;
9442                 ctsio->kern_total_len = alloc_len;
9443         }
9444         ctsio->kern_data_resid = 0;
9445         ctsio->kern_rel_offset = 0;
9446         ctsio->kern_sg_entries = 0;
9447
9448         /*
9449          * The control device is always connected.  The disk device, on the
9450          * other hand, may not be online all the time.  Need to change this
9451          * to figure out whether the disk device is actually online or not.
9452          */
9453         if (lun != NULL)
9454                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9455                                   lun->be_lun->lun_type;
9456         else
9457                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9458
9459         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9460         sn_ptr->length = CTL_SN_LEN;
9461         /*
9462          * If we don't have a LUN, we just leave the serial number as
9463          * all spaces.
9464          */
9465         if (lun != NULL) {
9466                 strncpy((char *)sn_ptr->serial_num,
9467                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9468         } else
9469                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9470
9471         ctl_set_success(ctsio);
9472         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9473         ctsio->be_move_done = ctl_config_move_done;
9474         ctl_datamove((union ctl_io *)ctsio);
9475         return (CTL_RETVAL_COMPLETE);
9476 }
9477
9478
9479 /*
9480  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9481  */
9482 static int
9483 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9484 {
9485         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9486         struct ctl_lun *lun;
9487         int data_len;
9488
9489         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9490
9491         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9492         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9493         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9494         ctsio->kern_sg_entries = 0;
9495
9496         if (data_len < alloc_len) {
9497                 ctsio->residual = alloc_len - data_len;
9498                 ctsio->kern_data_len = data_len;
9499                 ctsio->kern_total_len = data_len;
9500         } else {
9501                 ctsio->residual = 0;
9502                 ctsio->kern_data_len = alloc_len;
9503                 ctsio->kern_total_len = alloc_len;
9504         }
9505         ctsio->kern_data_resid = 0;
9506         ctsio->kern_rel_offset = 0;
9507         ctsio->kern_sg_entries = 0;
9508
9509         /*
9510          * The control device is always connected.  The disk device, on the
9511          * other hand, may not be online all the time.
9512          */
9513         if (lun != NULL)
9514                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9515                                      lun->be_lun->lun_type;
9516         else
9517                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9518         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9519         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9520         /*
9521          * We support head of queue, ordered and simple tags.
9522          */
9523         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9524         /*
9525          * Volatile cache supported.
9526          */
9527         eid_ptr->flags3 = SVPD_EID_V_SUP;
9528
9529         /*
9530          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9531          * attention for a particular IT nexus on all LUNs once we report
9532          * it to that nexus once.  This bit is required as of SPC-4.
9533          */
9534         eid_ptr->flags4 = SVPD_EID_LUICLR;
9535
9536         /*
9537          * XXX KDM in order to correctly answer this, we would need
9538          * information from the SIM to determine how much sense data it
9539          * can send.  So this would really be a path inquiry field, most
9540          * likely.  This can be set to a maximum of 252 according to SPC-4,
9541          * but the hardware may or may not be able to support that much.
9542          * 0 just means that the maximum sense data length is not reported.
9543          */
9544         eid_ptr->max_sense_length = 0;
9545
9546         ctl_set_success(ctsio);
9547         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9548         ctsio->be_move_done = ctl_config_move_done;
9549         ctl_datamove((union ctl_io *)ctsio);
9550         return (CTL_RETVAL_COMPLETE);
9551 }
9552
9553 static int
9554 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9555 {
9556         struct scsi_vpd_mode_page_policy *mpp_ptr;
9557         struct ctl_lun *lun;
9558         int data_len;
9559
9560         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9561
9562         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9563             sizeof(struct scsi_vpd_mode_page_policy_descr);
9564
9565         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9566         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9567         ctsio->kern_sg_entries = 0;
9568
9569         if (data_len < alloc_len) {
9570                 ctsio->residual = alloc_len - data_len;
9571                 ctsio->kern_data_len = data_len;
9572                 ctsio->kern_total_len = data_len;
9573         } else {
9574                 ctsio->residual = 0;
9575                 ctsio->kern_data_len = alloc_len;
9576                 ctsio->kern_total_len = alloc_len;
9577         }
9578         ctsio->kern_data_resid = 0;
9579         ctsio->kern_rel_offset = 0;
9580         ctsio->kern_sg_entries = 0;
9581
9582         /*
9583          * The control device is always connected.  The disk device, on the
9584          * other hand, may not be online all the time.
9585          */
9586         if (lun != NULL)
9587                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9588                                      lun->be_lun->lun_type;
9589         else
9590                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9591         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9592         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9593         mpp_ptr->descr[0].page_code = 0x3f;
9594         mpp_ptr->descr[0].subpage_code = 0xff;
9595         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9596
9597         ctl_set_success(ctsio);
9598         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9599         ctsio->be_move_done = ctl_config_move_done;
9600         ctl_datamove((union ctl_io *)ctsio);
9601         return (CTL_RETVAL_COMPLETE);
9602 }
9603
9604 /*
9605  * SCSI VPD page 0x83, the Device Identification page.
9606  */
9607 static int
9608 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9609 {
9610         struct scsi_vpd_device_id *devid_ptr;
9611         struct scsi_vpd_id_descriptor *desc;
9612         struct ctl_softc *softc;
9613         struct ctl_lun *lun;
9614         struct ctl_port *port;
9615         int data_len, g;
9616         uint8_t proto;
9617
9618         softc = control_softc;
9619
9620         port = ctl_io_port(&ctsio->io_hdr);
9621         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9622
9623         data_len = sizeof(struct scsi_vpd_device_id) +
9624             sizeof(struct scsi_vpd_id_descriptor) +
9625                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9626             sizeof(struct scsi_vpd_id_descriptor) +
9627                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9628         if (lun && lun->lun_devid)
9629                 data_len += lun->lun_devid->len;
9630         if (port && port->port_devid)
9631                 data_len += port->port_devid->len;
9632         if (port && port->target_devid)
9633                 data_len += port->target_devid->len;
9634
9635         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9636         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9637         ctsio->kern_sg_entries = 0;
9638
9639         if (data_len < alloc_len) {
9640                 ctsio->residual = alloc_len - data_len;
9641                 ctsio->kern_data_len = data_len;
9642                 ctsio->kern_total_len = data_len;
9643         } else {
9644                 ctsio->residual = 0;
9645                 ctsio->kern_data_len = alloc_len;
9646                 ctsio->kern_total_len = alloc_len;
9647         }
9648         ctsio->kern_data_resid = 0;
9649         ctsio->kern_rel_offset = 0;
9650         ctsio->kern_sg_entries = 0;
9651
9652         /*
9653          * The control device is always connected.  The disk device, on the
9654          * other hand, may not be online all the time.
9655          */
9656         if (lun != NULL)
9657                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9658                                      lun->be_lun->lun_type;
9659         else
9660                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9661         devid_ptr->page_code = SVPD_DEVICE_ID;
9662         scsi_ulto2b(data_len - 4, devid_ptr->length);
9663
9664         if (port && port->port_type == CTL_PORT_FC)
9665                 proto = SCSI_PROTO_FC << 4;
9666         else if (port && port->port_type == CTL_PORT_ISCSI)
9667                 proto = SCSI_PROTO_ISCSI << 4;
9668         else
9669                 proto = SCSI_PROTO_SPI << 4;
9670         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9671
9672         /*
9673          * We're using a LUN association here.  i.e., this device ID is a
9674          * per-LUN identifier.
9675          */
9676         if (lun && lun->lun_devid) {
9677                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9678                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9679                     lun->lun_devid->len);
9680         }
9681
9682         /*
9683          * This is for the WWPN which is a port association.
9684          */
9685         if (port && port->port_devid) {
9686                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9687                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9688                     port->port_devid->len);
9689         }
9690
9691         /*
9692          * This is for the Relative Target Port(type 4h) identifier
9693          */
9694         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9695         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9696             SVPD_ID_TYPE_RELTARG;
9697         desc->length = 4;
9698         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9699         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9700             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9701
9702         /*
9703          * This is for the Target Port Group(type 5h) identifier
9704          */
9705         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9706         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9707             SVPD_ID_TYPE_TPORTGRP;
9708         desc->length = 4;
9709         if (softc->is_single ||
9710             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9711                 g = 1;
9712         else
9713                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9714         scsi_ulto2b(g, &desc->identifier[2]);
9715         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9716             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9717
9718         /*
9719          * This is for the Target identifier
9720          */
9721         if (port && port->target_devid) {
9722                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9723         }
9724
9725         ctl_set_success(ctsio);
9726         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9727         ctsio->be_move_done = ctl_config_move_done;
9728         ctl_datamove((union ctl_io *)ctsio);
9729         return (CTL_RETVAL_COMPLETE);
9730 }
9731
9732 static int
9733 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9734 {
9735         struct ctl_softc *softc = control_softc;
9736         struct scsi_vpd_scsi_ports *sp;
9737         struct scsi_vpd_port_designation *pd;
9738         struct scsi_vpd_port_designation_cont *pdc;
9739         struct ctl_lun *lun;
9740         struct ctl_port *port;
9741         int data_len, num_target_ports, iid_len, id_len;
9742
9743         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9744
9745         num_target_ports = 0;
9746         iid_len = 0;
9747         id_len = 0;
9748         mtx_lock(&softc->ctl_lock);
9749         STAILQ_FOREACH(port, &softc->port_list, links) {
9750                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9751                         continue;
9752                 if (lun != NULL &&
9753                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9754                         continue;
9755                 num_target_ports++;
9756                 if (port->init_devid)
9757                         iid_len += port->init_devid->len;
9758                 if (port->port_devid)
9759                         id_len += port->port_devid->len;
9760         }
9761         mtx_unlock(&softc->ctl_lock);
9762
9763         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9764             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9765              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9766         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9767         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9768         ctsio->kern_sg_entries = 0;
9769
9770         if (data_len < alloc_len) {
9771                 ctsio->residual = alloc_len - data_len;
9772                 ctsio->kern_data_len = data_len;
9773                 ctsio->kern_total_len = data_len;
9774         } else {
9775                 ctsio->residual = 0;
9776                 ctsio->kern_data_len = alloc_len;
9777                 ctsio->kern_total_len = alloc_len;
9778         }
9779         ctsio->kern_data_resid = 0;
9780         ctsio->kern_rel_offset = 0;
9781         ctsio->kern_sg_entries = 0;
9782
9783         /*
9784          * The control device is always connected.  The disk device, on the
9785          * other hand, may not be online all the time.  Need to change this
9786          * to figure out whether the disk device is actually online or not.
9787          */
9788         if (lun != NULL)
9789                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9790                                   lun->be_lun->lun_type;
9791         else
9792                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9793
9794         sp->page_code = SVPD_SCSI_PORTS;
9795         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9796             sp->page_length);
9797         pd = &sp->design[0];
9798
9799         mtx_lock(&softc->ctl_lock);
9800         STAILQ_FOREACH(port, &softc->port_list, links) {
9801                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9802                         continue;
9803                 if (lun != NULL &&
9804                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9805                         continue;
9806                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9807                 if (port->init_devid) {
9808                         iid_len = port->init_devid->len;
9809                         memcpy(pd->initiator_transportid,
9810                             port->init_devid->data, port->init_devid->len);
9811                 } else
9812                         iid_len = 0;
9813                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9814                 pdc = (struct scsi_vpd_port_designation_cont *)
9815                     (&pd->initiator_transportid[iid_len]);
9816                 if (port->port_devid) {
9817                         id_len = port->port_devid->len;
9818                         memcpy(pdc->target_port_descriptors,
9819                             port->port_devid->data, port->port_devid->len);
9820                 } else
9821                         id_len = 0;
9822                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9823                 pd = (struct scsi_vpd_port_designation *)
9824                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9825         }
9826         mtx_unlock(&softc->ctl_lock);
9827
9828         ctl_set_success(ctsio);
9829         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9830         ctsio->be_move_done = ctl_config_move_done;
9831         ctl_datamove((union ctl_io *)ctsio);
9832         return (CTL_RETVAL_COMPLETE);
9833 }
9834
9835 static int
9836 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9837 {
9838         struct scsi_vpd_block_limits *bl_ptr;
9839         struct ctl_lun *lun;
9840         uint64_t ival;
9841
9842         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9843
9844         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9845         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9846         ctsio->kern_sg_entries = 0;
9847
9848         if (sizeof(*bl_ptr) < alloc_len) {
9849                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9850                 ctsio->kern_data_len = sizeof(*bl_ptr);
9851                 ctsio->kern_total_len = sizeof(*bl_ptr);
9852         } else {
9853                 ctsio->residual = 0;
9854                 ctsio->kern_data_len = alloc_len;
9855                 ctsio->kern_total_len = alloc_len;
9856         }
9857         ctsio->kern_data_resid = 0;
9858         ctsio->kern_rel_offset = 0;
9859         ctsio->kern_sg_entries = 0;
9860
9861         /*
9862          * The control device is always connected.  The disk device, on the
9863          * other hand, may not be online all the time.  Need to change this
9864          * to figure out whether the disk device is actually online or not.
9865          */
9866         if (lun != NULL)
9867                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9868                                   lun->be_lun->lun_type;
9869         else
9870                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9871
9872         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9873         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9874         bl_ptr->max_cmp_write_len = 0xff;
9875         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9876         if (lun != NULL) {
9877                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9878                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9879                         ival = 0xffffffff;
9880                         ctl_get_opt_number(&lun->be_lun->options,
9881                             "unmap_max_lba", &ival);
9882                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9883                         ival = 0xffffffff;
9884                         ctl_get_opt_number(&lun->be_lun->options,
9885                             "unmap_max_descr", &ival);
9886                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9887                         if (lun->be_lun->ublockexp != 0) {
9888                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9889                                     bl_ptr->opt_unmap_grain);
9890                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9891                                     bl_ptr->unmap_grain_align);
9892                         }
9893                 }
9894                 scsi_ulto4b(lun->be_lun->atomicblock,
9895                     bl_ptr->max_atomic_transfer_length);
9896                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9897                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9898                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9899                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9900                 ival = UINT64_MAX;
9901                 ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9902                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9903         }
9904
9905         ctl_set_success(ctsio);
9906         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9907         ctsio->be_move_done = ctl_config_move_done;
9908         ctl_datamove((union ctl_io *)ctsio);
9909         return (CTL_RETVAL_COMPLETE);
9910 }
9911
9912 static int
9913 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9914 {
9915         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9916         struct ctl_lun *lun;
9917         const char *value;
9918         u_int i;
9919
9920         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9921
9922         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9923         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9924         ctsio->kern_sg_entries = 0;
9925
9926         if (sizeof(*bdc_ptr) < alloc_len) {
9927                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9928                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9929                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9930         } else {
9931                 ctsio->residual = 0;
9932                 ctsio->kern_data_len = alloc_len;
9933                 ctsio->kern_total_len = alloc_len;
9934         }
9935         ctsio->kern_data_resid = 0;
9936         ctsio->kern_rel_offset = 0;
9937         ctsio->kern_sg_entries = 0;
9938
9939         /*
9940          * The control device is always connected.  The disk device, on the
9941          * other hand, may not be online all the time.  Need to change this
9942          * to figure out whether the disk device is actually online or not.
9943          */
9944         if (lun != NULL)
9945                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9946                                   lun->be_lun->lun_type;
9947         else
9948                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9949         bdc_ptr->page_code = SVPD_BDC;
9950         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9951         if (lun != NULL &&
9952             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9953                 i = strtol(value, NULL, 0);
9954         else
9955                 i = CTL_DEFAULT_ROTATION_RATE;
9956         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9957         if (lun != NULL &&
9958             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9959                 i = strtol(value, NULL, 0);
9960         else
9961                 i = 0;
9962         bdc_ptr->wab_wac_ff = (i & 0x0f);
9963         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9964
9965         ctl_set_success(ctsio);
9966         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9967         ctsio->be_move_done = ctl_config_move_done;
9968         ctl_datamove((union ctl_io *)ctsio);
9969         return (CTL_RETVAL_COMPLETE);
9970 }
9971
9972 static int
9973 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9974 {
9975         struct scsi_vpd_logical_block_prov *lbp_ptr;
9976         struct ctl_lun *lun;
9977         const char *value;
9978
9979         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9980
9981         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9982         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9983         ctsio->kern_sg_entries = 0;
9984
9985         if (sizeof(*lbp_ptr) < alloc_len) {
9986                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9987                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9988                 ctsio->kern_total_len = sizeof(*lbp_ptr);
9989         } else {
9990                 ctsio->residual = 0;
9991                 ctsio->kern_data_len = alloc_len;
9992                 ctsio->kern_total_len = alloc_len;
9993         }
9994         ctsio->kern_data_resid = 0;
9995         ctsio->kern_rel_offset = 0;
9996         ctsio->kern_sg_entries = 0;
9997
9998         /*
9999          * The control device is always connected.  The disk device, on the
10000          * other hand, may not be online all the time.  Need to change this
10001          * to figure out whether the disk device is actually online or not.
10002          */
10003         if (lun != NULL)
10004                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10005                                   lun->be_lun->lun_type;
10006         else
10007                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10008
10009         lbp_ptr->page_code = SVPD_LBP;
10010         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10011         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10012         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10013                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10014                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10015                 value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10016                 if (value != NULL) {
10017                         if (strcmp(value, "resource") == 0)
10018                                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10019                         else if (strcmp(value, "thin") == 0)
10020                                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10021                 } else
10022                         lbp_ptr->prov_type = SVPD_LBP_THIN;
10023         }
10024
10025         ctl_set_success(ctsio);
10026         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10027         ctsio->be_move_done = ctl_config_move_done;
10028         ctl_datamove((union ctl_io *)ctsio);
10029         return (CTL_RETVAL_COMPLETE);
10030 }
10031
10032 /*
10033  * INQUIRY with the EVPD bit set.
10034  */
10035 static int
10036 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10037 {
10038         struct ctl_lun *lun;
10039         struct scsi_inquiry *cdb;
10040         int alloc_len, retval;
10041
10042         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10043         cdb = (struct scsi_inquiry *)ctsio->cdb;
10044         alloc_len = scsi_2btoul(cdb->length);
10045
10046         switch (cdb->page_code) {
10047         case SVPD_SUPPORTED_PAGES:
10048                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10049                 break;
10050         case SVPD_UNIT_SERIAL_NUMBER:
10051                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10052                 break;
10053         case SVPD_DEVICE_ID:
10054                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10055                 break;
10056         case SVPD_EXTENDED_INQUIRY_DATA:
10057                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10058                 break;
10059         case SVPD_MODE_PAGE_POLICY:
10060                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10061                 break;
10062         case SVPD_SCSI_PORTS:
10063                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10064                 break;
10065         case SVPD_SCSI_TPC:
10066                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10067                 break;
10068         case SVPD_BLOCK_LIMITS:
10069                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10070                         goto err;
10071                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10072                 break;
10073         case SVPD_BDC:
10074                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10075                         goto err;
10076                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10077                 break;
10078         case SVPD_LBP:
10079                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10080                         goto err;
10081                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10082                 break;
10083         default:
10084 err:
10085                 ctl_set_invalid_field(ctsio,
10086                                       /*sks_valid*/ 1,
10087                                       /*command*/ 1,
10088                                       /*field*/ 2,
10089                                       /*bit_valid*/ 0,
10090                                       /*bit*/ 0);
10091                 ctl_done((union ctl_io *)ctsio);
10092                 retval = CTL_RETVAL_COMPLETE;
10093                 break;
10094         }
10095
10096         return (retval);
10097 }
10098
10099 /*
10100  * Standard INQUIRY data.
10101  */
10102 static int
10103 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10104 {
10105         struct scsi_inquiry_data *inq_ptr;
10106         struct scsi_inquiry *cdb;
10107         struct ctl_softc *softc = control_softc;
10108         struct ctl_port *port;
10109         struct ctl_lun *lun;
10110         char *val;
10111         uint32_t alloc_len, data_len;
10112         ctl_port_type port_type;
10113
10114         port = ctl_io_port(&ctsio->io_hdr);
10115         port_type = port->port_type;
10116         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10117                 port_type = CTL_PORT_SCSI;
10118
10119         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10120         cdb = (struct scsi_inquiry *)ctsio->cdb;
10121         alloc_len = scsi_2btoul(cdb->length);
10122
10123         /*
10124          * We malloc the full inquiry data size here and fill it
10125          * in.  If the user only asks for less, we'll give him
10126          * that much.
10127          */
10128         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10129         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10130         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10131         ctsio->kern_sg_entries = 0;
10132         ctsio->kern_data_resid = 0;
10133         ctsio->kern_rel_offset = 0;
10134
10135         if (data_len < alloc_len) {
10136                 ctsio->residual = alloc_len - data_len;
10137                 ctsio->kern_data_len = data_len;
10138                 ctsio->kern_total_len = data_len;
10139         } else {
10140                 ctsio->residual = 0;
10141                 ctsio->kern_data_len = alloc_len;
10142                 ctsio->kern_total_len = alloc_len;
10143         }
10144
10145         if (lun != NULL) {
10146                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10147                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10148                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10149                             lun->be_lun->lun_type;
10150                 } else {
10151                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10152                             lun->be_lun->lun_type;
10153                 }
10154                 if (lun->flags & CTL_LUN_REMOVABLE)
10155                         inq_ptr->dev_qual2 |= SID_RMB;
10156         } else
10157                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10158
10159         /* RMB in byte 2 is 0 */
10160         inq_ptr->version = SCSI_REV_SPC5;
10161
10162         /*
10163          * According to SAM-3, even if a device only supports a single
10164          * level of LUN addressing, it should still set the HISUP bit:
10165          *
10166          * 4.9.1 Logical unit numbers overview
10167          *
10168          * All logical unit number formats described in this standard are
10169          * hierarchical in structure even when only a single level in that
10170          * hierarchy is used. The HISUP bit shall be set to one in the
10171          * standard INQUIRY data (see SPC-2) when any logical unit number
10172          * format described in this standard is used.  Non-hierarchical
10173          * formats are outside the scope of this standard.
10174          *
10175          * Therefore we set the HiSup bit here.
10176          *
10177          * The response format is 2, per SPC-3.
10178          */
10179         inq_ptr->response_format = SID_HiSup | 2;
10180
10181         inq_ptr->additional_length = data_len -
10182             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10183         CTL_DEBUG_PRINT(("additional_length = %d\n",
10184                          inq_ptr->additional_length));
10185
10186         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10187         if (port_type == CTL_PORT_SCSI)
10188                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10189         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10190         inq_ptr->flags = SID_CmdQue;
10191         if (port_type == CTL_PORT_SCSI)
10192                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10193
10194         /*
10195          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10196          * We have 8 bytes for the vendor name, and 16 bytes for the device
10197          * name and 4 bytes for the revision.
10198          */
10199         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10200             "vendor")) == NULL) {
10201                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10202         } else {
10203                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10204                 strncpy(inq_ptr->vendor, val,
10205                     min(sizeof(inq_ptr->vendor), strlen(val)));
10206         }
10207         if (lun == NULL) {
10208                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10209                     sizeof(inq_ptr->product));
10210         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10211                 switch (lun->be_lun->lun_type) {
10212                 case T_DIRECT:
10213                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10214                             sizeof(inq_ptr->product));
10215                         break;
10216                 case T_PROCESSOR:
10217                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10218                             sizeof(inq_ptr->product));
10219                         break;
10220                 case T_CDROM:
10221                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10222                             sizeof(inq_ptr->product));
10223                         break;
10224                 default:
10225                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10226                             sizeof(inq_ptr->product));
10227                         break;
10228                 }
10229         } else {
10230                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10231                 strncpy(inq_ptr->product, val,
10232                     min(sizeof(inq_ptr->product), strlen(val)));
10233         }
10234
10235         /*
10236          * XXX make this a macro somewhere so it automatically gets
10237          * incremented when we make changes.
10238          */
10239         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10240             "revision")) == NULL) {
10241                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10242         } else {
10243                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10244                 strncpy(inq_ptr->revision, val,
10245                     min(sizeof(inq_ptr->revision), strlen(val)));
10246         }
10247
10248         /*
10249          * For parallel SCSI, we support double transition and single
10250          * transition clocking.  We also support QAS (Quick Arbitration
10251          * and Selection) and Information Unit transfers on both the
10252          * control and array devices.
10253          */
10254         if (port_type == CTL_PORT_SCSI)
10255                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10256                                     SID_SPI_IUS;
10257
10258         /* SAM-6 (no version claimed) */
10259         scsi_ulto2b(0x00C0, inq_ptr->version1);
10260         /* SPC-5 (no version claimed) */
10261         scsi_ulto2b(0x05C0, inq_ptr->version2);
10262         if (port_type == CTL_PORT_FC) {
10263                 /* FCP-2 ANSI INCITS.350:2003 */
10264                 scsi_ulto2b(0x0917, inq_ptr->version3);
10265         } else if (port_type == CTL_PORT_SCSI) {
10266                 /* SPI-4 ANSI INCITS.362:200x */
10267                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10268         } else if (port_type == CTL_PORT_ISCSI) {
10269                 /* iSCSI (no version claimed) */
10270                 scsi_ulto2b(0x0960, inq_ptr->version3);
10271         } else if (port_type == CTL_PORT_SAS) {
10272                 /* SAS (no version claimed) */
10273                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10274         }
10275
10276         if (lun == NULL) {
10277                 /* SBC-4 (no version claimed) */
10278                 scsi_ulto2b(0x0600, inq_ptr->version4);
10279         } else {
10280                 switch (lun->be_lun->lun_type) {
10281                 case T_DIRECT:
10282                         /* SBC-4 (no version claimed) */
10283                         scsi_ulto2b(0x0600, inq_ptr->version4);
10284                         break;
10285                 case T_PROCESSOR:
10286                         break;
10287                 case T_CDROM:
10288                         /* MMC-6 (no version claimed) */
10289                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10290                         break;
10291                 default:
10292                         break;
10293                 }
10294         }
10295
10296         ctl_set_success(ctsio);
10297         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10298         ctsio->be_move_done = ctl_config_move_done;
10299         ctl_datamove((union ctl_io *)ctsio);
10300         return (CTL_RETVAL_COMPLETE);
10301 }
10302
10303 int
10304 ctl_inquiry(struct ctl_scsiio *ctsio)
10305 {
10306         struct scsi_inquiry *cdb;
10307         int retval;
10308
10309         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10310
10311         cdb = (struct scsi_inquiry *)ctsio->cdb;
10312         if (cdb->byte2 & SI_EVPD)
10313                 retval = ctl_inquiry_evpd(ctsio);
10314         else if (cdb->page_code == 0)
10315                 retval = ctl_inquiry_std(ctsio);
10316         else {
10317                 ctl_set_invalid_field(ctsio,
10318                                       /*sks_valid*/ 1,
10319                                       /*command*/ 1,
10320                                       /*field*/ 2,
10321                                       /*bit_valid*/ 0,
10322                                       /*bit*/ 0);
10323                 ctl_done((union ctl_io *)ctsio);
10324                 return (CTL_RETVAL_COMPLETE);
10325         }
10326
10327         return (retval);
10328 }
10329
10330 int
10331 ctl_get_config(struct ctl_scsiio *ctsio)
10332 {
10333         struct scsi_get_config_header *hdr;
10334         struct scsi_get_config_feature *feature;
10335         struct scsi_get_config *cdb;
10336         struct ctl_lun *lun;
10337         uint32_t alloc_len, data_len;
10338         int rt, starting;
10339
10340         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10341         cdb = (struct scsi_get_config *)ctsio->cdb;
10342         rt = (cdb->rt & SGC_RT_MASK);
10343         starting = scsi_2btoul(cdb->starting_feature);
10344         alloc_len = scsi_2btoul(cdb->length);
10345
10346         data_len = sizeof(struct scsi_get_config_header) +
10347             sizeof(struct scsi_get_config_feature) + 8 +
10348             sizeof(struct scsi_get_config_feature) + 8 +
10349             sizeof(struct scsi_get_config_feature) + 4 +
10350             sizeof(struct scsi_get_config_feature) + 4 +
10351             sizeof(struct scsi_get_config_feature) + 8 +
10352             sizeof(struct scsi_get_config_feature) +
10353             sizeof(struct scsi_get_config_feature) + 4 +
10354             sizeof(struct scsi_get_config_feature) + 4 +
10355             sizeof(struct scsi_get_config_feature) + 4 +
10356             sizeof(struct scsi_get_config_feature) + 4 +
10357             sizeof(struct scsi_get_config_feature) + 4 +
10358             sizeof(struct scsi_get_config_feature) + 4;
10359         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10360         ctsio->kern_sg_entries = 0;
10361         ctsio->kern_data_resid = 0;
10362         ctsio->kern_rel_offset = 0;
10363
10364         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10365         if (lun->flags & CTL_LUN_NO_MEDIA)
10366                 scsi_ulto2b(0x0000, hdr->current_profile);
10367         else
10368                 scsi_ulto2b(0x0010, hdr->current_profile);
10369         feature = (struct scsi_get_config_feature *)(hdr + 1);
10370
10371         if (starting > 0x003b)
10372                 goto done;
10373         if (starting > 0x003a)
10374                 goto f3b;
10375         if (starting > 0x002b)
10376                 goto f3a;
10377         if (starting > 0x002a)
10378                 goto f2b;
10379         if (starting > 0x001f)
10380                 goto f2a;
10381         if (starting > 0x001e)
10382                 goto f1f;
10383         if (starting > 0x001d)
10384                 goto f1e;
10385         if (starting > 0x0010)
10386                 goto f1d;
10387         if (starting > 0x0003)
10388                 goto f10;
10389         if (starting > 0x0002)
10390                 goto f3;
10391         if (starting > 0x0001)
10392                 goto f2;
10393         if (starting > 0x0000)
10394                 goto f1;
10395
10396         /* Profile List */
10397         scsi_ulto2b(0x0000, feature->feature_code);
10398         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10399         feature->add_length = 8;
10400         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10401         feature->feature_data[2] = 0x00;
10402         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10403         feature->feature_data[6] = 0x01;
10404         feature = (struct scsi_get_config_feature *)
10405             &feature->feature_data[feature->add_length];
10406
10407 f1:     /* Core */
10408         scsi_ulto2b(0x0001, feature->feature_code);
10409         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10410         feature->add_length = 8;
10411         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10412         feature->feature_data[4] = 0x03;
10413         feature = (struct scsi_get_config_feature *)
10414             &feature->feature_data[feature->add_length];
10415
10416 f2:     /* Morphing */
10417         scsi_ulto2b(0x0002, feature->feature_code);
10418         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10419         feature->add_length = 4;
10420         feature->feature_data[0] = 0x02;
10421         feature = (struct scsi_get_config_feature *)
10422             &feature->feature_data[feature->add_length];
10423
10424 f3:     /* Removable Medium */
10425         scsi_ulto2b(0x0003, feature->feature_code);
10426         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10427         feature->add_length = 4;
10428         feature->feature_data[0] = 0x39;
10429         feature = (struct scsi_get_config_feature *)
10430             &feature->feature_data[feature->add_length];
10431
10432         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10433                 goto done;
10434
10435 f10:    /* Random Read */
10436         scsi_ulto2b(0x0010, feature->feature_code);
10437         feature->flags = 0x00;
10438         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10439                 feature->flags |= SGC_F_CURRENT;
10440         feature->add_length = 8;
10441         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10442         scsi_ulto2b(1, &feature->feature_data[4]);
10443         feature->feature_data[6] = 0x00;
10444         feature = (struct scsi_get_config_feature *)
10445             &feature->feature_data[feature->add_length];
10446
10447 f1d:    /* Multi-Read */
10448         scsi_ulto2b(0x001D, feature->feature_code);
10449         feature->flags = 0x00;
10450         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10451                 feature->flags |= SGC_F_CURRENT;
10452         feature->add_length = 0;
10453         feature = (struct scsi_get_config_feature *)
10454             &feature->feature_data[feature->add_length];
10455
10456 f1e:    /* CD Read */
10457         scsi_ulto2b(0x001E, feature->feature_code);
10458         feature->flags = 0x00;
10459         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10460                 feature->flags |= SGC_F_CURRENT;
10461         feature->add_length = 4;
10462         feature->feature_data[0] = 0x00;
10463         feature = (struct scsi_get_config_feature *)
10464             &feature->feature_data[feature->add_length];
10465
10466 f1f:    /* DVD Read */
10467         scsi_ulto2b(0x001F, feature->feature_code);
10468         feature->flags = 0x08;
10469         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10470                 feature->flags |= SGC_F_CURRENT;
10471         feature->add_length = 4;
10472         feature->feature_data[0] = 0x01;
10473         feature->feature_data[2] = 0x03;
10474         feature = (struct scsi_get_config_feature *)
10475             &feature->feature_data[feature->add_length];
10476
10477 f2a:    /* DVD+RW */
10478         scsi_ulto2b(0x002A, feature->feature_code);
10479         feature->flags = 0x04;
10480         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10481                 feature->flags |= SGC_F_CURRENT;
10482         feature->add_length = 4;
10483         feature->feature_data[0] = 0x00;
10484         feature->feature_data[1] = 0x00;
10485         feature = (struct scsi_get_config_feature *)
10486             &feature->feature_data[feature->add_length];
10487
10488 f2b:    /* DVD+R */
10489         scsi_ulto2b(0x002B, feature->feature_code);
10490         feature->flags = 0x00;
10491         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10492                 feature->flags |= SGC_F_CURRENT;
10493         feature->add_length = 4;
10494         feature->feature_data[0] = 0x00;
10495         feature = (struct scsi_get_config_feature *)
10496             &feature->feature_data[feature->add_length];
10497
10498 f3a:    /* DVD+RW Dual Layer */
10499         scsi_ulto2b(0x003A, feature->feature_code);
10500         feature->flags = 0x00;
10501         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10502                 feature->flags |= SGC_F_CURRENT;
10503         feature->add_length = 4;
10504         feature->feature_data[0] = 0x00;
10505         feature->feature_data[1] = 0x00;
10506         feature = (struct scsi_get_config_feature *)
10507             &feature->feature_data[feature->add_length];
10508
10509 f3b:    /* DVD+R Dual Layer */
10510         scsi_ulto2b(0x003B, feature->feature_code);
10511         feature->flags = 0x00;
10512         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10513                 feature->flags |= SGC_F_CURRENT;
10514         feature->add_length = 4;
10515         feature->feature_data[0] = 0x00;
10516         feature = (struct scsi_get_config_feature *)
10517             &feature->feature_data[feature->add_length];
10518
10519 done:
10520         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10521         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10522                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10523                 if (scsi_2btoul(feature->feature_code) == starting)
10524                         feature = (struct scsi_get_config_feature *)
10525                             &feature->feature_data[feature->add_length];
10526                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10527         }
10528         scsi_ulto4b(data_len - 4, hdr->data_length);
10529         if (data_len < alloc_len) {
10530                 ctsio->residual = alloc_len - data_len;
10531                 ctsio->kern_data_len = data_len;
10532                 ctsio->kern_total_len = data_len;
10533         } else {
10534                 ctsio->residual = 0;
10535                 ctsio->kern_data_len = alloc_len;
10536                 ctsio->kern_total_len = alloc_len;
10537         }
10538
10539         ctl_set_success(ctsio);
10540         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10541         ctsio->be_move_done = ctl_config_move_done;
10542         ctl_datamove((union ctl_io *)ctsio);
10543         return (CTL_RETVAL_COMPLETE);
10544 }
10545
10546 int
10547 ctl_get_event_status(struct ctl_scsiio *ctsio)
10548 {
10549         struct scsi_get_event_status_header *hdr;
10550         struct scsi_get_event_status *cdb;
10551         struct ctl_lun *lun;
10552         uint32_t alloc_len, data_len;
10553         int notif_class;
10554
10555         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10556         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10557         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10558                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10559                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10560                 ctl_done((union ctl_io *)ctsio);
10561                 return (CTL_RETVAL_COMPLETE);
10562         }
10563         notif_class = cdb->notif_class;
10564         alloc_len = scsi_2btoul(cdb->length);
10565
10566         data_len = sizeof(struct scsi_get_event_status_header);
10567         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10568         ctsio->kern_sg_entries = 0;
10569         ctsio->kern_data_resid = 0;
10570         ctsio->kern_rel_offset = 0;
10571
10572         if (data_len < alloc_len) {
10573                 ctsio->residual = alloc_len - data_len;
10574                 ctsio->kern_data_len = data_len;
10575                 ctsio->kern_total_len = data_len;
10576         } else {
10577                 ctsio->residual = 0;
10578                 ctsio->kern_data_len = alloc_len;
10579                 ctsio->kern_total_len = alloc_len;
10580         }
10581
10582         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10583         scsi_ulto2b(0, hdr->descr_length);
10584         hdr->nea_class = SGESN_NEA;
10585         hdr->supported_class = 0;
10586
10587         ctl_set_success(ctsio);
10588         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10589         ctsio->be_move_done = ctl_config_move_done;
10590         ctl_datamove((union ctl_io *)ctsio);
10591         return (CTL_RETVAL_COMPLETE);
10592 }
10593
10594 int
10595 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10596 {
10597         struct scsi_mechanism_status_header *hdr;
10598         struct scsi_mechanism_status *cdb;
10599         struct ctl_lun *lun;
10600         uint32_t alloc_len, data_len;
10601
10602         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10603         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10604         alloc_len = scsi_2btoul(cdb->length);
10605
10606         data_len = sizeof(struct scsi_mechanism_status_header);
10607         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10608         ctsio->kern_sg_entries = 0;
10609         ctsio->kern_data_resid = 0;
10610         ctsio->kern_rel_offset = 0;
10611
10612         if (data_len < alloc_len) {
10613                 ctsio->residual = alloc_len - data_len;
10614                 ctsio->kern_data_len = data_len;
10615                 ctsio->kern_total_len = data_len;
10616         } else {
10617                 ctsio->residual = 0;
10618                 ctsio->kern_data_len = alloc_len;
10619                 ctsio->kern_total_len = alloc_len;
10620         }
10621
10622         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10623         hdr->state1 = 0x00;
10624         hdr->state2 = 0xe0;
10625         scsi_ulto3b(0, hdr->lba);
10626         hdr->slots_num = 0;
10627         scsi_ulto2b(0, hdr->slots_length);
10628
10629         ctl_set_success(ctsio);
10630         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10631         ctsio->be_move_done = ctl_config_move_done;
10632         ctl_datamove((union ctl_io *)ctsio);
10633         return (CTL_RETVAL_COMPLETE);
10634 }
10635
10636 static void
10637 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10638 {
10639
10640         lba += 150;
10641         buf[0] = 0;
10642         buf[1] = bin2bcd((lba / 75) / 60);
10643         buf[2] = bin2bcd((lba / 75) % 60);
10644         buf[3] = bin2bcd(lba % 75);
10645 }
10646
10647 int
10648 ctl_read_toc(struct ctl_scsiio *ctsio)
10649 {
10650         struct scsi_read_toc_hdr *hdr;
10651         struct scsi_read_toc_type01_descr *descr;
10652         struct scsi_read_toc *cdb;
10653         struct ctl_lun *lun;
10654         uint32_t alloc_len, data_len;
10655         int format, msf;
10656
10657         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10658         cdb = (struct scsi_read_toc *)ctsio->cdb;
10659         msf = (cdb->byte2 & CD_MSF) != 0;
10660         format = cdb->format;
10661         alloc_len = scsi_2btoul(cdb->data_len);
10662
10663         data_len = sizeof(struct scsi_read_toc_hdr);
10664         if (format == 0)
10665                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10666         else
10667                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10668         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10669         ctsio->kern_sg_entries = 0;
10670         ctsio->kern_data_resid = 0;
10671         ctsio->kern_rel_offset = 0;
10672
10673         if (data_len < alloc_len) {
10674                 ctsio->residual = alloc_len - data_len;
10675                 ctsio->kern_data_len = data_len;
10676                 ctsio->kern_total_len = data_len;
10677         } else {
10678                 ctsio->residual = 0;
10679                 ctsio->kern_data_len = alloc_len;
10680                 ctsio->kern_total_len = alloc_len;
10681         }
10682
10683         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10684         if (format == 0) {
10685                 scsi_ulto2b(0x12, hdr->data_length);
10686                 hdr->first = 1;
10687                 hdr->last = 1;
10688                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10689                 descr->addr_ctl = 0x14;
10690                 descr->track_number = 1;
10691                 if (msf)
10692                         ctl_ultomsf(0, descr->track_start);
10693                 else
10694                         scsi_ulto4b(0, descr->track_start);
10695                 descr++;
10696                 descr->addr_ctl = 0x14;
10697                 descr->track_number = 0xaa;
10698                 if (msf)
10699                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10700                 else
10701                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10702         } else {
10703                 scsi_ulto2b(0x0a, hdr->data_length);
10704                 hdr->first = 1;
10705                 hdr->last = 1;
10706                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10707                 descr->addr_ctl = 0x14;
10708                 descr->track_number = 1;
10709                 if (msf)
10710                         ctl_ultomsf(0, descr->track_start);
10711                 else
10712                         scsi_ulto4b(0, descr->track_start);
10713         }
10714
10715         ctl_set_success(ctsio);
10716         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10717         ctsio->be_move_done = ctl_config_move_done;
10718         ctl_datamove((union ctl_io *)ctsio);
10719         return (CTL_RETVAL_COMPLETE);
10720 }
10721
10722 /*
10723  * For known CDB types, parse the LBA and length.
10724  */
10725 static int
10726 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10727 {
10728         if (io->io_hdr.io_type != CTL_IO_SCSI)
10729                 return (1);
10730
10731         switch (io->scsiio.cdb[0]) {
10732         case COMPARE_AND_WRITE: {
10733                 struct scsi_compare_and_write *cdb;
10734
10735                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10736
10737                 *lba = scsi_8btou64(cdb->addr);
10738                 *len = cdb->length;
10739                 break;
10740         }
10741         case READ_6:
10742         case WRITE_6: {
10743                 struct scsi_rw_6 *cdb;
10744
10745                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10746
10747                 *lba = scsi_3btoul(cdb->addr);
10748                 /* only 5 bits are valid in the most significant address byte */
10749                 *lba &= 0x1fffff;
10750                 *len = cdb->length;
10751                 break;
10752         }
10753         case READ_10:
10754         case WRITE_10: {
10755                 struct scsi_rw_10 *cdb;
10756
10757                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10758
10759                 *lba = scsi_4btoul(cdb->addr);
10760                 *len = scsi_2btoul(cdb->length);
10761                 break;
10762         }
10763         case WRITE_VERIFY_10: {
10764                 struct scsi_write_verify_10 *cdb;
10765
10766                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10767
10768                 *lba = scsi_4btoul(cdb->addr);
10769                 *len = scsi_2btoul(cdb->length);
10770                 break;
10771         }
10772         case READ_12:
10773         case WRITE_12: {
10774                 struct scsi_rw_12 *cdb;
10775
10776                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10777
10778                 *lba = scsi_4btoul(cdb->addr);
10779                 *len = scsi_4btoul(cdb->length);
10780                 break;
10781         }
10782         case WRITE_VERIFY_12: {
10783                 struct scsi_write_verify_12 *cdb;
10784
10785                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10786
10787                 *lba = scsi_4btoul(cdb->addr);
10788                 *len = scsi_4btoul(cdb->length);
10789                 break;
10790         }
10791         case READ_16:
10792         case WRITE_16: {
10793                 struct scsi_rw_16 *cdb;
10794
10795                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10796
10797                 *lba = scsi_8btou64(cdb->addr);
10798                 *len = scsi_4btoul(cdb->length);
10799                 break;
10800         }
10801         case WRITE_ATOMIC_16: {
10802                 struct scsi_write_atomic_16 *cdb;
10803
10804                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10805
10806                 *lba = scsi_8btou64(cdb->addr);
10807                 *len = scsi_2btoul(cdb->length);
10808                 break;
10809         }
10810         case WRITE_VERIFY_16: {
10811                 struct scsi_write_verify_16 *cdb;
10812
10813                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10814
10815                 *lba = scsi_8btou64(cdb->addr);
10816                 *len = scsi_4btoul(cdb->length);
10817                 break;
10818         }
10819         case WRITE_SAME_10: {
10820                 struct scsi_write_same_10 *cdb;
10821
10822                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10823
10824                 *lba = scsi_4btoul(cdb->addr);
10825                 *len = scsi_2btoul(cdb->length);
10826                 break;
10827         }
10828         case WRITE_SAME_16: {
10829                 struct scsi_write_same_16 *cdb;
10830
10831                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10832
10833                 *lba = scsi_8btou64(cdb->addr);
10834                 *len = scsi_4btoul(cdb->length);
10835                 break;
10836         }
10837         case VERIFY_10: {
10838                 struct scsi_verify_10 *cdb;
10839
10840                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10841
10842                 *lba = scsi_4btoul(cdb->addr);
10843                 *len = scsi_2btoul(cdb->length);
10844                 break;
10845         }
10846         case VERIFY_12: {
10847                 struct scsi_verify_12 *cdb;
10848
10849                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10850
10851                 *lba = scsi_4btoul(cdb->addr);
10852                 *len = scsi_4btoul(cdb->length);
10853                 break;
10854         }
10855         case VERIFY_16: {
10856                 struct scsi_verify_16 *cdb;
10857
10858                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10859
10860                 *lba = scsi_8btou64(cdb->addr);
10861                 *len = scsi_4btoul(cdb->length);
10862                 break;
10863         }
10864         case UNMAP: {
10865                 *lba = 0;
10866                 *len = UINT64_MAX;
10867                 break;
10868         }
10869         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10870                 struct scsi_get_lba_status *cdb;
10871
10872                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10873                 *lba = scsi_8btou64(cdb->addr);
10874                 *len = UINT32_MAX;
10875                 break;
10876         }
10877         default:
10878                 return (1);
10879                 break; /* NOTREACHED */
10880         }
10881
10882         return (0);
10883 }
10884
10885 static ctl_action
10886 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10887     bool seq)
10888 {
10889         uint64_t endlba1, endlba2;
10890
10891         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10892         endlba2 = lba2 + len2 - 1;
10893
10894         if ((endlba1 < lba2) || (endlba2 < lba1))
10895                 return (CTL_ACTION_PASS);
10896         else
10897                 return (CTL_ACTION_BLOCK);
10898 }
10899
10900 static int
10901 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10902 {
10903         struct ctl_ptr_len_flags *ptrlen;
10904         struct scsi_unmap_desc *buf, *end, *range;
10905         uint64_t lba;
10906         uint32_t len;
10907
10908         /* If not UNMAP -- go other way. */
10909         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10910             io->scsiio.cdb[0] != UNMAP)
10911                 return (CTL_ACTION_ERROR);
10912
10913         /* If UNMAP without data -- block and wait for data. */
10914         ptrlen = (struct ctl_ptr_len_flags *)
10915             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10916         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10917             ptrlen->ptr == NULL)
10918                 return (CTL_ACTION_BLOCK);
10919
10920         /* UNMAP with data -- check for collision. */
10921         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10922         end = buf + ptrlen->len / sizeof(*buf);
10923         for (range = buf; range < end; range++) {
10924                 lba = scsi_8btou64(range->lba);
10925                 len = scsi_4btoul(range->length);
10926                 if ((lba < lba2 + len2) && (lba + len > lba2))
10927                         return (CTL_ACTION_BLOCK);
10928         }
10929         return (CTL_ACTION_PASS);
10930 }
10931
10932 static ctl_action
10933 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10934 {
10935         uint64_t lba1, lba2;
10936         uint64_t len1, len2;
10937         int retval;
10938
10939         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10940                 return (CTL_ACTION_ERROR);
10941
10942         retval = ctl_extent_check_unmap(io1, lba2, len2);
10943         if (retval != CTL_ACTION_ERROR)
10944                 return (retval);
10945
10946         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10947                 return (CTL_ACTION_ERROR);
10948
10949         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10950                 seq = FALSE;
10951         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10952 }
10953
10954 static ctl_action
10955 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10956 {
10957         uint64_t lba1, lba2;
10958         uint64_t len1, len2;
10959
10960         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10961                 return (CTL_ACTION_PASS);
10962         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10963                 return (CTL_ACTION_ERROR);
10964         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10965                 return (CTL_ACTION_ERROR);
10966
10967         if (lba1 + len1 == lba2)
10968                 return (CTL_ACTION_BLOCK);
10969         return (CTL_ACTION_PASS);
10970 }
10971
10972 static ctl_action
10973 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10974     union ctl_io *ooa_io)
10975 {
10976         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10977         const ctl_serialize_action *serialize_row;
10978
10979         /*
10980          * The initiator attempted multiple untagged commands at the same
10981          * time.  Can't do that.
10982          */
10983         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10984          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10985          && ((pending_io->io_hdr.nexus.targ_port ==
10986               ooa_io->io_hdr.nexus.targ_port)
10987           && (pending_io->io_hdr.nexus.initid ==
10988               ooa_io->io_hdr.nexus.initid))
10989          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10990               CTL_FLAG_STATUS_SENT)) == 0))
10991                 return (CTL_ACTION_OVERLAP);
10992
10993         /*
10994          * The initiator attempted to send multiple tagged commands with
10995          * the same ID.  (It's fine if different initiators have the same
10996          * tag ID.)
10997          *
10998          * Even if all of those conditions are true, we don't kill the I/O
10999          * if the command ahead of us has been aborted.  We won't end up
11000          * sending it to the FETD, and it's perfectly legal to resend a
11001          * command with the same tag number as long as the previous
11002          * instance of this tag number has been aborted somehow.
11003          */
11004         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11005          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11006          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11007          && ((pending_io->io_hdr.nexus.targ_port ==
11008               ooa_io->io_hdr.nexus.targ_port)
11009           && (pending_io->io_hdr.nexus.initid ==
11010               ooa_io->io_hdr.nexus.initid))
11011          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11012               CTL_FLAG_STATUS_SENT)) == 0))
11013                 return (CTL_ACTION_OVERLAP_TAG);
11014
11015         /*
11016          * If we get a head of queue tag, SAM-3 says that we should
11017          * immediately execute it.
11018          *
11019          * What happens if this command would normally block for some other
11020          * reason?  e.g. a request sense with a head of queue tag
11021          * immediately after a write.  Normally that would block, but this
11022          * will result in its getting executed immediately...
11023          *
11024          * We currently return "pass" instead of "skip", so we'll end up
11025          * going through the rest of the queue to check for overlapped tags.
11026          *
11027          * XXX KDM check for other types of blockage first??
11028          */
11029         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11030                 return (CTL_ACTION_PASS);
11031
11032         /*
11033          * Ordered tags have to block until all items ahead of them
11034          * have completed.  If we get called with an ordered tag, we always
11035          * block, if something else is ahead of us in the queue.
11036          */
11037         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11038                 return (CTL_ACTION_BLOCK);
11039
11040         /*
11041          * Simple tags get blocked until all head of queue and ordered tags
11042          * ahead of them have completed.  I'm lumping untagged commands in
11043          * with simple tags here.  XXX KDM is that the right thing to do?
11044          */
11045         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11046           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11047          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11048           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11049                 return (CTL_ACTION_BLOCK);
11050
11051         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11052         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11053             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11054              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11055              pending_io->scsiio.cdb[1], pending_io));
11056         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11057         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11058                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11059         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11060             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11061              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11062              ooa_io->scsiio.cdb[1], ooa_io));
11063
11064         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11065
11066         switch (serialize_row[pending_entry->seridx]) {
11067         case CTL_SER_BLOCK:
11068                 return (CTL_ACTION_BLOCK);
11069         case CTL_SER_EXTENT:
11070                 return (ctl_extent_check(ooa_io, pending_io,
11071                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11072         case CTL_SER_EXTENTOPT:
11073                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11074                     SCP_QUEUE_ALG_UNRESTRICTED)
11075                         return (ctl_extent_check(ooa_io, pending_io,
11076                             (lun->be_lun &&
11077                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11078                 return (CTL_ACTION_PASS);
11079         case CTL_SER_EXTENTSEQ:
11080                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11081                         return (ctl_extent_check_seq(ooa_io, pending_io));
11082                 return (CTL_ACTION_PASS);
11083         case CTL_SER_PASS:
11084                 return (CTL_ACTION_PASS);
11085         case CTL_SER_BLOCKOPT:
11086                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11087                     SCP_QUEUE_ALG_UNRESTRICTED)
11088                         return (CTL_ACTION_BLOCK);
11089                 return (CTL_ACTION_PASS);
11090         case CTL_SER_SKIP:
11091                 return (CTL_ACTION_SKIP);
11092         default:
11093                 panic("%s: Invalid serialization value %d for %d => %d",
11094                     __func__, serialize_row[pending_entry->seridx],
11095                     pending_entry->seridx, ooa_entry->seridx);
11096         }
11097
11098         return (CTL_ACTION_ERROR);
11099 }
11100
11101 /*
11102  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11103  * Assumptions:
11104  * - pending_io is generally either incoming, or on the blocked queue
11105  * - starting I/O is the I/O we want to start the check with.
11106  */
11107 static ctl_action
11108 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11109               union ctl_io *starting_io)
11110 {
11111         union ctl_io *ooa_io;
11112         ctl_action action;
11113
11114         mtx_assert(&lun->lun_lock, MA_OWNED);
11115
11116         /*
11117          * Run back along the OOA queue, starting with the current
11118          * blocked I/O and going through every I/O before it on the
11119          * queue.  If starting_io is NULL, we'll just end up returning
11120          * CTL_ACTION_PASS.
11121          */
11122         for (ooa_io = starting_io; ooa_io != NULL;
11123              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11124              ooa_links)){
11125
11126                 /*
11127                  * This routine just checks to see whether
11128                  * cur_blocked is blocked by ooa_io, which is ahead
11129                  * of it in the queue.  It doesn't queue/dequeue
11130                  * cur_blocked.
11131                  */
11132                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11133                 switch (action) {
11134                 case CTL_ACTION_BLOCK:
11135                 case CTL_ACTION_OVERLAP:
11136                 case CTL_ACTION_OVERLAP_TAG:
11137                 case CTL_ACTION_SKIP:
11138                 case CTL_ACTION_ERROR:
11139                         return (action);
11140                         break; /* NOTREACHED */
11141                 case CTL_ACTION_PASS:
11142                         break;
11143                 default:
11144                         panic("%s: Invalid action %d\n", __func__, action);
11145                 }
11146         }
11147
11148         return (CTL_ACTION_PASS);
11149 }
11150
11151 /*
11152  * Assumptions:
11153  * - An I/O has just completed, and has been removed from the per-LUN OOA
11154  *   queue, so some items on the blocked queue may now be unblocked.
11155  */
11156 static int
11157 ctl_check_blocked(struct ctl_lun *lun)
11158 {
11159         struct ctl_softc *softc = lun->ctl_softc;
11160         union ctl_io *cur_blocked, *next_blocked;
11161
11162         mtx_assert(&lun->lun_lock, MA_OWNED);
11163
11164         /*
11165          * Run forward from the head of the blocked queue, checking each
11166          * entry against the I/Os prior to it on the OOA queue to see if
11167          * there is still any blockage.
11168          *
11169          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11170          * with our removing a variable on it while it is traversing the
11171          * list.
11172          */
11173         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11174              cur_blocked != NULL; cur_blocked = next_blocked) {
11175                 union ctl_io *prev_ooa;
11176                 ctl_action action;
11177
11178                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11179                                                           blocked_links);
11180
11181                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11182                                                       ctl_ooaq, ooa_links);
11183
11184                 /*
11185                  * If cur_blocked happens to be the first item in the OOA
11186                  * queue now, prev_ooa will be NULL, and the action
11187                  * returned will just be CTL_ACTION_PASS.
11188                  */
11189                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11190
11191                 switch (action) {
11192                 case CTL_ACTION_BLOCK:
11193                         /* Nothing to do here, still blocked */
11194                         break;
11195                 case CTL_ACTION_OVERLAP:
11196                 case CTL_ACTION_OVERLAP_TAG:
11197                         /*
11198                          * This shouldn't happen!  In theory we've already
11199                          * checked this command for overlap...
11200                          */
11201                         break;
11202                 case CTL_ACTION_PASS:
11203                 case CTL_ACTION_SKIP: {
11204                         const struct ctl_cmd_entry *entry;
11205
11206                         /*
11207                          * The skip case shouldn't happen, this transaction
11208                          * should have never made it onto the blocked queue.
11209                          */
11210                         /*
11211                          * This I/O is no longer blocked, we can remove it
11212                          * from the blocked queue.  Since this is a TAILQ
11213                          * (doubly linked list), we can do O(1) removals
11214                          * from any place on the list.
11215                          */
11216                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11217                                      blocked_links);
11218                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11219
11220                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11221                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11222                                 /*
11223                                  * Need to send IO back to original side to
11224                                  * run
11225                                  */
11226                                 union ctl_ha_msg msg_info;
11227
11228                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11229                                 msg_info.hdr.original_sc =
11230                                         cur_blocked->io_hdr.original_sc;
11231                                 msg_info.hdr.serializing_sc = cur_blocked;
11232                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11233                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11234                                     sizeof(msg_info.hdr), M_NOWAIT);
11235                                 break;
11236                         }
11237                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11238
11239                         /*
11240                          * Check this I/O for LUN state changes that may
11241                          * have happened while this command was blocked.
11242                          * The LUN state may have been changed by a command
11243                          * ahead of us in the queue, so we need to re-check
11244                          * for any states that can be caused by SCSI
11245                          * commands.
11246                          */
11247                         if (ctl_scsiio_lun_check(lun, entry,
11248                                                  &cur_blocked->scsiio) == 0) {
11249                                 cur_blocked->io_hdr.flags |=
11250                                                       CTL_FLAG_IS_WAS_ON_RTR;
11251                                 ctl_enqueue_rtr(cur_blocked);
11252                         } else
11253                                 ctl_done(cur_blocked);
11254                         break;
11255                 }
11256                 default:
11257                         /*
11258                          * This probably shouldn't happen -- we shouldn't
11259                          * get CTL_ACTION_ERROR, or anything else.
11260                          */
11261                         break;
11262                 }
11263         }
11264
11265         return (CTL_RETVAL_COMPLETE);
11266 }
11267
11268 /*
11269  * This routine (with one exception) checks LUN flags that can be set by
11270  * commands ahead of us in the OOA queue.  These flags have to be checked
11271  * when a command initially comes in, and when we pull a command off the
11272  * blocked queue and are preparing to execute it.  The reason we have to
11273  * check these flags for commands on the blocked queue is that the LUN
11274  * state may have been changed by a command ahead of us while we're on the
11275  * blocked queue.
11276  *
11277  * Ordering is somewhat important with these checks, so please pay
11278  * careful attention to the placement of any new checks.
11279  */
11280 static int
11281 ctl_scsiio_lun_check(struct ctl_lun *lun,
11282     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11283 {
11284         struct ctl_softc *softc = lun->ctl_softc;
11285         int retval;
11286         uint32_t residx;
11287
11288         retval = 0;
11289
11290         mtx_assert(&lun->lun_lock, MA_OWNED);
11291
11292         /*
11293          * If this shelf is a secondary shelf controller, we may have to
11294          * reject some commands disallowed by HA mode and link state.
11295          */
11296         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11297                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11298                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11299                         ctl_set_lun_unavail(ctsio);
11300                         retval = 1;
11301                         goto bailout;
11302                 }
11303                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11304                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11305                         ctl_set_lun_transit(ctsio);
11306                         retval = 1;
11307                         goto bailout;
11308                 }
11309                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11310                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11311                         ctl_set_lun_standby(ctsio);
11312                         retval = 1;
11313                         goto bailout;
11314                 }
11315
11316                 /* The rest of checks are only done on executing side */
11317                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11318                         goto bailout;
11319         }
11320
11321         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11322                 if (lun->be_lun &&
11323                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11324                         ctl_set_hw_write_protected(ctsio);
11325                         retval = 1;
11326                         goto bailout;
11327                 }
11328                 if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11329                         ctl_set_sense(ctsio, /*current_error*/ 1,
11330                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11331                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11332                         retval = 1;
11333                         goto bailout;
11334                 }
11335         }
11336
11337         /*
11338          * Check for a reservation conflict.  If this command isn't allowed
11339          * even on reserved LUNs, and if this initiator isn't the one who
11340          * reserved us, reject the command with a reservation conflict.
11341          */
11342         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11343         if ((lun->flags & CTL_LUN_RESERVED)
11344          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11345                 if (lun->res_idx != residx) {
11346                         ctl_set_reservation_conflict(ctsio);
11347                         retval = 1;
11348                         goto bailout;
11349                 }
11350         }
11351
11352         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11353             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11354                 /* No reservation or command is allowed. */;
11355         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11356             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11357              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11358              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11359                 /* The command is allowed for Write Exclusive resv. */;
11360         } else {
11361                 /*
11362                  * if we aren't registered or it's a res holder type
11363                  * reservation and this isn't the res holder then set a
11364                  * conflict.
11365                  */
11366                 if (ctl_get_prkey(lun, residx) == 0 ||
11367                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11368                         ctl_set_reservation_conflict(ctsio);
11369                         retval = 1;
11370                         goto bailout;
11371                 }
11372         }
11373
11374         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11375                 if (lun->flags & CTL_LUN_EJECTED)
11376                         ctl_set_lun_ejected(ctsio);
11377                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11378                         if (lun->flags & CTL_LUN_REMOVABLE)
11379                                 ctl_set_lun_no_media(ctsio);
11380                         else
11381                                 ctl_set_lun_int_reqd(ctsio);
11382                 } else if (lun->flags & CTL_LUN_STOPPED)
11383                         ctl_set_lun_stopped(ctsio);
11384                 else
11385                         goto bailout;
11386                 retval = 1;
11387                 goto bailout;
11388         }
11389
11390 bailout:
11391         return (retval);
11392 }
11393
11394 static void
11395 ctl_failover_io(union ctl_io *io, int have_lock)
11396 {
11397         ctl_set_busy(&io->scsiio);
11398         ctl_done(io);
11399 }
11400
11401 static void
11402 ctl_failover_lun(union ctl_io *rio)
11403 {
11404         struct ctl_softc *softc = control_softc;
11405         struct ctl_lun *lun;
11406         struct ctl_io_hdr *io, *next_io;
11407         uint32_t targ_lun;
11408
11409         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11410         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11411
11412         /* Find and lock the LUN. */
11413         mtx_lock(&softc->ctl_lock);
11414         if (targ_lun > CTL_MAX_LUNS ||
11415             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11416                 mtx_unlock(&softc->ctl_lock);
11417                 return;
11418         }
11419         mtx_lock(&lun->lun_lock);
11420         mtx_unlock(&softc->ctl_lock);
11421         if (lun->flags & CTL_LUN_DISABLED) {
11422                 mtx_unlock(&lun->lun_lock);
11423                 return;
11424         }
11425
11426         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11427                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11428                         /* We are master */
11429                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11430                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11431                                         io->flags |= CTL_FLAG_ABORT;
11432                                         io->flags |= CTL_FLAG_FAILOVER;
11433                                 } else { /* This can be only due to DATAMOVE */
11434                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11435                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11436                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11437                                         io->port_status = 31340;
11438                                         ctl_enqueue_isc((union ctl_io *)io);
11439                                 }
11440                         }
11441                         /* We are slave */
11442                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11443                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11444                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11445                                         io->flags |= CTL_FLAG_FAILOVER;
11446                                 } else {
11447                                         ctl_set_busy(&((union ctl_io *)io)->
11448                                             scsiio);
11449                                         ctl_done((union ctl_io *)io);
11450                                 }
11451                         }
11452                 }
11453         } else { /* SERIALIZE modes */
11454                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11455                     next_io) {
11456                         /* We are master */
11457                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11458                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11459                                     blocked_links);
11460                                 io->flags &= ~CTL_FLAG_BLOCKED;
11461                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11462                                 ctl_free_io((union ctl_io *)io);
11463                         }
11464                 }
11465                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11466                         /* We are master */
11467                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11468                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11469                                 ctl_free_io((union ctl_io *)io);
11470                         }
11471                         /* We are slave */
11472                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11473                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11474                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11475                                         ctl_set_busy(&((union ctl_io *)io)->
11476                                             scsiio);
11477                                         ctl_done((union ctl_io *)io);
11478                                 }
11479                         }
11480                 }
11481                 ctl_check_blocked(lun);
11482         }
11483         mtx_unlock(&lun->lun_lock);
11484 }
11485
11486 static int
11487 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11488 {
11489         struct ctl_lun *lun;
11490         const struct ctl_cmd_entry *entry;
11491         uint32_t initidx, targ_lun;
11492         int retval = 0;
11493
11494         lun = NULL;
11495         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11496         if (targ_lun < CTL_MAX_LUNS)
11497                 lun = softc->ctl_luns[targ_lun];
11498         if (lun) {
11499                 /*
11500                  * If the LUN is invalid, pretend that it doesn't exist.
11501                  * It will go away as soon as all pending I/O has been
11502                  * completed.
11503                  */
11504                 mtx_lock(&lun->lun_lock);
11505                 if (lun->flags & CTL_LUN_DISABLED) {
11506                         mtx_unlock(&lun->lun_lock);
11507                         lun = NULL;
11508                 }
11509         }
11510         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11511         if (lun) {
11512                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11513                     lun->be_lun;
11514
11515                 /*
11516                  * Every I/O goes into the OOA queue for a particular LUN,
11517                  * and stays there until completion.
11518                  */
11519 #ifdef CTL_TIME_IO
11520                 if (TAILQ_EMPTY(&lun->ooa_queue))
11521                         lun->idle_time += getsbinuptime() - lun->last_busy;
11522 #endif
11523                 TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11524         }
11525
11526         /* Get command entry and return error if it is unsuppotyed. */
11527         entry = ctl_validate_command(ctsio);
11528         if (entry == NULL) {
11529                 if (lun)
11530                         mtx_unlock(&lun->lun_lock);
11531                 return (retval);
11532         }
11533
11534         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11535         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11536
11537         /*
11538          * Check to see whether we can send this command to LUNs that don't
11539          * exist.  This should pretty much only be the case for inquiry
11540          * and request sense.  Further checks, below, really require having
11541          * a LUN, so we can't really check the command anymore.  Just put
11542          * it on the rtr queue.
11543          */
11544         if (lun == NULL) {
11545                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11546                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11547                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11548                         return (retval);
11549                 }
11550
11551                 ctl_set_unsupported_lun(ctsio);
11552                 ctl_done((union ctl_io *)ctsio);
11553                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11554                 return (retval);
11555         } else {
11556                 /*
11557                  * Make sure we support this particular command on this LUN.
11558                  * e.g., we don't support writes to the control LUN.
11559                  */
11560                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11561                         mtx_unlock(&lun->lun_lock);
11562                         ctl_set_invalid_opcode(ctsio);
11563                         ctl_done((union ctl_io *)ctsio);
11564                         return (retval);
11565                 }
11566         }
11567
11568         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11569
11570 #ifdef CTL_WITH_CA
11571         /*
11572          * If we've got a request sense, it'll clear the contingent
11573          * allegiance condition.  Otherwise, if we have a CA condition for
11574          * this initiator, clear it, because it sent down a command other
11575          * than request sense.
11576          */
11577         if ((ctsio->cdb[0] != REQUEST_SENSE)
11578          && (ctl_is_set(lun->have_ca, initidx)))
11579                 ctl_clear_mask(lun->have_ca, initidx);
11580 #endif
11581
11582         /*
11583          * If the command has this flag set, it handles its own unit
11584          * attention reporting, we shouldn't do anything.  Otherwise we
11585          * check for any pending unit attentions, and send them back to the
11586          * initiator.  We only do this when a command initially comes in,
11587          * not when we pull it off the blocked queue.
11588          *
11589          * According to SAM-3, section 5.3.2, the order that things get
11590          * presented back to the host is basically unit attentions caused
11591          * by some sort of reset event, busy status, reservation conflicts
11592          * or task set full, and finally any other status.
11593          *
11594          * One issue here is that some of the unit attentions we report
11595          * don't fall into the "reset" category (e.g. "reported luns data
11596          * has changed").  So reporting it here, before the reservation
11597          * check, may be technically wrong.  I guess the only thing to do
11598          * would be to check for and report the reset events here, and then
11599          * check for the other unit attention types after we check for a
11600          * reservation conflict.
11601          *
11602          * XXX KDM need to fix this
11603          */
11604         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11605                 ctl_ua_type ua_type;
11606                 u_int sense_len = 0;
11607
11608                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11609                     &sense_len, SSD_TYPE_NONE);
11610                 if (ua_type != CTL_UA_NONE) {
11611                         mtx_unlock(&lun->lun_lock);
11612                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11613                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11614                         ctsio->sense_len = sense_len;
11615                         ctl_done((union ctl_io *)ctsio);
11616                         return (retval);
11617                 }
11618         }
11619
11620
11621         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11622                 mtx_unlock(&lun->lun_lock);
11623                 ctl_done((union ctl_io *)ctsio);
11624                 return (retval);
11625         }
11626
11627         /*
11628          * XXX CHD this is where we want to send IO to other side if
11629          * this LUN is secondary on this SC. We will need to make a copy
11630          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11631          * the copy we send as FROM_OTHER.
11632          * We also need to stuff the address of the original IO so we can
11633          * find it easily. Something similar will need be done on the other
11634          * side so when we are done we can find the copy.
11635          */
11636         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11637             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11638             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11639                 union ctl_ha_msg msg_info;
11640                 int isc_retval;
11641
11642                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11643                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11644                 mtx_unlock(&lun->lun_lock);
11645
11646                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11647                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11648                 msg_info.hdr.serializing_sc = NULL;
11649                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11650                 msg_info.scsi.tag_num = ctsio->tag_num;
11651                 msg_info.scsi.tag_type = ctsio->tag_type;
11652                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11653                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11654
11655                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11656                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11657                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11658                         ctl_set_busy(ctsio);
11659                         ctl_done((union ctl_io *)ctsio);
11660                         return (retval);
11661                 }
11662                 return (retval);
11663         }
11664
11665         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11666                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11667                               ctl_ooaq, ooa_links))) {
11668         case CTL_ACTION_BLOCK:
11669                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11670                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11671                                   blocked_links);
11672                 mtx_unlock(&lun->lun_lock);
11673                 return (retval);
11674         case CTL_ACTION_PASS:
11675         case CTL_ACTION_SKIP:
11676                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11677                 mtx_unlock(&lun->lun_lock);
11678                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11679                 break;
11680         case CTL_ACTION_OVERLAP:
11681                 mtx_unlock(&lun->lun_lock);
11682                 ctl_set_overlapped_cmd(ctsio);
11683                 ctl_done((union ctl_io *)ctsio);
11684                 break;
11685         case CTL_ACTION_OVERLAP_TAG:
11686                 mtx_unlock(&lun->lun_lock);
11687                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11688                 ctl_done((union ctl_io *)ctsio);
11689                 break;
11690         case CTL_ACTION_ERROR:
11691         default:
11692                 mtx_unlock(&lun->lun_lock);
11693                 ctl_set_internal_failure(ctsio,
11694                                          /*sks_valid*/ 0,
11695                                          /*retry_count*/ 0);
11696                 ctl_done((union ctl_io *)ctsio);
11697                 break;
11698         }
11699         return (retval);
11700 }
11701
11702 const struct ctl_cmd_entry *
11703 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11704 {
11705         const struct ctl_cmd_entry *entry;
11706         int service_action;
11707
11708         entry = &ctl_cmd_table[ctsio->cdb[0]];
11709         if (sa)
11710                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11711         if (entry->flags & CTL_CMD_FLAG_SA5) {
11712                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11713                 entry = &((const struct ctl_cmd_entry *)
11714                     entry->execute)[service_action];
11715         }
11716         return (entry);
11717 }
11718
11719 const struct ctl_cmd_entry *
11720 ctl_validate_command(struct ctl_scsiio *ctsio)
11721 {
11722         const struct ctl_cmd_entry *entry;
11723         int i, sa;
11724         uint8_t diff;
11725
11726         entry = ctl_get_cmd_entry(ctsio, &sa);
11727         if (entry->execute == NULL) {
11728                 if (sa)
11729                         ctl_set_invalid_field(ctsio,
11730                                               /*sks_valid*/ 1,
11731                                               /*command*/ 1,
11732                                               /*field*/ 1,
11733                                               /*bit_valid*/ 1,
11734                                               /*bit*/ 4);
11735                 else
11736                         ctl_set_invalid_opcode(ctsio);
11737                 ctl_done((union ctl_io *)ctsio);
11738                 return (NULL);
11739         }
11740         KASSERT(entry->length > 0,
11741             ("Not defined length for command 0x%02x/0x%02x",
11742              ctsio->cdb[0], ctsio->cdb[1]));
11743         for (i = 1; i < entry->length; i++) {
11744                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11745                 if (diff == 0)
11746                         continue;
11747                 ctl_set_invalid_field(ctsio,
11748                                       /*sks_valid*/ 1,
11749                                       /*command*/ 1,
11750                                       /*field*/ i,
11751                                       /*bit_valid*/ 1,
11752                                       /*bit*/ fls(diff) - 1);
11753                 ctl_done((union ctl_io *)ctsio);
11754                 return (NULL);
11755         }
11756         return (entry);
11757 }
11758
11759 static int
11760 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11761 {
11762
11763         switch (lun_type) {
11764         case T_DIRECT:
11765                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11766                         return (0);
11767                 break;
11768         case T_PROCESSOR:
11769                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11770                         return (0);
11771                 break;
11772         case T_CDROM:
11773                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11774                         return (0);
11775                 break;
11776         default:
11777                 return (0);
11778         }
11779         return (1);
11780 }
11781
11782 static int
11783 ctl_scsiio(struct ctl_scsiio *ctsio)
11784 {
11785         int retval;
11786         const struct ctl_cmd_entry *entry;
11787
11788         retval = CTL_RETVAL_COMPLETE;
11789
11790         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11791
11792         entry = ctl_get_cmd_entry(ctsio, NULL);
11793
11794         /*
11795          * If this I/O has been aborted, just send it straight to
11796          * ctl_done() without executing it.
11797          */
11798         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11799                 ctl_done((union ctl_io *)ctsio);
11800                 goto bailout;
11801         }
11802
11803         /*
11804          * All the checks should have been handled by ctl_scsiio_precheck().
11805          * We should be clear now to just execute the I/O.
11806          */
11807         retval = entry->execute(ctsio);
11808
11809 bailout:
11810         return (retval);
11811 }
11812
11813 /*
11814  * Since we only implement one target right now, a bus reset simply resets
11815  * our single target.
11816  */
11817 static int
11818 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11819 {
11820         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11821 }
11822
11823 static int
11824 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11825                  ctl_ua_type ua_type)
11826 {
11827         struct ctl_port *port;
11828         struct ctl_lun *lun;
11829         int retval;
11830
11831         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11832                 union ctl_ha_msg msg_info;
11833
11834                 msg_info.hdr.nexus = io->io_hdr.nexus;
11835                 if (ua_type==CTL_UA_TARG_RESET)
11836                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11837                 else
11838                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11839                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11840                 msg_info.hdr.original_sc = NULL;
11841                 msg_info.hdr.serializing_sc = NULL;
11842                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11843                     sizeof(msg_info.task), M_WAITOK);
11844         }
11845         retval = 0;
11846
11847         mtx_lock(&softc->ctl_lock);
11848         port = ctl_io_port(&io->io_hdr);
11849         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11850                 if (port != NULL &&
11851                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11852                         continue;
11853                 retval += ctl_do_lun_reset(lun, io, ua_type);
11854         }
11855         mtx_unlock(&softc->ctl_lock);
11856         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11857         return (retval);
11858 }
11859
11860 /*
11861  * The LUN should always be set.  The I/O is optional, and is used to
11862  * distinguish between I/Os sent by this initiator, and by other
11863  * initiators.  We set unit attention for initiators other than this one.
11864  * SAM-3 is vague on this point.  It does say that a unit attention should
11865  * be established for other initiators when a LUN is reset (see section
11866  * 5.7.3), but it doesn't specifically say that the unit attention should
11867  * be established for this particular initiator when a LUN is reset.  Here
11868  * is the relevant text, from SAM-3 rev 8:
11869  *
11870  * 5.7.2 When a SCSI initiator port aborts its own tasks
11871  *
11872  * When a SCSI initiator port causes its own task(s) to be aborted, no
11873  * notification that the task(s) have been aborted shall be returned to
11874  * the SCSI initiator port other than the completion response for the
11875  * command or task management function action that caused the task(s) to
11876  * be aborted and notification(s) associated with related effects of the
11877  * action (e.g., a reset unit attention condition).
11878  *
11879  * XXX KDM for now, we're setting unit attention for all initiators.
11880  */
11881 static int
11882 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11883 {
11884         union ctl_io *xio;
11885 #if 0
11886         uint32_t initidx;
11887 #endif
11888         int i;
11889
11890         mtx_lock(&lun->lun_lock);
11891         /*
11892          * Run through the OOA queue and abort each I/O.
11893          */
11894         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11895              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11896                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11897         }
11898
11899         /*
11900          * This version sets unit attention for every
11901          */
11902 #if 0
11903         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11904         ctl_est_ua_all(lun, initidx, ua_type);
11905 #else
11906         ctl_est_ua_all(lun, -1, ua_type);
11907 #endif
11908
11909         /*
11910          * A reset (any kind, really) clears reservations established with
11911          * RESERVE/RELEASE.  It does not clear reservations established
11912          * with PERSISTENT RESERVE OUT, but we don't support that at the
11913          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11914          * reservations made with the RESERVE/RELEASE commands, because
11915          * those commands are obsolete in SPC-3.
11916          */
11917         lun->flags &= ~CTL_LUN_RESERVED;
11918
11919 #ifdef CTL_WITH_CA
11920         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11921                 ctl_clear_mask(lun->have_ca, i);
11922 #endif
11923         lun->prevent_count = 0;
11924         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11925                 ctl_clear_mask(lun->prevent, i);
11926         mtx_unlock(&lun->lun_lock);
11927
11928         return (0);
11929 }
11930
11931 static int
11932 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11933 {
11934         struct ctl_lun *lun;
11935         uint32_t targ_lun;
11936         int retval;
11937
11938         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11939         mtx_lock(&softc->ctl_lock);
11940         if (targ_lun >= CTL_MAX_LUNS ||
11941             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11942                 mtx_unlock(&softc->ctl_lock);
11943                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11944                 return (1);
11945         }
11946         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11947         mtx_unlock(&softc->ctl_lock);
11948         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11949
11950         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11951                 union ctl_ha_msg msg_info;
11952
11953                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11954                 msg_info.hdr.nexus = io->io_hdr.nexus;
11955                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11956                 msg_info.hdr.original_sc = NULL;
11957                 msg_info.hdr.serializing_sc = NULL;
11958                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11959                     sizeof(msg_info.task), M_WAITOK);
11960         }
11961         return (retval);
11962 }
11963
11964 static void
11965 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11966     int other_sc)
11967 {
11968         union ctl_io *xio;
11969
11970         mtx_assert(&lun->lun_lock, MA_OWNED);
11971
11972         /*
11973          * Run through the OOA queue and attempt to find the given I/O.
11974          * The target port, initiator ID, tag type and tag number have to
11975          * match the values that we got from the initiator.  If we have an
11976          * untagged command to abort, simply abort the first untagged command
11977          * we come to.  We only allow one untagged command at a time of course.
11978          */
11979         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11980              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11981
11982                 if ((targ_port == UINT32_MAX ||
11983                      targ_port == xio->io_hdr.nexus.targ_port) &&
11984                     (init_id == UINT32_MAX ||
11985                      init_id == xio->io_hdr.nexus.initid)) {
11986                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11987                             init_id != xio->io_hdr.nexus.initid)
11988                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11989                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11990                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11991                                 union ctl_ha_msg msg_info;
11992
11993                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11994                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11995                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11996                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11997                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11998                                 msg_info.hdr.original_sc = NULL;
11999                                 msg_info.hdr.serializing_sc = NULL;
12000                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12001                                     sizeof(msg_info.task), M_NOWAIT);
12002                         }
12003                 }
12004         }
12005 }
12006
12007 static int
12008 ctl_abort_task_set(union ctl_io *io)
12009 {
12010         struct ctl_softc *softc = control_softc;
12011         struct ctl_lun *lun;
12012         uint32_t targ_lun;
12013
12014         /*
12015          * Look up the LUN.
12016          */
12017         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12018         mtx_lock(&softc->ctl_lock);
12019         if (targ_lun >= CTL_MAX_LUNS ||
12020             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12021                 mtx_unlock(&softc->ctl_lock);
12022                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12023                 return (1);
12024         }
12025
12026         mtx_lock(&lun->lun_lock);
12027         mtx_unlock(&softc->ctl_lock);
12028         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12029                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12030                     io->io_hdr.nexus.initid,
12031                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12032         } else { /* CTL_TASK_CLEAR_TASK_SET */
12033                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12034                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12035         }
12036         mtx_unlock(&lun->lun_lock);
12037         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12038         return (0);
12039 }
12040
12041 static int
12042 ctl_i_t_nexus_reset(union ctl_io *io)
12043 {
12044         struct ctl_softc *softc = control_softc;
12045         struct ctl_lun *lun;
12046         uint32_t initidx;
12047
12048         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12049                 union ctl_ha_msg msg_info;
12050
12051                 msg_info.hdr.nexus = io->io_hdr.nexus;
12052                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12053                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12054                 msg_info.hdr.original_sc = NULL;
12055                 msg_info.hdr.serializing_sc = NULL;
12056                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12057                     sizeof(msg_info.task), M_WAITOK);
12058         }
12059
12060         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12061         mtx_lock(&softc->ctl_lock);
12062         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12063                 mtx_lock(&lun->lun_lock);
12064                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12065                     io->io_hdr.nexus.initid, 1);
12066 #ifdef CTL_WITH_CA
12067                 ctl_clear_mask(lun->have_ca, initidx);
12068 #endif
12069                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12070                         lun->flags &= ~CTL_LUN_RESERVED;
12071                 if (ctl_is_set(lun->prevent, initidx)) {
12072                         ctl_clear_mask(lun->prevent, initidx);
12073                         lun->prevent_count--;
12074                 }
12075                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12076                 mtx_unlock(&lun->lun_lock);
12077         }
12078         mtx_unlock(&softc->ctl_lock);
12079         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12080         return (0);
12081 }
12082
12083 static int
12084 ctl_abort_task(union ctl_io *io)
12085 {
12086         union ctl_io *xio;
12087         struct ctl_lun *lun;
12088         struct ctl_softc *softc;
12089 #if 0
12090         struct sbuf sb;
12091         char printbuf[128];
12092 #endif
12093         int found;
12094         uint32_t targ_lun;
12095
12096         softc = control_softc;
12097         found = 0;
12098
12099         /*
12100          * Look up the LUN.
12101          */
12102         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12103         mtx_lock(&softc->ctl_lock);
12104         if (targ_lun >= CTL_MAX_LUNS ||
12105             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12106                 mtx_unlock(&softc->ctl_lock);
12107                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12108                 return (1);
12109         }
12110
12111 #if 0
12112         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12113                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12114 #endif
12115
12116         mtx_lock(&lun->lun_lock);
12117         mtx_unlock(&softc->ctl_lock);
12118         /*
12119          * Run through the OOA queue and attempt to find the given I/O.
12120          * The target port, initiator ID, tag type and tag number have to
12121          * match the values that we got from the initiator.  If we have an
12122          * untagged command to abort, simply abort the first untagged command
12123          * we come to.  We only allow one untagged command at a time of course.
12124          */
12125         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12126              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12127 #if 0
12128                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12129
12130                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12131                             lun->lun, xio->scsiio.tag_num,
12132                             xio->scsiio.tag_type,
12133                             (xio->io_hdr.blocked_links.tqe_prev
12134                             == NULL) ? "" : " BLOCKED",
12135                             (xio->io_hdr.flags &
12136                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12137                             (xio->io_hdr.flags &
12138                             CTL_FLAG_ABORT) ? " ABORT" : "",
12139                             (xio->io_hdr.flags &
12140                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12141                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12142                 sbuf_finish(&sb);
12143                 printf("%s\n", sbuf_data(&sb));
12144 #endif
12145
12146                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12147                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12148                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12149                         continue;
12150
12151                 /*
12152                  * If the abort says that the task is untagged, the
12153                  * task in the queue must be untagged.  Otherwise,
12154                  * we just check to see whether the tag numbers
12155                  * match.  This is because the QLogic firmware
12156                  * doesn't pass back the tag type in an abort
12157                  * request.
12158                  */
12159 #if 0
12160                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12161                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12162                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12163 #endif
12164                 /*
12165                  * XXX KDM we've got problems with FC, because it
12166                  * doesn't send down a tag type with aborts.  So we
12167                  * can only really go by the tag number...
12168                  * This may cause problems with parallel SCSI.
12169                  * Need to figure that out!!
12170                  */
12171                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12172                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12173                         found = 1;
12174                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12175                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12176                                 union ctl_ha_msg msg_info;
12177
12178                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12179                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12180                                 msg_info.task.tag_num = io->taskio.tag_num;
12181                                 msg_info.task.tag_type = io->taskio.tag_type;
12182                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12183                                 msg_info.hdr.original_sc = NULL;
12184                                 msg_info.hdr.serializing_sc = NULL;
12185 #if 0
12186                                 printf("Sent Abort to other side\n");
12187 #endif
12188                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12189                                     sizeof(msg_info.task), M_NOWAIT);
12190                         }
12191 #if 0
12192                         printf("ctl_abort_task: found I/O to abort\n");
12193 #endif
12194                 }
12195         }
12196         mtx_unlock(&lun->lun_lock);
12197
12198         if (found == 0) {
12199                 /*
12200                  * This isn't really an error.  It's entirely possible for
12201                  * the abort and command completion to cross on the wire.
12202                  * This is more of an informative/diagnostic error.
12203                  */
12204 #if 0
12205                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12206                        "%u:%u:%u tag %d type %d\n",
12207                        io->io_hdr.nexus.initid,
12208                        io->io_hdr.nexus.targ_port,
12209                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12210                        io->taskio.tag_type);
12211 #endif
12212         }
12213         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12214         return (0);
12215 }
12216
12217 static int
12218 ctl_query_task(union ctl_io *io, int task_set)
12219 {
12220         union ctl_io *xio;
12221         struct ctl_lun *lun;
12222         struct ctl_softc *softc;
12223         int found = 0;
12224         uint32_t targ_lun;
12225
12226         softc = control_softc;
12227         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12228         mtx_lock(&softc->ctl_lock);
12229         if (targ_lun >= CTL_MAX_LUNS ||
12230             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12231                 mtx_unlock(&softc->ctl_lock);
12232                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12233                 return (1);
12234         }
12235         mtx_lock(&lun->lun_lock);
12236         mtx_unlock(&softc->ctl_lock);
12237         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12238              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12239
12240                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12241                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12242                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12243                         continue;
12244
12245                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12246                         found = 1;
12247                         break;
12248                 }
12249         }
12250         mtx_unlock(&lun->lun_lock);
12251         if (found)
12252                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12253         else
12254                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12255         return (0);
12256 }
12257
12258 static int
12259 ctl_query_async_event(union ctl_io *io)
12260 {
12261         struct ctl_lun *lun;
12262         struct ctl_softc *softc;
12263         ctl_ua_type ua;
12264         uint32_t targ_lun, initidx;
12265
12266         softc = control_softc;
12267         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12268         mtx_lock(&softc->ctl_lock);
12269         if (targ_lun >= CTL_MAX_LUNS ||
12270             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12271                 mtx_unlock(&softc->ctl_lock);
12272                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12273                 return (1);
12274         }
12275         mtx_lock(&lun->lun_lock);
12276         mtx_unlock(&softc->ctl_lock);
12277         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12278         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12279         mtx_unlock(&lun->lun_lock);
12280         if (ua != CTL_UA_NONE)
12281                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12282         else
12283                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12284         return (0);
12285 }
12286
12287 static void
12288 ctl_run_task(union ctl_io *io)
12289 {
12290         struct ctl_softc *softc = control_softc;
12291         int retval = 1;
12292
12293         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12294         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12295             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12296         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12297         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12298         switch (io->taskio.task_action) {
12299         case CTL_TASK_ABORT_TASK:
12300                 retval = ctl_abort_task(io);
12301                 break;
12302         case CTL_TASK_ABORT_TASK_SET:
12303         case CTL_TASK_CLEAR_TASK_SET:
12304                 retval = ctl_abort_task_set(io);
12305                 break;
12306         case CTL_TASK_CLEAR_ACA:
12307                 break;
12308         case CTL_TASK_I_T_NEXUS_RESET:
12309                 retval = ctl_i_t_nexus_reset(io);
12310                 break;
12311         case CTL_TASK_LUN_RESET:
12312                 retval = ctl_lun_reset(softc, io);
12313                 break;
12314         case CTL_TASK_TARGET_RESET:
12315                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12316                 break;
12317         case CTL_TASK_BUS_RESET:
12318                 retval = ctl_bus_reset(softc, io);
12319                 break;
12320         case CTL_TASK_PORT_LOGIN:
12321                 break;
12322         case CTL_TASK_PORT_LOGOUT:
12323                 break;
12324         case CTL_TASK_QUERY_TASK:
12325                 retval = ctl_query_task(io, 0);
12326                 break;
12327         case CTL_TASK_QUERY_TASK_SET:
12328                 retval = ctl_query_task(io, 1);
12329                 break;
12330         case CTL_TASK_QUERY_ASYNC_EVENT:
12331                 retval = ctl_query_async_event(io);
12332                 break;
12333         default:
12334                 printf("%s: got unknown task management event %d\n",
12335                        __func__, io->taskio.task_action);
12336                 break;
12337         }
12338         if (retval == 0)
12339                 io->io_hdr.status = CTL_SUCCESS;
12340         else
12341                 io->io_hdr.status = CTL_ERROR;
12342         ctl_done(io);
12343 }
12344
12345 /*
12346  * For HA operation.  Handle commands that come in from the other
12347  * controller.
12348  */
12349 static void
12350 ctl_handle_isc(union ctl_io *io)
12351 {
12352         struct ctl_softc *softc = control_softc;
12353         struct ctl_lun *lun;
12354         const struct ctl_cmd_entry *entry;
12355         uint32_t targ_lun;
12356
12357         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12358         switch (io->io_hdr.msg_type) {
12359         case CTL_MSG_SERIALIZE:
12360                 ctl_serialize_other_sc_cmd(&io->scsiio);
12361                 break;
12362         case CTL_MSG_R2R:               /* Only used in SER_ONLY mode. */
12363                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12364                 if (targ_lun >= CTL_MAX_LUNS ||
12365                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12366                         ctl_done(io);
12367                         break;
12368                 }
12369                 mtx_lock(&lun->lun_lock);
12370                 if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12371                         mtx_unlock(&lun->lun_lock);
12372                         ctl_done(io);
12373                         break;
12374                 }
12375                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12376                 mtx_unlock(&lun->lun_lock);
12377                 ctl_enqueue_rtr(io);
12378                 break;
12379         case CTL_MSG_FINISH_IO:
12380                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12381                         ctl_done(io);
12382                         break;
12383                 }
12384                 if (targ_lun >= CTL_MAX_LUNS ||
12385                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12386                         ctl_free_io(io);
12387                         break;
12388                 }
12389                 mtx_lock(&lun->lun_lock);
12390                 TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12391                 ctl_check_blocked(lun);
12392                 mtx_unlock(&lun->lun_lock);
12393                 ctl_free_io(io);
12394                 break;
12395         case CTL_MSG_PERS_ACTION:
12396                 ctl_hndl_per_res_out_on_other_sc(
12397                         (union ctl_ha_msg *)&io->presio.pr_msg);
12398                 ctl_free_io(io);
12399                 break;
12400         case CTL_MSG_BAD_JUJU:
12401                 ctl_done(io);
12402                 break;
12403         case CTL_MSG_DATAMOVE:          /* Only used in XFER mode */
12404                 ctl_datamove_remote(io);
12405                 break;
12406         case CTL_MSG_DATAMOVE_DONE:     /* Only used in XFER mode */
12407                 io->scsiio.be_move_done(io);
12408                 break;
12409         case CTL_MSG_FAILOVER:
12410                 ctl_failover_lun(io);
12411                 ctl_free_io(io);
12412                 break;
12413         default:
12414                 printf("%s: Invalid message type %d\n",
12415                        __func__, io->io_hdr.msg_type);
12416                 ctl_free_io(io);
12417                 break;
12418         }
12419
12420 }
12421
12422
12423 /*
12424  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12425  * there is no match.
12426  */
12427 static ctl_lun_error_pattern
12428 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12429 {
12430         const struct ctl_cmd_entry *entry;
12431         ctl_lun_error_pattern filtered_pattern, pattern;
12432
12433         pattern = desc->error_pattern;
12434
12435         /*
12436          * XXX KDM we need more data passed into this function to match a
12437          * custom pattern, and we actually need to implement custom pattern
12438          * matching.
12439          */
12440         if (pattern & CTL_LUN_PAT_CMD)
12441                 return (CTL_LUN_PAT_CMD);
12442
12443         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12444                 return (CTL_LUN_PAT_ANY);
12445
12446         entry = ctl_get_cmd_entry(ctsio, NULL);
12447
12448         filtered_pattern = entry->pattern & pattern;
12449
12450         /*
12451          * If the user requested specific flags in the pattern (e.g.
12452          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12453          * flags.
12454          *
12455          * If the user did not specify any flags, it doesn't matter whether
12456          * or not the command supports the flags.
12457          */
12458         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12459              (pattern & ~CTL_LUN_PAT_MASK))
12460                 return (CTL_LUN_PAT_NONE);
12461
12462         /*
12463          * If the user asked for a range check, see if the requested LBA
12464          * range overlaps with this command's LBA range.
12465          */
12466         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12467                 uint64_t lba1;
12468                 uint64_t len1;
12469                 ctl_action action;
12470                 int retval;
12471
12472                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12473                 if (retval != 0)
12474                         return (CTL_LUN_PAT_NONE);
12475
12476                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12477                                               desc->lba_range.len, FALSE);
12478                 /*
12479                  * A "pass" means that the LBA ranges don't overlap, so
12480                  * this doesn't match the user's range criteria.
12481                  */
12482                 if (action == CTL_ACTION_PASS)
12483                         return (CTL_LUN_PAT_NONE);
12484         }
12485
12486         return (filtered_pattern);
12487 }
12488
12489 static void
12490 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12491 {
12492         struct ctl_error_desc *desc, *desc2;
12493
12494         mtx_assert(&lun->lun_lock, MA_OWNED);
12495
12496         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12497                 ctl_lun_error_pattern pattern;
12498                 /*
12499                  * Check to see whether this particular command matches
12500                  * the pattern in the descriptor.
12501                  */
12502                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12503                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12504                         continue;
12505
12506                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12507                 case CTL_LUN_INJ_ABORTED:
12508                         ctl_set_aborted(&io->scsiio);
12509                         break;
12510                 case CTL_LUN_INJ_MEDIUM_ERR:
12511                         ctl_set_medium_error(&io->scsiio,
12512                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12513                              CTL_FLAG_DATA_OUT);
12514                         break;
12515                 case CTL_LUN_INJ_UA:
12516                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12517                          * OCCURRED */
12518                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12519                         break;
12520                 case CTL_LUN_INJ_CUSTOM:
12521                         /*
12522                          * We're assuming the user knows what he is doing.
12523                          * Just copy the sense information without doing
12524                          * checks.
12525                          */
12526                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12527                               MIN(sizeof(desc->custom_sense),
12528                                   sizeof(io->scsiio.sense_data)));
12529                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12530                         io->scsiio.sense_len = SSD_FULL_SIZE;
12531                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12532                         break;
12533                 case CTL_LUN_INJ_NONE:
12534                 default:
12535                         /*
12536                          * If this is an error injection type we don't know
12537                          * about, clear the continuous flag (if it is set)
12538                          * so it will get deleted below.
12539                          */
12540                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12541                         break;
12542                 }
12543                 /*
12544                  * By default, each error injection action is a one-shot
12545                  */
12546                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12547                         continue;
12548
12549                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12550
12551                 free(desc, M_CTL);
12552         }
12553 }
12554
12555 #ifdef CTL_IO_DELAY
12556 static void
12557 ctl_datamove_timer_wakeup(void *arg)
12558 {
12559         union ctl_io *io;
12560
12561         io = (union ctl_io *)arg;
12562
12563         ctl_datamove(io);
12564 }
12565 #endif /* CTL_IO_DELAY */
12566
12567 void
12568 ctl_datamove(union ctl_io *io)
12569 {
12570         struct ctl_lun *lun;
12571         void (*fe_datamove)(union ctl_io *io);
12572
12573         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12574
12575         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12576
12577         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12578 #ifdef CTL_TIME_IO
12579         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12580                 char str[256];
12581                 char path_str[64];
12582                 struct sbuf sb;
12583
12584                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12585                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12586
12587                 sbuf_cat(&sb, path_str);
12588                 switch (io->io_hdr.io_type) {
12589                 case CTL_IO_SCSI:
12590                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12591                         sbuf_printf(&sb, "\n");
12592                         sbuf_cat(&sb, path_str);
12593                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12594                                     io->scsiio.tag_num, io->scsiio.tag_type);
12595                         break;
12596                 case CTL_IO_TASK:
12597                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12598                                     "Tag Type: %d\n", io->taskio.task_action,
12599                                     io->taskio.tag_num, io->taskio.tag_type);
12600                         break;
12601                 default:
12602                         panic("%s: Invalid CTL I/O type %d\n",
12603                             __func__, io->io_hdr.io_type);
12604                 }
12605                 sbuf_cat(&sb, path_str);
12606                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12607                             (intmax_t)time_uptime - io->io_hdr.start_time);
12608                 sbuf_finish(&sb);
12609                 printf("%s", sbuf_data(&sb));
12610         }
12611 #endif /* CTL_TIME_IO */
12612
12613 #ifdef CTL_IO_DELAY
12614         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12615                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12616         } else {
12617                 if ((lun != NULL)
12618                  && (lun->delay_info.datamove_delay > 0)) {
12619
12620                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12621                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12622                         callout_reset(&io->io_hdr.delay_callout,
12623                                       lun->delay_info.datamove_delay * hz,
12624                                       ctl_datamove_timer_wakeup, io);
12625                         if (lun->delay_info.datamove_type ==
12626                             CTL_DELAY_TYPE_ONESHOT)
12627                                 lun->delay_info.datamove_delay = 0;
12628                         return;
12629                 }
12630         }
12631 #endif
12632
12633         /*
12634          * This command has been aborted.  Set the port status, so we fail
12635          * the data move.
12636          */
12637         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12638                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12639                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12640                        io->io_hdr.nexus.targ_port,
12641                        io->io_hdr.nexus.targ_lun);
12642                 io->io_hdr.port_status = 31337;
12643                 /*
12644                  * Note that the backend, in this case, will get the
12645                  * callback in its context.  In other cases it may get
12646                  * called in the frontend's interrupt thread context.
12647                  */
12648                 io->scsiio.be_move_done(io);
12649                 return;
12650         }
12651
12652         /* Don't confuse frontend with zero length data move. */
12653         if (io->scsiio.kern_data_len == 0) {
12654                 io->scsiio.be_move_done(io);
12655                 return;
12656         }
12657
12658         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12659         fe_datamove(io);
12660 }
12661
12662 static void
12663 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12664 {
12665         union ctl_ha_msg msg;
12666 #ifdef CTL_TIME_IO
12667         struct bintime cur_bt;
12668 #endif
12669
12670         memset(&msg, 0, sizeof(msg));
12671         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12672         msg.hdr.original_sc = io;
12673         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12674         msg.hdr.nexus = io->io_hdr.nexus;
12675         msg.hdr.status = io->io_hdr.status;
12676         msg.scsi.tag_num = io->scsiio.tag_num;
12677         msg.scsi.tag_type = io->scsiio.tag_type;
12678         msg.scsi.scsi_status = io->scsiio.scsi_status;
12679         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12680                io->scsiio.sense_len);
12681         msg.scsi.sense_len = io->scsiio.sense_len;
12682         msg.scsi.sense_residual = io->scsiio.sense_residual;
12683         msg.scsi.fetd_status = io->io_hdr.port_status;
12684         msg.scsi.residual = io->scsiio.residual;
12685         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12686         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12687                 ctl_failover_io(io, /*have_lock*/ have_lock);
12688                 return;
12689         }
12690         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12691             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12692             msg.scsi.sense_len, M_WAITOK);
12693
12694 #ifdef CTL_TIME_IO
12695         getbinuptime(&cur_bt);
12696         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12697         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12698 #endif
12699         io->io_hdr.num_dmas++;
12700 }
12701
12702 /*
12703  * The DMA to the remote side is done, now we need to tell the other side
12704  * we're done so it can continue with its data movement.
12705  */
12706 static void
12707 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12708 {
12709         union ctl_io *io;
12710         uint32_t i;
12711
12712         io = rq->context;
12713
12714         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12715                 printf("%s: ISC DMA write failed with error %d", __func__,
12716                        rq->ret);
12717                 ctl_set_internal_failure(&io->scsiio,
12718                                          /*sks_valid*/ 1,
12719                                          /*retry_count*/ rq->ret);
12720         }
12721
12722         ctl_dt_req_free(rq);
12723
12724         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12725                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12726         free(io->io_hdr.remote_sglist, M_CTL);
12727         io->io_hdr.remote_sglist = NULL;
12728         io->io_hdr.local_sglist = NULL;
12729
12730         /*
12731          * The data is in local and remote memory, so now we need to send
12732          * status (good or back) back to the other side.
12733          */
12734         ctl_send_datamove_done(io, /*have_lock*/ 0);
12735 }
12736
12737 /*
12738  * We've moved the data from the host/controller into local memory.  Now we
12739  * need to push it over to the remote controller's memory.
12740  */
12741 static int
12742 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12743 {
12744         int retval;
12745
12746         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12747                                           ctl_datamove_remote_write_cb);
12748         return (retval);
12749 }
12750
12751 static void
12752 ctl_datamove_remote_write(union ctl_io *io)
12753 {
12754         int retval;
12755         void (*fe_datamove)(union ctl_io *io);
12756
12757         /*
12758          * - Get the data from the host/HBA into local memory.
12759          * - DMA memory from the local controller to the remote controller.
12760          * - Send status back to the remote controller.
12761          */
12762
12763         retval = ctl_datamove_remote_sgl_setup(io);
12764         if (retval != 0)
12765                 return;
12766
12767         /* Switch the pointer over so the FETD knows what to do */
12768         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12769
12770         /*
12771          * Use a custom move done callback, since we need to send completion
12772          * back to the other controller, not to the backend on this side.
12773          */
12774         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12775
12776         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12777         fe_datamove(io);
12778 }
12779
12780 static int
12781 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12782 {
12783 #if 0
12784         char str[256];
12785         char path_str[64];
12786         struct sbuf sb;
12787 #endif
12788         uint32_t i;
12789
12790         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12791                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12792         free(io->io_hdr.remote_sglist, M_CTL);
12793         io->io_hdr.remote_sglist = NULL;
12794         io->io_hdr.local_sglist = NULL;
12795
12796 #if 0
12797         scsi_path_string(io, path_str, sizeof(path_str));
12798         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12799         sbuf_cat(&sb, path_str);
12800         scsi_command_string(&io->scsiio, NULL, &sb);
12801         sbuf_printf(&sb, "\n");
12802         sbuf_cat(&sb, path_str);
12803         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12804                     io->scsiio.tag_num, io->scsiio.tag_type);
12805         sbuf_cat(&sb, path_str);
12806         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12807                     io->io_hdr.flags, io->io_hdr.status);
12808         sbuf_finish(&sb);
12809         printk("%s", sbuf_data(&sb));
12810 #endif
12811
12812
12813         /*
12814          * The read is done, now we need to send status (good or bad) back
12815          * to the other side.
12816          */
12817         ctl_send_datamove_done(io, /*have_lock*/ 0);
12818
12819         return (0);
12820 }
12821
12822 static void
12823 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12824 {
12825         union ctl_io *io;
12826         void (*fe_datamove)(union ctl_io *io);
12827
12828         io = rq->context;
12829
12830         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12831                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12832                        rq->ret);
12833                 ctl_set_internal_failure(&io->scsiio,
12834                                          /*sks_valid*/ 1,
12835                                          /*retry_count*/ rq->ret);
12836         }
12837
12838         ctl_dt_req_free(rq);
12839
12840         /* Switch the pointer over so the FETD knows what to do */
12841         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12842
12843         /*
12844          * Use a custom move done callback, since we need to send completion
12845          * back to the other controller, not to the backend on this side.
12846          */
12847         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12848
12849         /* XXX KDM add checks like the ones in ctl_datamove? */
12850
12851         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12852         fe_datamove(io);
12853 }
12854
12855 static int
12856 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12857 {
12858         struct ctl_sg_entry *local_sglist;
12859         uint32_t len_to_go;
12860         int retval;
12861         int i;
12862
12863         retval = 0;
12864         local_sglist = io->io_hdr.local_sglist;
12865         len_to_go = io->scsiio.kern_data_len;
12866
12867         /*
12868          * The difficult thing here is that the size of the various
12869          * S/G segments may be different than the size from the
12870          * remote controller.  That'll make it harder when DMAing
12871          * the data back to the other side.
12872          */
12873         for (i = 0; len_to_go > 0; i++) {
12874                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12875                 local_sglist[i].addr =
12876                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12877
12878                 len_to_go -= local_sglist[i].len;
12879         }
12880         /*
12881          * Reset the number of S/G entries accordingly.  The original
12882          * number of S/G entries is available in rem_sg_entries.
12883          */
12884         io->scsiio.kern_sg_entries = i;
12885
12886 #if 0
12887         printf("%s: kern_sg_entries = %d\n", __func__,
12888                io->scsiio.kern_sg_entries);
12889         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12890                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12891                        local_sglist[i].addr, local_sglist[i].len);
12892 #endif
12893
12894         return (retval);
12895 }
12896
12897 static int
12898 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12899                          ctl_ha_dt_cb callback)
12900 {
12901         struct ctl_ha_dt_req *rq;
12902         struct ctl_sg_entry *remote_sglist, *local_sglist;
12903         uint32_t local_used, remote_used, total_used;
12904         int i, j, isc_ret;
12905
12906         rq = ctl_dt_req_alloc();
12907
12908         /*
12909          * If we failed to allocate the request, and if the DMA didn't fail
12910          * anyway, set busy status.  This is just a resource allocation
12911          * failure.
12912          */
12913         if ((rq == NULL)
12914          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12915              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12916                 ctl_set_busy(&io->scsiio);
12917
12918         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12919             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12920
12921                 if (rq != NULL)
12922                         ctl_dt_req_free(rq);
12923
12924                 /*
12925                  * The data move failed.  We need to return status back
12926                  * to the other controller.  No point in trying to DMA
12927                  * data to the remote controller.
12928                  */
12929
12930                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12931
12932                 return (1);
12933         }
12934
12935         local_sglist = io->io_hdr.local_sglist;
12936         remote_sglist = io->io_hdr.remote_sglist;
12937         local_used = 0;
12938         remote_used = 0;
12939         total_used = 0;
12940
12941         /*
12942          * Pull/push the data over the wire from/to the other controller.
12943          * This takes into account the possibility that the local and
12944          * remote sglists may not be identical in terms of the size of
12945          * the elements and the number of elements.
12946          *
12947          * One fundamental assumption here is that the length allocated for
12948          * both the local and remote sglists is identical.  Otherwise, we've
12949          * essentially got a coding error of some sort.
12950          */
12951         isc_ret = CTL_HA_STATUS_SUCCESS;
12952         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12953                 uint32_t cur_len;
12954                 uint8_t *tmp_ptr;
12955
12956                 rq->command = command;
12957                 rq->context = io;
12958
12959                 /*
12960                  * Both pointers should be aligned.  But it is possible
12961                  * that the allocation length is not.  They should both
12962                  * also have enough slack left over at the end, though,
12963                  * to round up to the next 8 byte boundary.
12964                  */
12965                 cur_len = MIN(local_sglist[i].len - local_used,
12966                               remote_sglist[j].len - remote_used);
12967                 rq->size = cur_len;
12968
12969                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12970                 tmp_ptr += local_used;
12971
12972 #if 0
12973                 /* Use physical addresses when talking to ISC hardware */
12974                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12975                         /* XXX KDM use busdma */
12976                         rq->local = vtophys(tmp_ptr);
12977                 } else
12978                         rq->local = tmp_ptr;
12979 #else
12980                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12981                     ("HA does not support BUS_ADDR"));
12982                 rq->local = tmp_ptr;
12983 #endif
12984
12985                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12986                 tmp_ptr += remote_used;
12987                 rq->remote = tmp_ptr;
12988
12989                 rq->callback = NULL;
12990
12991                 local_used += cur_len;
12992                 if (local_used >= local_sglist[i].len) {
12993                         i++;
12994                         local_used = 0;
12995                 }
12996
12997                 remote_used += cur_len;
12998                 if (remote_used >= remote_sglist[j].len) {
12999                         j++;
13000                         remote_used = 0;
13001                 }
13002                 total_used += cur_len;
13003
13004                 if (total_used >= io->scsiio.kern_data_len)
13005                         rq->callback = callback;
13006
13007 #if 0
13008                 printf("%s: %s: local %p remote %p size %d\n", __func__,
13009                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13010                        rq->local, rq->remote, rq->size);
13011 #endif
13012
13013                 isc_ret = ctl_dt_single(rq);
13014                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
13015                         break;
13016         }
13017         if (isc_ret != CTL_HA_STATUS_WAIT) {
13018                 rq->ret = isc_ret;
13019                 callback(rq);
13020         }
13021
13022         return (0);
13023 }
13024
13025 static void
13026 ctl_datamove_remote_read(union ctl_io *io)
13027 {
13028         int retval;
13029         uint32_t i;
13030
13031         /*
13032          * This will send an error to the other controller in the case of a
13033          * failure.
13034          */
13035         retval = ctl_datamove_remote_sgl_setup(io);
13036         if (retval != 0)
13037                 return;
13038
13039         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13040                                           ctl_datamove_remote_read_cb);
13041         if (retval != 0) {
13042                 /*
13043                  * Make sure we free memory if there was an error..  The
13044                  * ctl_datamove_remote_xfer() function will send the
13045                  * datamove done message, or call the callback with an
13046                  * error if there is a problem.
13047                  */
13048                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13049                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13050                 free(io->io_hdr.remote_sglist, M_CTL);
13051                 io->io_hdr.remote_sglist = NULL;
13052                 io->io_hdr.local_sglist = NULL;
13053         }
13054 }
13055
13056 /*
13057  * Process a datamove request from the other controller.  This is used for
13058  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13059  * first.  Once that is complete, the data gets DMAed into the remote
13060  * controller's memory.  For reads, we DMA from the remote controller's
13061  * memory into our memory first, and then move it out to the FETD.
13062  */
13063 static void
13064 ctl_datamove_remote(union ctl_io *io)
13065 {
13066
13067         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13068
13069         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13070                 ctl_failover_io(io, /*have_lock*/ 0);
13071                 return;
13072         }
13073
13074         /*
13075          * Note that we look for an aborted I/O here, but don't do some of
13076          * the other checks that ctl_datamove() normally does.
13077          * We don't need to run the datamove delay code, since that should
13078          * have been done if need be on the other controller.
13079          */
13080         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13081                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13082                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13083                        io->io_hdr.nexus.targ_port,
13084                        io->io_hdr.nexus.targ_lun);
13085                 io->io_hdr.port_status = 31338;
13086                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13087                 return;
13088         }
13089
13090         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13091                 ctl_datamove_remote_write(io);
13092         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13093                 ctl_datamove_remote_read(io);
13094         else {
13095                 io->io_hdr.port_status = 31339;
13096                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13097         }
13098 }
13099
13100 static void
13101 ctl_process_done(union ctl_io *io)
13102 {
13103         struct ctl_lun *lun;
13104         struct ctl_softc *softc = control_softc;
13105         void (*fe_done)(union ctl_io *io);
13106         union ctl_ha_msg msg;
13107         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13108
13109         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13110         fe_done = softc->ctl_ports[targ_port]->fe_done;
13111
13112 #ifdef CTL_TIME_IO
13113         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13114                 char str[256];
13115                 char path_str[64];
13116                 struct sbuf sb;
13117
13118                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13119                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13120
13121                 sbuf_cat(&sb, path_str);
13122                 switch (io->io_hdr.io_type) {
13123                 case CTL_IO_SCSI:
13124                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13125                         sbuf_printf(&sb, "\n");
13126                         sbuf_cat(&sb, path_str);
13127                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13128                                     io->scsiio.tag_num, io->scsiio.tag_type);
13129                         break;
13130                 case CTL_IO_TASK:
13131                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13132                                     "Tag Type: %d\n", io->taskio.task_action,
13133                                     io->taskio.tag_num, io->taskio.tag_type);
13134                         break;
13135                 default:
13136                         panic("%s: Invalid CTL I/O type %d\n",
13137                             __func__, io->io_hdr.io_type);
13138                 }
13139                 sbuf_cat(&sb, path_str);
13140                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13141                             (intmax_t)time_uptime - io->io_hdr.start_time);
13142                 sbuf_finish(&sb);
13143                 printf("%s", sbuf_data(&sb));
13144         }
13145 #endif /* CTL_TIME_IO */
13146
13147         switch (io->io_hdr.io_type) {
13148         case CTL_IO_SCSI:
13149                 break;
13150         case CTL_IO_TASK:
13151                 if (ctl_debug & CTL_DEBUG_INFO)
13152                         ctl_io_error_print(io, NULL);
13153                 fe_done(io);
13154                 return;
13155         default:
13156                 panic("%s: Invalid CTL I/O type %d\n",
13157                     __func__, io->io_hdr.io_type);
13158         }
13159
13160         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13161         if (lun == NULL) {
13162                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13163                                  io->io_hdr.nexus.targ_mapped_lun));
13164                 goto bailout;
13165         }
13166
13167         mtx_lock(&lun->lun_lock);
13168
13169         /*
13170          * Check to see if we have any informational exception and status
13171          * of this command can be modified to report it in form of either
13172          * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13173          */
13174         if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13175             io->io_hdr.status == CTL_SUCCESS &&
13176             (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13177                 uint8_t mrie = lun->MODE_IE.mrie;
13178                 uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13179                     (lun->MODE_VER.byte3 & SMS_VER_PER));
13180                 if (((mrie == SIEP_MRIE_REC_COND && per) ||
13181                      mrie == SIEP_MRIE_REC_UNCOND ||
13182                      mrie == SIEP_MRIE_NO_SENSE) &&
13183                     (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13184                      CTL_CMD_FLAG_NO_SENSE) == 0) {
13185                         ctl_set_sense(&io->scsiio,
13186                               /*current_error*/ 1,
13187                               /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13188                                 SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13189                               /*asc*/ lun->ie_asc,
13190                               /*ascq*/ lun->ie_ascq,
13191                               SSD_ELEM_NONE);
13192                         lun->ie_reported = 1;
13193                 }
13194         } else if (lun->ie_reported < 0)
13195                 lun->ie_reported = 0;
13196
13197         /*
13198          * Check to see if we have any errors to inject here.  We only
13199          * inject errors for commands that don't already have errors set.
13200          */
13201         if (!STAILQ_EMPTY(&lun->error_list) &&
13202             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13203             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13204                 ctl_inject_error(lun, io);
13205
13206         /*
13207          * XXX KDM how do we treat commands that aren't completed
13208          * successfully?
13209          *
13210          * XXX KDM should we also track I/O latency?
13211          */
13212         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13213             io->io_hdr.io_type == CTL_IO_SCSI) {
13214 #ifdef CTL_TIME_IO
13215                 struct bintime cur_bt;
13216 #endif
13217                 int type;
13218
13219                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13220                     CTL_FLAG_DATA_IN)
13221                         type = CTL_STATS_READ;
13222                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13223                     CTL_FLAG_DATA_OUT)
13224                         type = CTL_STATS_WRITE;
13225                 else
13226                         type = CTL_STATS_NO_IO;
13227
13228                 lun->stats.ports[targ_port].bytes[type] +=
13229                     io->scsiio.kern_total_len;
13230                 lun->stats.ports[targ_port].operations[type]++;
13231 #ifdef CTL_TIME_IO
13232                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13233                    &io->io_hdr.dma_bt);
13234                 getbinuptime(&cur_bt);
13235                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13236                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13237 #endif
13238                 lun->stats.ports[targ_port].num_dmas[type] +=
13239                     io->io_hdr.num_dmas;
13240         }
13241
13242         /*
13243          * Remove this from the OOA queue.
13244          */
13245         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13246 #ifdef CTL_TIME_IO
13247         if (TAILQ_EMPTY(&lun->ooa_queue))
13248                 lun->last_busy = getsbinuptime();
13249 #endif
13250
13251         /*
13252          * Run through the blocked queue on this LUN and see if anything
13253          * has become unblocked, now that this transaction is done.
13254          */
13255         ctl_check_blocked(lun);
13256
13257         /*
13258          * If the LUN has been invalidated, free it if there is nothing
13259          * left on its OOA queue.
13260          */
13261         if ((lun->flags & CTL_LUN_INVALID)
13262          && TAILQ_EMPTY(&lun->ooa_queue)) {
13263                 mtx_unlock(&lun->lun_lock);
13264                 mtx_lock(&softc->ctl_lock);
13265                 ctl_free_lun(lun);
13266                 mtx_unlock(&softc->ctl_lock);
13267         } else
13268                 mtx_unlock(&lun->lun_lock);
13269
13270 bailout:
13271
13272         /*
13273          * If this command has been aborted, make sure we set the status
13274          * properly.  The FETD is responsible for freeing the I/O and doing
13275          * whatever it needs to do to clean up its state.
13276          */
13277         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13278                 ctl_set_task_aborted(&io->scsiio);
13279
13280         /*
13281          * If enabled, print command error status.
13282          */
13283         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13284             (ctl_debug & CTL_DEBUG_INFO) != 0)
13285                 ctl_io_error_print(io, NULL);
13286
13287         /*
13288          * Tell the FETD or the other shelf controller we're done with this
13289          * command.  Note that only SCSI commands get to this point.  Task
13290          * management commands are completed above.
13291          */
13292         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13293             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13294                 memset(&msg, 0, sizeof(msg));
13295                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13296                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13297                 msg.hdr.nexus = io->io_hdr.nexus;
13298                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13299                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13300                     M_WAITOK);
13301         }
13302
13303         fe_done(io);
13304 }
13305
13306 #ifdef CTL_WITH_CA
13307 /*
13308  * Front end should call this if it doesn't do autosense.  When the request
13309  * sense comes back in from the initiator, we'll dequeue this and send it.
13310  */
13311 int
13312 ctl_queue_sense(union ctl_io *io)
13313 {
13314         struct ctl_lun *lun;
13315         struct ctl_port *port;
13316         struct ctl_softc *softc;
13317         uint32_t initidx, targ_lun;
13318
13319         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13320
13321         softc = control_softc;
13322         port = ctl_io_port(&ctsio->io_hdr);
13323         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13324
13325         /*
13326          * LUN lookup will likely move to the ctl_work_thread() once we
13327          * have our new queueing infrastructure (that doesn't put things on
13328          * a per-LUN queue initially).  That is so that we can handle
13329          * things like an INQUIRY to a LUN that we don't have enabled.  We
13330          * can't deal with that right now.
13331          * If we don't have a LUN for this, just toss the sense information.
13332          */
13333         mtx_lock(&softc->ctl_lock);
13334         if (targ_lun >= CTL_MAX_LUNS ||
13335             (lun = softc->ctl_luns[targ_lun]) == NULL) {
13336                 mtx_unlock(&softc->ctl_lock);
13337                 goto bailout;
13338         }
13339         mtx_lock(&lun->lun_lock);
13340         mtx_unlock(&softc->ctl_lock);
13341
13342         /*
13343          * Already have CA set for this LUN...toss the sense information.
13344          */
13345         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13346         if (ctl_is_set(lun->have_ca, initidx)) {
13347                 mtx_unlock(&lun->lun_lock);
13348                 goto bailout;
13349         }
13350
13351         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13352                MIN(sizeof(lun->pending_sense[initidx]),
13353                sizeof(io->scsiio.sense_data)));
13354         ctl_set_mask(lun->have_ca, initidx);
13355         mtx_unlock(&lun->lun_lock);
13356
13357 bailout:
13358         ctl_free_io(io);
13359         return (CTL_RETVAL_COMPLETE);
13360 }
13361 #endif
13362
13363 /*
13364  * Primary command inlet from frontend ports.  All SCSI and task I/O
13365  * requests must go through this function.
13366  */
13367 int
13368 ctl_queue(union ctl_io *io)
13369 {
13370         struct ctl_port *port;
13371
13372         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13373
13374 #ifdef CTL_TIME_IO
13375         io->io_hdr.start_time = time_uptime;
13376         getbinuptime(&io->io_hdr.start_bt);
13377 #endif /* CTL_TIME_IO */
13378
13379         /* Map FE-specific LUN ID into global one. */
13380         port = ctl_io_port(&io->io_hdr);
13381         io->io_hdr.nexus.targ_mapped_lun =
13382             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13383
13384         switch (io->io_hdr.io_type) {
13385         case CTL_IO_SCSI:
13386         case CTL_IO_TASK:
13387                 if (ctl_debug & CTL_DEBUG_CDB)
13388                         ctl_io_print(io);
13389                 ctl_enqueue_incoming(io);
13390                 break;
13391         default:
13392                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13393                 return (EINVAL);
13394         }
13395
13396         return (CTL_RETVAL_COMPLETE);
13397 }
13398
13399 #ifdef CTL_IO_DELAY
13400 static void
13401 ctl_done_timer_wakeup(void *arg)
13402 {
13403         union ctl_io *io;
13404
13405         io = (union ctl_io *)arg;
13406         ctl_done(io);
13407 }
13408 #endif /* CTL_IO_DELAY */
13409
13410 void
13411 ctl_serseq_done(union ctl_io *io)
13412 {
13413         struct ctl_lun *lun;
13414
13415         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13416         if (lun->be_lun == NULL ||
13417             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13418                 return;
13419         mtx_lock(&lun->lun_lock);
13420         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13421         ctl_check_blocked(lun);
13422         mtx_unlock(&lun->lun_lock);
13423 }
13424
13425 void
13426 ctl_done(union ctl_io *io)
13427 {
13428
13429         /*
13430          * Enable this to catch duplicate completion issues.
13431          */
13432 #if 0
13433         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13434                 printf("%s: type %d msg %d cdb %x iptl: "
13435                        "%u:%u:%u tag 0x%04x "
13436                        "flag %#x status %x\n",
13437                         __func__,
13438                         io->io_hdr.io_type,
13439                         io->io_hdr.msg_type,
13440                         io->scsiio.cdb[0],
13441                         io->io_hdr.nexus.initid,
13442                         io->io_hdr.nexus.targ_port,
13443                         io->io_hdr.nexus.targ_lun,
13444                         (io->io_hdr.io_type ==
13445                         CTL_IO_TASK) ?
13446                         io->taskio.tag_num :
13447                         io->scsiio.tag_num,
13448                         io->io_hdr.flags,
13449                         io->io_hdr.status);
13450         } else
13451                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13452 #endif
13453
13454         /*
13455          * This is an internal copy of an I/O, and should not go through
13456          * the normal done processing logic.
13457          */
13458         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13459                 return;
13460
13461 #ifdef CTL_IO_DELAY
13462         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13463                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13464         } else {
13465                 struct ctl_lun *lun;
13466
13467                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13468
13469                 if ((lun != NULL)
13470                  && (lun->delay_info.done_delay > 0)) {
13471
13472                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13473                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13474                         callout_reset(&io->io_hdr.delay_callout,
13475                                       lun->delay_info.done_delay * hz,
13476                                       ctl_done_timer_wakeup, io);
13477                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13478                                 lun->delay_info.done_delay = 0;
13479                         return;
13480                 }
13481         }
13482 #endif /* CTL_IO_DELAY */
13483
13484         ctl_enqueue_done(io);
13485 }
13486
13487 static void
13488 ctl_work_thread(void *arg)
13489 {
13490         struct ctl_thread *thr = (struct ctl_thread *)arg;
13491         struct ctl_softc *softc = thr->ctl_softc;
13492         union ctl_io *io;
13493         int retval;
13494
13495         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13496
13497         for (;;) {
13498                 /*
13499                  * We handle the queues in this order:
13500                  * - ISC
13501                  * - done queue (to free up resources, unblock other commands)
13502                  * - RtR queue
13503                  * - incoming queue
13504                  *
13505                  * If those queues are empty, we break out of the loop and
13506                  * go to sleep.
13507                  */
13508                 mtx_lock(&thr->queue_lock);
13509                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13510                 if (io != NULL) {
13511                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13512                         mtx_unlock(&thr->queue_lock);
13513                         ctl_handle_isc(io);
13514                         continue;
13515                 }
13516                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13517                 if (io != NULL) {
13518                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13519                         /* clear any blocked commands, call fe_done */
13520                         mtx_unlock(&thr->queue_lock);
13521                         ctl_process_done(io);
13522                         continue;
13523                 }
13524                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13525                 if (io != NULL) {
13526                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13527                         mtx_unlock(&thr->queue_lock);
13528                         if (io->io_hdr.io_type == CTL_IO_TASK)
13529                                 ctl_run_task(io);
13530                         else
13531                                 ctl_scsiio_precheck(softc, &io->scsiio);
13532                         continue;
13533                 }
13534                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13535                 if (io != NULL) {
13536                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13537                         mtx_unlock(&thr->queue_lock);
13538                         retval = ctl_scsiio(&io->scsiio);
13539                         if (retval != CTL_RETVAL_COMPLETE)
13540                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13541                         continue;
13542                 }
13543
13544                 /* Sleep until we have something to do. */
13545                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13546         }
13547 }
13548
13549 static void
13550 ctl_lun_thread(void *arg)
13551 {
13552         struct ctl_softc *softc = (struct ctl_softc *)arg;
13553         struct ctl_be_lun *be_lun;
13554
13555         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13556
13557         for (;;) {
13558                 mtx_lock(&softc->ctl_lock);
13559                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13560                 if (be_lun != NULL) {
13561                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13562                         mtx_unlock(&softc->ctl_lock);
13563                         ctl_create_lun(be_lun);
13564                         continue;
13565                 }
13566
13567                 /* Sleep until we have something to do. */
13568                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13569                     PDROP | PRIBIO, "-", 0);
13570         }
13571 }
13572
13573 static void
13574 ctl_thresh_thread(void *arg)
13575 {
13576         struct ctl_softc *softc = (struct ctl_softc *)arg;
13577         struct ctl_lun *lun;
13578         struct ctl_logical_block_provisioning_page *page;
13579         const char *attr;
13580         union ctl_ha_msg msg;
13581         uint64_t thres, val;
13582         int i, e, set;
13583
13584         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13585
13586         for (;;) {
13587                 mtx_lock(&softc->ctl_lock);
13588                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13589                         if ((lun->flags & CTL_LUN_DISABLED) ||
13590                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13591                             lun->backend->lun_attr == NULL)
13592                                 continue;
13593                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13594                             softc->ha_mode == CTL_HA_MODE_XFER)
13595                                 continue;
13596                         if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13597                                 continue;
13598                         e = 0;
13599                         page = &lun->MODE_LBP;
13600                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13601                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13602                                         continue;
13603                                 thres = scsi_4btoul(page->descr[i].count);
13604                                 thres <<= CTL_LBP_EXPONENT;
13605                                 switch (page->descr[i].resource) {
13606                                 case 0x01:
13607                                         attr = "blocksavail";
13608                                         break;
13609                                 case 0x02:
13610                                         attr = "blocksused";
13611                                         break;
13612                                 case 0xf1:
13613                                         attr = "poolblocksavail";
13614                                         break;
13615                                 case 0xf2:
13616                                         attr = "poolblocksused";
13617                                         break;
13618                                 default:
13619                                         continue;
13620                                 }
13621                                 mtx_unlock(&softc->ctl_lock); // XXX
13622                                 val = lun->backend->lun_attr(
13623                                     lun->be_lun->be_lun, attr);
13624                                 mtx_lock(&softc->ctl_lock);
13625                                 if (val == UINT64_MAX)
13626                                         continue;
13627                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13628                                     == SLBPPD_ARMING_INC)
13629                                         e = (val >= thres);
13630                                 else
13631                                         e = (val <= thres);
13632                                 if (e)
13633                                         break;
13634                         }
13635                         mtx_lock(&lun->lun_lock);
13636                         if (e) {
13637                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13638                                     (uint8_t *)page, lun->ua_tpt_info);
13639                                 if (lun->lasttpt == 0 ||
13640                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13641                                         lun->lasttpt = time_uptime;
13642                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13643                                         set = 1;
13644                                 } else
13645                                         set = 0;
13646                         } else {
13647                                 lun->lasttpt = 0;
13648                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13649                                 set = -1;
13650                         }
13651                         mtx_unlock(&lun->lun_lock);
13652                         if (set != 0 &&
13653                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13654                                 /* Send msg to other side. */
13655                                 bzero(&msg.ua, sizeof(msg.ua));
13656                                 msg.hdr.msg_type = CTL_MSG_UA;
13657                                 msg.hdr.nexus.initid = -1;
13658                                 msg.hdr.nexus.targ_port = -1;
13659                                 msg.hdr.nexus.targ_lun = lun->lun;
13660                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13661                                 msg.ua.ua_all = 1;
13662                                 msg.ua.ua_set = (set > 0);
13663                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13664                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13665                                 mtx_unlock(&softc->ctl_lock); // XXX
13666                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13667                                     sizeof(msg.ua), M_WAITOK);
13668                                 mtx_lock(&softc->ctl_lock);
13669                         }
13670                 }
13671                 mtx_unlock(&softc->ctl_lock);
13672                 pause("-", CTL_LBP_PERIOD * hz);
13673         }
13674 }
13675
13676 static void
13677 ctl_enqueue_incoming(union ctl_io *io)
13678 {
13679         struct ctl_softc *softc = control_softc;
13680         struct ctl_thread *thr;
13681         u_int idx;
13682
13683         idx = (io->io_hdr.nexus.targ_port * 127 +
13684                io->io_hdr.nexus.initid) % worker_threads;
13685         thr = &softc->threads[idx];
13686         mtx_lock(&thr->queue_lock);
13687         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13688         mtx_unlock(&thr->queue_lock);
13689         wakeup(thr);
13690 }
13691
13692 static void
13693 ctl_enqueue_rtr(union ctl_io *io)
13694 {
13695         struct ctl_softc *softc = control_softc;
13696         struct ctl_thread *thr;
13697
13698         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13699         mtx_lock(&thr->queue_lock);
13700         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13701         mtx_unlock(&thr->queue_lock);
13702         wakeup(thr);
13703 }
13704
13705 static void
13706 ctl_enqueue_done(union ctl_io *io)
13707 {
13708         struct ctl_softc *softc = control_softc;
13709         struct ctl_thread *thr;
13710
13711         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13712         mtx_lock(&thr->queue_lock);
13713         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13714         mtx_unlock(&thr->queue_lock);
13715         wakeup(thr);
13716 }
13717
13718 static void
13719 ctl_enqueue_isc(union ctl_io *io)
13720 {
13721         struct ctl_softc *softc = control_softc;
13722         struct ctl_thread *thr;
13723
13724         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13725         mtx_lock(&thr->queue_lock);
13726         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13727         mtx_unlock(&thr->queue_lock);
13728         wakeup(thr);
13729 }
13730
13731 /*
13732  *  vim: ts=8
13733  */