]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r307350: Add LUN options to limit UNMAP and WRITE SAME sizes.
[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 copan_debugconf_subpage debugconf_page_default = {
97         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
98         DBGCNF_SUBPAGE_CODE,            /* subpage */
99         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
100          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
101         DBGCNF_VERSION,                 /* page_version */
102         {CTL_TIME_IO_DEFAULT_SECS>>8,
103          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
104 };
105
106 const static struct copan_debugconf_subpage debugconf_page_changeable = {
107         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
108         DBGCNF_SUBPAGE_CODE,            /* subpage */
109         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
110          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
111         0,                              /* page_version */
112         {0xff,0xff},                    /* ctl_time_io_secs */
113 };
114
115 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
116         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
117         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
118         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
119         /*read_retry_count*/0,
120         /*correction_span*/0,
121         /*head_offset_count*/0,
122         /*data_strobe_offset_cnt*/0,
123         /*byte8*/SMS_RWER_LBPERE,
124         /*write_retry_count*/0,
125         /*reserved2*/0,
126         /*recovery_time_limit*/{0, 0},
127 };
128
129 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
130         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
131         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
132         /*byte3*/0,
133         /*read_retry_count*/0,
134         /*correction_span*/0,
135         /*head_offset_count*/0,
136         /*data_strobe_offset_cnt*/0,
137         /*byte8*/0,
138         /*write_retry_count*/0,
139         /*reserved2*/0,
140         /*recovery_time_limit*/{0, 0},
141 };
142
143 const static struct scsi_format_page format_page_default = {
144         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
145         /*page_length*/sizeof(struct scsi_format_page) - 2,
146         /*tracks_per_zone*/ {0, 0},
147         /*alt_sectors_per_zone*/ {0, 0},
148         /*alt_tracks_per_zone*/ {0, 0},
149         /*alt_tracks_per_lun*/ {0, 0},
150         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
151                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
152         /*bytes_per_sector*/ {0, 0},
153         /*interleave*/ {0, 0},
154         /*track_skew*/ {0, 0},
155         /*cylinder_skew*/ {0, 0},
156         /*flags*/ SFP_HSEC,
157         /*reserved*/ {0, 0, 0}
158 };
159
160 const static struct scsi_format_page format_page_changeable = {
161         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
162         /*page_length*/sizeof(struct scsi_format_page) - 2,
163         /*tracks_per_zone*/ {0, 0},
164         /*alt_sectors_per_zone*/ {0, 0},
165         /*alt_tracks_per_zone*/ {0, 0},
166         /*alt_tracks_per_lun*/ {0, 0},
167         /*sectors_per_track*/ {0, 0},
168         /*bytes_per_sector*/ {0, 0},
169         /*interleave*/ {0, 0},
170         /*track_skew*/ {0, 0},
171         /*cylinder_skew*/ {0, 0},
172         /*flags*/ 0,
173         /*reserved*/ {0, 0, 0}
174 };
175
176 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
177         /*page_code*/SMS_RIGID_DISK_PAGE,
178         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
179         /*cylinders*/ {0, 0, 0},
180         /*heads*/ CTL_DEFAULT_HEADS,
181         /*start_write_precomp*/ {0, 0, 0},
182         /*start_reduced_current*/ {0, 0, 0},
183         /*step_rate*/ {0, 0},
184         /*landing_zone_cylinder*/ {0, 0, 0},
185         /*rpl*/ SRDP_RPL_DISABLED,
186         /*rotational_offset*/ 0,
187         /*reserved1*/ 0,
188         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
189                            CTL_DEFAULT_ROTATION_RATE & 0xff},
190         /*reserved2*/ {0, 0}
191 };
192
193 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
194         /*page_code*/SMS_RIGID_DISK_PAGE,
195         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196         /*cylinders*/ {0, 0, 0},
197         /*heads*/ 0,
198         /*start_write_precomp*/ {0, 0, 0},
199         /*start_reduced_current*/ {0, 0, 0},
200         /*step_rate*/ {0, 0},
201         /*landing_zone_cylinder*/ {0, 0, 0},
202         /*rpl*/ 0,
203         /*rotational_offset*/ 0,
204         /*reserved1*/ 0,
205         /*rotation_rate*/ {0, 0},
206         /*reserved2*/ {0, 0}
207 };
208
209 const static struct scsi_caching_page caching_page_default = {
210         /*page_code*/SMS_CACHING_PAGE,
211         /*page_length*/sizeof(struct scsi_caching_page) - 2,
212         /*flags1*/ SCP_DISC | SCP_WCE,
213         /*ret_priority*/ 0,
214         /*disable_pf_transfer_len*/ {0xff, 0xff},
215         /*min_prefetch*/ {0, 0},
216         /*max_prefetch*/ {0xff, 0xff},
217         /*max_pf_ceiling*/ {0xff, 0xff},
218         /*flags2*/ 0,
219         /*cache_segments*/ 0,
220         /*cache_seg_size*/ {0, 0},
221         /*reserved*/ 0,
222         /*non_cache_seg_size*/ {0, 0, 0}
223 };
224
225 const static struct scsi_caching_page caching_page_changeable = {
226         /*page_code*/SMS_CACHING_PAGE,
227         /*page_length*/sizeof(struct scsi_caching_page) - 2,
228         /*flags1*/ SCP_WCE | SCP_RCD,
229         /*ret_priority*/ 0,
230         /*disable_pf_transfer_len*/ {0, 0},
231         /*min_prefetch*/ {0, 0},
232         /*max_prefetch*/ {0, 0},
233         /*max_pf_ceiling*/ {0, 0},
234         /*flags2*/ 0,
235         /*cache_segments*/ 0,
236         /*cache_seg_size*/ {0, 0},
237         /*reserved*/ 0,
238         /*non_cache_seg_size*/ {0, 0, 0}
239 };
240
241 const static struct scsi_control_page control_page_default = {
242         /*page_code*/SMS_CONTROL_MODE_PAGE,
243         /*page_length*/sizeof(struct scsi_control_page) - 2,
244         /*rlec*/0,
245         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
246         /*eca_and_aen*/0,
247         /*flags4*/SCP_TAS,
248         /*aen_holdoff_period*/{0, 0},
249         /*busy_timeout_period*/{0, 0},
250         /*extended_selftest_completion_time*/{0, 0}
251 };
252
253 const static struct scsi_control_page control_page_changeable = {
254         /*page_code*/SMS_CONTROL_MODE_PAGE,
255         /*page_length*/sizeof(struct scsi_control_page) - 2,
256         /*rlec*/SCP_DSENSE,
257         /*queue_flags*/SCP_QUEUE_ALG_MASK,
258         /*eca_and_aen*/SCP_SWP,
259         /*flags4*/0,
260         /*aen_holdoff_period*/{0, 0},
261         /*busy_timeout_period*/{0, 0},
262         /*extended_selftest_completion_time*/{0, 0}
263 };
264
265 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
266
267 const static struct scsi_control_ext_page control_ext_page_default = {
268         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
269         /*subpage_code*/0x01,
270         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
271         /*flags*/0,
272         /*prio*/0,
273         /*max_sense*/0
274 };
275
276 const static struct scsi_control_ext_page control_ext_page_changeable = {
277         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
278         /*subpage_code*/0x01,
279         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
280         /*flags*/0,
281         /*prio*/0,
282         /*max_sense*/0
283 };
284
285 const static struct scsi_info_exceptions_page ie_page_default = {
286         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
287         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
288         /*info_flags*/SIEP_FLAGS_DEXCPT,
289         /*mrie*/0,
290         /*interval_timer*/{0, 0, 0, 0},
291         /*report_count*/{0, 0, 0, 0}
292 };
293
294 const static struct scsi_info_exceptions_page ie_page_changeable = {
295         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
296         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
297         /*info_flags*/0,
298         /*mrie*/0,
299         /*interval_timer*/{0, 0, 0, 0},
300         /*report_count*/{0, 0, 0, 0}
301 };
302
303 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307         /*subpage_code*/0x02,
308         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309         /*flags*/0,
310         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311         /*descr*/{}},
312         {{/*flags*/0,
313           /*resource*/0x01,
314           /*reserved*/{0, 0},
315           /*count*/{0, 0, 0, 0}},
316          {/*flags*/0,
317           /*resource*/0x02,
318           /*reserved*/{0, 0},
319           /*count*/{0, 0, 0, 0}},
320          {/*flags*/0,
321           /*resource*/0xf1,
322           /*reserved*/{0, 0},
323           /*count*/{0, 0, 0, 0}},
324          {/*flags*/0,
325           /*resource*/0xf2,
326           /*reserved*/{0, 0},
327           /*count*/{0, 0, 0, 0}}
328         }
329 };
330
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333         /*subpage_code*/0x02,
334         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335         /*flags*/0,
336         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337         /*descr*/{}},
338         {{/*flags*/0,
339           /*resource*/0,
340           /*reserved*/{0, 0},
341           /*count*/{0, 0, 0, 0}},
342          {/*flags*/0,
343           /*resource*/0,
344           /*reserved*/{0, 0},
345           /*count*/{0, 0, 0, 0}},
346          {/*flags*/0,
347           /*resource*/0,
348           /*reserved*/{0, 0},
349           /*count*/{0, 0, 0, 0}},
350          {/*flags*/0,
351           /*resource*/0,
352           /*reserved*/{0, 0},
353           /*count*/{0, 0, 0, 0}}
354         }
355 };
356
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358         /*page_code*/SMS_CDDVD_CAPS_PAGE,
359         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360         /*caps1*/0x3f,
361         /*caps2*/0x00,
362         /*caps3*/0xf0,
363         /*caps4*/0x00,
364         /*caps5*/0x29,
365         /*caps6*/0x00,
366         /*obsolete*/{0, 0},
367         /*nvol_levels*/{0, 0},
368         /*buffer_size*/{8, 0},
369         /*obsolete2*/{0, 0},
370         /*reserved*/0,
371         /*digital*/0,
372         /*obsolete3*/0,
373         /*copy_management*/0,
374         /*reserved2*/0,
375         /*rotation_control*/0,
376         /*cur_write_speed*/0,
377         /*num_speed_descr*/0,
378 };
379
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381         /*page_code*/SMS_CDDVD_CAPS_PAGE,
382         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383         /*caps1*/0,
384         /*caps2*/0,
385         /*caps3*/0,
386         /*caps4*/0,
387         /*caps5*/0,
388         /*caps6*/0,
389         /*obsolete*/{0, 0},
390         /*nvol_levels*/{0, 0},
391         /*buffer_size*/{0, 0},
392         /*obsolete2*/{0, 0},
393         /*reserved*/0,
394         /*digital*/0,
395         /*obsolete3*/0,
396         /*copy_management*/0,
397         /*reserved2*/0,
398         /*rotation_control*/0,
399         /*cur_write_speed*/0,
400         /*num_speed_descr*/0,
401 };
402
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407     &worker_threads, 1, "Number of worker threads");
408 static int ctl_debug = CTL_DEBUG_NONE;
409 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411     &ctl_debug, 0, "Enabled debug flags");
412
413 /*
414  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
415  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
416  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
417  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
418  */
419 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
420
421 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
422                                   int param);
423 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
424 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
425 static int ctl_init(void);
426 void ctl_shutdown(void);
427 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
428 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
429 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
430 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
431                               struct ctl_ooa *ooa_hdr,
432                               struct ctl_ooa_entry *kern_entries);
433 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
434                      struct thread *td);
435 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
436                          struct ctl_be_lun *be_lun);
437 static int ctl_free_lun(struct ctl_lun *lun);
438 static void ctl_create_lun(struct ctl_be_lun *be_lun);
439 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
440
441 static int ctl_do_mode_select(union ctl_io *io);
442 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443                            uint64_t res_key, uint64_t sa_res_key,
444                            uint8_t type, uint32_t residx,
445                            struct ctl_scsiio *ctsio,
446                            struct scsi_per_res_out *cdb,
447                            struct scsi_per_res_out_parms* param);
448 static void ctl_pro_preempt_other(struct ctl_lun *lun,
449                                   union ctl_ha_msg *msg);
450 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
451 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457                                          int alloc_len);
458 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459                                          int alloc_len);
460 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466     bool seq);
467 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469     union ctl_io *pending_io, union ctl_io *ooa_io);
470 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471                                 union ctl_io *starting_io);
472 static int ctl_check_blocked(struct ctl_lun *lun);
473 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474                                 const struct ctl_cmd_entry *entry,
475                                 struct ctl_scsiio *ctsio);
476 static void ctl_failover_lun(union ctl_io *io);
477 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478                                struct ctl_scsiio *ctsio);
479 static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483                             ctl_ua_type ua_type);
484 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485                          ctl_ua_type ua_type);
486 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487 static int ctl_abort_task(union ctl_io *io);
488 static int ctl_abort_task_set(union ctl_io *io);
489 static int ctl_query_task(union ctl_io *io, int task_set);
490 static int ctl_i_t_nexus_reset(union ctl_io *io);
491 static int ctl_query_async_event(union ctl_io *io);
492 static void ctl_run_task(union ctl_io *io);
493 #ifdef CTL_IO_DELAY
494 static void ctl_datamove_timer_wakeup(void *arg);
495 static void ctl_done_timer_wakeup(void *arg);
496 #endif /* CTL_IO_DELAY */
497
498 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501 static void ctl_datamove_remote_write(union ctl_io *io);
502 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506                                     ctl_ha_dt_cb callback);
507 static void ctl_datamove_remote_read(union ctl_io *io);
508 static void ctl_datamove_remote(union ctl_io *io);
509 static void ctl_process_done(union ctl_io *io);
510 static void ctl_lun_thread(void *arg);
511 static void ctl_thresh_thread(void *arg);
512 static void ctl_work_thread(void *arg);
513 static void ctl_enqueue_incoming(union ctl_io *io);
514 static void ctl_enqueue_rtr(union ctl_io *io);
515 static void ctl_enqueue_done(union ctl_io *io);
516 static void ctl_enqueue_isc(union ctl_io *io);
517 static const struct ctl_cmd_entry *
518     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519 static const struct ctl_cmd_entry *
520     ctl_validate_command(struct ctl_scsiio *ctsio);
521 static int ctl_cmd_applicable(uint8_t lun_type,
522     const struct ctl_cmd_entry *entry);
523
524 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528
529 /*
530  * Load the serialization table.  This isn't very pretty, but is probably
531  * the easiest way to do it.
532  */
533 #include "ctl_ser_table.c"
534
535 /*
536  * We only need to define open, close and ioctl routines for this driver.
537  */
538 static struct cdevsw ctl_cdevsw = {
539         .d_version =    D_VERSION,
540         .d_flags =      0,
541         .d_open =       ctl_open,
542         .d_close =      ctl_close,
543         .d_ioctl =      ctl_ioctl,
544         .d_name =       "ctl",
545 };
546
547
548 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549
550 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551
552 static moduledata_t ctl_moduledata = {
553         "ctl",
554         ctl_module_event_handler,
555         NULL
556 };
557
558 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559 MODULE_VERSION(ctl, 1);
560
561 static struct ctl_frontend ha_frontend =
562 {
563         .name = "ha",
564 };
565
566 static void
567 ctl_ha_datamove(union ctl_io *io)
568 {
569         struct ctl_lun *lun;
570         struct ctl_sg_entry *sgl;
571         union ctl_ha_msg msg;
572         uint32_t sg_entries_sent;
573         int do_sg_copy, i, j;
574
575         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
576         memset(&msg.dt, 0, sizeof(msg.dt));
577         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
578         msg.hdr.original_sc = io->io_hdr.original_sc;
579         msg.hdr.serializing_sc = io;
580         msg.hdr.nexus = io->io_hdr.nexus;
581         msg.hdr.status = io->io_hdr.status;
582         msg.dt.flags = io->io_hdr.flags;
583
584         /*
585          * We convert everything into a S/G list here.  We can't
586          * pass by reference, only by value between controllers.
587          * So we can't pass a pointer to the S/G list, only as many
588          * S/G entries as we can fit in here.  If it's possible for
589          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
590          * then we need to break this up into multiple transfers.
591          */
592         if (io->scsiio.kern_sg_entries == 0) {
593                 msg.dt.kern_sg_entries = 1;
594 #if 0
595                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
596                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
597                 } else {
598                         /* XXX KDM use busdma here! */
599                         msg.dt.sg_list[0].addr =
600                             (void *)vtophys(io->scsiio.kern_data_ptr);
601                 }
602 #else
603                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
604                     ("HA does not support BUS_ADDR"));
605                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
606 #endif
607                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
608                 do_sg_copy = 0;
609         } else {
610                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
611                 do_sg_copy = 1;
612         }
613
614         msg.dt.kern_data_len = io->scsiio.kern_data_len;
615         msg.dt.kern_total_len = io->scsiio.kern_total_len;
616         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
617         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
618         msg.dt.sg_sequence = 0;
619
620         /*
621          * Loop until we've sent all of the S/G entries.  On the
622          * other end, we'll recompose these S/G entries into one
623          * contiguous list before processing.
624          */
625         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
626             msg.dt.sg_sequence++) {
627                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
628                     sizeof(msg.dt.sg_list[0])),
629                     msg.dt.kern_sg_entries - sg_entries_sent);
630                 if (do_sg_copy != 0) {
631                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
632                         for (i = sg_entries_sent, j = 0;
633                              i < msg.dt.cur_sg_entries; i++, j++) {
634 #if 0
635                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
636                                         msg.dt.sg_list[j].addr = sgl[i].addr;
637                                 } else {
638                                         /* XXX KDM use busdma here! */
639                                         msg.dt.sg_list[j].addr =
640                                             (void *)vtophys(sgl[i].addr);
641                                 }
642 #else
643                                 KASSERT((io->io_hdr.flags &
644                                     CTL_FLAG_BUS_ADDR) == 0,
645                                     ("HA does not support BUS_ADDR"));
646                                 msg.dt.sg_list[j].addr = sgl[i].addr;
647 #endif
648                                 msg.dt.sg_list[j].len = sgl[i].len;
649                         }
650                 }
651
652                 sg_entries_sent += msg.dt.cur_sg_entries;
653                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
654                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
655                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
656                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
657                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
658                         io->io_hdr.port_status = 31341;
659                         io->scsiio.be_move_done(io);
660                         return;
661                 }
662                 msg.dt.sent_sg_entries = sg_entries_sent;
663         }
664
665         /*
666          * Officially handover the request from us to peer.
667          * If failover has just happened, then we must return error.
668          * If failover happen just after, then it is not our problem.
669          */
670         if (lun)
671                 mtx_lock(&lun->lun_lock);
672         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
673                 if (lun)
674                         mtx_unlock(&lun->lun_lock);
675                 io->io_hdr.port_status = 31342;
676                 io->scsiio.be_move_done(io);
677                 return;
678         }
679         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
680         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
681         if (lun)
682                 mtx_unlock(&lun->lun_lock);
683 }
684
685 static void
686 ctl_ha_done(union ctl_io *io)
687 {
688         union ctl_ha_msg msg;
689
690         if (io->io_hdr.io_type == CTL_IO_SCSI) {
691                 memset(&msg, 0, sizeof(msg));
692                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
693                 msg.hdr.original_sc = io->io_hdr.original_sc;
694                 msg.hdr.nexus = io->io_hdr.nexus;
695                 msg.hdr.status = io->io_hdr.status;
696                 msg.scsi.scsi_status = io->scsiio.scsi_status;
697                 msg.scsi.tag_num = io->scsiio.tag_num;
698                 msg.scsi.tag_type = io->scsiio.tag_type;
699                 msg.scsi.sense_len = io->scsiio.sense_len;
700                 msg.scsi.sense_residual = io->scsiio.sense_residual;
701                 msg.scsi.residual = io->scsiio.residual;
702                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
703                     io->scsiio.sense_len);
704                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
705                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
706                     msg.scsi.sense_len, M_WAITOK);
707         }
708         ctl_free_io(io);
709 }
710
711 static void
712 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
713                             union ctl_ha_msg *msg_info)
714 {
715         struct ctl_scsiio *ctsio;
716
717         if (msg_info->hdr.original_sc == NULL) {
718                 printf("%s: original_sc == NULL!\n", __func__);
719                 /* XXX KDM now what? */
720                 return;
721         }
722
723         ctsio = &msg_info->hdr.original_sc->scsiio;
724         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
725         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
726         ctsio->io_hdr.status = msg_info->hdr.status;
727         ctsio->scsi_status = msg_info->scsi.scsi_status;
728         ctsio->sense_len = msg_info->scsi.sense_len;
729         ctsio->sense_residual = msg_info->scsi.sense_residual;
730         ctsio->residual = msg_info->scsi.residual;
731         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
732                msg_info->scsi.sense_len);
733         ctl_enqueue_isc((union ctl_io *)ctsio);
734 }
735
736 static void
737 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
738                                 union ctl_ha_msg *msg_info)
739 {
740         struct ctl_scsiio *ctsio;
741
742         if (msg_info->hdr.serializing_sc == NULL) {
743                 printf("%s: serializing_sc == NULL!\n", __func__);
744                 /* XXX KDM now what? */
745                 return;
746         }
747
748         ctsio = &msg_info->hdr.serializing_sc->scsiio;
749         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
750         ctl_enqueue_isc((union ctl_io *)ctsio);
751 }
752
753 void
754 ctl_isc_announce_lun(struct ctl_lun *lun)
755 {
756         struct ctl_softc *softc = lun->ctl_softc;
757         union ctl_ha_msg *msg;
758         struct ctl_ha_msg_lun_pr_key pr_key;
759         int i, k;
760
761         if (softc->ha_link != CTL_HA_LINK_ONLINE)
762                 return;
763         mtx_lock(&lun->lun_lock);
764         i = sizeof(msg->lun);
765         if (lun->lun_devid)
766                 i += lun->lun_devid->len;
767         i += sizeof(pr_key) * lun->pr_key_count;
768 alloc:
769         mtx_unlock(&lun->lun_lock);
770         msg = malloc(i, M_CTL, M_WAITOK);
771         mtx_lock(&lun->lun_lock);
772         k = sizeof(msg->lun);
773         if (lun->lun_devid)
774                 k += lun->lun_devid->len;
775         k += sizeof(pr_key) * lun->pr_key_count;
776         if (i < k) {
777                 free(msg, M_CTL);
778                 i = k;
779                 goto alloc;
780         }
781         bzero(&msg->lun, sizeof(msg->lun));
782         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
783         msg->hdr.nexus.targ_lun = lun->lun;
784         msg->hdr.nexus.targ_mapped_lun = lun->lun;
785         msg->lun.flags = lun->flags;
786         msg->lun.pr_generation = lun->pr_generation;
787         msg->lun.pr_res_idx = lun->pr_res_idx;
788         msg->lun.pr_res_type = lun->pr_res_type;
789         msg->lun.pr_key_count = lun->pr_key_count;
790         i = 0;
791         if (lun->lun_devid) {
792                 msg->lun.lun_devid_len = lun->lun_devid->len;
793                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
794                     msg->lun.lun_devid_len);
795                 i += msg->lun.lun_devid_len;
796         }
797         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
798                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
799                         continue;
800                 pr_key.pr_iid = k;
801                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
802                 i += sizeof(pr_key);
803         }
804         mtx_unlock(&lun->lun_lock);
805         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
806             M_WAITOK);
807         free(msg, M_CTL);
808
809         if (lun->flags & CTL_LUN_PRIMARY_SC) {
810                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
811                         ctl_isc_announce_mode(lun, -1,
812                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
813                             lun->mode_pages.index[i].subpage);
814                 }
815         }
816 }
817
818 void
819 ctl_isc_announce_port(struct ctl_port *port)
820 {
821         struct ctl_softc *softc = port->ctl_softc;
822         union ctl_ha_msg *msg;
823         int i;
824
825         if (port->targ_port < softc->port_min ||
826             port->targ_port >= softc->port_max ||
827             softc->ha_link != CTL_HA_LINK_ONLINE)
828                 return;
829         i = sizeof(msg->port) + strlen(port->port_name) + 1;
830         if (port->lun_map)
831                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
832         if (port->port_devid)
833                 i += port->port_devid->len;
834         if (port->target_devid)
835                 i += port->target_devid->len;
836         if (port->init_devid)
837                 i += port->init_devid->len;
838         msg = malloc(i, M_CTL, M_WAITOK);
839         bzero(&msg->port, sizeof(msg->port));
840         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
841         msg->hdr.nexus.targ_port = port->targ_port;
842         msg->port.port_type = port->port_type;
843         msg->port.physical_port = port->physical_port;
844         msg->port.virtual_port = port->virtual_port;
845         msg->port.status = port->status;
846         i = 0;
847         msg->port.name_len = sprintf(&msg->port.data[i],
848             "%d:%s", softc->ha_id, port->port_name) + 1;
849         i += msg->port.name_len;
850         if (port->lun_map) {
851                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
852                 memcpy(&msg->port.data[i], port->lun_map,
853                     msg->port.lun_map_len);
854                 i += msg->port.lun_map_len;
855         }
856         if (port->port_devid) {
857                 msg->port.port_devid_len = port->port_devid->len;
858                 memcpy(&msg->port.data[i], port->port_devid->data,
859                     msg->port.port_devid_len);
860                 i += msg->port.port_devid_len;
861         }
862         if (port->target_devid) {
863                 msg->port.target_devid_len = port->target_devid->len;
864                 memcpy(&msg->port.data[i], port->target_devid->data,
865                     msg->port.target_devid_len);
866                 i += msg->port.target_devid_len;
867         }
868         if (port->init_devid) {
869                 msg->port.init_devid_len = port->init_devid->len;
870                 memcpy(&msg->port.data[i], port->init_devid->data,
871                     msg->port.init_devid_len);
872                 i += msg->port.init_devid_len;
873         }
874         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
875             M_WAITOK);
876         free(msg, M_CTL);
877 }
878
879 void
880 ctl_isc_announce_iid(struct ctl_port *port, int iid)
881 {
882         struct ctl_softc *softc = port->ctl_softc;
883         union ctl_ha_msg *msg;
884         int i, l;
885
886         if (port->targ_port < softc->port_min ||
887             port->targ_port >= softc->port_max ||
888             softc->ha_link != CTL_HA_LINK_ONLINE)
889                 return;
890         mtx_lock(&softc->ctl_lock);
891         i = sizeof(msg->iid);
892         l = 0;
893         if (port->wwpn_iid[iid].name)
894                 l = strlen(port->wwpn_iid[iid].name) + 1;
895         i += l;
896         msg = malloc(i, M_CTL, M_NOWAIT);
897         if (msg == NULL) {
898                 mtx_unlock(&softc->ctl_lock);
899                 return;
900         }
901         bzero(&msg->iid, sizeof(msg->iid));
902         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
903         msg->hdr.nexus.targ_port = port->targ_port;
904         msg->hdr.nexus.initid = iid;
905         msg->iid.in_use = port->wwpn_iid[iid].in_use;
906         msg->iid.name_len = l;
907         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
908         if (port->wwpn_iid[iid].name)
909                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
910         mtx_unlock(&softc->ctl_lock);
911         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
912         free(msg, M_CTL);
913 }
914
915 void
916 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
917     uint8_t page, uint8_t subpage)
918 {
919         struct ctl_softc *softc = lun->ctl_softc;
920         union ctl_ha_msg msg;
921         u_int i;
922
923         if (softc->ha_link != CTL_HA_LINK_ONLINE)
924                 return;
925         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
926                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
927                     page && lun->mode_pages.index[i].subpage == subpage)
928                         break;
929         }
930         if (i == CTL_NUM_MODE_PAGES)
931                 return;
932
933         /* Don't try to replicate pages not present on this device. */
934         if (lun->mode_pages.index[i].page_data == NULL)
935                 return;
936
937         bzero(&msg.mode, sizeof(msg.mode));
938         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
939         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
940         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
941         msg.hdr.nexus.targ_lun = lun->lun;
942         msg.hdr.nexus.targ_mapped_lun = lun->lun;
943         msg.mode.page_code = page;
944         msg.mode.subpage = subpage;
945         msg.mode.page_len = lun->mode_pages.index[i].page_len;
946         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
947             msg.mode.page_len);
948         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
949             M_WAITOK);
950 }
951
952 static void
953 ctl_isc_ha_link_up(struct ctl_softc *softc)
954 {
955         struct ctl_port *port;
956         struct ctl_lun *lun;
957         union ctl_ha_msg msg;
958         int i;
959
960         /* Announce this node parameters to peer for validation. */
961         msg.login.msg_type = CTL_MSG_LOGIN;
962         msg.login.version = CTL_HA_VERSION;
963         msg.login.ha_mode = softc->ha_mode;
964         msg.login.ha_id = softc->ha_id;
965         msg.login.max_luns = CTL_MAX_LUNS;
966         msg.login.max_ports = CTL_MAX_PORTS;
967         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
968         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
969             M_WAITOK);
970
971         STAILQ_FOREACH(port, &softc->port_list, links) {
972                 ctl_isc_announce_port(port);
973                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
974                         if (port->wwpn_iid[i].in_use)
975                                 ctl_isc_announce_iid(port, i);
976                 }
977         }
978         STAILQ_FOREACH(lun, &softc->lun_list, links)
979                 ctl_isc_announce_lun(lun);
980 }
981
982 static void
983 ctl_isc_ha_link_down(struct ctl_softc *softc)
984 {
985         struct ctl_port *port;
986         struct ctl_lun *lun;
987         union ctl_io *io;
988         int i;
989
990         mtx_lock(&softc->ctl_lock);
991         STAILQ_FOREACH(lun, &softc->lun_list, links) {
992                 mtx_lock(&lun->lun_lock);
993                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
994                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
995                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
996                 }
997                 mtx_unlock(&lun->lun_lock);
998
999                 mtx_unlock(&softc->ctl_lock);
1000                 io = ctl_alloc_io(softc->othersc_pool);
1001                 mtx_lock(&softc->ctl_lock);
1002                 ctl_zero_io(io);
1003                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1004                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1005                 ctl_enqueue_isc(io);
1006         }
1007
1008         STAILQ_FOREACH(port, &softc->port_list, links) {
1009                 if (port->targ_port >= softc->port_min &&
1010                     port->targ_port < softc->port_max)
1011                         continue;
1012                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1013                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1014                         port->wwpn_iid[i].in_use = 0;
1015                         free(port->wwpn_iid[i].name, M_CTL);
1016                         port->wwpn_iid[i].name = NULL;
1017                 }
1018         }
1019         mtx_unlock(&softc->ctl_lock);
1020 }
1021
1022 static void
1023 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1024 {
1025         struct ctl_lun *lun;
1026         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1027
1028         mtx_lock(&softc->ctl_lock);
1029         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1030             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1031                 mtx_lock(&lun->lun_lock);
1032                 mtx_unlock(&softc->ctl_lock);
1033                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1034                     msg->ua.ua_set)
1035                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1036                 if (msg->ua.ua_all) {
1037                         if (msg->ua.ua_set)
1038                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1039                         else
1040                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1041                 } else {
1042                         if (msg->ua.ua_set)
1043                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
1044                         else
1045                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
1046                 }
1047                 mtx_unlock(&lun->lun_lock);
1048         } else
1049                 mtx_unlock(&softc->ctl_lock);
1050 }
1051
1052 static void
1053 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1054 {
1055         struct ctl_lun *lun;
1056         struct ctl_ha_msg_lun_pr_key pr_key;
1057         int i, k;
1058         ctl_lun_flags oflags;
1059         uint32_t targ_lun;
1060
1061         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1062         mtx_lock(&softc->ctl_lock);
1063         if ((targ_lun >= CTL_MAX_LUNS) ||
1064             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1065                 mtx_unlock(&softc->ctl_lock);
1066                 return;
1067         }
1068         mtx_lock(&lun->lun_lock);
1069         mtx_unlock(&softc->ctl_lock);
1070         if (lun->flags & CTL_LUN_DISABLED) {
1071                 mtx_unlock(&lun->lun_lock);
1072                 return;
1073         }
1074         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1075         if (msg->lun.lun_devid_len != i || (i > 0 &&
1076             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1077                 mtx_unlock(&lun->lun_lock);
1078                 printf("%s: Received conflicting HA LUN %d\n",
1079                     __func__, msg->hdr.nexus.targ_lun);
1080                 return;
1081         } else {
1082                 /* Record whether peer is primary. */
1083                 oflags = lun->flags;
1084                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1085                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1086                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1087                 else
1088                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1089                 if (oflags != lun->flags)
1090                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1091
1092                 /* If peer is primary and we are not -- use data */
1093                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1094                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1095                         lun->pr_generation = msg->lun.pr_generation;
1096                         lun->pr_res_idx = msg->lun.pr_res_idx;
1097                         lun->pr_res_type = msg->lun.pr_res_type;
1098                         lun->pr_key_count = msg->lun.pr_key_count;
1099                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1100                                 ctl_clr_prkey(lun, k);
1101                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1102                                 memcpy(&pr_key, &msg->lun.data[i],
1103                                     sizeof(pr_key));
1104                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1105                                 ctl_set_prkey(lun, pr_key.pr_iid,
1106                                     pr_key.pr_key);
1107                                 i += sizeof(pr_key);
1108                         }
1109                 }
1110
1111                 mtx_unlock(&lun->lun_lock);
1112                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1113                     __func__, msg->hdr.nexus.targ_lun,
1114                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1115                     "primary" : "secondary"));
1116
1117                 /* If we are primary but peer doesn't know -- notify */
1118                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1119                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1120                         ctl_isc_announce_lun(lun);
1121         }
1122 }
1123
1124 static void
1125 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1126 {
1127         struct ctl_port *port;
1128         struct ctl_lun *lun;
1129         int i, new;
1130
1131         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1132         if (port == NULL) {
1133                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1134                     msg->hdr.nexus.targ_port));
1135                 new = 1;
1136                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1137                 port->frontend = &ha_frontend;
1138                 port->targ_port = msg->hdr.nexus.targ_port;
1139                 port->fe_datamove = ctl_ha_datamove;
1140                 port->fe_done = ctl_ha_done;
1141         } else if (port->frontend == &ha_frontend) {
1142                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1143                     msg->hdr.nexus.targ_port));
1144                 new = 0;
1145         } else {
1146                 printf("%s: Received conflicting HA port %d\n",
1147                     __func__, msg->hdr.nexus.targ_port);
1148                 return;
1149         }
1150         port->port_type = msg->port.port_type;
1151         port->physical_port = msg->port.physical_port;
1152         port->virtual_port = msg->port.virtual_port;
1153         port->status = msg->port.status;
1154         i = 0;
1155         free(port->port_name, M_CTL);
1156         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1157             M_CTL);
1158         i += msg->port.name_len;
1159         if (msg->port.lun_map_len != 0) {
1160                 if (port->lun_map == NULL)
1161                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1162                             M_CTL, M_WAITOK);
1163                 memcpy(port->lun_map, &msg->port.data[i],
1164                     sizeof(uint32_t) * CTL_MAX_LUNS);
1165                 i += msg->port.lun_map_len;
1166         } else {
1167                 free(port->lun_map, M_CTL);
1168                 port->lun_map = NULL;
1169         }
1170         if (msg->port.port_devid_len != 0) {
1171                 if (port->port_devid == NULL ||
1172                     port->port_devid->len != msg->port.port_devid_len) {
1173                         free(port->port_devid, M_CTL);
1174                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1175                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1176                 }
1177                 memcpy(port->port_devid->data, &msg->port.data[i],
1178                     msg->port.port_devid_len);
1179                 port->port_devid->len = msg->port.port_devid_len;
1180                 i += msg->port.port_devid_len;
1181         } else {
1182                 free(port->port_devid, M_CTL);
1183                 port->port_devid = NULL;
1184         }
1185         if (msg->port.target_devid_len != 0) {
1186                 if (port->target_devid == NULL ||
1187                     port->target_devid->len != msg->port.target_devid_len) {
1188                         free(port->target_devid, M_CTL);
1189                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1190                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1191                 }
1192                 memcpy(port->target_devid->data, &msg->port.data[i],
1193                     msg->port.target_devid_len);
1194                 port->target_devid->len = msg->port.target_devid_len;
1195                 i += msg->port.target_devid_len;
1196         } else {
1197                 free(port->target_devid, M_CTL);
1198                 port->target_devid = NULL;
1199         }
1200         if (msg->port.init_devid_len != 0) {
1201                 if (port->init_devid == NULL ||
1202                     port->init_devid->len != msg->port.init_devid_len) {
1203                         free(port->init_devid, M_CTL);
1204                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1205                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1206                 }
1207                 memcpy(port->init_devid->data, &msg->port.data[i],
1208                     msg->port.init_devid_len);
1209                 port->init_devid->len = msg->port.init_devid_len;
1210                 i += msg->port.init_devid_len;
1211         } else {
1212                 free(port->init_devid, M_CTL);
1213                 port->init_devid = NULL;
1214         }
1215         if (new) {
1216                 if (ctl_port_register(port) != 0) {
1217                         printf("%s: ctl_port_register() failed with error\n",
1218                             __func__);
1219                 }
1220         }
1221         mtx_lock(&softc->ctl_lock);
1222         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1223                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1224                         continue;
1225                 mtx_lock(&lun->lun_lock);
1226                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1227                 mtx_unlock(&lun->lun_lock);
1228         }
1229         mtx_unlock(&softc->ctl_lock);
1230 }
1231
1232 static void
1233 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1234 {
1235         struct ctl_port *port;
1236         int iid;
1237
1238         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1239         if (port == NULL) {
1240                 printf("%s: Received IID for unknown port %d\n",
1241                     __func__, msg->hdr.nexus.targ_port);
1242                 return;
1243         }
1244         iid = msg->hdr.nexus.initid;
1245         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1246         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1247         free(port->wwpn_iid[iid].name, M_CTL);
1248         if (msg->iid.name_len) {
1249                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1250                     msg->iid.name_len, M_CTL);
1251         } else
1252                 port->wwpn_iid[iid].name = NULL;
1253 }
1254
1255 static void
1256 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1257 {
1258
1259         if (msg->login.version != CTL_HA_VERSION) {
1260                 printf("CTL HA peers have different versions %d != %d\n",
1261                     msg->login.version, CTL_HA_VERSION);
1262                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1263                 return;
1264         }
1265         if (msg->login.ha_mode != softc->ha_mode) {
1266                 printf("CTL HA peers have different ha_mode %d != %d\n",
1267                     msg->login.ha_mode, softc->ha_mode);
1268                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1269                 return;
1270         }
1271         if (msg->login.ha_id == softc->ha_id) {
1272                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1273                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274                 return;
1275         }
1276         if (msg->login.max_luns != CTL_MAX_LUNS ||
1277             msg->login.max_ports != CTL_MAX_PORTS ||
1278             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1279                 printf("CTL HA peers have different limits\n");
1280                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281                 return;
1282         }
1283 }
1284
1285 static void
1286 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1287 {
1288         struct ctl_lun *lun;
1289         u_int i;
1290         uint32_t initidx, targ_lun;
1291
1292         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1293         mtx_lock(&softc->ctl_lock);
1294         if ((targ_lun >= CTL_MAX_LUNS) ||
1295             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1296                 mtx_unlock(&softc->ctl_lock);
1297                 return;
1298         }
1299         mtx_lock(&lun->lun_lock);
1300         mtx_unlock(&softc->ctl_lock);
1301         if (lun->flags & CTL_LUN_DISABLED) {
1302                 mtx_unlock(&lun->lun_lock);
1303                 return;
1304         }
1305         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1306                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1307                     msg->mode.page_code &&
1308                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1309                         break;
1310         }
1311         if (i == CTL_NUM_MODE_PAGES) {
1312                 mtx_unlock(&lun->lun_lock);
1313                 return;
1314         }
1315         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1316             lun->mode_pages.index[i].page_len);
1317         initidx = ctl_get_initindex(&msg->hdr.nexus);
1318         if (initidx != -1)
1319                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1320         mtx_unlock(&lun->lun_lock);
1321 }
1322
1323 /*
1324  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1325  * subsystem come in here.
1326  */
1327 static void
1328 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1329 {
1330         struct ctl_softc *softc = control_softc;
1331         union ctl_io *io;
1332         struct ctl_prio *presio;
1333         ctl_ha_status isc_status;
1334
1335         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1336         if (event == CTL_HA_EVT_MSG_RECV) {
1337                 union ctl_ha_msg *msg, msgbuf;
1338
1339                 if (param > sizeof(msgbuf))
1340                         msg = malloc(param, M_CTL, M_WAITOK);
1341                 else
1342                         msg = &msgbuf;
1343                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1344                     M_WAITOK);
1345                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1346                         printf("%s: Error receiving message: %d\n",
1347                             __func__, isc_status);
1348                         if (msg != &msgbuf)
1349                                 free(msg, M_CTL);
1350                         return;
1351                 }
1352
1353                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1354                 switch (msg->hdr.msg_type) {
1355                 case CTL_MSG_SERIALIZE:
1356                         io = ctl_alloc_io(softc->othersc_pool);
1357                         ctl_zero_io(io);
1358                         // populate ctsio from msg
1359                         io->io_hdr.io_type = CTL_IO_SCSI;
1360                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1361                         io->io_hdr.original_sc = msg->hdr.original_sc;
1362                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1363                                             CTL_FLAG_IO_ACTIVE;
1364                         /*
1365                          * If we're in serialization-only mode, we don't
1366                          * want to go through full done processing.  Thus
1367                          * the COPY flag.
1368                          *
1369                          * XXX KDM add another flag that is more specific.
1370                          */
1371                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1372                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1373                         io->io_hdr.nexus = msg->hdr.nexus;
1374 #if 0
1375                         printf("port %u, iid %u, lun %u\n",
1376                                io->io_hdr.nexus.targ_port,
1377                                io->io_hdr.nexus.initid,
1378                                io->io_hdr.nexus.targ_lun);
1379 #endif
1380                         io->scsiio.tag_num = msg->scsi.tag_num;
1381                         io->scsiio.tag_type = msg->scsi.tag_type;
1382 #ifdef CTL_TIME_IO
1383                         io->io_hdr.start_time = time_uptime;
1384                         getbinuptime(&io->io_hdr.start_bt);
1385 #endif /* CTL_TIME_IO */
1386                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1387                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1388                                CTL_MAX_CDBLEN);
1389                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1390                                 const struct ctl_cmd_entry *entry;
1391
1392                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1393                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1394                                 io->io_hdr.flags |=
1395                                         entry->flags & CTL_FLAG_DATA_MASK;
1396                         }
1397                         ctl_enqueue_isc(io);
1398                         break;
1399
1400                 /* Performed on the Originating SC, XFER mode only */
1401                 case CTL_MSG_DATAMOVE: {
1402                         struct ctl_sg_entry *sgl;
1403                         int i, j;
1404
1405                         io = msg->hdr.original_sc;
1406                         if (io == NULL) {
1407                                 printf("%s: original_sc == NULL!\n", __func__);
1408                                 /* XXX KDM do something here */
1409                                 break;
1410                         }
1411                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1412                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1413                         /*
1414                          * Keep track of this, we need to send it back over
1415                          * when the datamove is complete.
1416                          */
1417                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1418                         if (msg->hdr.status == CTL_SUCCESS)
1419                                 io->io_hdr.status = msg->hdr.status;
1420
1421                         if (msg->dt.sg_sequence == 0) {
1422 #ifdef CTL_TIME_IO
1423                                 getbinuptime(&io->io_hdr.dma_start_bt);
1424 #endif
1425                                 i = msg->dt.kern_sg_entries +
1426                                     msg->dt.kern_data_len /
1427                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1428                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1429                                     M_WAITOK | M_ZERO);
1430                                 io->io_hdr.remote_sglist = sgl;
1431                                 io->io_hdr.local_sglist =
1432                                     &sgl[msg->dt.kern_sg_entries];
1433
1434                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1435
1436                                 io->scsiio.kern_sg_entries =
1437                                         msg->dt.kern_sg_entries;
1438                                 io->scsiio.rem_sg_entries =
1439                                         msg->dt.kern_sg_entries;
1440                                 io->scsiio.kern_data_len =
1441                                         msg->dt.kern_data_len;
1442                                 io->scsiio.kern_total_len =
1443                                         msg->dt.kern_total_len;
1444                                 io->scsiio.kern_data_resid =
1445                                         msg->dt.kern_data_resid;
1446                                 io->scsiio.kern_rel_offset =
1447                                         msg->dt.kern_rel_offset;
1448                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1449                                 io->io_hdr.flags |= msg->dt.flags &
1450                                     CTL_FLAG_BUS_ADDR;
1451                         } else
1452                                 sgl = (struct ctl_sg_entry *)
1453                                         io->scsiio.kern_data_ptr;
1454
1455                         for (i = msg->dt.sent_sg_entries, j = 0;
1456                              i < (msg->dt.sent_sg_entries +
1457                              msg->dt.cur_sg_entries); i++, j++) {
1458                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1459                                 sgl[i].len = msg->dt.sg_list[j].len;
1460
1461 #if 0
1462                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1463                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1464 #endif
1465                         }
1466
1467                         /*
1468                          * If this is the last piece of the I/O, we've got
1469                          * the full S/G list.  Queue processing in the thread.
1470                          * Otherwise wait for the next piece.
1471                          */
1472                         if (msg->dt.sg_last != 0)
1473                                 ctl_enqueue_isc(io);
1474                         break;
1475                 }
1476                 /* Performed on the Serializing (primary) SC, XFER mode only */
1477                 case CTL_MSG_DATAMOVE_DONE: {
1478                         if (msg->hdr.serializing_sc == NULL) {
1479                                 printf("%s: serializing_sc == NULL!\n",
1480                                        __func__);
1481                                 /* XXX KDM now what? */
1482                                 break;
1483                         }
1484                         /*
1485                          * We grab the sense information here in case
1486                          * there was a failure, so we can return status
1487                          * back to the initiator.
1488                          */
1489                         io = msg->hdr.serializing_sc;
1490                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1491                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1492                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1493                         io->io_hdr.port_status = msg->scsi.fetd_status;
1494                         io->scsiio.residual = msg->scsi.residual;
1495                         if (msg->hdr.status != CTL_STATUS_NONE) {
1496                                 io->io_hdr.status = msg->hdr.status;
1497                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1498                                 io->scsiio.sense_len = msg->scsi.sense_len;
1499                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1500                                 memcpy(&io->scsiio.sense_data,
1501                                     &msg->scsi.sense_data,
1502                                     msg->scsi.sense_len);
1503                                 if (msg->hdr.status == CTL_SUCCESS)
1504                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1505                         }
1506                         ctl_enqueue_isc(io);
1507                         break;
1508                 }
1509
1510                 /* Preformed on Originating SC, SER_ONLY mode */
1511                 case CTL_MSG_R2R:
1512                         io = msg->hdr.original_sc;
1513                         if (io == NULL) {
1514                                 printf("%s: original_sc == NULL!\n",
1515                                     __func__);
1516                                 break;
1517                         }
1518                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1519                         io->io_hdr.msg_type = CTL_MSG_R2R;
1520                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1521                         ctl_enqueue_isc(io);
1522                         break;
1523
1524                 /*
1525                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1526                  * mode.
1527                  * Performed on the Originating (i.e. secondary) SC in XFER
1528                  * mode
1529                  */
1530                 case CTL_MSG_FINISH_IO:
1531                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1532                                 ctl_isc_handler_finish_xfer(softc, msg);
1533                         else
1534                                 ctl_isc_handler_finish_ser_only(softc, msg);
1535                         break;
1536
1537                 /* Preformed on Originating SC */
1538                 case CTL_MSG_BAD_JUJU:
1539                         io = msg->hdr.original_sc;
1540                         if (io == NULL) {
1541                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1542                                        __func__);
1543                                 break;
1544                         }
1545                         ctl_copy_sense_data(msg, io);
1546                         /*
1547                          * IO should have already been cleaned up on other
1548                          * SC so clear this flag so we won't send a message
1549                          * back to finish the IO there.
1550                          */
1551                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1552                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1553
1554                         /* io = msg->hdr.serializing_sc; */
1555                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1556                         ctl_enqueue_isc(io);
1557                         break;
1558
1559                 /* Handle resets sent from the other side */
1560                 case CTL_MSG_MANAGE_TASKS: {
1561                         struct ctl_taskio *taskio;
1562                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1563                             softc->othersc_pool);
1564                         ctl_zero_io((union ctl_io *)taskio);
1565                         taskio->io_hdr.io_type = CTL_IO_TASK;
1566                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1567                         taskio->io_hdr.nexus = msg->hdr.nexus;
1568                         taskio->task_action = msg->task.task_action;
1569                         taskio->tag_num = msg->task.tag_num;
1570                         taskio->tag_type = msg->task.tag_type;
1571 #ifdef CTL_TIME_IO
1572                         taskio->io_hdr.start_time = time_uptime;
1573                         getbinuptime(&taskio->io_hdr.start_bt);
1574 #endif /* CTL_TIME_IO */
1575                         ctl_run_task((union ctl_io *)taskio);
1576                         break;
1577                 }
1578                 /* Persistent Reserve action which needs attention */
1579                 case CTL_MSG_PERS_ACTION:
1580                         presio = (struct ctl_prio *)ctl_alloc_io(
1581                             softc->othersc_pool);
1582                         ctl_zero_io((union ctl_io *)presio);
1583                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1584                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1585                         presio->io_hdr.nexus = msg->hdr.nexus;
1586                         presio->pr_msg = msg->pr;
1587                         ctl_enqueue_isc((union ctl_io *)presio);
1588                         break;
1589                 case CTL_MSG_UA:
1590                         ctl_isc_ua(softc, msg, param);
1591                         break;
1592                 case CTL_MSG_PORT_SYNC:
1593                         ctl_isc_port_sync(softc, msg, param);
1594                         break;
1595                 case CTL_MSG_LUN_SYNC:
1596                         ctl_isc_lun_sync(softc, msg, param);
1597                         break;
1598                 case CTL_MSG_IID_SYNC:
1599                         ctl_isc_iid_sync(softc, msg, param);
1600                         break;
1601                 case CTL_MSG_LOGIN:
1602                         ctl_isc_login(softc, msg, param);
1603                         break;
1604                 case CTL_MSG_MODE_SYNC:
1605                         ctl_isc_mode_sync(softc, msg, param);
1606                         break;
1607                 default:
1608                         printf("Received HA message of unknown type %d\n",
1609                             msg->hdr.msg_type);
1610                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1611                         break;
1612                 }
1613                 if (msg != &msgbuf)
1614                         free(msg, M_CTL);
1615         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1616                 printf("CTL: HA link status changed from %d to %d\n",
1617                     softc->ha_link, param);
1618                 if (param == softc->ha_link)
1619                         return;
1620                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1621                         softc->ha_link = param;
1622                         ctl_isc_ha_link_down(softc);
1623                 } else {
1624                         softc->ha_link = param;
1625                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1626                                 ctl_isc_ha_link_up(softc);
1627                 }
1628                 return;
1629         } else {
1630                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1631                 return;
1632         }
1633 }
1634
1635 static void
1636 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1637 {
1638
1639         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1640             src->scsi.sense_len);
1641         dest->scsiio.scsi_status = src->scsi.scsi_status;
1642         dest->scsiio.sense_len = src->scsi.sense_len;
1643         dest->io_hdr.status = src->hdr.status;
1644 }
1645
1646 static void
1647 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1648 {
1649
1650         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1651             src->scsiio.sense_len);
1652         dest->scsi.scsi_status = src->scsiio.scsi_status;
1653         dest->scsi.sense_len = src->scsiio.sense_len;
1654         dest->hdr.status = src->io_hdr.status;
1655 }
1656
1657 void
1658 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1659 {
1660         struct ctl_softc *softc = lun->ctl_softc;
1661         ctl_ua_type *pu;
1662
1663         if (initidx < softc->init_min || initidx >= softc->init_max)
1664                 return;
1665         mtx_assert(&lun->lun_lock, MA_OWNED);
1666         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1667         if (pu == NULL)
1668                 return;
1669         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1670 }
1671
1672 void
1673 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1674 {
1675         int i;
1676
1677         mtx_assert(&lun->lun_lock, MA_OWNED);
1678         if (lun->pending_ua[port] == NULL)
1679                 return;
1680         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1681                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1682                         continue;
1683                 lun->pending_ua[port][i] |= ua;
1684         }
1685 }
1686
1687 void
1688 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1689 {
1690         struct ctl_softc *softc = lun->ctl_softc;
1691         int i;
1692
1693         mtx_assert(&lun->lun_lock, MA_OWNED);
1694         for (i = softc->port_min; i < softc->port_max; i++)
1695                 ctl_est_ua_port(lun, i, except, ua);
1696 }
1697
1698 void
1699 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1700 {
1701         struct ctl_softc *softc = lun->ctl_softc;
1702         ctl_ua_type *pu;
1703
1704         if (initidx < softc->init_min || initidx >= softc->init_max)
1705                 return;
1706         mtx_assert(&lun->lun_lock, MA_OWNED);
1707         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1708         if (pu == NULL)
1709                 return;
1710         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1711 }
1712
1713 void
1714 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1715 {
1716         struct ctl_softc *softc = lun->ctl_softc;
1717         int i, j;
1718
1719         mtx_assert(&lun->lun_lock, MA_OWNED);
1720         for (i = softc->port_min; i < softc->port_max; i++) {
1721                 if (lun->pending_ua[i] == NULL)
1722                         continue;
1723                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1724                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1725                                 continue;
1726                         lun->pending_ua[i][j] &= ~ua;
1727                 }
1728         }
1729 }
1730
1731 void
1732 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1733     ctl_ua_type ua_type)
1734 {
1735         struct ctl_lun *lun;
1736
1737         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1738         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1739                 mtx_lock(&lun->lun_lock);
1740                 ctl_clr_ua(lun, initidx, ua_type);
1741                 mtx_unlock(&lun->lun_lock);
1742         }
1743 }
1744
1745 static int
1746 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1747 {
1748         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1749         struct ctl_lun *lun;
1750         struct ctl_lun_req ireq;
1751         int error, value;
1752
1753         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1754         error = sysctl_handle_int(oidp, &value, 0, req);
1755         if ((error != 0) || (req->newptr == NULL))
1756                 return (error);
1757
1758         mtx_lock(&softc->ctl_lock);
1759         if (value == 0)
1760                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1761         else
1762                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1763         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1764                 mtx_unlock(&softc->ctl_lock);
1765                 bzero(&ireq, sizeof(ireq));
1766                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1767                 ireq.reqdata.modify.lun_id = lun->lun;
1768                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1769                     curthread);
1770                 if (ireq.status != CTL_LUN_OK) {
1771                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1772                             __func__, ireq.status, ireq.error_str);
1773                 }
1774                 mtx_lock(&softc->ctl_lock);
1775         }
1776         mtx_unlock(&softc->ctl_lock);
1777         return (0);
1778 }
1779
1780 static int
1781 ctl_init(void)
1782 {
1783         struct make_dev_args args;
1784         struct ctl_softc *softc;
1785         void *other_pool;
1786         int i, error;
1787
1788         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1789                                M_WAITOK | M_ZERO);
1790
1791         make_dev_args_init(&args);
1792         args.mda_devsw = &ctl_cdevsw;
1793         args.mda_uid = UID_ROOT;
1794         args.mda_gid = GID_OPERATOR;
1795         args.mda_mode = 0600;
1796         args.mda_si_drv1 = softc;
1797         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1798         if (error != 0) {
1799                 free(control_softc, M_DEVBUF);
1800                 return (error);
1801         }
1802
1803         sysctl_ctx_init(&softc->sysctl_ctx);
1804         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1805                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1806                 CTLFLAG_RD, 0, "CAM Target Layer");
1807
1808         if (softc->sysctl_tree == NULL) {
1809                 printf("%s: unable to allocate sysctl tree\n", __func__);
1810                 destroy_dev(softc->dev);
1811                 free(control_softc, M_DEVBUF);
1812                 control_softc = NULL;
1813                 return (ENOMEM);
1814         }
1815
1816         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1817         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1818             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1819         softc->flags = 0;
1820
1821         TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1822         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1823             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1824             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1825
1826         /*
1827          * In Copan's HA scheme, the "master" and "slave" roles are
1828          * figured out through the slot the controller is in.  Although it
1829          * is an active/active system, someone has to be in charge.
1830          */
1831         TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1832         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1833             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1834             "HA head ID (0 - no HA)");
1835         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1836                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1837                 softc->is_single = 1;
1838                 softc->port_cnt = CTL_MAX_PORTS;
1839                 softc->port_min = 0;
1840         } else {
1841                 softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1842                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1843         }
1844         softc->port_max = softc->port_min + softc->port_cnt;
1845         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1846         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1847
1848         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1849             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1850             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1851
1852         STAILQ_INIT(&softc->lun_list);
1853         STAILQ_INIT(&softc->pending_lun_queue);
1854         STAILQ_INIT(&softc->fe_list);
1855         STAILQ_INIT(&softc->port_list);
1856         STAILQ_INIT(&softc->be_list);
1857         ctl_tpc_init(softc);
1858
1859         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1860                             &other_pool) != 0)
1861         {
1862                 printf("ctl: can't allocate %d entry other SC pool, "
1863                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1864                 return (ENOMEM);
1865         }
1866         softc->othersc_pool = other_pool;
1867
1868         if (worker_threads <= 0)
1869                 worker_threads = max(1, mp_ncpus / 4);
1870         if (worker_threads > CTL_MAX_THREADS)
1871                 worker_threads = CTL_MAX_THREADS;
1872
1873         for (i = 0; i < worker_threads; i++) {
1874                 struct ctl_thread *thr = &softc->threads[i];
1875
1876                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1877                 thr->ctl_softc = softc;
1878                 STAILQ_INIT(&thr->incoming_queue);
1879                 STAILQ_INIT(&thr->rtr_queue);
1880                 STAILQ_INIT(&thr->done_queue);
1881                 STAILQ_INIT(&thr->isc_queue);
1882
1883                 error = kproc_kthread_add(ctl_work_thread, thr,
1884                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1885                 if (error != 0) {
1886                         printf("error creating CTL work thread!\n");
1887                         ctl_pool_free(other_pool);
1888                         return (error);
1889                 }
1890         }
1891         error = kproc_kthread_add(ctl_lun_thread, softc,
1892             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1893         if (error != 0) {
1894                 printf("error creating CTL lun thread!\n");
1895                 ctl_pool_free(other_pool);
1896                 return (error);
1897         }
1898         error = kproc_kthread_add(ctl_thresh_thread, softc,
1899             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1900         if (error != 0) {
1901                 printf("error creating CTL threshold thread!\n");
1902                 ctl_pool_free(other_pool);
1903                 return (error);
1904         }
1905
1906         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1907             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1908             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1909
1910         if (softc->is_single == 0) {
1911                 ctl_frontend_register(&ha_frontend);
1912                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1913                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1914                         softc->is_single = 1;
1915                 } else
1916                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1917                     != CTL_HA_STATUS_SUCCESS) {
1918                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1919                         softc->is_single = 1;
1920                 }
1921         }
1922         return (0);
1923 }
1924
1925 void
1926 ctl_shutdown(void)
1927 {
1928         struct ctl_softc *softc = control_softc;
1929         struct ctl_lun *lun, *next_lun;
1930
1931         if (softc->is_single == 0) {
1932                 ctl_ha_msg_shutdown(softc);
1933                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1934                     != CTL_HA_STATUS_SUCCESS)
1935                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1936                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1937                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1938                 ctl_frontend_deregister(&ha_frontend);
1939         }
1940
1941         mtx_lock(&softc->ctl_lock);
1942
1943         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1944                 ctl_free_lun(lun);
1945
1946         mtx_unlock(&softc->ctl_lock);
1947
1948 #if 0
1949         ctl_shutdown_thread(softc->work_thread);
1950         mtx_destroy(&softc->queue_lock);
1951 #endif
1952
1953         ctl_tpc_shutdown(softc);
1954         uma_zdestroy(softc->io_zone);
1955         mtx_destroy(&softc->ctl_lock);
1956
1957         destroy_dev(softc->dev);
1958
1959         sysctl_ctx_free(&softc->sysctl_ctx);
1960
1961         free(control_softc, M_DEVBUF);
1962         control_softc = NULL;
1963 }
1964
1965 static int
1966 ctl_module_event_handler(module_t mod, int what, void *arg)
1967 {
1968
1969         switch (what) {
1970         case MOD_LOAD:
1971                 return (ctl_init());
1972         case MOD_UNLOAD:
1973                 return (EBUSY);
1974         default:
1975                 return (EOPNOTSUPP);
1976         }
1977 }
1978
1979 /*
1980  * XXX KDM should we do some access checks here?  Bump a reference count to
1981  * prevent a CTL module from being unloaded while someone has it open?
1982  */
1983 static int
1984 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1985 {
1986         return (0);
1987 }
1988
1989 static int
1990 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1991 {
1992         return (0);
1993 }
1994
1995 /*
1996  * Remove an initiator by port number and initiator ID.
1997  * Returns 0 for success, -1 for failure.
1998  */
1999 int
2000 ctl_remove_initiator(struct ctl_port *port, int iid)
2001 {
2002         struct ctl_softc *softc = port->ctl_softc;
2003
2004         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2005
2006         if (iid > CTL_MAX_INIT_PER_PORT) {
2007                 printf("%s: initiator ID %u > maximun %u!\n",
2008                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2009                 return (-1);
2010         }
2011
2012         mtx_lock(&softc->ctl_lock);
2013         port->wwpn_iid[iid].in_use--;
2014         port->wwpn_iid[iid].last_use = time_uptime;
2015         mtx_unlock(&softc->ctl_lock);
2016         ctl_isc_announce_iid(port, iid);
2017
2018         return (0);
2019 }
2020
2021 /*
2022  * Add an initiator to the initiator map.
2023  * Returns iid for success, < 0 for failure.
2024  */
2025 int
2026 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2027 {
2028         struct ctl_softc *softc = port->ctl_softc;
2029         time_t best_time;
2030         int i, best;
2031
2032         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2033
2034         if (iid >= CTL_MAX_INIT_PER_PORT) {
2035                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2036                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2037                 free(name, M_CTL);
2038                 return (-1);
2039         }
2040
2041         mtx_lock(&softc->ctl_lock);
2042
2043         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2044                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2045                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2046                                 iid = i;
2047                                 break;
2048                         }
2049                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2050                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2051                                 iid = i;
2052                                 break;
2053                         }
2054                 }
2055         }
2056
2057         if (iid < 0) {
2058                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2059                         if (port->wwpn_iid[i].in_use == 0 &&
2060                             port->wwpn_iid[i].wwpn == 0 &&
2061                             port->wwpn_iid[i].name == NULL) {
2062                                 iid = i;
2063                                 break;
2064                         }
2065                 }
2066         }
2067
2068         if (iid < 0) {
2069                 best = -1;
2070                 best_time = INT32_MAX;
2071                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2072                         if (port->wwpn_iid[i].in_use == 0) {
2073                                 if (port->wwpn_iid[i].last_use < best_time) {
2074                                         best = i;
2075                                         best_time = port->wwpn_iid[i].last_use;
2076                                 }
2077                         }
2078                 }
2079                 iid = best;
2080         }
2081
2082         if (iid < 0) {
2083                 mtx_unlock(&softc->ctl_lock);
2084                 free(name, M_CTL);
2085                 return (-2);
2086         }
2087
2088         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2089                 /*
2090                  * This is not an error yet.
2091                  */
2092                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2093 #if 0
2094                         printf("%s: port %d iid %u WWPN %#jx arrived"
2095                             " again\n", __func__, port->targ_port,
2096                             iid, (uintmax_t)wwpn);
2097 #endif
2098                         goto take;
2099                 }
2100                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2101                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2102 #if 0
2103                         printf("%s: port %d iid %u name '%s' arrived"
2104                             " again\n", __func__, port->targ_port,
2105                             iid, name);
2106 #endif
2107                         goto take;
2108                 }
2109
2110                 /*
2111                  * This is an error, but what do we do about it?  The
2112                  * driver is telling us we have a new WWPN for this
2113                  * initiator ID, so we pretty much need to use it.
2114                  */
2115                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2116                     " but WWPN %#jx '%s' is still at that address\n",
2117                     __func__, port->targ_port, iid, wwpn, name,
2118                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2119                     port->wwpn_iid[iid].name);
2120
2121                 /*
2122                  * XXX KDM clear have_ca and ua_pending on each LUN for
2123                  * this initiator.
2124                  */
2125         }
2126 take:
2127         free(port->wwpn_iid[iid].name, M_CTL);
2128         port->wwpn_iid[iid].name = name;
2129         port->wwpn_iid[iid].wwpn = wwpn;
2130         port->wwpn_iid[iid].in_use++;
2131         mtx_unlock(&softc->ctl_lock);
2132         ctl_isc_announce_iid(port, iid);
2133
2134         return (iid);
2135 }
2136
2137 static int
2138 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2139 {
2140         int len;
2141
2142         switch (port->port_type) {
2143         case CTL_PORT_FC:
2144         {
2145                 struct scsi_transportid_fcp *id =
2146                     (struct scsi_transportid_fcp *)buf;
2147                 if (port->wwpn_iid[iid].wwpn == 0)
2148                         return (0);
2149                 memset(id, 0, sizeof(*id));
2150                 id->format_protocol = SCSI_PROTO_FC;
2151                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2152                 return (sizeof(*id));
2153         }
2154         case CTL_PORT_ISCSI:
2155         {
2156                 struct scsi_transportid_iscsi_port *id =
2157                     (struct scsi_transportid_iscsi_port *)buf;
2158                 if (port->wwpn_iid[iid].name == NULL)
2159                         return (0);
2160                 memset(id, 0, 256);
2161                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2162                     SCSI_PROTO_ISCSI;
2163                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2164                 len = roundup2(min(len, 252), 4);
2165                 scsi_ulto2b(len, id->additional_length);
2166                 return (sizeof(*id) + len);
2167         }
2168         case CTL_PORT_SAS:
2169         {
2170                 struct scsi_transportid_sas *id =
2171                     (struct scsi_transportid_sas *)buf;
2172                 if (port->wwpn_iid[iid].wwpn == 0)
2173                         return (0);
2174                 memset(id, 0, sizeof(*id));
2175                 id->format_protocol = SCSI_PROTO_SAS;
2176                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2177                 return (sizeof(*id));
2178         }
2179         default:
2180         {
2181                 struct scsi_transportid_spi *id =
2182                     (struct scsi_transportid_spi *)buf;
2183                 memset(id, 0, sizeof(*id));
2184                 id->format_protocol = SCSI_PROTO_SPI;
2185                 scsi_ulto2b(iid, id->scsi_addr);
2186                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2187                 return (sizeof(*id));
2188         }
2189         }
2190 }
2191
2192 /*
2193  * Serialize a command that went down the "wrong" side, and so was sent to
2194  * this controller for execution.  The logic is a little different than the
2195  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2196  * sent back to the other side, but in the success case, we execute the
2197  * command on this side (XFER mode) or tell the other side to execute it
2198  * (SER_ONLY mode).
2199  */
2200 static int
2201 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2202 {
2203         struct ctl_softc *softc = control_softc;
2204         union ctl_ha_msg msg_info;
2205         struct ctl_port *port;
2206         struct ctl_lun *lun;
2207         const struct ctl_cmd_entry *entry;
2208         int retval = 0;
2209         uint32_t targ_lun;
2210
2211         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2212         mtx_lock(&softc->ctl_lock);
2213
2214         /* Make sure that we know about this port. */
2215         port = ctl_io_port(&ctsio->io_hdr);
2216         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2217                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2218                                          /*retry_count*/ 1);
2219                 goto badjuju;
2220         }
2221
2222         /* Make sure that we know about this LUN. */
2223         if ((targ_lun < CTL_MAX_LUNS) &&
2224             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2225                 mtx_lock(&lun->lun_lock);
2226                 mtx_unlock(&softc->ctl_lock);
2227                 /*
2228                  * If the LUN is invalid, pretend that it doesn't exist.
2229                  * It will go away as soon as all pending I/O has been
2230                  * completed.
2231                  */
2232                 if (lun->flags & CTL_LUN_DISABLED) {
2233                         mtx_unlock(&lun->lun_lock);
2234                         lun = NULL;
2235                 }
2236         } else {
2237                 mtx_unlock(&softc->ctl_lock);
2238                 lun = NULL;
2239         }
2240         if (lun == NULL) {
2241                 /*
2242                  * The other node would not send this request to us unless
2243                  * received announce that we are primary node for this LUN.
2244                  * If this LUN does not exist now, it is probably result of
2245                  * a race, so respond to initiator in the most opaque way.
2246                  */
2247                 ctl_set_busy(ctsio);
2248                 goto badjuju;
2249         }
2250
2251         entry = ctl_get_cmd_entry(ctsio, NULL);
2252         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2253                 mtx_unlock(&lun->lun_lock);
2254                 goto badjuju;
2255         }
2256
2257         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2258         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2259
2260         /*
2261          * Every I/O goes into the OOA queue for a
2262          * particular LUN, and stays there until completion.
2263          */
2264 #ifdef CTL_TIME_IO
2265         if (TAILQ_EMPTY(&lun->ooa_queue))
2266                 lun->idle_time += getsbinuptime() - lun->last_busy;
2267 #endif
2268         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2269
2270         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2271                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2272                  ooa_links))) {
2273         case CTL_ACTION_BLOCK:
2274                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2275                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2276                                   blocked_links);
2277                 mtx_unlock(&lun->lun_lock);
2278                 break;
2279         case CTL_ACTION_PASS:
2280         case CTL_ACTION_SKIP:
2281                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2282                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2283                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2284                         mtx_unlock(&lun->lun_lock);
2285                 } else {
2286                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2287                         mtx_unlock(&lun->lun_lock);
2288
2289                         /* send msg back to other side */
2290                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2291                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2292                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2293                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2294                             sizeof(msg_info.hdr), M_WAITOK);
2295                 }
2296                 break;
2297         case CTL_ACTION_OVERLAP:
2298                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2299                 mtx_unlock(&lun->lun_lock);
2300                 ctl_set_overlapped_cmd(ctsio);
2301                 goto badjuju;
2302         case CTL_ACTION_OVERLAP_TAG:
2303                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2304                 mtx_unlock(&lun->lun_lock);
2305                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2306                 goto badjuju;
2307         case CTL_ACTION_ERROR:
2308         default:
2309                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2310                 mtx_unlock(&lun->lun_lock);
2311
2312                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2313                                          /*retry_count*/ 0);
2314 badjuju:
2315                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2316                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2317                 msg_info.hdr.serializing_sc = NULL;
2318                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2319                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2320                     sizeof(msg_info.scsi), M_WAITOK);
2321                 retval = 1;
2322                 break;
2323         }
2324         return (retval);
2325 }
2326
2327 /*
2328  * Returns 0 for success, errno for failure.
2329  */
2330 static void
2331 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2332                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2333 {
2334         union ctl_io *io;
2335
2336         mtx_lock(&lun->lun_lock);
2337         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2338              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2339              ooa_links)) {
2340                 struct ctl_ooa_entry *entry;
2341
2342                 /*
2343                  * If we've got more than we can fit, just count the
2344                  * remaining entries.
2345                  */
2346                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2347                         continue;
2348
2349                 entry = &kern_entries[*cur_fill_num];
2350
2351                 entry->tag_num = io->scsiio.tag_num;
2352                 entry->lun_num = lun->lun;
2353 #ifdef CTL_TIME_IO
2354                 entry->start_bt = io->io_hdr.start_bt;
2355 #endif
2356                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2357                 entry->cdb_len = io->scsiio.cdb_len;
2358                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2359                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2360
2361                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2362                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2363
2364                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2365                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2366
2367                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2368                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2369
2370                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2371                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2372         }
2373         mtx_unlock(&lun->lun_lock);
2374 }
2375
2376 static void *
2377 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2378                  size_t error_str_len)
2379 {
2380         void *kptr;
2381
2382         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2383
2384         if (copyin(user_addr, kptr, len) != 0) {
2385                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2386                          "from user address %p to kernel address %p", len,
2387                          user_addr, kptr);
2388                 free(kptr, M_CTL);
2389                 return (NULL);
2390         }
2391
2392         return (kptr);
2393 }
2394
2395 static void
2396 ctl_free_args(int num_args, struct ctl_be_arg *args)
2397 {
2398         int i;
2399
2400         if (args == NULL)
2401                 return;
2402
2403         for (i = 0; i < num_args; i++) {
2404                 free(args[i].kname, M_CTL);
2405                 free(args[i].kvalue, M_CTL);
2406         }
2407
2408         free(args, M_CTL);
2409 }
2410
2411 static struct ctl_be_arg *
2412 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2413                 char *error_str, size_t error_str_len)
2414 {
2415         struct ctl_be_arg *args;
2416         int i;
2417
2418         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2419                                 error_str, error_str_len);
2420
2421         if (args == NULL)
2422                 goto bailout;
2423
2424         for (i = 0; i < num_args; i++) {
2425                 args[i].kname = NULL;
2426                 args[i].kvalue = NULL;
2427         }
2428
2429         for (i = 0; i < num_args; i++) {
2430                 uint8_t *tmpptr;
2431
2432                 args[i].kname = ctl_copyin_alloc(args[i].name,
2433                         args[i].namelen, error_str, error_str_len);
2434                 if (args[i].kname == NULL)
2435                         goto bailout;
2436
2437                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2438                         snprintf(error_str, error_str_len, "Argument %d "
2439                                  "name is not NUL-terminated", i);
2440                         goto bailout;
2441                 }
2442
2443                 if (args[i].flags & CTL_BEARG_RD) {
2444                         tmpptr = ctl_copyin_alloc(args[i].value,
2445                                 args[i].vallen, error_str, error_str_len);
2446                         if (tmpptr == NULL)
2447                                 goto bailout;
2448                         if ((args[i].flags & CTL_BEARG_ASCII)
2449                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2450                                 snprintf(error_str, error_str_len, "Argument "
2451                                     "%d value is not NUL-terminated", i);
2452                                 free(tmpptr, M_CTL);
2453                                 goto bailout;
2454                         }
2455                         args[i].kvalue = tmpptr;
2456                 } else {
2457                         args[i].kvalue = malloc(args[i].vallen,
2458                             M_CTL, M_WAITOK | M_ZERO);
2459                 }
2460         }
2461
2462         return (args);
2463 bailout:
2464
2465         ctl_free_args(num_args, args);
2466
2467         return (NULL);
2468 }
2469
2470 static void
2471 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2472 {
2473         int i;
2474
2475         for (i = 0; i < num_args; i++) {
2476                 if (args[i].flags & CTL_BEARG_WR)
2477                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2478         }
2479 }
2480
2481 /*
2482  * Escape characters that are illegal or not recommended in XML.
2483  */
2484 int
2485 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2486 {
2487         char *end = str + size;
2488         int retval;
2489
2490         retval = 0;
2491
2492         for (; *str && str < end; str++) {
2493                 switch (*str) {
2494                 case '&':
2495                         retval = sbuf_printf(sb, "&amp;");
2496                         break;
2497                 case '>':
2498                         retval = sbuf_printf(sb, "&gt;");
2499                         break;
2500                 case '<':
2501                         retval = sbuf_printf(sb, "&lt;");
2502                         break;
2503                 default:
2504                         retval = sbuf_putc(sb, *str);
2505                         break;
2506                 }
2507
2508                 if (retval != 0)
2509                         break;
2510
2511         }
2512
2513         return (retval);
2514 }
2515
2516 static void
2517 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2518 {
2519         struct scsi_vpd_id_descriptor *desc;
2520         int i;
2521
2522         if (id == NULL || id->len < 4)
2523                 return;
2524         desc = (struct scsi_vpd_id_descriptor *)id->data;
2525         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2526         case SVPD_ID_TYPE_T10:
2527                 sbuf_printf(sb, "t10.");
2528                 break;
2529         case SVPD_ID_TYPE_EUI64:
2530                 sbuf_printf(sb, "eui.");
2531                 break;
2532         case SVPD_ID_TYPE_NAA:
2533                 sbuf_printf(sb, "naa.");
2534                 break;
2535         case SVPD_ID_TYPE_SCSI_NAME:
2536                 break;
2537         }
2538         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2539         case SVPD_ID_CODESET_BINARY:
2540                 for (i = 0; i < desc->length; i++)
2541                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2542                 break;
2543         case SVPD_ID_CODESET_ASCII:
2544                 sbuf_printf(sb, "%.*s", (int)desc->length,
2545                     (char *)desc->identifier);
2546                 break;
2547         case SVPD_ID_CODESET_UTF8:
2548                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2549                 break;
2550         }
2551 }
2552
2553 static int
2554 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2555           struct thread *td)
2556 {
2557         struct ctl_softc *softc = dev->si_drv1;
2558         struct ctl_lun *lun;
2559         int retval;
2560
2561         retval = 0;
2562
2563         switch (cmd) {
2564         case CTL_IO:
2565                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2566                 break;
2567         case CTL_ENABLE_PORT:
2568         case CTL_DISABLE_PORT:
2569         case CTL_SET_PORT_WWNS: {
2570                 struct ctl_port *port;
2571                 struct ctl_port_entry *entry;
2572
2573                 entry = (struct ctl_port_entry *)addr;
2574                 
2575                 mtx_lock(&softc->ctl_lock);
2576                 STAILQ_FOREACH(port, &softc->port_list, links) {
2577                         int action, done;
2578
2579                         if (port->targ_port < softc->port_min ||
2580                             port->targ_port >= softc->port_max)
2581                                 continue;
2582
2583                         action = 0;
2584                         done = 0;
2585                         if ((entry->port_type == CTL_PORT_NONE)
2586                          && (entry->targ_port == port->targ_port)) {
2587                                 /*
2588                                  * If the user only wants to enable or
2589                                  * disable or set WWNs on a specific port,
2590                                  * do the operation and we're done.
2591                                  */
2592                                 action = 1;
2593                                 done = 1;
2594                         } else if (entry->port_type & port->port_type) {
2595                                 /*
2596                                  * Compare the user's type mask with the
2597                                  * particular frontend type to see if we
2598                                  * have a match.
2599                                  */
2600                                 action = 1;
2601                                 done = 0;
2602
2603                                 /*
2604                                  * Make sure the user isn't trying to set
2605                                  * WWNs on multiple ports at the same time.
2606                                  */
2607                                 if (cmd == CTL_SET_PORT_WWNS) {
2608                                         printf("%s: Can't set WWNs on "
2609                                                "multiple ports\n", __func__);
2610                                         retval = EINVAL;
2611                                         break;
2612                                 }
2613                         }
2614                         if (action == 0)
2615                                 continue;
2616
2617                         /*
2618                          * XXX KDM we have to drop the lock here, because
2619                          * the online/offline operations can potentially
2620                          * block.  We need to reference count the frontends
2621                          * so they can't go away,
2622                          */
2623                         if (cmd == CTL_ENABLE_PORT) {
2624                                 mtx_unlock(&softc->ctl_lock);
2625                                 ctl_port_online(port);
2626                                 mtx_lock(&softc->ctl_lock);
2627                         } else if (cmd == CTL_DISABLE_PORT) {
2628                                 mtx_unlock(&softc->ctl_lock);
2629                                 ctl_port_offline(port);
2630                                 mtx_lock(&softc->ctl_lock);
2631                         } else if (cmd == CTL_SET_PORT_WWNS) {
2632                                 ctl_port_set_wwns(port,
2633                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2634                                     1 : 0, entry->wwnn,
2635                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2636                                     1 : 0, entry->wwpn);
2637                         }
2638                         if (done != 0)
2639                                 break;
2640                 }
2641                 mtx_unlock(&softc->ctl_lock);
2642                 break;
2643         }
2644         case CTL_GET_OOA: {
2645                 struct ctl_ooa *ooa_hdr;
2646                 struct ctl_ooa_entry *entries;
2647                 uint32_t cur_fill_num;
2648
2649                 ooa_hdr = (struct ctl_ooa *)addr;
2650
2651                 if ((ooa_hdr->alloc_len == 0)
2652                  || (ooa_hdr->alloc_num == 0)) {
2653                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2654                                "must be non-zero\n", __func__,
2655                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2656                         retval = EINVAL;
2657                         break;
2658                 }
2659
2660                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2661                     sizeof(struct ctl_ooa_entry))) {
2662                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2663                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2664                                __func__, ooa_hdr->alloc_len,
2665                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2666                         retval = EINVAL;
2667                         break;
2668                 }
2669
2670                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2671                 if (entries == NULL) {
2672                         printf("%s: could not allocate %d bytes for OOA "
2673                                "dump\n", __func__, ooa_hdr->alloc_len);
2674                         retval = ENOMEM;
2675                         break;
2676                 }
2677
2678                 mtx_lock(&softc->ctl_lock);
2679                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2680                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2681                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2682                         mtx_unlock(&softc->ctl_lock);
2683                         free(entries, M_CTL);
2684                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2685                                __func__, (uintmax_t)ooa_hdr->lun_num);
2686                         retval = EINVAL;
2687                         break;
2688                 }
2689
2690                 cur_fill_num = 0;
2691
2692                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2693                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2694                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2695                                     ooa_hdr, entries);
2696                         }
2697                 } else {
2698                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2699                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2700                             entries);
2701                 }
2702                 mtx_unlock(&softc->ctl_lock);
2703
2704                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2705                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2706                         sizeof(struct ctl_ooa_entry);
2707                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2708                 if (retval != 0) {
2709                         printf("%s: error copying out %d bytes for OOA dump\n", 
2710                                __func__, ooa_hdr->fill_len);
2711                 }
2712
2713                 getbinuptime(&ooa_hdr->cur_bt);
2714
2715                 if (cur_fill_num > ooa_hdr->alloc_num) {
2716                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2717                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2718                 } else {
2719                         ooa_hdr->dropped_num = 0;
2720                         ooa_hdr->status = CTL_OOA_OK;
2721                 }
2722
2723                 free(entries, M_CTL);
2724                 break;
2725         }
2726         case CTL_DELAY_IO: {
2727                 struct ctl_io_delay_info *delay_info;
2728
2729                 delay_info = (struct ctl_io_delay_info *)addr;
2730
2731 #ifdef CTL_IO_DELAY
2732                 mtx_lock(&softc->ctl_lock);
2733
2734                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2735                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2736                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2737                 } else {
2738                         lun = softc->ctl_luns[delay_info->lun_id];
2739                         mtx_lock(&lun->lun_lock);
2740
2741                         delay_info->status = CTL_DELAY_STATUS_OK;
2742
2743                         switch (delay_info->delay_type) {
2744                         case CTL_DELAY_TYPE_CONT:
2745                                 break;
2746                         case CTL_DELAY_TYPE_ONESHOT:
2747                                 break;
2748                         default:
2749                                 delay_info->status =
2750                                         CTL_DELAY_STATUS_INVALID_TYPE;
2751                                 break;
2752                         }
2753
2754                         switch (delay_info->delay_loc) {
2755                         case CTL_DELAY_LOC_DATAMOVE:
2756                                 lun->delay_info.datamove_type =
2757                                         delay_info->delay_type;
2758                                 lun->delay_info.datamove_delay =
2759                                         delay_info->delay_secs;
2760                                 break;
2761                         case CTL_DELAY_LOC_DONE:
2762                                 lun->delay_info.done_type =
2763                                         delay_info->delay_type;
2764                                 lun->delay_info.done_delay =
2765                                         delay_info->delay_secs;
2766                                 break;
2767                         default:
2768                                 delay_info->status =
2769                                         CTL_DELAY_STATUS_INVALID_LOC;
2770                                 break;
2771                         }
2772                         mtx_unlock(&lun->lun_lock);
2773                 }
2774
2775                 mtx_unlock(&softc->ctl_lock);
2776 #else
2777                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2778 #endif /* CTL_IO_DELAY */
2779                 break;
2780         }
2781         case CTL_GETSTATS: {
2782                 struct ctl_stats *stats;
2783                 int i;
2784
2785                 stats = (struct ctl_stats *)addr;
2786
2787                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2788                      stats->alloc_len) {
2789                         stats->status = CTL_SS_NEED_MORE_SPACE;
2790                         stats->num_luns = softc->num_luns;
2791                         break;
2792                 }
2793                 /*
2794                  * XXX KDM no locking here.  If the LUN list changes,
2795                  * things can blow up.
2796                  */
2797                 i = 0;
2798                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2799                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2800                                          sizeof(lun->stats));
2801                         if (retval != 0)
2802                                 break;
2803                 }
2804                 stats->num_luns = softc->num_luns;
2805                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2806                                  softc->num_luns;
2807                 stats->status = CTL_SS_OK;
2808 #ifdef CTL_TIME_IO
2809                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2810 #else
2811                 stats->flags = CTL_STATS_FLAG_NONE;
2812 #endif
2813                 getnanouptime(&stats->timestamp);
2814                 break;
2815         }
2816         case CTL_ERROR_INJECT: {
2817                 struct ctl_error_desc *err_desc, *new_err_desc;
2818
2819                 err_desc = (struct ctl_error_desc *)addr;
2820
2821                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2822                                       M_WAITOK | M_ZERO);
2823                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2824
2825                 mtx_lock(&softc->ctl_lock);
2826                 lun = softc->ctl_luns[err_desc->lun_id];
2827                 if (lun == NULL) {
2828                         mtx_unlock(&softc->ctl_lock);
2829                         free(new_err_desc, M_CTL);
2830                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2831                                __func__, (uintmax_t)err_desc->lun_id);
2832                         retval = EINVAL;
2833                         break;
2834                 }
2835                 mtx_lock(&lun->lun_lock);
2836                 mtx_unlock(&softc->ctl_lock);
2837
2838                 /*
2839                  * We could do some checking here to verify the validity
2840                  * of the request, but given the complexity of error
2841                  * injection requests, the checking logic would be fairly
2842                  * complex.
2843                  *
2844                  * For now, if the request is invalid, it just won't get
2845                  * executed and might get deleted.
2846                  */
2847                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2848
2849                 /*
2850                  * XXX KDM check to make sure the serial number is unique,
2851                  * in case we somehow manage to wrap.  That shouldn't
2852                  * happen for a very long time, but it's the right thing to
2853                  * do.
2854                  */
2855                 new_err_desc->serial = lun->error_serial;
2856                 err_desc->serial = lun->error_serial;
2857                 lun->error_serial++;
2858
2859                 mtx_unlock(&lun->lun_lock);
2860                 break;
2861         }
2862         case CTL_ERROR_INJECT_DELETE: {
2863                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2864                 int delete_done;
2865
2866                 delete_desc = (struct ctl_error_desc *)addr;
2867                 delete_done = 0;
2868
2869                 mtx_lock(&softc->ctl_lock);
2870                 lun = softc->ctl_luns[delete_desc->lun_id];
2871                 if (lun == NULL) {
2872                         mtx_unlock(&softc->ctl_lock);
2873                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2874                                __func__, (uintmax_t)delete_desc->lun_id);
2875                         retval = EINVAL;
2876                         break;
2877                 }
2878                 mtx_lock(&lun->lun_lock);
2879                 mtx_unlock(&softc->ctl_lock);
2880                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2881                         if (desc->serial != delete_desc->serial)
2882                                 continue;
2883
2884                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2885                                       links);
2886                         free(desc, M_CTL);
2887                         delete_done = 1;
2888                 }
2889                 mtx_unlock(&lun->lun_lock);
2890                 if (delete_done == 0) {
2891                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2892                                "error serial %ju on LUN %u\n", __func__, 
2893                                delete_desc->serial, delete_desc->lun_id);
2894                         retval = EINVAL;
2895                         break;
2896                 }
2897                 break;
2898         }
2899         case CTL_DUMP_STRUCTS: {
2900                 int i, j, k;
2901                 struct ctl_port *port;
2902                 struct ctl_frontend *fe;
2903
2904                 mtx_lock(&softc->ctl_lock);
2905                 printf("CTL Persistent Reservation information start:\n");
2906                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2907                         lun = softc->ctl_luns[i];
2908
2909                         if ((lun == NULL)
2910                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2911                                 continue;
2912
2913                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2914                                 if (lun->pr_keys[j] == NULL)
2915                                         continue;
2916                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2917                                         if (lun->pr_keys[j][k] == 0)
2918                                                 continue;
2919                                         printf("  LUN %d port %d iid %d key "
2920                                                "%#jx\n", i, j, k,
2921                                                (uintmax_t)lun->pr_keys[j][k]);
2922                                 }
2923                         }
2924                 }
2925                 printf("CTL Persistent Reservation information end\n");
2926                 printf("CTL Ports:\n");
2927                 STAILQ_FOREACH(port, &softc->port_list, links) {
2928                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2929                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2930                                port->frontend->name, port->port_type,
2931                                port->physical_port, port->virtual_port,
2932                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2933                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2934                                 if (port->wwpn_iid[j].in_use == 0 &&
2935                                     port->wwpn_iid[j].wwpn == 0 &&
2936                                     port->wwpn_iid[j].name == NULL)
2937                                         continue;
2938
2939                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2940                                     j, port->wwpn_iid[j].in_use,
2941                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2942                                     port->wwpn_iid[j].name);
2943                         }
2944                 }
2945                 printf("CTL Port information end\n");
2946                 mtx_unlock(&softc->ctl_lock);
2947                 /*
2948                  * XXX KDM calling this without a lock.  We'd likely want
2949                  * to drop the lock before calling the frontend's dump
2950                  * routine anyway.
2951                  */
2952                 printf("CTL Frontends:\n");
2953                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2954                         printf("  Frontend '%s'\n", fe->name);
2955                         if (fe->fe_dump != NULL)
2956                                 fe->fe_dump();
2957                 }
2958                 printf("CTL Frontend information end\n");
2959                 break;
2960         }
2961         case CTL_LUN_REQ: {
2962                 struct ctl_lun_req *lun_req;
2963                 struct ctl_backend_driver *backend;
2964
2965                 lun_req = (struct ctl_lun_req *)addr;
2966
2967                 backend = ctl_backend_find(lun_req->backend);
2968                 if (backend == NULL) {
2969                         lun_req->status = CTL_LUN_ERROR;
2970                         snprintf(lun_req->error_str,
2971                                  sizeof(lun_req->error_str),
2972                                  "Backend \"%s\" not found.",
2973                                  lun_req->backend);
2974                         break;
2975                 }
2976                 if (lun_req->num_be_args > 0) {
2977                         lun_req->kern_be_args = ctl_copyin_args(
2978                                 lun_req->num_be_args,
2979                                 lun_req->be_args,
2980                                 lun_req->error_str,
2981                                 sizeof(lun_req->error_str));
2982                         if (lun_req->kern_be_args == NULL) {
2983                                 lun_req->status = CTL_LUN_ERROR;
2984                                 break;
2985                         }
2986                 }
2987
2988                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2989
2990                 if (lun_req->num_be_args > 0) {
2991                         ctl_copyout_args(lun_req->num_be_args,
2992                                       lun_req->kern_be_args);
2993                         ctl_free_args(lun_req->num_be_args,
2994                                       lun_req->kern_be_args);
2995                 }
2996                 break;
2997         }
2998         case CTL_LUN_LIST: {
2999                 struct sbuf *sb;
3000                 struct ctl_lun_list *list;
3001                 struct ctl_option *opt;
3002
3003                 list = (struct ctl_lun_list *)addr;
3004
3005                 /*
3006                  * Allocate a fixed length sbuf here, based on the length
3007                  * of the user's buffer.  We could allocate an auto-extending
3008                  * buffer, and then tell the user how much larger our
3009                  * amount of data is than his buffer, but that presents
3010                  * some problems:
3011                  *
3012                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3013                  *     we can't hold a lock while calling them with an
3014                  *     auto-extending buffer.
3015                  *
3016                  * 2.  There is not currently a LUN reference counting
3017                  *     mechanism, outside of outstanding transactions on
3018                  *     the LUN's OOA queue.  So a LUN could go away on us
3019                  *     while we're getting the LUN number, backend-specific
3020                  *     information, etc.  Thus, given the way things
3021                  *     currently work, we need to hold the CTL lock while
3022                  *     grabbing LUN information.
3023                  *
3024                  * So, from the user's standpoint, the best thing to do is
3025                  * allocate what he thinks is a reasonable buffer length,
3026                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3027                  * double the buffer length and try again.  (And repeat
3028                  * that until he succeeds.)
3029                  */
3030                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3031                 if (sb == NULL) {
3032                         list->status = CTL_LUN_LIST_ERROR;
3033                         snprintf(list->error_str, sizeof(list->error_str),
3034                                  "Unable to allocate %d bytes for LUN list",
3035                                  list->alloc_len);
3036                         break;
3037                 }
3038
3039                 sbuf_printf(sb, "<ctllunlist>\n");
3040
3041                 mtx_lock(&softc->ctl_lock);
3042                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3043                         mtx_lock(&lun->lun_lock);
3044                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3045                                              (uintmax_t)lun->lun);
3046
3047                         /*
3048                          * Bail out as soon as we see that we've overfilled
3049                          * the buffer.
3050                          */
3051                         if (retval != 0)
3052                                 break;
3053
3054                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3055                                              "</backend_type>\n",
3056                                              (lun->backend == NULL) ?  "none" :
3057                                              lun->backend->name);
3058
3059                         if (retval != 0)
3060                                 break;
3061
3062                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3063                                              lun->be_lun->lun_type);
3064
3065                         if (retval != 0)
3066                                 break;
3067
3068                         if (lun->backend == NULL) {
3069                                 retval = sbuf_printf(sb, "</lun>\n");
3070                                 if (retval != 0)
3071                                         break;
3072                                 continue;
3073                         }
3074
3075                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3076                                              (lun->be_lun->maxlba > 0) ?
3077                                              lun->be_lun->maxlba + 1 : 0);
3078
3079                         if (retval != 0)
3080                                 break;
3081
3082                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3083                                              lun->be_lun->blocksize);
3084
3085                         if (retval != 0)
3086                                 break;
3087
3088                         retval = sbuf_printf(sb, "\t<serial_number>");
3089
3090                         if (retval != 0)
3091                                 break;
3092
3093                         retval = ctl_sbuf_printf_esc(sb,
3094                             lun->be_lun->serial_num,
3095                             sizeof(lun->be_lun->serial_num));
3096
3097                         if (retval != 0)
3098                                 break;
3099
3100                         retval = sbuf_printf(sb, "</serial_number>\n");
3101                 
3102                         if (retval != 0)
3103                                 break;
3104
3105                         retval = sbuf_printf(sb, "\t<device_id>");
3106
3107                         if (retval != 0)
3108                                 break;
3109
3110                         retval = ctl_sbuf_printf_esc(sb,
3111                             lun->be_lun->device_id,
3112                             sizeof(lun->be_lun->device_id));
3113
3114                         if (retval != 0)
3115                                 break;
3116
3117                         retval = sbuf_printf(sb, "</device_id>\n");
3118
3119                         if (retval != 0)
3120                                 break;
3121
3122                         if (lun->backend->lun_info != NULL) {
3123                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3124                                 if (retval != 0)
3125                                         break;
3126                         }
3127                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3128                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3129                                     opt->name, opt->value, opt->name);
3130                                 if (retval != 0)
3131                                         break;
3132                         }
3133
3134                         retval = sbuf_printf(sb, "</lun>\n");
3135
3136                         if (retval != 0)
3137                                 break;
3138                         mtx_unlock(&lun->lun_lock);
3139                 }
3140                 if (lun != NULL)
3141                         mtx_unlock(&lun->lun_lock);
3142                 mtx_unlock(&softc->ctl_lock);
3143
3144                 if ((retval != 0)
3145                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3146                         retval = 0;
3147                         sbuf_delete(sb);
3148                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3149                         snprintf(list->error_str, sizeof(list->error_str),
3150                                  "Out of space, %d bytes is too small",
3151                                  list->alloc_len);
3152                         break;
3153                 }
3154
3155                 sbuf_finish(sb);
3156
3157                 retval = copyout(sbuf_data(sb), list->lun_xml,
3158                                  sbuf_len(sb) + 1);
3159
3160                 list->fill_len = sbuf_len(sb) + 1;
3161                 list->status = CTL_LUN_LIST_OK;
3162                 sbuf_delete(sb);
3163                 break;
3164         }
3165         case CTL_ISCSI: {
3166                 struct ctl_iscsi *ci;
3167                 struct ctl_frontend *fe;
3168
3169                 ci = (struct ctl_iscsi *)addr;
3170
3171                 fe = ctl_frontend_find("iscsi");
3172                 if (fe == NULL) {
3173                         ci->status = CTL_ISCSI_ERROR;
3174                         snprintf(ci->error_str, sizeof(ci->error_str),
3175                             "Frontend \"iscsi\" not found.");
3176                         break;
3177                 }
3178
3179                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3180                 break;
3181         }
3182         case CTL_PORT_REQ: {
3183                 struct ctl_req *req;
3184                 struct ctl_frontend *fe;
3185
3186                 req = (struct ctl_req *)addr;
3187
3188                 fe = ctl_frontend_find(req->driver);
3189                 if (fe == NULL) {
3190                         req->status = CTL_LUN_ERROR;
3191                         snprintf(req->error_str, sizeof(req->error_str),
3192                             "Frontend \"%s\" not found.", req->driver);
3193                         break;
3194                 }
3195                 if (req->num_args > 0) {
3196                         req->kern_args = ctl_copyin_args(req->num_args,
3197                             req->args, req->error_str, sizeof(req->error_str));
3198                         if (req->kern_args == NULL) {
3199                                 req->status = CTL_LUN_ERROR;
3200                                 break;
3201                         }
3202                 }
3203
3204                 if (fe->ioctl)
3205                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3206                 else
3207                         retval = ENODEV;
3208
3209                 if (req->num_args > 0) {
3210                         ctl_copyout_args(req->num_args, req->kern_args);
3211                         ctl_free_args(req->num_args, req->kern_args);
3212                 }
3213                 break;
3214         }
3215         case CTL_PORT_LIST: {
3216                 struct sbuf *sb;
3217                 struct ctl_port *port;
3218                 struct ctl_lun_list *list;
3219                 struct ctl_option *opt;
3220                 int j;
3221                 uint32_t plun;
3222
3223                 list = (struct ctl_lun_list *)addr;
3224
3225                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226                 if (sb == NULL) {
3227                         list->status = CTL_LUN_LIST_ERROR;
3228                         snprintf(list->error_str, sizeof(list->error_str),
3229                                  "Unable to allocate %d bytes for LUN list",
3230                                  list->alloc_len);
3231                         break;
3232                 }
3233
3234                 sbuf_printf(sb, "<ctlportlist>\n");
3235
3236                 mtx_lock(&softc->ctl_lock);
3237                 STAILQ_FOREACH(port, &softc->port_list, links) {
3238                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3239                                              (uintmax_t)port->targ_port);
3240
3241                         /*
3242                          * Bail out as soon as we see that we've overfilled
3243                          * the buffer.
3244                          */
3245                         if (retval != 0)
3246                                 break;
3247
3248                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3249                             "</frontend_type>\n", port->frontend->name);
3250                         if (retval != 0)
3251                                 break;
3252
3253                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3254                                              port->port_type);
3255                         if (retval != 0)
3256                                 break;
3257
3258                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3259                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3260                         if (retval != 0)
3261                                 break;
3262
3263                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3264                             port->port_name);
3265                         if (retval != 0)
3266                                 break;
3267
3268                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3269                             port->physical_port);
3270                         if (retval != 0)
3271                                 break;
3272
3273                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3274                             port->virtual_port);
3275                         if (retval != 0)
3276                                 break;
3277
3278                         if (port->target_devid != NULL) {
3279                                 sbuf_printf(sb, "\t<target>");
3280                                 ctl_id_sbuf(port->target_devid, sb);
3281                                 sbuf_printf(sb, "</target>\n");
3282                         }
3283
3284                         if (port->port_devid != NULL) {
3285                                 sbuf_printf(sb, "\t<port>");
3286                                 ctl_id_sbuf(port->port_devid, sb);
3287                                 sbuf_printf(sb, "</port>\n");
3288                         }
3289
3290                         if (port->port_info != NULL) {
3291                                 retval = port->port_info(port->onoff_arg, sb);
3292                                 if (retval != 0)
3293                                         break;
3294                         }
3295                         STAILQ_FOREACH(opt, &port->options, links) {
3296                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3297                                     opt->name, opt->value, opt->name);
3298                                 if (retval != 0)
3299                                         break;
3300                         }
3301
3302                         if (port->lun_map != NULL) {
3303                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3304                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3305                                         plun = ctl_lun_map_from_port(port, j);
3306                                         if (plun >= CTL_MAX_LUNS)
3307                                                 continue;
3308                                         sbuf_printf(sb,
3309                                             "\t<lun id=\"%u\">%u</lun>\n",
3310                                             j, plun);
3311                                 }
3312                         }
3313
3314                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3315                                 if (port->wwpn_iid[j].in_use == 0 ||
3316                                     (port->wwpn_iid[j].wwpn == 0 &&
3317                                      port->wwpn_iid[j].name == NULL))
3318                                         continue;
3319
3320                                 if (port->wwpn_iid[j].name != NULL)
3321                                         retval = sbuf_printf(sb,
3322                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3323                                             j, port->wwpn_iid[j].name);
3324                                 else
3325                                         retval = sbuf_printf(sb,
3326                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3327                                             j, port->wwpn_iid[j].wwpn);
3328                                 if (retval != 0)
3329                                         break;
3330                         }
3331                         if (retval != 0)
3332                                 break;
3333
3334                         retval = sbuf_printf(sb, "</targ_port>\n");
3335                         if (retval != 0)
3336                                 break;
3337                 }
3338                 mtx_unlock(&softc->ctl_lock);
3339
3340                 if ((retval != 0)
3341                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3342                         retval = 0;
3343                         sbuf_delete(sb);
3344                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3345                         snprintf(list->error_str, sizeof(list->error_str),
3346                                  "Out of space, %d bytes is too small",
3347                                  list->alloc_len);
3348                         break;
3349                 }
3350
3351                 sbuf_finish(sb);
3352
3353                 retval = copyout(sbuf_data(sb), list->lun_xml,
3354                                  sbuf_len(sb) + 1);
3355
3356                 list->fill_len = sbuf_len(sb) + 1;
3357                 list->status = CTL_LUN_LIST_OK;
3358                 sbuf_delete(sb);
3359                 break;
3360         }
3361         case CTL_LUN_MAP: {
3362                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3363                 struct ctl_port *port;
3364
3365                 mtx_lock(&softc->ctl_lock);
3366                 if (lm->port < softc->port_min ||
3367                     lm->port >= softc->port_max ||
3368                     (port = softc->ctl_ports[lm->port]) == NULL) {
3369                         mtx_unlock(&softc->ctl_lock);
3370                         return (ENXIO);
3371                 }
3372                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3373                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3374                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3375                                     CTL_MAX_LUNS)
3376                                         continue;
3377                                 mtx_lock(&lun->lun_lock);
3378                                 ctl_est_ua_port(lun, lm->port, -1,
3379                                     CTL_UA_LUN_CHANGE);
3380                                 mtx_unlock(&lun->lun_lock);
3381                         }
3382                 }
3383                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3384                 if (lm->plun < CTL_MAX_LUNS) {
3385                         if (lm->lun == UINT32_MAX)
3386                                 retval = ctl_lun_map_unset(port, lm->plun);
3387                         else if (lm->lun < CTL_MAX_LUNS &&
3388                             softc->ctl_luns[lm->lun] != NULL)
3389                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3390                         else
3391                                 return (ENXIO);
3392                 } else if (lm->plun == UINT32_MAX) {
3393                         if (lm->lun == UINT32_MAX)
3394                                 retval = ctl_lun_map_deinit(port);
3395                         else
3396                                 retval = ctl_lun_map_init(port);
3397                 } else
3398                         return (ENXIO);
3399                 if (port->status & CTL_PORT_STATUS_ONLINE)
3400                         ctl_isc_announce_port(port);
3401                 break;
3402         }
3403         default: {
3404                 /* XXX KDM should we fix this? */
3405 #if 0
3406                 struct ctl_backend_driver *backend;
3407                 unsigned int type;
3408                 int found;
3409
3410                 found = 0;
3411
3412                 /*
3413                  * We encode the backend type as the ioctl type for backend
3414                  * ioctls.  So parse it out here, and then search for a
3415                  * backend of this type.
3416                  */
3417                 type = _IOC_TYPE(cmd);
3418
3419                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3420                         if (backend->type == type) {
3421                                 found = 1;
3422                                 break;
3423                         }
3424                 }
3425                 if (found == 0) {
3426                         printf("ctl: unknown ioctl command %#lx or backend "
3427                                "%d\n", cmd, type);
3428                         retval = EINVAL;
3429                         break;
3430                 }
3431                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3432 #endif
3433                 retval = ENOTTY;
3434                 break;
3435         }
3436         }
3437         return (retval);
3438 }
3439
3440 uint32_t
3441 ctl_get_initindex(struct ctl_nexus *nexus)
3442 {
3443         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3444 }
3445
3446 int
3447 ctl_lun_map_init(struct ctl_port *port)
3448 {
3449         struct ctl_softc *softc = port->ctl_softc;
3450         struct ctl_lun *lun;
3451         uint32_t i;
3452
3453         if (port->lun_map == NULL)
3454                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3455                     M_CTL, M_NOWAIT);
3456         if (port->lun_map == NULL)
3457                 return (ENOMEM);
3458         for (i = 0; i < CTL_MAX_LUNS; i++)
3459                 port->lun_map[i] = UINT32_MAX;
3460         if (port->status & CTL_PORT_STATUS_ONLINE) {
3461                 if (port->lun_disable != NULL) {
3462                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3463                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3464                 }
3465                 ctl_isc_announce_port(port);
3466         }
3467         return (0);
3468 }
3469
3470 int
3471 ctl_lun_map_deinit(struct ctl_port *port)
3472 {
3473         struct ctl_softc *softc = port->ctl_softc;
3474         struct ctl_lun *lun;
3475
3476         if (port->lun_map == NULL)
3477                 return (0);
3478         free(port->lun_map, M_CTL);
3479         port->lun_map = NULL;
3480         if (port->status & CTL_PORT_STATUS_ONLINE) {
3481                 if (port->lun_enable != NULL) {
3482                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3483                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3484                 }
3485                 ctl_isc_announce_port(port);
3486         }
3487         return (0);
3488 }
3489
3490 int
3491 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3492 {
3493         int status;
3494         uint32_t old;
3495
3496         if (port->lun_map == NULL) {
3497                 status = ctl_lun_map_init(port);
3498                 if (status != 0)
3499                         return (status);
3500         }
3501         old = port->lun_map[plun];
3502         port->lun_map[plun] = glun;
3503         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3504                 if (port->lun_enable != NULL)
3505                         port->lun_enable(port->targ_lun_arg, plun);
3506                 ctl_isc_announce_port(port);
3507         }
3508         return (0);
3509 }
3510
3511 int
3512 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3513 {
3514         uint32_t old;
3515
3516         if (port->lun_map == NULL)
3517                 return (0);
3518         old = port->lun_map[plun];
3519         port->lun_map[plun] = UINT32_MAX;
3520         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3521                 if (port->lun_disable != NULL)
3522                         port->lun_disable(port->targ_lun_arg, plun);
3523                 ctl_isc_announce_port(port);
3524         }
3525         return (0);
3526 }
3527
3528 uint32_t
3529 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3530 {
3531
3532         if (port == NULL)
3533                 return (UINT32_MAX);
3534         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3535                 return (lun_id);
3536         return (port->lun_map[lun_id]);
3537 }
3538
3539 uint32_t
3540 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3541 {
3542         uint32_t i;
3543
3544         if (port == NULL)
3545                 return (UINT32_MAX);
3546         if (port->lun_map == NULL)
3547                 return (lun_id);
3548         for (i = 0; i < CTL_MAX_LUNS; i++) {
3549                 if (port->lun_map[i] == lun_id)
3550                         return (i);
3551         }
3552         return (UINT32_MAX);
3553 }
3554
3555 uint32_t
3556 ctl_decode_lun(uint64_t encoded)
3557 {
3558         uint8_t lun[8];
3559         uint32_t result = 0xffffffff;
3560
3561         be64enc(lun, encoded);
3562         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3563         case RPL_LUNDATA_ATYP_PERIPH:
3564                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3565                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3566                         result = lun[1];
3567                 break;
3568         case RPL_LUNDATA_ATYP_FLAT:
3569                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3570                     lun[6] == 0 && lun[7] == 0)
3571                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3572                 break;
3573         case RPL_LUNDATA_ATYP_EXTLUN:
3574                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3575                 case 0x02:
3576                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3577                         case 0x00:
3578                                 result = lun[1];
3579                                 break;
3580                         case 0x10:
3581                                 result = (lun[1] << 16) + (lun[2] << 8) +
3582                                     lun[3];
3583                                 break;
3584                         case 0x20:
3585                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3586                                         result = (lun[2] << 24) +
3587                                             (lun[3] << 16) + (lun[4] << 8) +
3588                                             lun[5];
3589                                 break;
3590                         }
3591                         break;
3592                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3593                         result = 0xffffffff;
3594                         break;
3595                 }
3596                 break;
3597         }
3598         return (result);
3599 }
3600
3601 uint64_t
3602 ctl_encode_lun(uint32_t decoded)
3603 {
3604         uint64_t l = decoded;
3605
3606         if (l <= 0xff)
3607                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3608         if (l <= 0x3fff)
3609                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3610         if (l <= 0xffffff)
3611                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3612                     (l << 32));
3613         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3614 }
3615
3616 static struct ctl_port *
3617 ctl_io_port(struct ctl_io_hdr *io_hdr)
3618 {
3619
3620         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3621 }
3622
3623 int
3624 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3625 {
3626         int i;
3627
3628         for (i = first; i < last; i++) {
3629                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3630                         return (i);
3631         }
3632         return (-1);
3633 }
3634
3635 int
3636 ctl_set_mask(uint32_t *mask, uint32_t bit)
3637 {
3638         uint32_t chunk, piece;
3639
3640         chunk = bit >> 5;
3641         piece = bit % (sizeof(uint32_t) * 8);
3642
3643         if ((mask[chunk] & (1 << piece)) != 0)
3644                 return (-1);
3645         else
3646                 mask[chunk] |= (1 << piece);
3647
3648         return (0);
3649 }
3650
3651 int
3652 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3653 {
3654         uint32_t chunk, piece;
3655
3656         chunk = bit >> 5;
3657         piece = bit % (sizeof(uint32_t) * 8);
3658
3659         if ((mask[chunk] & (1 << piece)) == 0)
3660                 return (-1);
3661         else
3662                 mask[chunk] &= ~(1 << piece);
3663
3664         return (0);
3665 }
3666
3667 int
3668 ctl_is_set(uint32_t *mask, uint32_t bit)
3669 {
3670         uint32_t chunk, piece;
3671
3672         chunk = bit >> 5;
3673         piece = bit % (sizeof(uint32_t) * 8);
3674
3675         if ((mask[chunk] & (1 << piece)) == 0)
3676                 return (0);
3677         else
3678                 return (1);
3679 }
3680
3681 static uint64_t
3682 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3683 {
3684         uint64_t *t;
3685
3686         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3687         if (t == NULL)
3688                 return (0);
3689         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3690 }
3691
3692 static void
3693 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3694 {
3695         uint64_t *t;
3696
3697         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3698         if (t == NULL)
3699                 return;
3700         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3701 }
3702
3703 static void
3704 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3705 {
3706         uint64_t *p;
3707         u_int i;
3708
3709         i = residx/CTL_MAX_INIT_PER_PORT;
3710         if (lun->pr_keys[i] != NULL)
3711                 return;
3712         mtx_unlock(&lun->lun_lock);
3713         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3714             M_WAITOK | M_ZERO);
3715         mtx_lock(&lun->lun_lock);
3716         if (lun->pr_keys[i] == NULL)
3717                 lun->pr_keys[i] = p;
3718         else
3719                 free(p, M_CTL);
3720 }
3721
3722 static void
3723 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3724 {
3725         uint64_t *t;
3726
3727         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3728         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3729         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3730 }
3731
3732 /*
3733  * ctl_softc, pool_name, total_ctl_io are passed in.
3734  * npool is passed out.
3735  */
3736 int
3737 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3738                 uint32_t total_ctl_io, void **npool)
3739 {
3740 #ifdef IO_POOLS
3741         struct ctl_io_pool *pool;
3742
3743         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3744                                             M_NOWAIT | M_ZERO);
3745         if (pool == NULL)
3746                 return (ENOMEM);
3747
3748         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3749         pool->ctl_softc = ctl_softc;
3750         pool->zone = uma_zsecond_create(pool->name, NULL,
3751             NULL, NULL, NULL, ctl_softc->io_zone);
3752         /* uma_prealloc(pool->zone, total_ctl_io); */
3753
3754         *npool = pool;
3755 #else
3756         *npool = ctl_softc->io_zone;
3757 #endif
3758         return (0);
3759 }
3760
3761 void
3762 ctl_pool_free(struct ctl_io_pool *pool)
3763 {
3764
3765         if (pool == NULL)
3766                 return;
3767
3768 #ifdef IO_POOLS
3769         uma_zdestroy(pool->zone);
3770         free(pool, M_CTL);
3771 #endif
3772 }
3773
3774 union ctl_io *
3775 ctl_alloc_io(void *pool_ref)
3776 {
3777         union ctl_io *io;
3778 #ifdef IO_POOLS
3779         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3780
3781         io = uma_zalloc(pool->zone, M_WAITOK);
3782 #else
3783         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3784 #endif
3785         if (io != NULL)
3786                 io->io_hdr.pool = pool_ref;
3787         return (io);
3788 }
3789
3790 union ctl_io *
3791 ctl_alloc_io_nowait(void *pool_ref)
3792 {
3793         union ctl_io *io;
3794 #ifdef IO_POOLS
3795         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3796
3797         io = uma_zalloc(pool->zone, M_NOWAIT);
3798 #else
3799         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3800 #endif
3801         if (io != NULL)
3802                 io->io_hdr.pool = pool_ref;
3803         return (io);
3804 }
3805
3806 void
3807 ctl_free_io(union ctl_io *io)
3808 {
3809 #ifdef IO_POOLS
3810         struct ctl_io_pool *pool;
3811 #endif
3812
3813         if (io == NULL)
3814                 return;
3815
3816 #ifdef IO_POOLS
3817         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3818         uma_zfree(pool->zone, io);
3819 #else
3820         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3821 #endif
3822 }
3823
3824 void
3825 ctl_zero_io(union ctl_io *io)
3826 {
3827         void *pool_ref;
3828
3829         if (io == NULL)
3830                 return;
3831
3832         /*
3833          * May need to preserve linked list pointers at some point too.
3834          */
3835         pool_ref = io->io_hdr.pool;
3836         memset(io, 0, sizeof(*io));
3837         io->io_hdr.pool = pool_ref;
3838 }
3839
3840 int
3841 ctl_expand_number(const char *buf, uint64_t *num)
3842 {
3843         char *endptr;
3844         uint64_t number;
3845         unsigned shift;
3846
3847         number = strtoq(buf, &endptr, 0);
3848
3849         switch (tolower((unsigned char)*endptr)) {
3850         case 'e':
3851                 shift = 60;
3852                 break;
3853         case 'p':
3854                 shift = 50;
3855                 break;
3856         case 't':
3857                 shift = 40;
3858                 break;
3859         case 'g':
3860                 shift = 30;
3861                 break;
3862         case 'm':
3863                 shift = 20;
3864                 break;
3865         case 'k':
3866                 shift = 10;
3867                 break;
3868         case 'b':
3869         case '\0': /* No unit. */
3870                 *num = number;
3871                 return (0);
3872         default:
3873                 /* Unrecognized unit. */
3874                 return (-1);
3875         }
3876
3877         if ((number << shift) >> shift != number) {
3878                 /* Overflow */
3879                 return (-1);
3880         }
3881         *num = number << shift;
3882         return (0);
3883 }
3884
3885
3886 /*
3887  * This routine could be used in the future to load default and/or saved
3888  * mode page parameters for a particuar lun.
3889  */
3890 static int
3891 ctl_init_page_index(struct ctl_lun *lun)
3892 {
3893         int i, page_code;
3894         struct ctl_page_index *page_index;
3895         const char *value;
3896         uint64_t ival;
3897
3898         memcpy(&lun->mode_pages.index, page_index_template,
3899                sizeof(page_index_template));
3900
3901         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3902
3903                 page_index = &lun->mode_pages.index[i];
3904                 if (lun->be_lun->lun_type == T_DIRECT &&
3905                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3906                         continue;
3907                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3908                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3909                         continue;
3910                 if (lun->be_lun->lun_type == T_CDROM &&
3911                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3912                         continue;
3913
3914                 page_code = page_index->page_code & SMPH_PC_MASK;
3915                 switch (page_code) {
3916                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3917                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3918                             ("subpage %#x for page %#x is incorrect!",
3919                             page_index->subpage, page_code));
3920                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3921                                &rw_er_page_default,
3922                                sizeof(rw_er_page_default));
3923                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3924                                &rw_er_page_changeable,
3925                                sizeof(rw_er_page_changeable));
3926                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3927                                &rw_er_page_default,
3928                                sizeof(rw_er_page_default));
3929                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3930                                &rw_er_page_default,
3931                                sizeof(rw_er_page_default));
3932                         page_index->page_data =
3933                                 (uint8_t *)lun->mode_pages.rw_er_page;
3934                         break;
3935                 }
3936                 case SMS_FORMAT_DEVICE_PAGE: {
3937                         struct scsi_format_page *format_page;
3938
3939                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3940                             ("subpage %#x for page %#x is incorrect!",
3941                             page_index->subpage, page_code));
3942
3943                         /*
3944                          * Sectors per track are set above.  Bytes per
3945                          * sector need to be set here on a per-LUN basis.
3946                          */
3947                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3948                                &format_page_default,
3949                                sizeof(format_page_default));
3950                         memcpy(&lun->mode_pages.format_page[
3951                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3952                                sizeof(format_page_changeable));
3953                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3954                                &format_page_default,
3955                                sizeof(format_page_default));
3956                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3957                                &format_page_default,
3958                                sizeof(format_page_default));
3959
3960                         format_page = &lun->mode_pages.format_page[
3961                                 CTL_PAGE_CURRENT];
3962                         scsi_ulto2b(lun->be_lun->blocksize,
3963                                     format_page->bytes_per_sector);
3964
3965                         format_page = &lun->mode_pages.format_page[
3966                                 CTL_PAGE_DEFAULT];
3967                         scsi_ulto2b(lun->be_lun->blocksize,
3968                                     format_page->bytes_per_sector);
3969
3970                         format_page = &lun->mode_pages.format_page[
3971                                 CTL_PAGE_SAVED];
3972                         scsi_ulto2b(lun->be_lun->blocksize,
3973                                     format_page->bytes_per_sector);
3974
3975                         page_index->page_data =
3976                                 (uint8_t *)lun->mode_pages.format_page;
3977                         break;
3978                 }
3979                 case SMS_RIGID_DISK_PAGE: {
3980                         struct scsi_rigid_disk_page *rigid_disk_page;
3981                         uint32_t sectors_per_cylinder;
3982                         uint64_t cylinders;
3983 #ifndef __XSCALE__
3984                         int shift;
3985 #endif /* !__XSCALE__ */
3986
3987                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3988                             ("subpage %#x for page %#x is incorrect!",
3989                             page_index->subpage, page_code));
3990
3991                         /*
3992                          * Rotation rate and sectors per track are set
3993                          * above.  We calculate the cylinders here based on
3994                          * capacity.  Due to the number of heads and
3995                          * sectors per track we're using, smaller arrays
3996                          * may turn out to have 0 cylinders.  Linux and
3997                          * FreeBSD don't pay attention to these mode pages
3998                          * to figure out capacity, but Solaris does.  It
3999                          * seems to deal with 0 cylinders just fine, and
4000                          * works out a fake geometry based on the capacity.
4001                          */
4002                         memcpy(&lun->mode_pages.rigid_disk_page[
4003                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4004                                sizeof(rigid_disk_page_default));
4005                         memcpy(&lun->mode_pages.rigid_disk_page[
4006                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4007                                sizeof(rigid_disk_page_changeable));
4008
4009                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4010                                 CTL_DEFAULT_HEADS;
4011
4012                         /*
4013                          * The divide method here will be more accurate,
4014                          * probably, but results in floating point being
4015                          * used in the kernel on i386 (__udivdi3()).  On the
4016                          * XScale, though, __udivdi3() is implemented in
4017                          * software.
4018                          *
4019                          * The shift method for cylinder calculation is
4020                          * accurate if sectors_per_cylinder is a power of
4021                          * 2.  Otherwise it might be slightly off -- you
4022                          * might have a bit of a truncation problem.
4023                          */
4024 #ifdef  __XSCALE__
4025                         cylinders = (lun->be_lun->maxlba + 1) /
4026                                 sectors_per_cylinder;
4027 #else
4028                         for (shift = 31; shift > 0; shift--) {
4029                                 if (sectors_per_cylinder & (1 << shift))
4030                                         break;
4031                         }
4032                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4033 #endif
4034
4035                         /*
4036                          * We've basically got 3 bytes, or 24 bits for the
4037                          * cylinder size in the mode page.  If we're over,
4038                          * just round down to 2^24.
4039                          */
4040                         if (cylinders > 0xffffff)
4041                                 cylinders = 0xffffff;
4042
4043                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4044                                 CTL_PAGE_DEFAULT];
4045                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4046
4047                         if ((value = ctl_get_opt(&lun->be_lun->options,
4048                             "rpm")) != NULL) {
4049                                 scsi_ulto2b(strtol(value, NULL, 0),
4050                                      rigid_disk_page->rotation_rate);
4051                         }
4052
4053                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4054                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4055                                sizeof(rigid_disk_page_default));
4056                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4057                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4058                                sizeof(rigid_disk_page_default));
4059
4060                         page_index->page_data =
4061                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4062                         break;
4063                 }
4064                 case SMS_CACHING_PAGE: {
4065                         struct scsi_caching_page *caching_page;
4066
4067                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4068                             ("subpage %#x for page %#x is incorrect!",
4069                             page_index->subpage, page_code));
4070                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4071                                &caching_page_default,
4072                                sizeof(caching_page_default));
4073                         memcpy(&lun->mode_pages.caching_page[
4074                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4075                                sizeof(caching_page_changeable));
4076                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4077                                &caching_page_default,
4078                                sizeof(caching_page_default));
4079                         caching_page = &lun->mode_pages.caching_page[
4080                             CTL_PAGE_SAVED];
4081                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4082                         if (value != NULL && strcmp(value, "off") == 0)
4083                                 caching_page->flags1 &= ~SCP_WCE;
4084                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4085                         if (value != NULL && strcmp(value, "off") == 0)
4086                                 caching_page->flags1 |= SCP_RCD;
4087                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4088                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4089                                sizeof(caching_page_default));
4090                         page_index->page_data =
4091                                 (uint8_t *)lun->mode_pages.caching_page;
4092                         break;
4093                 }
4094                 case SMS_CONTROL_MODE_PAGE: {
4095                         switch (page_index->subpage) {
4096                         case SMS_SUBPAGE_PAGE_0: {
4097                                 struct scsi_control_page *control_page;
4098
4099                                 memcpy(&lun->mode_pages.control_page[
4100                                     CTL_PAGE_DEFAULT],
4101                                        &control_page_default,
4102                                        sizeof(control_page_default));
4103                                 memcpy(&lun->mode_pages.control_page[
4104                                     CTL_PAGE_CHANGEABLE],
4105                                        &control_page_changeable,
4106                                        sizeof(control_page_changeable));
4107                                 memcpy(&lun->mode_pages.control_page[
4108                                     CTL_PAGE_SAVED],
4109                                        &control_page_default,
4110                                        sizeof(control_page_default));
4111                                 control_page = &lun->mode_pages.control_page[
4112                                     CTL_PAGE_SAVED];
4113                                 value = ctl_get_opt(&lun->be_lun->options,
4114                                     "reordering");
4115                                 if (value != NULL &&
4116                                     strcmp(value, "unrestricted") == 0) {
4117                                         control_page->queue_flags &=
4118                                             ~SCP_QUEUE_ALG_MASK;
4119                                         control_page->queue_flags |=
4120                                             SCP_QUEUE_ALG_UNRESTRICTED;
4121                                 }
4122                                 memcpy(&lun->mode_pages.control_page[
4123                                     CTL_PAGE_CURRENT],
4124                                        &lun->mode_pages.control_page[
4125                                     CTL_PAGE_SAVED],
4126                                        sizeof(control_page_default));
4127                                 page_index->page_data =
4128                                     (uint8_t *)lun->mode_pages.control_page;
4129                                 break;
4130                         }
4131                         case 0x01:
4132                                 memcpy(&lun->mode_pages.control_ext_page[
4133                                     CTL_PAGE_DEFAULT],
4134                                        &control_ext_page_default,
4135                                        sizeof(control_ext_page_default));
4136                                 memcpy(&lun->mode_pages.control_ext_page[
4137                                     CTL_PAGE_CHANGEABLE],
4138                                        &control_ext_page_changeable,
4139                                        sizeof(control_ext_page_changeable));
4140                                 memcpy(&lun->mode_pages.control_ext_page[
4141                                     CTL_PAGE_SAVED],
4142                                        &control_ext_page_default,
4143                                        sizeof(control_ext_page_default));
4144                                 memcpy(&lun->mode_pages.control_ext_page[
4145                                     CTL_PAGE_CURRENT],
4146                                        &lun->mode_pages.control_ext_page[
4147                                     CTL_PAGE_SAVED],
4148                                        sizeof(control_ext_page_default));
4149                                 page_index->page_data =
4150                                     (uint8_t *)lun->mode_pages.control_ext_page;
4151                                 break;
4152                         default:
4153                                 panic("subpage %#x for page %#x is incorrect!",
4154                                       page_index->subpage, page_code);
4155                         }
4156                         break;
4157                 }
4158                 case SMS_INFO_EXCEPTIONS_PAGE: {
4159                         switch (page_index->subpage) {
4160                         case SMS_SUBPAGE_PAGE_0:
4161                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4162                                        &ie_page_default,
4163                                        sizeof(ie_page_default));
4164                                 memcpy(&lun->mode_pages.ie_page[
4165                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4166                                        sizeof(ie_page_changeable));
4167                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4168                                        &ie_page_default,
4169                                        sizeof(ie_page_default));
4170                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4171                                        &ie_page_default,
4172                                        sizeof(ie_page_default));
4173                                 page_index->page_data =
4174                                         (uint8_t *)lun->mode_pages.ie_page;
4175                                 break;
4176                         case 0x02: {
4177                                 struct ctl_logical_block_provisioning_page *page;
4178
4179                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4180                                        &lbp_page_default,
4181                                        sizeof(lbp_page_default));
4182                                 memcpy(&lun->mode_pages.lbp_page[
4183                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4184                                        sizeof(lbp_page_changeable));
4185                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4186                                        &lbp_page_default,
4187                                        sizeof(lbp_page_default));
4188                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4189                                 value = ctl_get_opt(&lun->be_lun->options,
4190                                     "avail-threshold");
4191                                 if (value != NULL &&
4192                                     ctl_expand_number(value, &ival) == 0) {
4193                                         page->descr[0].flags |= SLBPPD_ENABLED |
4194                                             SLBPPD_ARMING_DEC;
4195                                         if (lun->be_lun->blocksize)
4196                                                 ival /= lun->be_lun->blocksize;
4197                                         else
4198                                                 ival /= 512;
4199                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4200                                             page->descr[0].count);
4201                                 }
4202                                 value = ctl_get_opt(&lun->be_lun->options,
4203                                     "used-threshold");
4204                                 if (value != NULL &&
4205                                     ctl_expand_number(value, &ival) == 0) {
4206                                         page->descr[1].flags |= SLBPPD_ENABLED |
4207                                             SLBPPD_ARMING_INC;
4208                                         if (lun->be_lun->blocksize)
4209                                                 ival /= lun->be_lun->blocksize;
4210                                         else
4211                                                 ival /= 512;
4212                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4213                                             page->descr[1].count);
4214                                 }
4215                                 value = ctl_get_opt(&lun->be_lun->options,
4216                                     "pool-avail-threshold");
4217                                 if (value != NULL &&
4218                                     ctl_expand_number(value, &ival) == 0) {
4219                                         page->descr[2].flags |= SLBPPD_ENABLED |
4220                                             SLBPPD_ARMING_DEC;
4221                                         if (lun->be_lun->blocksize)
4222                                                 ival /= lun->be_lun->blocksize;
4223                                         else
4224                                                 ival /= 512;
4225                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4226                                             page->descr[2].count);
4227                                 }
4228                                 value = ctl_get_opt(&lun->be_lun->options,
4229                                     "pool-used-threshold");
4230                                 if (value != NULL &&
4231                                     ctl_expand_number(value, &ival) == 0) {
4232                                         page->descr[3].flags |= SLBPPD_ENABLED |
4233                                             SLBPPD_ARMING_INC;
4234                                         if (lun->be_lun->blocksize)
4235                                                 ival /= lun->be_lun->blocksize;
4236                                         else
4237                                                 ival /= 512;
4238                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4239                                             page->descr[3].count);
4240                                 }
4241                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4242                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4243                                        sizeof(lbp_page_default));
4244                                 page_index->page_data =
4245                                         (uint8_t *)lun->mode_pages.lbp_page;
4246                                 break;
4247                         }
4248                         default:
4249                                 panic("subpage %#x for page %#x is incorrect!",
4250                                       page_index->subpage, page_code);
4251                         }
4252                         break;
4253                 }
4254                 case SMS_CDDVD_CAPS_PAGE:{
4255                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4256                             ("subpage %#x for page %#x is incorrect!",
4257                             page_index->subpage, page_code));
4258                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4259                                &cddvd_page_default,
4260                                sizeof(cddvd_page_default));
4261                         memcpy(&lun->mode_pages.cddvd_page[
4262                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4263                                sizeof(cddvd_page_changeable));
4264                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4265                                &cddvd_page_default,
4266                                sizeof(cddvd_page_default));
4267                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4268                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4269                                sizeof(cddvd_page_default));
4270                         page_index->page_data =
4271                                 (uint8_t *)lun->mode_pages.cddvd_page;
4272                         break;
4273                 }
4274                 case SMS_VENDOR_SPECIFIC_PAGE:{
4275                         switch (page_index->subpage) {
4276                         case DBGCNF_SUBPAGE_CODE: {
4277                                 memcpy(&lun->mode_pages.debugconf_subpage[
4278                                        CTL_PAGE_CURRENT],
4279                                        &debugconf_page_default,
4280                                        sizeof(debugconf_page_default));
4281                                 memcpy(&lun->mode_pages.debugconf_subpage[
4282                                        CTL_PAGE_CHANGEABLE],
4283                                        &debugconf_page_changeable,
4284                                        sizeof(debugconf_page_changeable));
4285                                 memcpy(&lun->mode_pages.debugconf_subpage[
4286                                        CTL_PAGE_DEFAULT],
4287                                        &debugconf_page_default,
4288                                        sizeof(debugconf_page_default));
4289                                 memcpy(&lun->mode_pages.debugconf_subpage[
4290                                        CTL_PAGE_SAVED],
4291                                        &debugconf_page_default,
4292                                        sizeof(debugconf_page_default));
4293                                 page_index->page_data =
4294                                     (uint8_t *)lun->mode_pages.debugconf_subpage;
4295                                 break;
4296                         }
4297                         default:
4298                                 panic("subpage %#x for page %#x is incorrect!",
4299                                       page_index->subpage, page_code);
4300                         }
4301                         break;
4302                 }
4303                 default:
4304                         panic("invalid page code value %#x", page_code);
4305                 }
4306         }
4307
4308         return (CTL_RETVAL_COMPLETE);
4309 }
4310
4311 static int
4312 ctl_init_log_page_index(struct ctl_lun *lun)
4313 {
4314         struct ctl_page_index *page_index;
4315         int i, j, k, prev;
4316
4317         memcpy(&lun->log_pages.index, log_page_index_template,
4318                sizeof(log_page_index_template));
4319
4320         prev = -1;
4321         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4322
4323                 page_index = &lun->log_pages.index[i];
4324                 if (lun->be_lun->lun_type == T_DIRECT &&
4325                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4326                         continue;
4327                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4328                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4329                         continue;
4330                 if (lun->be_lun->lun_type == T_CDROM &&
4331                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4332                         continue;
4333
4334                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4335                     lun->backend->lun_attr == NULL)
4336                         continue;
4337
4338                 if (page_index->page_code != prev) {
4339                         lun->log_pages.pages_page[j] = page_index->page_code;
4340                         prev = page_index->page_code;
4341                         j++;
4342                 }
4343                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4344                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4345                 k++;
4346         }
4347         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4348         lun->log_pages.index[0].page_len = j;
4349         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4350         lun->log_pages.index[1].page_len = k * 2;
4351         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4352         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4353         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4354         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4355
4356         return (CTL_RETVAL_COMPLETE);
4357 }
4358
4359 static int
4360 hex2bin(const char *str, uint8_t *buf, int buf_size)
4361 {
4362         int i;
4363         u_char c;
4364
4365         memset(buf, 0, buf_size);
4366         while (isspace(str[0]))
4367                 str++;
4368         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4369                 str += 2;
4370         buf_size *= 2;
4371         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4372                 c = str[i];
4373                 if (isdigit(c))
4374                         c -= '0';
4375                 else if (isalpha(c))
4376                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4377                 else
4378                         break;
4379                 if (c >= 16)
4380                         break;
4381                 if ((i & 1) == 0)
4382                         buf[i / 2] |= (c << 4);
4383                 else
4384                         buf[i / 2] |= c;
4385         }
4386         return ((i + 1) / 2);
4387 }
4388
4389 /*
4390  * LUN allocation.
4391  *
4392  * Requirements:
4393  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4394  *   wants us to allocate the LUN and he can block.
4395  * - ctl_softc is always set
4396  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4397  *
4398  * Returns 0 for success, non-zero (errno) for failure.
4399  */
4400 static int
4401 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4402               struct ctl_be_lun *const be_lun)
4403 {
4404         struct ctl_lun *nlun, *lun;
4405         struct scsi_vpd_id_descriptor *desc;
4406         struct scsi_vpd_id_t10 *t10id;
4407         const char *eui, *naa, *scsiname, *vendor, *value;
4408         int lun_number, i, lun_malloced;
4409         int devidlen, idlen1, idlen2 = 0, len;
4410
4411         if (be_lun == NULL)
4412                 return (EINVAL);
4413
4414         /*
4415          * We currently only support Direct Access or Processor LUN types.
4416          */
4417         switch (be_lun->lun_type) {
4418         case T_DIRECT:
4419         case T_PROCESSOR:
4420         case T_CDROM:
4421                 break;
4422         case T_SEQUENTIAL:
4423         case T_CHANGER:
4424         default:
4425                 be_lun->lun_config_status(be_lun->be_lun,
4426                                           CTL_LUN_CONFIG_FAILURE);
4427                 break;
4428         }
4429         if (ctl_lun == NULL) {
4430                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4431                 lun_malloced = 1;
4432         } else {
4433                 lun_malloced = 0;
4434                 lun = ctl_lun;
4435         }
4436
4437         memset(lun, 0, sizeof(*lun));
4438         if (lun_malloced)
4439                 lun->flags = CTL_LUN_MALLOCED;
4440
4441         /* Generate LUN ID. */
4442         devidlen = max(CTL_DEVID_MIN_LEN,
4443             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4444         idlen1 = sizeof(*t10id) + devidlen;
4445         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4446         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4447         if (scsiname != NULL) {
4448                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4449                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4450         }
4451         eui = ctl_get_opt(&be_lun->options, "eui");
4452         if (eui != NULL) {
4453                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4454         }
4455         naa = ctl_get_opt(&be_lun->options, "naa");
4456         if (naa != NULL) {
4457                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4458         }
4459         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4460             M_CTL, M_WAITOK | M_ZERO);
4461         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4462         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4463         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4464         desc->length = idlen1;
4465         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4466         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4467         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4468                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4469         } else {
4470                 strncpy(t10id->vendor, vendor,
4471                     min(sizeof(t10id->vendor), strlen(vendor)));
4472         }
4473         strncpy((char *)t10id->vendor_spec_id,
4474             (char *)be_lun->device_id, devidlen);
4475         if (scsiname != NULL) {
4476                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4477                     desc->length);
4478                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4479                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4480                     SVPD_ID_TYPE_SCSI_NAME;
4481                 desc->length = idlen2;
4482                 strlcpy(desc->identifier, scsiname, idlen2);
4483         }
4484         if (eui != NULL) {
4485                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4486                     desc->length);
4487                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4488                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4489                     SVPD_ID_TYPE_EUI64;
4490                 desc->length = hex2bin(eui, desc->identifier, 16);
4491                 desc->length = desc->length > 12 ? 16 :
4492                     (desc->length > 8 ? 12 : 8);
4493                 len -= 16 - desc->length;
4494         }
4495         if (naa != NULL) {
4496                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4497                     desc->length);
4498                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4499                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4500                     SVPD_ID_TYPE_NAA;
4501                 desc->length = hex2bin(naa, desc->identifier, 16);
4502                 desc->length = desc->length > 8 ? 16 : 8;
4503                 len -= 16 - desc->length;
4504         }
4505         lun->lun_devid->len = len;
4506
4507         mtx_lock(&ctl_softc->ctl_lock);
4508         /*
4509          * See if the caller requested a particular LUN number.  If so, see
4510          * if it is available.  Otherwise, allocate the first available LUN.
4511          */
4512         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4513                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4514                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4515                         mtx_unlock(&ctl_softc->ctl_lock);
4516                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4517                                 printf("ctl: requested LUN ID %d is higher "
4518                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4519                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4520                         } else {
4521                                 /*
4522                                  * XXX KDM return an error, or just assign
4523                                  * another LUN ID in this case??
4524                                  */
4525                                 printf("ctl: requested LUN ID %d is already "
4526                                        "in use\n", be_lun->req_lun_id);
4527                         }
4528                         if (lun->flags & CTL_LUN_MALLOCED)
4529                                 free(lun, M_CTL);
4530                         be_lun->lun_config_status(be_lun->be_lun,
4531                                                   CTL_LUN_CONFIG_FAILURE);
4532                         return (ENOSPC);
4533                 }
4534                 lun_number = be_lun->req_lun_id;
4535         } else {
4536                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4537                 if (lun_number == -1) {
4538                         mtx_unlock(&ctl_softc->ctl_lock);
4539                         printf("ctl: can't allocate LUN, out of LUNs\n");
4540                         if (lun->flags & CTL_LUN_MALLOCED)
4541                                 free(lun, M_CTL);
4542                         be_lun->lun_config_status(be_lun->be_lun,
4543                                                   CTL_LUN_CONFIG_FAILURE);
4544                         return (ENOSPC);
4545                 }
4546         }
4547         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4548
4549         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4550         lun->lun = lun_number;
4551         lun->be_lun = be_lun;
4552         /*
4553          * The processor LUN is always enabled.  Disk LUNs come on line
4554          * disabled, and must be enabled by the backend.
4555          */
4556         lun->flags |= CTL_LUN_DISABLED;
4557         lun->backend = be_lun->be;
4558         be_lun->ctl_lun = lun;
4559         be_lun->lun_id = lun_number;
4560         atomic_add_int(&be_lun->be->num_luns, 1);
4561         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4562                 lun->flags |= CTL_LUN_EJECTED;
4563         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4564                 lun->flags |= CTL_LUN_NO_MEDIA;
4565         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4566                 lun->flags |= CTL_LUN_STOPPED;
4567
4568         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4569                 lun->flags |= CTL_LUN_PRIMARY_SC;
4570
4571         value = ctl_get_opt(&be_lun->options, "removable");
4572         if (value != NULL) {
4573                 if (strcmp(value, "on") == 0)
4574                         lun->flags |= CTL_LUN_REMOVABLE;
4575         } else if (be_lun->lun_type == T_CDROM)
4576                 lun->flags |= CTL_LUN_REMOVABLE;
4577
4578         lun->ctl_softc = ctl_softc;
4579 #ifdef CTL_TIME_IO
4580         lun->last_busy = getsbinuptime();
4581 #endif
4582         TAILQ_INIT(&lun->ooa_queue);
4583         TAILQ_INIT(&lun->blocked_queue);
4584         STAILQ_INIT(&lun->error_list);
4585         ctl_tpc_lun_init(lun);
4586
4587         /*
4588          * Initialize the mode and log page index.
4589          */
4590         ctl_init_page_index(lun);
4591         ctl_init_log_page_index(lun);
4592
4593         /*
4594          * Now, before we insert this lun on the lun list, set the lun
4595          * inventory changed UA for all other luns.
4596          */
4597         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4598                 mtx_lock(&nlun->lun_lock);
4599                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4600                 mtx_unlock(&nlun->lun_lock);
4601         }
4602
4603         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4604
4605         ctl_softc->ctl_luns[lun_number] = lun;
4606
4607         ctl_softc->num_luns++;
4608
4609         /* Setup statistics gathering */
4610         lun->stats.device_type = be_lun->lun_type;
4611         lun->stats.lun_number = lun_number;
4612         lun->stats.blocksize = be_lun->blocksize;
4613         if (be_lun->blocksize == 0)
4614                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4615         for (i = 0;i < CTL_MAX_PORTS;i++)
4616                 lun->stats.ports[i].targ_port = i;
4617
4618         mtx_unlock(&ctl_softc->ctl_lock);
4619
4620         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4621         return (0);
4622 }
4623
4624 /*
4625  * Delete a LUN.
4626  * Assumptions:
4627  * - LUN has already been marked invalid and any pending I/O has been taken
4628  *   care of.
4629  */
4630 static int
4631 ctl_free_lun(struct ctl_lun *lun)
4632 {
4633         struct ctl_softc *softc;
4634         struct ctl_lun *nlun;
4635         int i;
4636
4637         softc = lun->ctl_softc;
4638
4639         mtx_assert(&softc->ctl_lock, MA_OWNED);
4640
4641         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4642
4643         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4644
4645         softc->ctl_luns[lun->lun] = NULL;
4646
4647         if (!TAILQ_EMPTY(&lun->ooa_queue))
4648                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4649
4650         softc->num_luns--;
4651
4652         /*
4653          * Tell the backend to free resources, if this LUN has a backend.
4654          */
4655         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4656         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4657
4658         ctl_tpc_lun_shutdown(lun);
4659         mtx_destroy(&lun->lun_lock);
4660         free(lun->lun_devid, M_CTL);
4661         for (i = 0; i < CTL_MAX_PORTS; i++)
4662                 free(lun->pending_ua[i], M_CTL);
4663         for (i = 0; i < CTL_MAX_PORTS; i++)
4664                 free(lun->pr_keys[i], M_CTL);
4665         free(lun->write_buffer, M_CTL);
4666         if (lun->flags & CTL_LUN_MALLOCED)
4667                 free(lun, M_CTL);
4668
4669         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4670                 mtx_lock(&nlun->lun_lock);
4671                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4672                 mtx_unlock(&nlun->lun_lock);
4673         }
4674
4675         return (0);
4676 }
4677
4678 static void
4679 ctl_create_lun(struct ctl_be_lun *be_lun)
4680 {
4681
4682         /*
4683          * ctl_alloc_lun() should handle all potential failure cases.
4684          */
4685         ctl_alloc_lun(control_softc, NULL, be_lun);
4686 }
4687
4688 int
4689 ctl_add_lun(struct ctl_be_lun *be_lun)
4690 {
4691         struct ctl_softc *softc = control_softc;
4692
4693         mtx_lock(&softc->ctl_lock);
4694         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4695         mtx_unlock(&softc->ctl_lock);
4696         wakeup(&softc->pending_lun_queue);
4697
4698         return (0);
4699 }
4700
4701 int
4702 ctl_enable_lun(struct ctl_be_lun *be_lun)
4703 {
4704         struct ctl_softc *softc;
4705         struct ctl_port *port, *nport;
4706         struct ctl_lun *lun;
4707         int retval;
4708
4709         lun = (struct ctl_lun *)be_lun->ctl_lun;
4710         softc = lun->ctl_softc;
4711
4712         mtx_lock(&softc->ctl_lock);
4713         mtx_lock(&lun->lun_lock);
4714         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4715                 /*
4716                  * eh?  Why did we get called if the LUN is already
4717                  * enabled?
4718                  */
4719                 mtx_unlock(&lun->lun_lock);
4720                 mtx_unlock(&softc->ctl_lock);
4721                 return (0);
4722         }
4723         lun->flags &= ~CTL_LUN_DISABLED;
4724         mtx_unlock(&lun->lun_lock);
4725
4726         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4727                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4728                     port->lun_map != NULL || port->lun_enable == NULL)
4729                         continue;
4730
4731                 /*
4732                  * Drop the lock while we call the FETD's enable routine.
4733                  * This can lead to a callback into CTL (at least in the
4734                  * case of the internal initiator frontend.
4735                  */
4736                 mtx_unlock(&softc->ctl_lock);
4737                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4738                 mtx_lock(&softc->ctl_lock);
4739                 if (retval != 0) {
4740                         printf("%s: FETD %s port %d returned error "
4741                                "%d for lun_enable on lun %jd\n",
4742                                __func__, port->port_name, port->targ_port,
4743                                retval, (intmax_t)lun->lun);
4744                 }
4745         }
4746
4747         mtx_unlock(&softc->ctl_lock);
4748         ctl_isc_announce_lun(lun);
4749
4750         return (0);
4751 }
4752
4753 int
4754 ctl_disable_lun(struct ctl_be_lun *be_lun)
4755 {
4756         struct ctl_softc *softc;
4757         struct ctl_port *port;
4758         struct ctl_lun *lun;
4759         int retval;
4760
4761         lun = (struct ctl_lun *)be_lun->ctl_lun;
4762         softc = lun->ctl_softc;
4763
4764         mtx_lock(&softc->ctl_lock);
4765         mtx_lock(&lun->lun_lock);
4766         if (lun->flags & CTL_LUN_DISABLED) {
4767                 mtx_unlock(&lun->lun_lock);
4768                 mtx_unlock(&softc->ctl_lock);
4769                 return (0);
4770         }
4771         lun->flags |= CTL_LUN_DISABLED;
4772         mtx_unlock(&lun->lun_lock);
4773
4774         STAILQ_FOREACH(port, &softc->port_list, links) {
4775                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4776                     port->lun_map != NULL || port->lun_disable == NULL)
4777                         continue;
4778
4779                 /*
4780                  * Drop the lock before we call the frontend's disable
4781                  * routine, to avoid lock order reversals.
4782                  *
4783                  * XXX KDM what happens if the frontend list changes while
4784                  * we're traversing it?  It's unlikely, but should be handled.
4785                  */
4786                 mtx_unlock(&softc->ctl_lock);
4787                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4788                 mtx_lock(&softc->ctl_lock);
4789                 if (retval != 0) {
4790                         printf("%s: FETD %s port %d returned error "
4791                                "%d for lun_disable on lun %jd\n",
4792                                __func__, port->port_name, port->targ_port,
4793                                retval, (intmax_t)lun->lun);
4794                 }
4795         }
4796
4797         mtx_unlock(&softc->ctl_lock);
4798         ctl_isc_announce_lun(lun);
4799
4800         return (0);
4801 }
4802
4803 int
4804 ctl_start_lun(struct ctl_be_lun *be_lun)
4805 {
4806         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4807
4808         mtx_lock(&lun->lun_lock);
4809         lun->flags &= ~CTL_LUN_STOPPED;
4810         mtx_unlock(&lun->lun_lock);
4811         return (0);
4812 }
4813
4814 int
4815 ctl_stop_lun(struct ctl_be_lun *be_lun)
4816 {
4817         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4818
4819         mtx_lock(&lun->lun_lock);
4820         lun->flags |= CTL_LUN_STOPPED;
4821         mtx_unlock(&lun->lun_lock);
4822         return (0);
4823 }
4824
4825 int
4826 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4827 {
4828         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4829
4830         mtx_lock(&lun->lun_lock);
4831         lun->flags |= CTL_LUN_NO_MEDIA;
4832         mtx_unlock(&lun->lun_lock);
4833         return (0);
4834 }
4835
4836 int
4837 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4838 {
4839         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4840         union ctl_ha_msg msg;
4841
4842         mtx_lock(&lun->lun_lock);
4843         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4844         if (lun->flags & CTL_LUN_REMOVABLE)
4845                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4846         mtx_unlock(&lun->lun_lock);
4847         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4848             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4849                 bzero(&msg.ua, sizeof(msg.ua));
4850                 msg.hdr.msg_type = CTL_MSG_UA;
4851                 msg.hdr.nexus.initid = -1;
4852                 msg.hdr.nexus.targ_port = -1;
4853                 msg.hdr.nexus.targ_lun = lun->lun;
4854                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4855                 msg.ua.ua_all = 1;
4856                 msg.ua.ua_set = 1;
4857                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4858                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4859                     M_WAITOK);
4860         }
4861         return (0);
4862 }
4863
4864 int
4865 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4866 {
4867         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4868
4869         mtx_lock(&lun->lun_lock);
4870         lun->flags |= CTL_LUN_EJECTED;
4871         mtx_unlock(&lun->lun_lock);
4872         return (0);
4873 }
4874
4875 int
4876 ctl_lun_primary(struct ctl_be_lun *be_lun)
4877 {
4878         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4879
4880         mtx_lock(&lun->lun_lock);
4881         lun->flags |= CTL_LUN_PRIMARY_SC;
4882         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4883         mtx_unlock(&lun->lun_lock);
4884         ctl_isc_announce_lun(lun);
4885         return (0);
4886 }
4887
4888 int
4889 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4890 {
4891         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4892
4893         mtx_lock(&lun->lun_lock);
4894         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4895         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4896         mtx_unlock(&lun->lun_lock);
4897         ctl_isc_announce_lun(lun);
4898         return (0);
4899 }
4900
4901 int
4902 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4903 {
4904         struct ctl_softc *softc;
4905         struct ctl_lun *lun;
4906
4907         lun = (struct ctl_lun *)be_lun->ctl_lun;
4908         softc = lun->ctl_softc;
4909
4910         mtx_lock(&lun->lun_lock);
4911
4912         /*
4913          * The LUN needs to be disabled before it can be marked invalid.
4914          */
4915         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4916                 mtx_unlock(&lun->lun_lock);
4917                 return (-1);
4918         }
4919         /*
4920          * Mark the LUN invalid.
4921          */
4922         lun->flags |= CTL_LUN_INVALID;
4923
4924         /*
4925          * If there is nothing in the OOA queue, go ahead and free the LUN.
4926          * If we have something in the OOA queue, we'll free it when the
4927          * last I/O completes.
4928          */
4929         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4930                 mtx_unlock(&lun->lun_lock);
4931                 mtx_lock(&softc->ctl_lock);
4932                 ctl_free_lun(lun);
4933                 mtx_unlock(&softc->ctl_lock);
4934         } else
4935                 mtx_unlock(&lun->lun_lock);
4936
4937         return (0);
4938 }
4939
4940 void
4941 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4942 {
4943         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4944         union ctl_ha_msg msg;
4945
4946         mtx_lock(&lun->lun_lock);
4947         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4948         mtx_unlock(&lun->lun_lock);
4949         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4950                 /* Send msg to other side. */
4951                 bzero(&msg.ua, sizeof(msg.ua));
4952                 msg.hdr.msg_type = CTL_MSG_UA;
4953                 msg.hdr.nexus.initid = -1;
4954                 msg.hdr.nexus.targ_port = -1;
4955                 msg.hdr.nexus.targ_lun = lun->lun;
4956                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4957                 msg.ua.ua_all = 1;
4958                 msg.ua.ua_set = 1;
4959                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4960                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4961                     M_WAITOK);
4962         }
4963 }
4964
4965 /*
4966  * Backend "memory move is complete" callback for requests that never
4967  * make it down to say RAIDCore's configuration code.
4968  */
4969 int
4970 ctl_config_move_done(union ctl_io *io)
4971 {
4972         int retval;
4973
4974         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4975         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4976             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4977
4978         if ((io->io_hdr.port_status != 0) &&
4979             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4980              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4981                 /*
4982                  * For hardware error sense keys, the sense key
4983                  * specific value is defined to be a retry count,
4984                  * but we use it to pass back an internal FETD
4985                  * error code.  XXX KDM  Hopefully the FETD is only
4986                  * using 16 bits for an error code, since that's
4987                  * all the space we have in the sks field.
4988                  */
4989                 ctl_set_internal_failure(&io->scsiio,
4990                                          /*sks_valid*/ 1,
4991                                          /*retry_count*/
4992                                          io->io_hdr.port_status);
4993         }
4994
4995         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4996                 ctl_data_print(io);
4997         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4998             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4999              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5000             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5001                 /*
5002                  * XXX KDM just assuming a single pointer here, and not a
5003                  * S/G list.  If we start using S/G lists for config data,
5004                  * we'll need to know how to clean them up here as well.
5005                  */
5006                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5007                         free(io->scsiio.kern_data_ptr, M_CTL);
5008                 ctl_done(io);
5009                 retval = CTL_RETVAL_COMPLETE;
5010         } else {
5011                 /*
5012                  * XXX KDM now we need to continue data movement.  Some
5013                  * options:
5014                  * - call ctl_scsiio() again?  We don't do this for data
5015                  *   writes, because for those at least we know ahead of
5016                  *   time where the write will go and how long it is.  For
5017                  *   config writes, though, that information is largely
5018                  *   contained within the write itself, thus we need to
5019                  *   parse out the data again.
5020                  *
5021                  * - Call some other function once the data is in?
5022                  */
5023
5024                 /*
5025                  * XXX KDM call ctl_scsiio() again for now, and check flag
5026                  * bits to see whether we're allocated or not.
5027                  */
5028                 retval = ctl_scsiio(&io->scsiio);
5029         }
5030         return (retval);
5031 }
5032
5033 /*
5034  * This gets called by a backend driver when it is done with a
5035  * data_submit method.
5036  */
5037 void
5038 ctl_data_submit_done(union ctl_io *io)
5039 {
5040         /*
5041          * If the IO_CONT flag is set, we need to call the supplied
5042          * function to continue processing the I/O, instead of completing
5043          * the I/O just yet.
5044          *
5045          * If there is an error, though, we don't want to keep processing.
5046          * Instead, just send status back to the initiator.
5047          */
5048         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5049             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5050             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5051              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5052                 io->scsiio.io_cont(io);
5053                 return;
5054         }
5055         ctl_done(io);
5056 }
5057
5058 /*
5059  * This gets called by a backend driver when it is done with a
5060  * configuration write.
5061  */
5062 void
5063 ctl_config_write_done(union ctl_io *io)
5064 {
5065         uint8_t *buf;
5066
5067         /*
5068          * If the IO_CONT flag is set, we need to call the supplied
5069          * function to continue processing the I/O, instead of completing
5070          * the I/O just yet.
5071          *
5072          * If there is an error, though, we don't want to keep processing.
5073          * Instead, just send status back to the initiator.
5074          */
5075         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5076             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5077             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5078              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5079                 io->scsiio.io_cont(io);
5080                 return;
5081         }
5082         /*
5083          * Since a configuration write can be done for commands that actually
5084          * have data allocated, like write buffer, and commands that have
5085          * no data, like start/stop unit, we need to check here.
5086          */
5087         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5088                 buf = io->scsiio.kern_data_ptr;
5089         else
5090                 buf = NULL;
5091         ctl_done(io);
5092         if (buf)
5093                 free(buf, M_CTL);
5094 }
5095
5096 void
5097 ctl_config_read_done(union ctl_io *io)
5098 {
5099         uint8_t *buf;
5100
5101         /*
5102          * If there is some error -- we are done, skip data transfer.
5103          */
5104         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5105             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5106              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5107                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5108                         buf = io->scsiio.kern_data_ptr;
5109                 else
5110                         buf = NULL;
5111                 ctl_done(io);
5112                 if (buf)
5113                         free(buf, M_CTL);
5114                 return;
5115         }
5116
5117         /*
5118          * If the IO_CONT flag is set, we need to call the supplied
5119          * function to continue processing the I/O, instead of completing
5120          * the I/O just yet.
5121          */
5122         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5123                 io->scsiio.io_cont(io);
5124                 return;
5125         }
5126
5127         ctl_datamove(io);
5128 }
5129
5130 /*
5131  * SCSI release command.
5132  */
5133 int
5134 ctl_scsi_release(struct ctl_scsiio *ctsio)
5135 {
5136         struct ctl_lun *lun;
5137         uint32_t residx;
5138
5139         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5140
5141         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5142         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5143
5144         /*
5145          * XXX KDM right now, we only support LUN reservation.  We don't
5146          * support 3rd party reservations, or extent reservations, which
5147          * might actually need the parameter list.  If we've gotten this
5148          * far, we've got a LUN reservation.  Anything else got kicked out
5149          * above.  So, according to SPC, ignore the length.
5150          */
5151
5152         mtx_lock(&lun->lun_lock);
5153
5154         /*
5155          * According to SPC, it is not an error for an intiator to attempt
5156          * to release a reservation on a LUN that isn't reserved, or that
5157          * is reserved by another initiator.  The reservation can only be
5158          * released, though, by the initiator who made it or by one of
5159          * several reset type events.
5160          */
5161         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5162                         lun->flags &= ~CTL_LUN_RESERVED;
5163
5164         mtx_unlock(&lun->lun_lock);
5165
5166         ctl_set_success(ctsio);
5167         ctl_done((union ctl_io *)ctsio);
5168         return (CTL_RETVAL_COMPLETE);
5169 }
5170
5171 int
5172 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5173 {
5174         struct ctl_lun *lun;
5175         uint32_t residx;
5176
5177         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5178
5179         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5180         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5181
5182         /*
5183          * XXX KDM right now, we only support LUN reservation.  We don't
5184          * support 3rd party reservations, or extent reservations, which
5185          * might actually need the parameter list.  If we've gotten this
5186          * far, we've got a LUN reservation.  Anything else got kicked out
5187          * above.  So, according to SPC, ignore the length.
5188          */
5189
5190         mtx_lock(&lun->lun_lock);
5191         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5192                 ctl_set_reservation_conflict(ctsio);
5193                 goto bailout;
5194         }
5195
5196         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5197         if (lun->flags & CTL_LUN_PR_RESERVED) {
5198                 ctl_set_success(ctsio);
5199                 goto bailout;
5200         }
5201
5202         lun->flags |= CTL_LUN_RESERVED;
5203         lun->res_idx = residx;
5204         ctl_set_success(ctsio);
5205
5206 bailout:
5207         mtx_unlock(&lun->lun_lock);
5208         ctl_done((union ctl_io *)ctsio);
5209         return (CTL_RETVAL_COMPLETE);
5210 }
5211
5212 int
5213 ctl_start_stop(struct ctl_scsiio *ctsio)
5214 {
5215         struct scsi_start_stop_unit *cdb;
5216         struct ctl_lun *lun;
5217         int retval;
5218
5219         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5220
5221         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5222         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5223
5224         if ((cdb->how & SSS_PC_MASK) == 0) {
5225                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5226                     (cdb->how & SSS_START) == 0) {
5227                         uint32_t residx;
5228
5229                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5230                         if (ctl_get_prkey(lun, residx) == 0 ||
5231                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5232
5233                                 ctl_set_reservation_conflict(ctsio);
5234                                 ctl_done((union ctl_io *)ctsio);
5235                                 return (CTL_RETVAL_COMPLETE);
5236                         }
5237                 }
5238
5239                 if ((cdb->how & SSS_LOEJ) &&
5240                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5241                         ctl_set_invalid_field(ctsio,
5242                                               /*sks_valid*/ 1,
5243                                               /*command*/ 1,
5244                                               /*field*/ 4,
5245                                               /*bit_valid*/ 1,
5246                                               /*bit*/ 1);
5247                         ctl_done((union ctl_io *)ctsio);
5248                         return (CTL_RETVAL_COMPLETE);
5249                 }
5250
5251                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5252                     lun->prevent_count > 0) {
5253                         /* "Medium removal prevented" */
5254                         ctl_set_sense(ctsio, /*current_error*/ 1,
5255                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5256                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5257                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5258                         ctl_done((union ctl_io *)ctsio);
5259                         return (CTL_RETVAL_COMPLETE);
5260                 }
5261         }
5262
5263         retval = lun->backend->config_write((union ctl_io *)ctsio);
5264         return (retval);
5265 }
5266
5267 int
5268 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5269 {
5270         struct ctl_lun *lun;
5271         struct scsi_prevent *cdb;
5272         int retval;
5273         uint32_t initidx;
5274
5275         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5276
5277         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5278         cdb = (struct scsi_prevent *)ctsio->cdb;
5279
5280         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5281                 ctl_set_invalid_opcode(ctsio);
5282                 ctl_done((union ctl_io *)ctsio);
5283                 return (CTL_RETVAL_COMPLETE);
5284         }
5285
5286         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5287         mtx_lock(&lun->lun_lock);
5288         if ((cdb->how & PR_PREVENT) &&
5289             ctl_is_set(lun->prevent, initidx) == 0) {
5290                 ctl_set_mask(lun->prevent, initidx);
5291                 lun->prevent_count++;
5292         } else if ((cdb->how & PR_PREVENT) == 0 &&
5293             ctl_is_set(lun->prevent, initidx)) {
5294                 ctl_clear_mask(lun->prevent, initidx);
5295                 lun->prevent_count--;
5296         }
5297         mtx_unlock(&lun->lun_lock);
5298         retval = lun->backend->config_write((union ctl_io *)ctsio);
5299         return (retval);
5300 }
5301
5302 /*
5303  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5304  * we don't really do anything with the LBA and length fields if the user
5305  * passes them in.  Instead we'll just flush out the cache for the entire
5306  * LUN.
5307  */
5308 int
5309 ctl_sync_cache(struct ctl_scsiio *ctsio)
5310 {
5311         struct ctl_lun *lun;
5312         struct ctl_softc *softc;
5313         struct ctl_lba_len_flags *lbalen;
5314         uint64_t starting_lba;
5315         uint32_t block_count;
5316         int retval;
5317         uint8_t byte2;
5318
5319         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5320
5321         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5322         softc = lun->ctl_softc;
5323         retval = 0;
5324
5325         switch (ctsio->cdb[0]) {
5326         case SYNCHRONIZE_CACHE: {
5327                 struct scsi_sync_cache *cdb;
5328                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5329
5330                 starting_lba = scsi_4btoul(cdb->begin_lba);
5331                 block_count = scsi_2btoul(cdb->lb_count);
5332                 byte2 = cdb->byte2;
5333                 break;
5334         }
5335         case SYNCHRONIZE_CACHE_16: {
5336                 struct scsi_sync_cache_16 *cdb;
5337                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5338
5339                 starting_lba = scsi_8btou64(cdb->begin_lba);
5340                 block_count = scsi_4btoul(cdb->lb_count);
5341                 byte2 = cdb->byte2;
5342                 break;
5343         }
5344         default:
5345                 ctl_set_invalid_opcode(ctsio);
5346                 ctl_done((union ctl_io *)ctsio);
5347                 goto bailout;
5348                 break; /* NOTREACHED */
5349         }
5350
5351         /*
5352          * We check the LBA and length, but don't do anything with them.
5353          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5354          * get flushed.  This check will just help satisfy anyone who wants
5355          * to see an error for an out of range LBA.
5356          */
5357         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5358                 ctl_set_lba_out_of_range(ctsio);
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 ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5497             (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5498             (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5499                 ctl_set_invalid_field(ctsio,
5500                                       /*sks_valid*/ 1,
5501                                       /*command*/ 1,
5502                                       /*field*/ 1,
5503                                       /*bit_valid*/ 1,
5504                                       /*bit*/ 4);
5505                 ctl_done((union ctl_io *)ctsio);
5506                 return (CTL_RETVAL_COMPLETE);
5507         }
5508
5509         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5510             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5511                 ctl_set_invalid_field(ctsio,
5512                                       /*sks_valid*/ 1,
5513                                       /*command*/ 1,
5514                                       /*field*/ 6,
5515                                       /*bit_valid*/ 0,
5516                                       /*bit*/ 0);
5517                 ctl_done((union ctl_io *)ctsio);
5518                 return (CTL_RETVAL_COMPLETE);
5519         }
5520
5521         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5522                 descr[0] = 0;
5523                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5524                 ctsio->kern_data_ptr = descr;
5525                 len = min(len, sizeof(descr));
5526         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5527                 ctsio->kern_data_ptr = echo_descr;
5528                 len = min(len, sizeof(echo_descr));
5529         } else {
5530                 if (lun->write_buffer == NULL) {
5531                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5532                             M_CTL, M_WAITOK);
5533                 }
5534                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5535         }
5536         ctsio->kern_data_len = len;
5537         ctsio->kern_total_len = len;
5538         ctsio->kern_data_resid = 0;
5539         ctsio->kern_rel_offset = 0;
5540         ctsio->kern_sg_entries = 0;
5541         ctl_set_success(ctsio);
5542         ctsio->be_move_done = ctl_config_move_done;
5543         ctl_datamove((union ctl_io *)ctsio);
5544         return (CTL_RETVAL_COMPLETE);
5545 }
5546
5547 int
5548 ctl_write_buffer(struct ctl_scsiio *ctsio)
5549 {
5550         struct scsi_write_buffer *cdb;
5551         struct ctl_lun *lun;
5552         int buffer_offset, len;
5553
5554         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5555
5556         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5557         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5558
5559         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5560                 ctl_set_invalid_field(ctsio,
5561                                       /*sks_valid*/ 1,
5562                                       /*command*/ 1,
5563                                       /*field*/ 1,
5564                                       /*bit_valid*/ 1,
5565                                       /*bit*/ 4);
5566                 ctl_done((union ctl_io *)ctsio);
5567                 return (CTL_RETVAL_COMPLETE);
5568         }
5569
5570         len = scsi_3btoul(cdb->length);
5571         buffer_offset = scsi_3btoul(cdb->offset);
5572
5573         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5574                 ctl_set_invalid_field(ctsio,
5575                                       /*sks_valid*/ 1,
5576                                       /*command*/ 1,
5577                                       /*field*/ 6,
5578                                       /*bit_valid*/ 0,
5579                                       /*bit*/ 0);
5580                 ctl_done((union ctl_io *)ctsio);
5581                 return (CTL_RETVAL_COMPLETE);
5582         }
5583
5584         /*
5585          * If we've got a kernel request that hasn't been malloced yet,
5586          * malloc it and tell the caller the data buffer is here.
5587          */
5588         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5589                 if (lun->write_buffer == NULL) {
5590                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5591                             M_CTL, M_WAITOK);
5592                 }
5593                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5594                 ctsio->kern_data_len = len;
5595                 ctsio->kern_total_len = len;
5596                 ctsio->kern_data_resid = 0;
5597                 ctsio->kern_rel_offset = 0;
5598                 ctsio->kern_sg_entries = 0;
5599                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5600                 ctsio->be_move_done = ctl_config_move_done;
5601                 ctl_datamove((union ctl_io *)ctsio);
5602
5603                 return (CTL_RETVAL_COMPLETE);
5604         }
5605
5606         ctl_set_success(ctsio);
5607         ctl_done((union ctl_io *)ctsio);
5608         return (CTL_RETVAL_COMPLETE);
5609 }
5610
5611 int
5612 ctl_write_same(struct ctl_scsiio *ctsio)
5613 {
5614         struct ctl_lun *lun;
5615         struct ctl_lba_len_flags *lbalen;
5616         uint64_t lba;
5617         uint32_t num_blocks;
5618         int len, retval;
5619         uint8_t byte2;
5620
5621         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5622
5623         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5624
5625         switch (ctsio->cdb[0]) {
5626         case WRITE_SAME_10: {
5627                 struct scsi_write_same_10 *cdb;
5628
5629                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5630
5631                 lba = scsi_4btoul(cdb->addr);
5632                 num_blocks = scsi_2btoul(cdb->length);
5633                 byte2 = cdb->byte2;
5634                 break;
5635         }
5636         case WRITE_SAME_16: {
5637                 struct scsi_write_same_16 *cdb;
5638
5639                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5640
5641                 lba = scsi_8btou64(cdb->addr);
5642                 num_blocks = scsi_4btoul(cdb->length);
5643                 byte2 = cdb->byte2;
5644                 break;
5645         }
5646         default:
5647                 /*
5648                  * We got a command we don't support.  This shouldn't
5649                  * happen, commands should be filtered out above us.
5650                  */
5651                 ctl_set_invalid_opcode(ctsio);
5652                 ctl_done((union ctl_io *)ctsio);
5653
5654                 return (CTL_RETVAL_COMPLETE);
5655                 break; /* NOTREACHED */
5656         }
5657
5658         /* ANCHOR flag can be used only together with UNMAP */
5659         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5660                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5661                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5662                 ctl_done((union ctl_io *)ctsio);
5663                 return (CTL_RETVAL_COMPLETE);
5664         }
5665
5666         /*
5667          * The first check is to make sure we're in bounds, the second
5668          * check is to catch wrap-around problems.  If the lba + num blocks
5669          * is less than the lba, then we've wrapped around and the block
5670          * range is invalid anyway.
5671          */
5672         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5673          || ((lba + num_blocks) < lba)) {
5674                 ctl_set_lba_out_of_range(ctsio);
5675                 ctl_done((union ctl_io *)ctsio);
5676                 return (CTL_RETVAL_COMPLETE);
5677         }
5678
5679         /* Zero number of blocks means "to the last logical block" */
5680         if (num_blocks == 0) {
5681                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5682                         ctl_set_invalid_field(ctsio,
5683                                               /*sks_valid*/ 0,
5684                                               /*command*/ 1,
5685                                               /*field*/ 0,
5686                                               /*bit_valid*/ 0,
5687                                               /*bit*/ 0);
5688                         ctl_done((union ctl_io *)ctsio);
5689                         return (CTL_RETVAL_COMPLETE);
5690                 }
5691                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5692         }
5693
5694         len = lun->be_lun->blocksize;
5695
5696         /*
5697          * If we've got a kernel request that hasn't been malloced yet,
5698          * malloc it and tell the caller the data buffer is here.
5699          */
5700         if ((byte2 & SWS_NDOB) == 0 &&
5701             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5702                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5703                 ctsio->kern_data_len = len;
5704                 ctsio->kern_total_len = len;
5705                 ctsio->kern_data_resid = 0;
5706                 ctsio->kern_rel_offset = 0;
5707                 ctsio->kern_sg_entries = 0;
5708                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5709                 ctsio->be_move_done = ctl_config_move_done;
5710                 ctl_datamove((union ctl_io *)ctsio);
5711
5712                 return (CTL_RETVAL_COMPLETE);
5713         }
5714
5715         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5716         lbalen->lba = lba;
5717         lbalen->len = num_blocks;
5718         lbalen->flags = byte2;
5719         retval = lun->backend->config_write((union ctl_io *)ctsio);
5720
5721         return (retval);
5722 }
5723
5724 int
5725 ctl_unmap(struct ctl_scsiio *ctsio)
5726 {
5727         struct ctl_lun *lun;
5728         struct scsi_unmap *cdb;
5729         struct ctl_ptr_len_flags *ptrlen;
5730         struct scsi_unmap_header *hdr;
5731         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5732         uint64_t lba;
5733         uint32_t num_blocks;
5734         int len, retval;
5735         uint8_t byte2;
5736
5737         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5738
5739         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5740         cdb = (struct scsi_unmap *)ctsio->cdb;
5741
5742         len = scsi_2btoul(cdb->length);
5743         byte2 = cdb->byte2;
5744
5745         /*
5746          * If we've got a kernel request that hasn't been malloced yet,
5747          * malloc it and tell the caller the data buffer is here.
5748          */
5749         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5750                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5751                 ctsio->kern_data_len = len;
5752                 ctsio->kern_total_len = len;
5753                 ctsio->kern_data_resid = 0;
5754                 ctsio->kern_rel_offset = 0;
5755                 ctsio->kern_sg_entries = 0;
5756                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5757                 ctsio->be_move_done = ctl_config_move_done;
5758                 ctl_datamove((union ctl_io *)ctsio);
5759
5760                 return (CTL_RETVAL_COMPLETE);
5761         }
5762
5763         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5764         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5765         if (len < sizeof (*hdr) ||
5766             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5767             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5768             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5769                 ctl_set_invalid_field(ctsio,
5770                                       /*sks_valid*/ 0,
5771                                       /*command*/ 0,
5772                                       /*field*/ 0,
5773                                       /*bit_valid*/ 0,
5774                                       /*bit*/ 0);
5775                 goto done;
5776         }
5777         len = scsi_2btoul(hdr->desc_length);
5778         buf = (struct scsi_unmap_desc *)(hdr + 1);
5779         end = buf + len / sizeof(*buf);
5780
5781         endnz = buf;
5782         for (range = buf; range < end; range++) {
5783                 lba = scsi_8btou64(range->lba);
5784                 num_blocks = scsi_4btoul(range->length);
5785                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5786                  || ((lba + num_blocks) < lba)) {
5787                         ctl_set_lba_out_of_range(ctsio);
5788                         ctl_done((union ctl_io *)ctsio);
5789                         return (CTL_RETVAL_COMPLETE);
5790                 }
5791                 if (num_blocks != 0)
5792                         endnz = range + 1;
5793         }
5794
5795         /*
5796          * Block backend can not handle zero last range.
5797          * Filter it out and return if there is nothing left.
5798          */
5799         len = (uint8_t *)endnz - (uint8_t *)buf;
5800         if (len == 0) {
5801                 ctl_set_success(ctsio);
5802                 goto done;
5803         }
5804
5805         mtx_lock(&lun->lun_lock);
5806         ptrlen = (struct ctl_ptr_len_flags *)
5807             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5808         ptrlen->ptr = (void *)buf;
5809         ptrlen->len = len;
5810         ptrlen->flags = byte2;
5811         ctl_check_blocked(lun);
5812         mtx_unlock(&lun->lun_lock);
5813
5814         retval = lun->backend->config_write((union ctl_io *)ctsio);
5815         return (retval);
5816
5817 done:
5818         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5819                 free(ctsio->kern_data_ptr, M_CTL);
5820                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5821         }
5822         ctl_done((union ctl_io *)ctsio);
5823         return (CTL_RETVAL_COMPLETE);
5824 }
5825
5826 /*
5827  * Note that this function currently doesn't actually do anything inside
5828  * CTL to enforce things if the DQue bit is turned on.
5829  *
5830  * Also note that this function can't be used in the default case, because
5831  * the DQue bit isn't set in the changeable mask for the control mode page
5832  * anyway.  This is just here as an example for how to implement a page
5833  * handler, and a placeholder in case we want to allow the user to turn
5834  * tagged queueing on and off.
5835  *
5836  * The D_SENSE bit handling is functional, however, and will turn
5837  * descriptor sense on and off for a given LUN.
5838  */
5839 int
5840 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5841                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5842 {
5843         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5844         struct ctl_lun *lun;
5845         int set_ua;
5846         uint32_t initidx;
5847
5848         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5849         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5850         set_ua = 0;
5851
5852         user_cp = (struct scsi_control_page *)page_ptr;
5853         current_cp = (struct scsi_control_page *)
5854                 (page_index->page_data + (page_index->page_len *
5855                 CTL_PAGE_CURRENT));
5856         saved_cp = (struct scsi_control_page *)
5857                 (page_index->page_data + (page_index->page_len *
5858                 CTL_PAGE_SAVED));
5859
5860         mtx_lock(&lun->lun_lock);
5861         if (((current_cp->rlec & SCP_DSENSE) == 0)
5862          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5863                 /*
5864                  * Descriptor sense is currently turned off and the user
5865                  * wants to turn it on.
5866                  */
5867                 current_cp->rlec |= SCP_DSENSE;
5868                 saved_cp->rlec |= SCP_DSENSE;
5869                 lun->flags |= CTL_LUN_SENSE_DESC;
5870                 set_ua = 1;
5871         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5872                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5873                 /*
5874                  * Descriptor sense is currently turned on, and the user
5875                  * wants to turn it off.
5876                  */
5877                 current_cp->rlec &= ~SCP_DSENSE;
5878                 saved_cp->rlec &= ~SCP_DSENSE;
5879                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5880                 set_ua = 1;
5881         }
5882         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5883             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5884                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5885                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5886                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5887                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5888                 set_ua = 1;
5889         }
5890         if ((current_cp->eca_and_aen & SCP_SWP) !=
5891             (user_cp->eca_and_aen & SCP_SWP)) {
5892                 current_cp->eca_and_aen &= ~SCP_SWP;
5893                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5894                 saved_cp->eca_and_aen &= ~SCP_SWP;
5895                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5896                 set_ua = 1;
5897         }
5898         if (set_ua != 0)
5899                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5900         mtx_unlock(&lun->lun_lock);
5901         if (set_ua) {
5902                 ctl_isc_announce_mode(lun,
5903                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5904                     page_index->page_code, page_index->subpage);
5905         }
5906         return (0);
5907 }
5908
5909 int
5910 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5911                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5912 {
5913         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5914         struct ctl_lun *lun;
5915         int set_ua;
5916         uint32_t initidx;
5917
5918         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5919         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5920         set_ua = 0;
5921
5922         user_cp = (struct scsi_caching_page *)page_ptr;
5923         current_cp = (struct scsi_caching_page *)
5924                 (page_index->page_data + (page_index->page_len *
5925                 CTL_PAGE_CURRENT));
5926         saved_cp = (struct scsi_caching_page *)
5927                 (page_index->page_data + (page_index->page_len *
5928                 CTL_PAGE_SAVED));
5929
5930         mtx_lock(&lun->lun_lock);
5931         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5932             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5933                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5934                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5935                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5936                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5937                 set_ua = 1;
5938         }
5939         if (set_ua != 0)
5940                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5941         mtx_unlock(&lun->lun_lock);
5942         if (set_ua) {
5943                 ctl_isc_announce_mode(lun,
5944                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5945                     page_index->page_code, page_index->subpage);
5946         }
5947         return (0);
5948 }
5949
5950 int
5951 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5952                                 struct ctl_page_index *page_index,
5953                                 uint8_t *page_ptr)
5954 {
5955         uint8_t *c;
5956         int i;
5957
5958         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5959         ctl_time_io_secs =
5960                 (c[0] << 8) |
5961                 (c[1] << 0) |
5962                 0;
5963         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5964         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5965         printf("page data:");
5966         for (i=0; i<8; i++)
5967                 printf(" %.2x",page_ptr[i]);
5968         printf("\n");
5969         return (0);
5970 }
5971
5972 int
5973 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5974                                struct ctl_page_index *page_index,
5975                                int pc)
5976 {
5977         struct copan_debugconf_subpage *page;
5978
5979         page = (struct copan_debugconf_subpage *)page_index->page_data +
5980                 (page_index->page_len * pc);
5981
5982         switch (pc) {
5983         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5984         case SMS_PAGE_CTRL_DEFAULT >> 6:
5985         case SMS_PAGE_CTRL_SAVED >> 6:
5986                 /*
5987                  * We don't update the changable or default bits for this page.
5988                  */
5989                 break;
5990         case SMS_PAGE_CTRL_CURRENT >> 6:
5991                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5992                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5993                 break;
5994         default:
5995                 break;
5996         }
5997         return (0);
5998 }
5999
6000
6001 static int
6002 ctl_do_mode_select(union ctl_io *io)
6003 {
6004         struct scsi_mode_page_header *page_header;
6005         struct ctl_page_index *page_index;
6006         struct ctl_scsiio *ctsio;
6007         int page_len, page_len_offset, page_len_size;
6008         union ctl_modepage_info *modepage_info;
6009         struct ctl_lun *lun;
6010         int *len_left, *len_used;
6011         int retval, i;
6012
6013         ctsio = &io->scsiio;
6014         page_index = NULL;
6015         page_len = 0;
6016         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6017
6018         modepage_info = (union ctl_modepage_info *)
6019                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6020         len_left = &modepage_info->header.len_left;
6021         len_used = &modepage_info->header.len_used;
6022
6023 do_next_page:
6024
6025         page_header = (struct scsi_mode_page_header *)
6026                 (ctsio->kern_data_ptr + *len_used);
6027
6028         if (*len_left == 0) {
6029                 free(ctsio->kern_data_ptr, M_CTL);
6030                 ctl_set_success(ctsio);
6031                 ctl_done((union ctl_io *)ctsio);
6032                 return (CTL_RETVAL_COMPLETE);
6033         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6034
6035                 free(ctsio->kern_data_ptr, M_CTL);
6036                 ctl_set_param_len_error(ctsio);
6037                 ctl_done((union ctl_io *)ctsio);
6038                 return (CTL_RETVAL_COMPLETE);
6039
6040         } else if ((page_header->page_code & SMPH_SPF)
6041                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6042
6043                 free(ctsio->kern_data_ptr, M_CTL);
6044                 ctl_set_param_len_error(ctsio);
6045                 ctl_done((union ctl_io *)ctsio);
6046                 return (CTL_RETVAL_COMPLETE);
6047         }
6048
6049
6050         /*
6051          * XXX KDM should we do something with the block descriptor?
6052          */
6053         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6054                 page_index = &lun->mode_pages.index[i];
6055                 if (lun->be_lun->lun_type == T_DIRECT &&
6056                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6057                         continue;
6058                 if (lun->be_lun->lun_type == T_PROCESSOR &&
6059                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6060                         continue;
6061                 if (lun->be_lun->lun_type == T_CDROM &&
6062                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6063                         continue;
6064
6065                 if ((page_index->page_code & SMPH_PC_MASK) !=
6066                     (page_header->page_code & SMPH_PC_MASK))
6067                         continue;
6068
6069                 /*
6070                  * If neither page has a subpage code, then we've got a
6071                  * match.
6072                  */
6073                 if (((page_index->page_code & SMPH_SPF) == 0)
6074                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6075                         page_len = page_header->page_length;
6076                         break;
6077                 }
6078
6079                 /*
6080                  * If both pages have subpages, then the subpage numbers
6081                  * have to match.
6082                  */
6083                 if ((page_index->page_code & SMPH_SPF)
6084                   && (page_header->page_code & SMPH_SPF)) {
6085                         struct scsi_mode_page_header_sp *sph;
6086
6087                         sph = (struct scsi_mode_page_header_sp *)page_header;
6088                         if (page_index->subpage == sph->subpage) {
6089                                 page_len = scsi_2btoul(sph->page_length);
6090                                 break;
6091                         }
6092                 }
6093         }
6094
6095         /*
6096          * If we couldn't find the page, or if we don't have a mode select
6097          * handler for it, send back an error to the user.
6098          */
6099         if ((i >= CTL_NUM_MODE_PAGES)
6100          || (page_index->select_handler == NULL)) {
6101                 ctl_set_invalid_field(ctsio,
6102                                       /*sks_valid*/ 1,
6103                                       /*command*/ 0,
6104                                       /*field*/ *len_used,
6105                                       /*bit_valid*/ 0,
6106                                       /*bit*/ 0);
6107                 free(ctsio->kern_data_ptr, M_CTL);
6108                 ctl_done((union ctl_io *)ctsio);
6109                 return (CTL_RETVAL_COMPLETE);
6110         }
6111
6112         if (page_index->page_code & SMPH_SPF) {
6113                 page_len_offset = 2;
6114                 page_len_size = 2;
6115         } else {
6116                 page_len_size = 1;
6117                 page_len_offset = 1;
6118         }
6119
6120         /*
6121          * If the length the initiator gives us isn't the one we specify in
6122          * the mode page header, or if they didn't specify enough data in
6123          * the CDB to avoid truncating this page, kick out the request.
6124          */
6125         if ((page_len != (page_index->page_len - page_len_offset -
6126                           page_len_size))
6127          || (*len_left < page_index->page_len)) {
6128
6129
6130                 ctl_set_invalid_field(ctsio,
6131                                       /*sks_valid*/ 1,
6132                                       /*command*/ 0,
6133                                       /*field*/ *len_used + page_len_offset,
6134                                       /*bit_valid*/ 0,
6135                                       /*bit*/ 0);
6136                 free(ctsio->kern_data_ptr, M_CTL);
6137                 ctl_done((union ctl_io *)ctsio);
6138                 return (CTL_RETVAL_COMPLETE);
6139         }
6140
6141         /*
6142          * Run through the mode page, checking to make sure that the bits
6143          * the user changed are actually legal for him to change.
6144          */
6145         for (i = 0; i < page_index->page_len; i++) {
6146                 uint8_t *user_byte, *change_mask, *current_byte;
6147                 int bad_bit;
6148                 int j;
6149
6150                 user_byte = (uint8_t *)page_header + i;
6151                 change_mask = page_index->page_data +
6152                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6153                 current_byte = page_index->page_data +
6154                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6155
6156                 /*
6157                  * Check to see whether the user set any bits in this byte
6158                  * that he is not allowed to set.
6159                  */
6160                 if ((*user_byte & ~(*change_mask)) ==
6161                     (*current_byte & ~(*change_mask)))
6162                         continue;
6163
6164                 /*
6165                  * Go through bit by bit to determine which one is illegal.
6166                  */
6167                 bad_bit = 0;
6168                 for (j = 7; j >= 0; j--) {
6169                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6170                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6171                                 bad_bit = i;
6172                                 break;
6173                         }
6174                 }
6175                 ctl_set_invalid_field(ctsio,
6176                                       /*sks_valid*/ 1,
6177                                       /*command*/ 0,
6178                                       /*field*/ *len_used + i,
6179                                       /*bit_valid*/ 1,
6180                                       /*bit*/ bad_bit);
6181                 free(ctsio->kern_data_ptr, M_CTL);
6182                 ctl_done((union ctl_io *)ctsio);
6183                 return (CTL_RETVAL_COMPLETE);
6184         }
6185
6186         /*
6187          * Decrement these before we call the page handler, since we may
6188          * end up getting called back one way or another before the handler
6189          * returns to this context.
6190          */
6191         *len_left -= page_index->page_len;
6192         *len_used += page_index->page_len;
6193
6194         retval = page_index->select_handler(ctsio, page_index,
6195                                             (uint8_t *)page_header);
6196
6197         /*
6198          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6199          * wait until this queued command completes to finish processing
6200          * the mode page.  If it returns anything other than
6201          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6202          * already set the sense information, freed the data pointer, and
6203          * completed the io for us.
6204          */
6205         if (retval != CTL_RETVAL_COMPLETE)
6206                 goto bailout_no_done;
6207
6208         /*
6209          * If the initiator sent us more than one page, parse the next one.
6210          */
6211         if (*len_left > 0)
6212                 goto do_next_page;
6213
6214         ctl_set_success(ctsio);
6215         free(ctsio->kern_data_ptr, M_CTL);
6216         ctl_done((union ctl_io *)ctsio);
6217
6218 bailout_no_done:
6219
6220         return (CTL_RETVAL_COMPLETE);
6221
6222 }
6223
6224 int
6225 ctl_mode_select(struct ctl_scsiio *ctsio)
6226 {
6227         int param_len, pf, sp;
6228         int header_size, bd_len;
6229         union ctl_modepage_info *modepage_info;
6230
6231         switch (ctsio->cdb[0]) {
6232         case MODE_SELECT_6: {
6233                 struct scsi_mode_select_6 *cdb;
6234
6235                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6236
6237                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6238                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6239                 param_len = cdb->length;
6240                 header_size = sizeof(struct scsi_mode_header_6);
6241                 break;
6242         }
6243         case MODE_SELECT_10: {
6244                 struct scsi_mode_select_10 *cdb;
6245
6246                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6247
6248                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6249                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6250                 param_len = scsi_2btoul(cdb->length);
6251                 header_size = sizeof(struct scsi_mode_header_10);
6252                 break;
6253         }
6254         default:
6255                 ctl_set_invalid_opcode(ctsio);
6256                 ctl_done((union ctl_io *)ctsio);
6257                 return (CTL_RETVAL_COMPLETE);
6258         }
6259
6260         /*
6261          * From SPC-3:
6262          * "A parameter list length of zero indicates that the Data-Out Buffer
6263          * shall be empty. This condition shall not be considered as an error."
6264          */
6265         if (param_len == 0) {
6266                 ctl_set_success(ctsio);
6267                 ctl_done((union ctl_io *)ctsio);
6268                 return (CTL_RETVAL_COMPLETE);
6269         }
6270
6271         /*
6272          * Since we'll hit this the first time through, prior to
6273          * allocation, we don't need to free a data buffer here.
6274          */
6275         if (param_len < header_size) {
6276                 ctl_set_param_len_error(ctsio);
6277                 ctl_done((union ctl_io *)ctsio);
6278                 return (CTL_RETVAL_COMPLETE);
6279         }
6280
6281         /*
6282          * Allocate the data buffer and grab the user's data.  In theory,
6283          * we shouldn't have to sanity check the parameter list length here
6284          * because the maximum size is 64K.  We should be able to malloc
6285          * that much without too many problems.
6286          */
6287         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6288                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6289                 ctsio->kern_data_len = param_len;
6290                 ctsio->kern_total_len = param_len;
6291                 ctsio->kern_data_resid = 0;
6292                 ctsio->kern_rel_offset = 0;
6293                 ctsio->kern_sg_entries = 0;
6294                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6295                 ctsio->be_move_done = ctl_config_move_done;
6296                 ctl_datamove((union ctl_io *)ctsio);
6297
6298                 return (CTL_RETVAL_COMPLETE);
6299         }
6300
6301         switch (ctsio->cdb[0]) {
6302         case MODE_SELECT_6: {
6303                 struct scsi_mode_header_6 *mh6;
6304
6305                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6306                 bd_len = mh6->blk_desc_len;
6307                 break;
6308         }
6309         case MODE_SELECT_10: {
6310                 struct scsi_mode_header_10 *mh10;
6311
6312                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6313                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6314                 break;
6315         }
6316         default:
6317                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6318         }
6319
6320         if (param_len < (header_size + bd_len)) {
6321                 free(ctsio->kern_data_ptr, M_CTL);
6322                 ctl_set_param_len_error(ctsio);
6323                 ctl_done((union ctl_io *)ctsio);
6324                 return (CTL_RETVAL_COMPLETE);
6325         }
6326
6327         /*
6328          * Set the IO_CONT flag, so that if this I/O gets passed to
6329          * ctl_config_write_done(), it'll get passed back to
6330          * ctl_do_mode_select() for further processing, or completion if
6331          * we're all done.
6332          */
6333         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6334         ctsio->io_cont = ctl_do_mode_select;
6335
6336         modepage_info = (union ctl_modepage_info *)
6337                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6338         memset(modepage_info, 0, sizeof(*modepage_info));
6339         modepage_info->header.len_left = param_len - header_size - bd_len;
6340         modepage_info->header.len_used = header_size + bd_len;
6341
6342         return (ctl_do_mode_select((union ctl_io *)ctsio));
6343 }
6344
6345 int
6346 ctl_mode_sense(struct ctl_scsiio *ctsio)
6347 {
6348         struct ctl_lun *lun;
6349         int pc, page_code, dbd, llba, subpage;
6350         int alloc_len, page_len, header_len, total_len;
6351         struct scsi_mode_block_descr *block_desc;
6352         struct ctl_page_index *page_index;
6353
6354         dbd = 0;
6355         llba = 0;
6356         block_desc = NULL;
6357
6358         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6359
6360         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6361         switch (ctsio->cdb[0]) {
6362         case MODE_SENSE_6: {
6363                 struct scsi_mode_sense_6 *cdb;
6364
6365                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6366
6367                 header_len = sizeof(struct scsi_mode_hdr_6);
6368                 if (cdb->byte2 & SMS_DBD)
6369                         dbd = 1;
6370                 else
6371                         header_len += sizeof(struct scsi_mode_block_descr);
6372
6373                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6374                 page_code = cdb->page & SMS_PAGE_CODE;
6375                 subpage = cdb->subpage;
6376                 alloc_len = cdb->length;
6377                 break;
6378         }
6379         case MODE_SENSE_10: {
6380                 struct scsi_mode_sense_10 *cdb;
6381
6382                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6383
6384                 header_len = sizeof(struct scsi_mode_hdr_10);
6385
6386                 if (cdb->byte2 & SMS_DBD)
6387                         dbd = 1;
6388                 else
6389                         header_len += sizeof(struct scsi_mode_block_descr);
6390                 if (cdb->byte2 & SMS10_LLBAA)
6391                         llba = 1;
6392                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6393                 page_code = cdb->page & SMS_PAGE_CODE;
6394                 subpage = cdb->subpage;
6395                 alloc_len = scsi_2btoul(cdb->length);
6396                 break;
6397         }
6398         default:
6399                 ctl_set_invalid_opcode(ctsio);
6400                 ctl_done((union ctl_io *)ctsio);
6401                 return (CTL_RETVAL_COMPLETE);
6402                 break; /* NOTREACHED */
6403         }
6404
6405         /*
6406          * We have to make a first pass through to calculate the size of
6407          * the pages that match the user's query.  Then we allocate enough
6408          * memory to hold it, and actually copy the data into the buffer.
6409          */
6410         switch (page_code) {
6411         case SMS_ALL_PAGES_PAGE: {
6412                 u_int i;
6413
6414                 page_len = 0;
6415
6416                 /*
6417                  * At the moment, values other than 0 and 0xff here are
6418                  * reserved according to SPC-3.
6419                  */
6420                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6421                  && (subpage != SMS_SUBPAGE_ALL)) {
6422                         ctl_set_invalid_field(ctsio,
6423                                               /*sks_valid*/ 1,
6424                                               /*command*/ 1,
6425                                               /*field*/ 3,
6426                                               /*bit_valid*/ 0,
6427                                               /*bit*/ 0);
6428                         ctl_done((union ctl_io *)ctsio);
6429                         return (CTL_RETVAL_COMPLETE);
6430                 }
6431
6432                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6433                         page_index = &lun->mode_pages.index[i];
6434
6435                         /* Make sure the page is supported for this dev type */
6436                         if (lun->be_lun->lun_type == T_DIRECT &&
6437                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6438                                 continue;
6439                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6440                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6441                                 continue;
6442                         if (lun->be_lun->lun_type == T_CDROM &&
6443                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6444                                 continue;
6445
6446                         /*
6447                          * We don't use this subpage if the user didn't
6448                          * request all subpages.
6449                          */
6450                         if ((page_index->subpage != 0)
6451                          && (subpage == SMS_SUBPAGE_PAGE_0))
6452                                 continue;
6453
6454 #if 0
6455                         printf("found page %#x len %d\n",
6456                                page_index->page_code & SMPH_PC_MASK,
6457                                page_index->page_len);
6458 #endif
6459                         page_len += page_index->page_len;
6460                 }
6461                 break;
6462         }
6463         default: {
6464                 u_int i;
6465
6466                 page_len = 0;
6467
6468                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6469                         page_index = &lun->mode_pages.index[i];
6470
6471                         /* Make sure the page is supported for this dev type */
6472                         if (lun->be_lun->lun_type == T_DIRECT &&
6473                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6474                                 continue;
6475                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6476                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6477                                 continue;
6478                         if (lun->be_lun->lun_type == T_CDROM &&
6479                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6480                                 continue;
6481
6482                         /* Look for the right page code */
6483                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6484                                 continue;
6485
6486                         /* Look for the right subpage or the subpage wildcard*/
6487                         if ((page_index->subpage != subpage)
6488                          && (subpage != SMS_SUBPAGE_ALL))
6489                                 continue;
6490
6491 #if 0
6492                         printf("found page %#x len %d\n",
6493                                page_index->page_code & SMPH_PC_MASK,
6494                                page_index->page_len);
6495 #endif
6496
6497                         page_len += page_index->page_len;
6498                 }
6499
6500                 if (page_len == 0) {
6501                         ctl_set_invalid_field(ctsio,
6502                                               /*sks_valid*/ 1,
6503                                               /*command*/ 1,
6504                                               /*field*/ 2,
6505                                               /*bit_valid*/ 1,
6506                                               /*bit*/ 5);
6507                         ctl_done((union ctl_io *)ctsio);
6508                         return (CTL_RETVAL_COMPLETE);
6509                 }
6510                 break;
6511         }
6512         }
6513
6514         total_len = header_len + page_len;
6515 #if 0
6516         printf("header_len = %d, page_len = %d, total_len = %d\n",
6517                header_len, page_len, total_len);
6518 #endif
6519
6520         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6521         ctsio->kern_sg_entries = 0;
6522         ctsio->kern_data_resid = 0;
6523         ctsio->kern_rel_offset = 0;
6524         if (total_len < alloc_len) {
6525                 ctsio->residual = alloc_len - total_len;
6526                 ctsio->kern_data_len = total_len;
6527                 ctsio->kern_total_len = total_len;
6528         } else {
6529                 ctsio->residual = 0;
6530                 ctsio->kern_data_len = alloc_len;
6531                 ctsio->kern_total_len = alloc_len;
6532         }
6533
6534         switch (ctsio->cdb[0]) {
6535         case MODE_SENSE_6: {
6536                 struct scsi_mode_hdr_6 *header;
6537
6538                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6539
6540                 header->datalen = MIN(total_len - 1, 254);
6541                 if (lun->be_lun->lun_type == T_DIRECT) {
6542                         header->dev_specific = 0x10; /* DPOFUA */
6543                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6544                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6545                             .eca_and_aen & SCP_SWP) != 0)
6546                                     header->dev_specific |= 0x80; /* WP */
6547                 }
6548                 if (dbd)
6549                         header->block_descr_len = 0;
6550                 else
6551                         header->block_descr_len =
6552                                 sizeof(struct scsi_mode_block_descr);
6553                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6554                 break;
6555         }
6556         case MODE_SENSE_10: {
6557                 struct scsi_mode_hdr_10 *header;
6558                 int datalen;
6559
6560                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6561
6562                 datalen = MIN(total_len - 2, 65533);
6563                 scsi_ulto2b(datalen, header->datalen);
6564                 if (lun->be_lun->lun_type == T_DIRECT) {
6565                         header->dev_specific = 0x10; /* DPOFUA */
6566                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6567                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6568                             .eca_and_aen & SCP_SWP) != 0)
6569                                     header->dev_specific |= 0x80; /* WP */
6570                 }
6571                 if (dbd)
6572                         scsi_ulto2b(0, header->block_descr_len);
6573                 else
6574                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6575                                     header->block_descr_len);
6576                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6577                 break;
6578         }
6579         default:
6580                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6581         }
6582
6583         /*
6584          * If we've got a disk, use its blocksize in the block
6585          * descriptor.  Otherwise, just set it to 0.
6586          */
6587         if (dbd == 0) {
6588                 if (lun->be_lun->lun_type == T_DIRECT)
6589                         scsi_ulto3b(lun->be_lun->blocksize,
6590                                     block_desc->block_len);
6591                 else
6592                         scsi_ulto3b(0, block_desc->block_len);
6593         }
6594
6595         switch (page_code) {
6596         case SMS_ALL_PAGES_PAGE: {
6597                 int i, data_used;
6598
6599                 data_used = header_len;
6600                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6601                         struct ctl_page_index *page_index;
6602
6603                         page_index = &lun->mode_pages.index[i];
6604                         if (lun->be_lun->lun_type == T_DIRECT &&
6605                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6606                                 continue;
6607                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6608                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6609                                 continue;
6610                         if (lun->be_lun->lun_type == T_CDROM &&
6611                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6612                                 continue;
6613
6614                         /*
6615                          * We don't use this subpage if the user didn't
6616                          * request all subpages.  We already checked (above)
6617                          * to make sure the user only specified a subpage
6618                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6619                          */
6620                         if ((page_index->subpage != 0)
6621                          && (subpage == SMS_SUBPAGE_PAGE_0))
6622                                 continue;
6623
6624                         /*
6625                          * Call the handler, if it exists, to update the
6626                          * page to the latest values.
6627                          */
6628                         if (page_index->sense_handler != NULL)
6629                                 page_index->sense_handler(ctsio, page_index,pc);
6630
6631                         memcpy(ctsio->kern_data_ptr + data_used,
6632                                page_index->page_data +
6633                                (page_index->page_len * pc),
6634                                page_index->page_len);
6635                         data_used += page_index->page_len;
6636                 }
6637                 break;
6638         }
6639         default: {
6640                 int i, data_used;
6641
6642                 data_used = header_len;
6643
6644                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6645                         struct ctl_page_index *page_index;
6646
6647                         page_index = &lun->mode_pages.index[i];
6648
6649                         /* Look for the right page code */
6650                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6651                                 continue;
6652
6653                         /* Look for the right subpage or the subpage wildcard*/
6654                         if ((page_index->subpage != subpage)
6655                          && (subpage != SMS_SUBPAGE_ALL))
6656                                 continue;
6657
6658                         /* Make sure the page is supported for this dev type */
6659                         if (lun->be_lun->lun_type == T_DIRECT &&
6660                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6661                                 continue;
6662                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6663                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6664                                 continue;
6665                         if (lun->be_lun->lun_type == T_CDROM &&
6666                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6667                                 continue;
6668
6669                         /*
6670                          * Call the handler, if it exists, to update the
6671                          * page to the latest values.
6672                          */
6673                         if (page_index->sense_handler != NULL)
6674                                 page_index->sense_handler(ctsio, page_index,pc);
6675
6676                         memcpy(ctsio->kern_data_ptr + data_used,
6677                                page_index->page_data +
6678                                (page_index->page_len * pc),
6679                                page_index->page_len);
6680                         data_used += page_index->page_len;
6681                 }
6682                 break;
6683         }
6684         }
6685
6686         ctl_set_success(ctsio);
6687         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6688         ctsio->be_move_done = ctl_config_move_done;
6689         ctl_datamove((union ctl_io *)ctsio);
6690         return (CTL_RETVAL_COMPLETE);
6691 }
6692
6693 int
6694 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6695                                struct ctl_page_index *page_index,
6696                                int pc)
6697 {
6698         struct ctl_lun *lun;
6699         struct scsi_log_param_header *phdr;
6700         uint8_t *data;
6701         uint64_t val;
6702
6703         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6704         data = page_index->page_data;
6705
6706         if (lun->backend->lun_attr != NULL &&
6707             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6708              != UINT64_MAX) {
6709                 phdr = (struct scsi_log_param_header *)data;
6710                 scsi_ulto2b(0x0001, phdr->param_code);
6711                 phdr->param_control = SLP_LBIN | SLP_LP;
6712                 phdr->param_len = 8;
6713                 data = (uint8_t *)(phdr + 1);
6714                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6715                 data[4] = 0x02; /* per-pool */
6716                 data += phdr->param_len;
6717         }
6718
6719         if (lun->backend->lun_attr != NULL &&
6720             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6721              != UINT64_MAX) {
6722                 phdr = (struct scsi_log_param_header *)data;
6723                 scsi_ulto2b(0x0002, phdr->param_code);
6724                 phdr->param_control = SLP_LBIN | SLP_LP;
6725                 phdr->param_len = 8;
6726                 data = (uint8_t *)(phdr + 1);
6727                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6728                 data[4] = 0x01; /* per-LUN */
6729                 data += phdr->param_len;
6730         }
6731
6732         if (lun->backend->lun_attr != NULL &&
6733             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6734              != UINT64_MAX) {
6735                 phdr = (struct scsi_log_param_header *)data;
6736                 scsi_ulto2b(0x00f1, phdr->param_code);
6737                 phdr->param_control = SLP_LBIN | SLP_LP;
6738                 phdr->param_len = 8;
6739                 data = (uint8_t *)(phdr + 1);
6740                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6741                 data[4] = 0x02; /* per-pool */
6742                 data += phdr->param_len;
6743         }
6744
6745         if (lun->backend->lun_attr != NULL &&
6746             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6747              != UINT64_MAX) {
6748                 phdr = (struct scsi_log_param_header *)data;
6749                 scsi_ulto2b(0x00f2, phdr->param_code);
6750                 phdr->param_control = SLP_LBIN | SLP_LP;
6751                 phdr->param_len = 8;
6752                 data = (uint8_t *)(phdr + 1);
6753                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6754                 data[4] = 0x02; /* per-pool */
6755                 data += phdr->param_len;
6756         }
6757
6758         page_index->page_len = data - page_index->page_data;
6759         return (0);
6760 }
6761
6762 int
6763 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6764                                struct ctl_page_index *page_index,
6765                                int pc)
6766 {
6767         struct ctl_lun *lun;
6768         struct stat_page *data;
6769         uint64_t rn, wn, rb, wb;
6770         struct bintime rt, wt;
6771         int i;
6772
6773         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6774         data = (struct stat_page *)page_index->page_data;
6775
6776         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6777         data->sap.hdr.param_control = SLP_LBIN;
6778         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6779             sizeof(struct scsi_log_param_header);
6780         rn = wn = rb = wb = 0;
6781         bintime_clear(&rt);
6782         bintime_clear(&wt);
6783         for (i = 0; i < CTL_MAX_PORTS; i++) {
6784                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6785                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6786                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6787                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6788                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6789                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6790         }
6791         scsi_u64to8b(rn, data->sap.read_num);
6792         scsi_u64to8b(wn, data->sap.write_num);
6793         if (lun->stats.blocksize > 0) {
6794                 scsi_u64to8b(wb / lun->stats.blocksize,
6795                     data->sap.recvieved_lba);
6796                 scsi_u64to8b(rb / lun->stats.blocksize,
6797                     data->sap.transmitted_lba);
6798         }
6799         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6800             data->sap.read_int);
6801         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6802             data->sap.write_int);
6803         scsi_u64to8b(0, data->sap.weighted_num);
6804         scsi_u64to8b(0, data->sap.weighted_int);
6805         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6806         data->it.hdr.param_control = SLP_LBIN;
6807         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6808             sizeof(struct scsi_log_param_header);
6809 #ifdef CTL_TIME_IO
6810         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6811 #endif
6812         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6813         data->it.hdr.param_control = SLP_LBIN;
6814         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6815             sizeof(struct scsi_log_param_header);
6816         scsi_ulto4b(3, data->ti.exponent);
6817         scsi_ulto4b(1, data->ti.integer);
6818
6819         page_index->page_len = sizeof(*data);
6820         return (0);
6821 }
6822
6823 int
6824 ctl_log_sense(struct ctl_scsiio *ctsio)
6825 {
6826         struct ctl_lun *lun;
6827         int i, pc, page_code, subpage;
6828         int alloc_len, total_len;
6829         struct ctl_page_index *page_index;
6830         struct scsi_log_sense *cdb;
6831         struct scsi_log_header *header;
6832
6833         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6834
6835         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6836         cdb = (struct scsi_log_sense *)ctsio->cdb;
6837         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6838         page_code = cdb->page & SLS_PAGE_CODE;
6839         subpage = cdb->subpage;
6840         alloc_len = scsi_2btoul(cdb->length);
6841
6842         page_index = NULL;
6843         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6844                 page_index = &lun->log_pages.index[i];
6845
6846                 /* Look for the right page code */
6847                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6848                         continue;
6849
6850                 /* Look for the right subpage or the subpage wildcard*/
6851                 if (page_index->subpage != subpage)
6852                         continue;
6853
6854                 break;
6855         }
6856         if (i >= CTL_NUM_LOG_PAGES) {
6857                 ctl_set_invalid_field(ctsio,
6858                                       /*sks_valid*/ 1,
6859                                       /*command*/ 1,
6860                                       /*field*/ 2,
6861                                       /*bit_valid*/ 0,
6862                                       /*bit*/ 0);
6863                 ctl_done((union ctl_io *)ctsio);
6864                 return (CTL_RETVAL_COMPLETE);
6865         }
6866
6867         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6868
6869         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6870         ctsio->kern_sg_entries = 0;
6871         ctsio->kern_data_resid = 0;
6872         ctsio->kern_rel_offset = 0;
6873         if (total_len < alloc_len) {
6874                 ctsio->residual = alloc_len - total_len;
6875                 ctsio->kern_data_len = total_len;
6876                 ctsio->kern_total_len = total_len;
6877         } else {
6878                 ctsio->residual = 0;
6879                 ctsio->kern_data_len = alloc_len;
6880                 ctsio->kern_total_len = alloc_len;
6881         }
6882
6883         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6884         header->page = page_index->page_code;
6885         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6886                 header->page |= SL_DS;
6887         if (page_index->subpage) {
6888                 header->page |= SL_SPF;
6889                 header->subpage = page_index->subpage;
6890         }
6891         scsi_ulto2b(page_index->page_len, header->datalen);
6892
6893         /*
6894          * Call the handler, if it exists, to update the
6895          * page to the latest values.
6896          */
6897         if (page_index->sense_handler != NULL)
6898                 page_index->sense_handler(ctsio, page_index, pc);
6899
6900         memcpy(header + 1, page_index->page_data, page_index->page_len);
6901
6902         ctl_set_success(ctsio);
6903         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6904         ctsio->be_move_done = ctl_config_move_done;
6905         ctl_datamove((union ctl_io *)ctsio);
6906         return (CTL_RETVAL_COMPLETE);
6907 }
6908
6909 int
6910 ctl_read_capacity(struct ctl_scsiio *ctsio)
6911 {
6912         struct scsi_read_capacity *cdb;
6913         struct scsi_read_capacity_data *data;
6914         struct ctl_lun *lun;
6915         uint32_t lba;
6916
6917         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6918
6919         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6920
6921         lba = scsi_4btoul(cdb->addr);
6922         if (((cdb->pmi & SRC_PMI) == 0)
6923          && (lba != 0)) {
6924                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6925                                       /*sks_valid*/ 1,
6926                                       /*command*/ 1,
6927                                       /*field*/ 2,
6928                                       /*bit_valid*/ 0,
6929                                       /*bit*/ 0);
6930                 ctl_done((union ctl_io *)ctsio);
6931                 return (CTL_RETVAL_COMPLETE);
6932         }
6933
6934         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6935
6936         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6937         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6938         ctsio->residual = 0;
6939         ctsio->kern_data_len = sizeof(*data);
6940         ctsio->kern_total_len = sizeof(*data);
6941         ctsio->kern_data_resid = 0;
6942         ctsio->kern_rel_offset = 0;
6943         ctsio->kern_sg_entries = 0;
6944
6945         /*
6946          * If the maximum LBA is greater than 0xfffffffe, the user must
6947          * issue a SERVICE ACTION IN (16) command, with the read capacity
6948          * serivce action set.
6949          */
6950         if (lun->be_lun->maxlba > 0xfffffffe)
6951                 scsi_ulto4b(0xffffffff, data->addr);
6952         else
6953                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6954
6955         /*
6956          * XXX KDM this may not be 512 bytes...
6957          */
6958         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6959
6960         ctl_set_success(ctsio);
6961         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6962         ctsio->be_move_done = ctl_config_move_done;
6963         ctl_datamove((union ctl_io *)ctsio);
6964         return (CTL_RETVAL_COMPLETE);
6965 }
6966
6967 int
6968 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6969 {
6970         struct scsi_read_capacity_16 *cdb;
6971         struct scsi_read_capacity_data_long *data;
6972         struct ctl_lun *lun;
6973         uint64_t lba;
6974         uint32_t alloc_len;
6975
6976         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6977
6978         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6979
6980         alloc_len = scsi_4btoul(cdb->alloc_len);
6981         lba = scsi_8btou64(cdb->addr);
6982
6983         if ((cdb->reladr & SRC16_PMI)
6984          && (lba != 0)) {
6985                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6986                                       /*sks_valid*/ 1,
6987                                       /*command*/ 1,
6988                                       /*field*/ 2,
6989                                       /*bit_valid*/ 0,
6990                                       /*bit*/ 0);
6991                 ctl_done((union ctl_io *)ctsio);
6992                 return (CTL_RETVAL_COMPLETE);
6993         }
6994
6995         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6996
6997         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6998         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6999
7000         if (sizeof(*data) < alloc_len) {
7001                 ctsio->residual = alloc_len - sizeof(*data);
7002                 ctsio->kern_data_len = sizeof(*data);
7003                 ctsio->kern_total_len = sizeof(*data);
7004         } else {
7005                 ctsio->residual = 0;
7006                 ctsio->kern_data_len = alloc_len;
7007                 ctsio->kern_total_len = alloc_len;
7008         }
7009         ctsio->kern_data_resid = 0;
7010         ctsio->kern_rel_offset = 0;
7011         ctsio->kern_sg_entries = 0;
7012
7013         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7014         /* XXX KDM this may not be 512 bytes... */
7015         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7016         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7017         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7018         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7019                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7020
7021         ctl_set_success(ctsio);
7022         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7023         ctsio->be_move_done = ctl_config_move_done;
7024         ctl_datamove((union ctl_io *)ctsio);
7025         return (CTL_RETVAL_COMPLETE);
7026 }
7027
7028 int
7029 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7030 {
7031         struct scsi_get_lba_status *cdb;
7032         struct scsi_get_lba_status_data *data;
7033         struct ctl_lun *lun;
7034         struct ctl_lba_len_flags *lbalen;
7035         uint64_t lba;
7036         uint32_t alloc_len, total_len;
7037         int retval;
7038
7039         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7040
7041         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7042         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7043         lba = scsi_8btou64(cdb->addr);
7044         alloc_len = scsi_4btoul(cdb->alloc_len);
7045
7046         if (lba > lun->be_lun->maxlba) {
7047                 ctl_set_lba_out_of_range(ctsio);
7048                 ctl_done((union ctl_io *)ctsio);
7049                 return (CTL_RETVAL_COMPLETE);
7050         }
7051
7052         total_len = sizeof(*data) + sizeof(data->descr[0]);
7053         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7054         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7055
7056         if (total_len < alloc_len) {
7057                 ctsio->residual = alloc_len - total_len;
7058                 ctsio->kern_data_len = total_len;
7059                 ctsio->kern_total_len = total_len;
7060         } else {
7061                 ctsio->residual = 0;
7062                 ctsio->kern_data_len = alloc_len;
7063                 ctsio->kern_total_len = alloc_len;
7064         }
7065         ctsio->kern_data_resid = 0;
7066         ctsio->kern_rel_offset = 0;
7067         ctsio->kern_sg_entries = 0;
7068
7069         /* Fill dummy data in case backend can't tell anything. */
7070         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7071         scsi_u64to8b(lba, data->descr[0].addr);
7072         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7073             data->descr[0].length);
7074         data->descr[0].status = 0; /* Mapped or unknown. */
7075
7076         ctl_set_success(ctsio);
7077         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7078         ctsio->be_move_done = ctl_config_move_done;
7079
7080         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7081         lbalen->lba = lba;
7082         lbalen->len = total_len;
7083         lbalen->flags = 0;
7084         retval = lun->backend->config_read((union ctl_io *)ctsio);
7085         return (CTL_RETVAL_COMPLETE);
7086 }
7087
7088 int
7089 ctl_read_defect(struct ctl_scsiio *ctsio)
7090 {
7091         struct scsi_read_defect_data_10 *ccb10;
7092         struct scsi_read_defect_data_12 *ccb12;
7093         struct scsi_read_defect_data_hdr_10 *data10;
7094         struct scsi_read_defect_data_hdr_12 *data12;
7095         uint32_t alloc_len, data_len;
7096         uint8_t format;
7097
7098         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7099
7100         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7101                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7102                 format = ccb10->format;
7103                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7104                 data_len = sizeof(*data10);
7105         } else {
7106                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7107                 format = ccb12->format;
7108                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7109                 data_len = sizeof(*data12);
7110         }
7111         if (alloc_len == 0) {
7112                 ctl_set_success(ctsio);
7113                 ctl_done((union ctl_io *)ctsio);
7114                 return (CTL_RETVAL_COMPLETE);
7115         }
7116
7117         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7118         if (data_len < alloc_len) {
7119                 ctsio->residual = alloc_len - data_len;
7120                 ctsio->kern_data_len = data_len;
7121                 ctsio->kern_total_len = data_len;
7122         } else {
7123                 ctsio->residual = 0;
7124                 ctsio->kern_data_len = alloc_len;
7125                 ctsio->kern_total_len = alloc_len;
7126         }
7127         ctsio->kern_data_resid = 0;
7128         ctsio->kern_rel_offset = 0;
7129         ctsio->kern_sg_entries = 0;
7130
7131         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7132                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7133                     ctsio->kern_data_ptr;
7134                 data10->format = format;
7135                 scsi_ulto2b(0, data10->length);
7136         } else {
7137                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7138                     ctsio->kern_data_ptr;
7139                 data12->format = format;
7140                 scsi_ulto2b(0, data12->generation);
7141                 scsi_ulto4b(0, data12->length);
7142         }
7143
7144         ctl_set_success(ctsio);
7145         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7146         ctsio->be_move_done = ctl_config_move_done;
7147         ctl_datamove((union ctl_io *)ctsio);
7148         return (CTL_RETVAL_COMPLETE);
7149 }
7150
7151 int
7152 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7153 {
7154         struct scsi_maintenance_in *cdb;
7155         int retval;
7156         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7157         int num_ha_groups, num_target_ports, shared_group;
7158         struct ctl_lun *lun;
7159         struct ctl_softc *softc;
7160         struct ctl_port *port;
7161         struct scsi_target_group_data *rtg_ptr;
7162         struct scsi_target_group_data_extended *rtg_ext_ptr;
7163         struct scsi_target_port_group_descriptor *tpg_desc;
7164
7165         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7166
7167         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7168         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7169         softc = lun->ctl_softc;
7170
7171         retval = CTL_RETVAL_COMPLETE;
7172
7173         switch (cdb->byte2 & STG_PDF_MASK) {
7174         case STG_PDF_LENGTH:
7175                 ext = 0;
7176                 break;
7177         case STG_PDF_EXTENDED:
7178                 ext = 1;
7179                 break;
7180         default:
7181                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7182                                       /*sks_valid*/ 1,
7183                                       /*command*/ 1,
7184                                       /*field*/ 2,
7185                                       /*bit_valid*/ 1,
7186                                       /*bit*/ 5);
7187                 ctl_done((union ctl_io *)ctsio);
7188                 return(retval);
7189         }
7190
7191         num_target_ports = 0;
7192         shared_group = (softc->is_single != 0);
7193         mtx_lock(&softc->ctl_lock);
7194         STAILQ_FOREACH(port, &softc->port_list, links) {
7195                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7196                         continue;
7197                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7198                         continue;
7199                 num_target_ports++;
7200                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7201                         shared_group = 1;
7202         }
7203         mtx_unlock(&softc->ctl_lock);
7204         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7205
7206         if (ext)
7207                 total_len = sizeof(struct scsi_target_group_data_extended);
7208         else
7209                 total_len = sizeof(struct scsi_target_group_data);
7210         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7211                 (shared_group + num_ha_groups) +
7212             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7213
7214         alloc_len = scsi_4btoul(cdb->length);
7215
7216         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7217
7218         ctsio->kern_sg_entries = 0;
7219
7220         if (total_len < alloc_len) {
7221                 ctsio->residual = alloc_len - total_len;
7222                 ctsio->kern_data_len = total_len;
7223                 ctsio->kern_total_len = total_len;
7224         } else {
7225                 ctsio->residual = 0;
7226                 ctsio->kern_data_len = alloc_len;
7227                 ctsio->kern_total_len = alloc_len;
7228         }
7229         ctsio->kern_data_resid = 0;
7230         ctsio->kern_rel_offset = 0;
7231
7232         if (ext) {
7233                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7234                     ctsio->kern_data_ptr;
7235                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7236                 rtg_ext_ptr->format_type = 0x10;
7237                 rtg_ext_ptr->implicit_transition_time = 0;
7238                 tpg_desc = &rtg_ext_ptr->groups[0];
7239         } else {
7240                 rtg_ptr = (struct scsi_target_group_data *)
7241                     ctsio->kern_data_ptr;
7242                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7243                 tpg_desc = &rtg_ptr->groups[0];
7244         }
7245
7246         mtx_lock(&softc->ctl_lock);
7247         pg = softc->port_min / softc->port_cnt;
7248         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7249                 /* Some shelf is known to be primary. */
7250                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7251                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7252                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7253                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7254                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7255                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7256                 else
7257                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7258                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7259                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7260                 } else {
7261                         ts = os;
7262                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7263                 }
7264         } else {
7265                 /* No known primary shelf. */
7266                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7267                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7268                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7269                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7270                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7271                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7272                 } else {
7273                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7274                 }
7275         }
7276         if (shared_group) {
7277                 tpg_desc->pref_state = ts;
7278                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7279                     TPG_U_SUP | TPG_T_SUP;
7280                 scsi_ulto2b(1, tpg_desc->target_port_group);
7281                 tpg_desc->status = TPG_IMPLICIT;
7282                 pc = 0;
7283                 STAILQ_FOREACH(port, &softc->port_list, links) {
7284                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7285                                 continue;
7286                         if (!softc->is_single &&
7287                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7288                                 continue;
7289                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7290                                 continue;
7291                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7292                             relative_target_port_identifier);
7293                         pc++;
7294                 }
7295                 tpg_desc->target_port_count = pc;
7296                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7297                     &tpg_desc->descriptors[pc];
7298         }
7299         for (g = 0; g < num_ha_groups; g++) {
7300                 tpg_desc->pref_state = (g == pg) ? ts : os;
7301                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7302                     TPG_U_SUP | TPG_T_SUP;
7303                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7304                 tpg_desc->status = TPG_IMPLICIT;
7305                 pc = 0;
7306                 STAILQ_FOREACH(port, &softc->port_list, links) {
7307                         if (port->targ_port < g * softc->port_cnt ||
7308                             port->targ_port >= (g + 1) * softc->port_cnt)
7309                                 continue;
7310                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7311                                 continue;
7312                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7313                                 continue;
7314                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7315                                 continue;
7316                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7317                             relative_target_port_identifier);
7318                         pc++;
7319                 }
7320                 tpg_desc->target_port_count = pc;
7321                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7322                     &tpg_desc->descriptors[pc];
7323         }
7324         mtx_unlock(&softc->ctl_lock);
7325
7326         ctl_set_success(ctsio);
7327         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7328         ctsio->be_move_done = ctl_config_move_done;
7329         ctl_datamove((union ctl_io *)ctsio);
7330         return(retval);
7331 }
7332
7333 int
7334 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7335 {
7336         struct ctl_lun *lun;
7337         struct scsi_report_supported_opcodes *cdb;
7338         const struct ctl_cmd_entry *entry, *sentry;
7339         struct scsi_report_supported_opcodes_all *all;
7340         struct scsi_report_supported_opcodes_descr *descr;
7341         struct scsi_report_supported_opcodes_one *one;
7342         int retval;
7343         int alloc_len, total_len;
7344         int opcode, service_action, i, j, num;
7345
7346         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7347
7348         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7349         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7350
7351         retval = CTL_RETVAL_COMPLETE;
7352
7353         opcode = cdb->requested_opcode;
7354         service_action = scsi_2btoul(cdb->requested_service_action);
7355         switch (cdb->options & RSO_OPTIONS_MASK) {
7356         case RSO_OPTIONS_ALL:
7357                 num = 0;
7358                 for (i = 0; i < 256; i++) {
7359                         entry = &ctl_cmd_table[i];
7360                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7361                                 for (j = 0; j < 32; j++) {
7362                                         sentry = &((const struct ctl_cmd_entry *)
7363                                             entry->execute)[j];
7364                                         if (ctl_cmd_applicable(
7365                                             lun->be_lun->lun_type, sentry))
7366                                                 num++;
7367                                 }
7368                         } else {
7369                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7370                                     entry))
7371                                         num++;
7372                         }
7373                 }
7374                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7375                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7376                 break;
7377         case RSO_OPTIONS_OC:
7378                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7379                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7380                                               /*sks_valid*/ 1,
7381                                               /*command*/ 1,
7382                                               /*field*/ 2,
7383                                               /*bit_valid*/ 1,
7384                                               /*bit*/ 2);
7385                         ctl_done((union ctl_io *)ctsio);
7386                         return (CTL_RETVAL_COMPLETE);
7387                 }
7388                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7389                 break;
7390         case RSO_OPTIONS_OC_SA:
7391                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7392                     service_action >= 32) {
7393                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7394                                               /*sks_valid*/ 1,
7395                                               /*command*/ 1,
7396                                               /*field*/ 2,
7397                                               /*bit_valid*/ 1,
7398                                               /*bit*/ 2);
7399                         ctl_done((union ctl_io *)ctsio);
7400                         return (CTL_RETVAL_COMPLETE);
7401                 }
7402                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7403                 break;
7404         default:
7405                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7406                                       /*sks_valid*/ 1,
7407                                       /*command*/ 1,
7408                                       /*field*/ 2,
7409                                       /*bit_valid*/ 1,
7410                                       /*bit*/ 2);
7411                 ctl_done((union ctl_io *)ctsio);
7412                 return (CTL_RETVAL_COMPLETE);
7413         }
7414
7415         alloc_len = scsi_4btoul(cdb->length);
7416
7417         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7418
7419         ctsio->kern_sg_entries = 0;
7420
7421         if (total_len < alloc_len) {
7422                 ctsio->residual = alloc_len - total_len;
7423                 ctsio->kern_data_len = total_len;
7424                 ctsio->kern_total_len = total_len;
7425         } else {
7426                 ctsio->residual = 0;
7427                 ctsio->kern_data_len = alloc_len;
7428                 ctsio->kern_total_len = alloc_len;
7429         }
7430         ctsio->kern_data_resid = 0;
7431         ctsio->kern_rel_offset = 0;
7432
7433         switch (cdb->options & RSO_OPTIONS_MASK) {
7434         case RSO_OPTIONS_ALL:
7435                 all = (struct scsi_report_supported_opcodes_all *)
7436                     ctsio->kern_data_ptr;
7437                 num = 0;
7438                 for (i = 0; i < 256; i++) {
7439                         entry = &ctl_cmd_table[i];
7440                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7441                                 for (j = 0; j < 32; j++) {
7442                                         sentry = &((const struct ctl_cmd_entry *)
7443                                             entry->execute)[j];
7444                                         if (!ctl_cmd_applicable(
7445                                             lun->be_lun->lun_type, sentry))
7446                                                 continue;
7447                                         descr = &all->descr[num++];
7448                                         descr->opcode = i;
7449                                         scsi_ulto2b(j, descr->service_action);
7450                                         descr->flags = RSO_SERVACTV;
7451                                         scsi_ulto2b(sentry->length,
7452                                             descr->cdb_length);
7453                                 }
7454                         } else {
7455                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7456                                     entry))
7457                                         continue;
7458                                 descr = &all->descr[num++];
7459                                 descr->opcode = i;
7460                                 scsi_ulto2b(0, descr->service_action);
7461                                 descr->flags = 0;
7462                                 scsi_ulto2b(entry->length, descr->cdb_length);
7463                         }
7464                 }
7465                 scsi_ulto4b(
7466                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7467                     all->length);
7468                 break;
7469         case RSO_OPTIONS_OC:
7470                 one = (struct scsi_report_supported_opcodes_one *)
7471                     ctsio->kern_data_ptr;
7472                 entry = &ctl_cmd_table[opcode];
7473                 goto fill_one;
7474         case RSO_OPTIONS_OC_SA:
7475                 one = (struct scsi_report_supported_opcodes_one *)
7476                     ctsio->kern_data_ptr;
7477                 entry = &ctl_cmd_table[opcode];
7478                 entry = &((const struct ctl_cmd_entry *)
7479                     entry->execute)[service_action];
7480 fill_one:
7481                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7482                         one->support = 3;
7483                         scsi_ulto2b(entry->length, one->cdb_length);
7484                         one->cdb_usage[0] = opcode;
7485                         memcpy(&one->cdb_usage[1], entry->usage,
7486                             entry->length - 1);
7487                 } else
7488                         one->support = 1;
7489                 break;
7490         }
7491
7492         ctl_set_success(ctsio);
7493         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7494         ctsio->be_move_done = ctl_config_move_done;
7495         ctl_datamove((union ctl_io *)ctsio);
7496         return(retval);
7497 }
7498
7499 int
7500 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7501 {
7502         struct scsi_report_supported_tmf *cdb;
7503         struct scsi_report_supported_tmf_data *data;
7504         int retval;
7505         int alloc_len, total_len;
7506
7507         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7508
7509         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7510
7511         retval = CTL_RETVAL_COMPLETE;
7512
7513         total_len = sizeof(struct scsi_report_supported_tmf_data);
7514         alloc_len = scsi_4btoul(cdb->length);
7515
7516         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7517
7518         ctsio->kern_sg_entries = 0;
7519
7520         if (total_len < alloc_len) {
7521                 ctsio->residual = alloc_len - total_len;
7522                 ctsio->kern_data_len = total_len;
7523                 ctsio->kern_total_len = total_len;
7524         } else {
7525                 ctsio->residual = 0;
7526                 ctsio->kern_data_len = alloc_len;
7527                 ctsio->kern_total_len = alloc_len;
7528         }
7529         ctsio->kern_data_resid = 0;
7530         ctsio->kern_rel_offset = 0;
7531
7532         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7533         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7534             RST_TRS;
7535         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7536
7537         ctl_set_success(ctsio);
7538         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7539         ctsio->be_move_done = ctl_config_move_done;
7540         ctl_datamove((union ctl_io *)ctsio);
7541         return (retval);
7542 }
7543
7544 int
7545 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7546 {
7547         struct scsi_report_timestamp *cdb;
7548         struct scsi_report_timestamp_data *data;
7549         struct timeval tv;
7550         int64_t timestamp;
7551         int retval;
7552         int alloc_len, total_len;
7553
7554         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7555
7556         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7557
7558         retval = CTL_RETVAL_COMPLETE;
7559
7560         total_len = sizeof(struct scsi_report_timestamp_data);
7561         alloc_len = scsi_4btoul(cdb->length);
7562
7563         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7564
7565         ctsio->kern_sg_entries = 0;
7566
7567         if (total_len < alloc_len) {
7568                 ctsio->residual = alloc_len - total_len;
7569                 ctsio->kern_data_len = total_len;
7570                 ctsio->kern_total_len = total_len;
7571         } else {
7572                 ctsio->residual = 0;
7573                 ctsio->kern_data_len = alloc_len;
7574                 ctsio->kern_total_len = alloc_len;
7575         }
7576         ctsio->kern_data_resid = 0;
7577         ctsio->kern_rel_offset = 0;
7578
7579         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7580         scsi_ulto2b(sizeof(*data) - 2, data->length);
7581         data->origin = RTS_ORIG_OUTSIDE;
7582         getmicrotime(&tv);
7583         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7584         scsi_ulto4b(timestamp >> 16, data->timestamp);
7585         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7586
7587         ctl_set_success(ctsio);
7588         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7589         ctsio->be_move_done = ctl_config_move_done;
7590         ctl_datamove((union ctl_io *)ctsio);
7591         return (retval);
7592 }
7593
7594 int
7595 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7596 {
7597         struct scsi_per_res_in *cdb;
7598         int alloc_len, total_len = 0;
7599         /* struct scsi_per_res_in_rsrv in_data; */
7600         struct ctl_lun *lun;
7601         struct ctl_softc *softc;
7602         uint64_t key;
7603
7604         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7605
7606         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7607
7608         alloc_len = scsi_2btoul(cdb->length);
7609
7610         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7611         softc = lun->ctl_softc;
7612
7613 retry:
7614         mtx_lock(&lun->lun_lock);
7615         switch (cdb->action) {
7616         case SPRI_RK: /* read keys */
7617                 total_len = sizeof(struct scsi_per_res_in_keys) +
7618                         lun->pr_key_count *
7619                         sizeof(struct scsi_per_res_key);
7620                 break;
7621         case SPRI_RR: /* read reservation */
7622                 if (lun->flags & CTL_LUN_PR_RESERVED)
7623                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7624                 else
7625                         total_len = sizeof(struct scsi_per_res_in_header);
7626                 break;
7627         case SPRI_RC: /* report capabilities */
7628                 total_len = sizeof(struct scsi_per_res_cap);
7629                 break;
7630         case SPRI_RS: /* read full status */
7631                 total_len = sizeof(struct scsi_per_res_in_header) +
7632                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7633                     lun->pr_key_count;
7634                 break;
7635         default:
7636                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7637         }
7638         mtx_unlock(&lun->lun_lock);
7639
7640         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7641
7642         if (total_len < alloc_len) {
7643                 ctsio->residual = alloc_len - total_len;
7644                 ctsio->kern_data_len = total_len;
7645                 ctsio->kern_total_len = total_len;
7646         } else {
7647                 ctsio->residual = 0;
7648                 ctsio->kern_data_len = alloc_len;
7649                 ctsio->kern_total_len = alloc_len;
7650         }
7651
7652         ctsio->kern_data_resid = 0;
7653         ctsio->kern_rel_offset = 0;
7654         ctsio->kern_sg_entries = 0;
7655
7656         mtx_lock(&lun->lun_lock);
7657         switch (cdb->action) {
7658         case SPRI_RK: { // read keys
7659         struct scsi_per_res_in_keys *res_keys;
7660                 int i, key_count;
7661
7662                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7663
7664                 /*
7665                  * We had to drop the lock to allocate our buffer, which
7666                  * leaves time for someone to come in with another
7667                  * persistent reservation.  (That is unlikely, though,
7668                  * since this should be the only persistent reservation
7669                  * command active right now.)
7670                  */
7671                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7672                     (lun->pr_key_count *
7673                      sizeof(struct scsi_per_res_key)))){
7674                         mtx_unlock(&lun->lun_lock);
7675                         free(ctsio->kern_data_ptr, M_CTL);
7676                         printf("%s: reservation length changed, retrying\n",
7677                                __func__);
7678                         goto retry;
7679                 }
7680
7681                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7682
7683                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7684                              lun->pr_key_count, res_keys->header.length);
7685
7686                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7687                         if ((key = ctl_get_prkey(lun, i)) == 0)
7688                                 continue;
7689
7690                         /*
7691                          * We used lun->pr_key_count to calculate the
7692                          * size to allocate.  If it turns out the number of
7693                          * initiators with the registered flag set is
7694                          * larger than that (i.e. they haven't been kept in
7695                          * sync), we've got a problem.
7696                          */
7697                         if (key_count >= lun->pr_key_count) {
7698                                 key_count++;
7699                                 continue;
7700                         }
7701                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7702                         key_count++;
7703                 }
7704                 break;
7705         }
7706         case SPRI_RR: { // read reservation
7707                 struct scsi_per_res_in_rsrv *res;
7708                 int tmp_len, header_only;
7709
7710                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7711
7712                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7713
7714                 if (lun->flags & CTL_LUN_PR_RESERVED)
7715                 {
7716                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7717                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7718                                     res->header.length);
7719                         header_only = 0;
7720                 } else {
7721                         tmp_len = sizeof(struct scsi_per_res_in_header);
7722                         scsi_ulto4b(0, res->header.length);
7723                         header_only = 1;
7724                 }
7725
7726                 /*
7727                  * We had to drop the lock to allocate our buffer, which
7728                  * leaves time for someone to come in with another
7729                  * persistent reservation.  (That is unlikely, though,
7730                  * since this should be the only persistent reservation
7731                  * command active right now.)
7732                  */
7733                 if (tmp_len != total_len) {
7734                         mtx_unlock(&lun->lun_lock);
7735                         free(ctsio->kern_data_ptr, M_CTL);
7736                         printf("%s: reservation status changed, retrying\n",
7737                                __func__);
7738                         goto retry;
7739                 }
7740
7741                 /*
7742                  * No reservation held, so we're done.
7743                  */
7744                 if (header_only != 0)
7745                         break;
7746
7747                 /*
7748                  * If the registration is an All Registrants type, the key
7749                  * is 0, since it doesn't really matter.
7750                  */
7751                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7752                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7753                             res->data.reservation);
7754                 }
7755                 res->data.scopetype = lun->pr_res_type;
7756                 break;
7757         }
7758         case SPRI_RC:     //report capabilities
7759         {
7760                 struct scsi_per_res_cap *res_cap;
7761                 uint16_t type_mask;
7762
7763                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7764                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7765                 res_cap->flags1 = SPRI_CRH;
7766                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7767                 type_mask = SPRI_TM_WR_EX_AR |
7768                             SPRI_TM_EX_AC_RO |
7769                             SPRI_TM_WR_EX_RO |
7770                             SPRI_TM_EX_AC |
7771                             SPRI_TM_WR_EX |
7772                             SPRI_TM_EX_AC_AR;
7773                 scsi_ulto2b(type_mask, res_cap->type_mask);
7774                 break;
7775         }
7776         case SPRI_RS: { // read full status
7777                 struct scsi_per_res_in_full *res_status;
7778                 struct scsi_per_res_in_full_desc *res_desc;
7779                 struct ctl_port *port;
7780                 int i, len;
7781
7782                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7783
7784                 /*
7785                  * We had to drop the lock to allocate our buffer, which
7786                  * leaves time for someone to come in with another
7787                  * persistent reservation.  (That is unlikely, though,
7788                  * since this should be the only persistent reservation
7789                  * command active right now.)
7790                  */
7791                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7792                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7793                      lun->pr_key_count)){
7794                         mtx_unlock(&lun->lun_lock);
7795                         free(ctsio->kern_data_ptr, M_CTL);
7796                         printf("%s: reservation length changed, retrying\n",
7797                                __func__);
7798                         goto retry;
7799                 }
7800
7801                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7802
7803                 res_desc = &res_status->desc[0];
7804                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7805                         if ((key = ctl_get_prkey(lun, i)) == 0)
7806                                 continue;
7807
7808                         scsi_u64to8b(key, res_desc->res_key.key);
7809                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7810                             (lun->pr_res_idx == i ||
7811                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7812                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7813                                 res_desc->scopetype = lun->pr_res_type;
7814                         }
7815                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7816                             res_desc->rel_trgt_port_id);
7817                         len = 0;
7818                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7819                         if (port != NULL)
7820                                 len = ctl_create_iid(port,
7821                                     i % CTL_MAX_INIT_PER_PORT,
7822                                     res_desc->transport_id);
7823                         scsi_ulto4b(len, res_desc->additional_length);
7824                         res_desc = (struct scsi_per_res_in_full_desc *)
7825                             &res_desc->transport_id[len];
7826                 }
7827                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7828                     res_status->header.length);
7829                 break;
7830         }
7831         default:
7832                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7833         }
7834         mtx_unlock(&lun->lun_lock);
7835
7836         ctl_set_success(ctsio);
7837         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7838         ctsio->be_move_done = ctl_config_move_done;
7839         ctl_datamove((union ctl_io *)ctsio);
7840         return (CTL_RETVAL_COMPLETE);
7841 }
7842
7843 /*
7844  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7845  * it should return.
7846  */
7847 static int
7848 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7849                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7850                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7851                 struct scsi_per_res_out_parms* param)
7852 {
7853         union ctl_ha_msg persis_io;
7854         int i;
7855
7856         mtx_lock(&lun->lun_lock);
7857         if (sa_res_key == 0) {
7858                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7859                         /* validate scope and type */
7860                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7861                              SPR_LU_SCOPE) {
7862                                 mtx_unlock(&lun->lun_lock);
7863                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7864                                                       /*sks_valid*/ 1,
7865                                                       /*command*/ 1,
7866                                                       /*field*/ 2,
7867                                                       /*bit_valid*/ 1,
7868                                                       /*bit*/ 4);
7869                                 ctl_done((union ctl_io *)ctsio);
7870                                 return (1);
7871                         }
7872
7873                         if (type>8 || type==2 || type==4 || type==0) {
7874                                 mtx_unlock(&lun->lun_lock);
7875                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7876                                                       /*sks_valid*/ 1,
7877                                                       /*command*/ 1,
7878                                                       /*field*/ 2,
7879                                                       /*bit_valid*/ 1,
7880                                                       /*bit*/ 0);
7881                                 ctl_done((union ctl_io *)ctsio);
7882                                 return (1);
7883                         }
7884
7885                         /*
7886                          * Unregister everybody else and build UA for
7887                          * them
7888                          */
7889                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7890                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7891                                         continue;
7892
7893                                 ctl_clr_prkey(lun, i);
7894                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7895                         }
7896                         lun->pr_key_count = 1;
7897                         lun->pr_res_type = type;
7898                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7899                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7900                                 lun->pr_res_idx = residx;
7901                         lun->pr_generation++;
7902                         mtx_unlock(&lun->lun_lock);
7903
7904                         /* send msg to other side */
7905                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7906                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7907                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7908                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7909                         persis_io.pr.pr_info.res_type = type;
7910                         memcpy(persis_io.pr.pr_info.sa_res_key,
7911                                param->serv_act_res_key,
7912                                sizeof(param->serv_act_res_key));
7913                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7914                             sizeof(persis_io.pr), M_WAITOK);
7915                 } else {
7916                         /* not all registrants */
7917                         mtx_unlock(&lun->lun_lock);
7918                         free(ctsio->kern_data_ptr, M_CTL);
7919                         ctl_set_invalid_field(ctsio,
7920                                               /*sks_valid*/ 1,
7921                                               /*command*/ 0,
7922                                               /*field*/ 8,
7923                                               /*bit_valid*/ 0,
7924                                               /*bit*/ 0);
7925                         ctl_done((union ctl_io *)ctsio);
7926                         return (1);
7927                 }
7928         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7929                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7930                 int found = 0;
7931
7932                 if (res_key == sa_res_key) {
7933                         /* special case */
7934                         /*
7935                          * The spec implies this is not good but doesn't
7936                          * say what to do. There are two choices either
7937                          * generate a res conflict or check condition
7938                          * with illegal field in parameter data. Since
7939                          * that is what is done when the sa_res_key is
7940                          * zero I'll take that approach since this has
7941                          * to do with the sa_res_key.
7942                          */
7943                         mtx_unlock(&lun->lun_lock);
7944                         free(ctsio->kern_data_ptr, M_CTL);
7945                         ctl_set_invalid_field(ctsio,
7946                                               /*sks_valid*/ 1,
7947                                               /*command*/ 0,
7948                                               /*field*/ 8,
7949                                               /*bit_valid*/ 0,
7950                                               /*bit*/ 0);
7951                         ctl_done((union ctl_io *)ctsio);
7952                         return (1);
7953                 }
7954
7955                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7956                         if (ctl_get_prkey(lun, i) != sa_res_key)
7957                                 continue;
7958
7959                         found = 1;
7960                         ctl_clr_prkey(lun, i);
7961                         lun->pr_key_count--;
7962                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7963                 }
7964                 if (!found) {
7965                         mtx_unlock(&lun->lun_lock);
7966                         free(ctsio->kern_data_ptr, M_CTL);
7967                         ctl_set_reservation_conflict(ctsio);
7968                         ctl_done((union ctl_io *)ctsio);
7969                         return (CTL_RETVAL_COMPLETE);
7970                 }
7971                 lun->pr_generation++;
7972                 mtx_unlock(&lun->lun_lock);
7973
7974                 /* send msg to other side */
7975                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7976                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7977                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7978                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7979                 persis_io.pr.pr_info.res_type = type;
7980                 memcpy(persis_io.pr.pr_info.sa_res_key,
7981                        param->serv_act_res_key,
7982                        sizeof(param->serv_act_res_key));
7983                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7984                     sizeof(persis_io.pr), M_WAITOK);
7985         } else {
7986                 /* Reserved but not all registrants */
7987                 /* sa_res_key is res holder */
7988                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7989                         /* validate scope and type */
7990                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7991                              SPR_LU_SCOPE) {
7992                                 mtx_unlock(&lun->lun_lock);
7993                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7994                                                       /*sks_valid*/ 1,
7995                                                       /*command*/ 1,
7996                                                       /*field*/ 2,
7997                                                       /*bit_valid*/ 1,
7998                                                       /*bit*/ 4);
7999                                 ctl_done((union ctl_io *)ctsio);
8000                                 return (1);
8001                         }
8002
8003                         if (type>8 || type==2 || type==4 || type==0) {
8004                                 mtx_unlock(&lun->lun_lock);
8005                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8006                                                       /*sks_valid*/ 1,
8007                                                       /*command*/ 1,
8008                                                       /*field*/ 2,
8009                                                       /*bit_valid*/ 1,
8010                                                       /*bit*/ 0);
8011                                 ctl_done((union ctl_io *)ctsio);
8012                                 return (1);
8013                         }
8014
8015                         /*
8016                          * Do the following:
8017                          * if sa_res_key != res_key remove all
8018                          * registrants w/sa_res_key and generate UA
8019                          * for these registrants(Registrations
8020                          * Preempted) if it wasn't an exclusive
8021                          * reservation generate UA(Reservations
8022                          * Preempted) for all other registered nexuses
8023                          * if the type has changed. Establish the new
8024                          * reservation and holder. If res_key and
8025                          * sa_res_key are the same do the above
8026                          * except don't unregister the res holder.
8027                          */
8028
8029                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8030                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8031                                         continue;
8032
8033                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8034                                         ctl_clr_prkey(lun, i);
8035                                         lun->pr_key_count--;
8036                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8037                                 } else if (type != lun->pr_res_type &&
8038                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8039                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8040                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8041                                 }
8042                         }
8043                         lun->pr_res_type = type;
8044                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8045                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8046                                 lun->pr_res_idx = residx;
8047                         else
8048                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8049                         lun->pr_generation++;
8050                         mtx_unlock(&lun->lun_lock);
8051
8052                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8053                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8054                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8055                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8056                         persis_io.pr.pr_info.res_type = type;
8057                         memcpy(persis_io.pr.pr_info.sa_res_key,
8058                                param->serv_act_res_key,
8059                                sizeof(param->serv_act_res_key));
8060                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8061                             sizeof(persis_io.pr), M_WAITOK);
8062                 } else {
8063                         /*
8064                          * sa_res_key is not the res holder just
8065                          * remove registrants
8066                          */
8067                         int found=0;
8068
8069                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8070                                 if (sa_res_key != ctl_get_prkey(lun, i))
8071                                         continue;
8072
8073                                 found = 1;
8074                                 ctl_clr_prkey(lun, i);
8075                                 lun->pr_key_count--;
8076                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8077                         }
8078
8079                         if (!found) {
8080                                 mtx_unlock(&lun->lun_lock);
8081                                 free(ctsio->kern_data_ptr, M_CTL);
8082                                 ctl_set_reservation_conflict(ctsio);
8083                                 ctl_done((union ctl_io *)ctsio);
8084                                 return (1);
8085                         }
8086                         lun->pr_generation++;
8087                         mtx_unlock(&lun->lun_lock);
8088
8089                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8090                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8091                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8092                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8093                         persis_io.pr.pr_info.res_type = type;
8094                         memcpy(persis_io.pr.pr_info.sa_res_key,
8095                                param->serv_act_res_key,
8096                                sizeof(param->serv_act_res_key));
8097                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8098                             sizeof(persis_io.pr), M_WAITOK);
8099                 }
8100         }
8101         return (0);
8102 }
8103
8104 static void
8105 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8106 {
8107         uint64_t sa_res_key;
8108         int i;
8109
8110         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8111
8112         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8113          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8114          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8115                 if (sa_res_key == 0) {
8116                         /*
8117                          * Unregister everybody else and build UA for
8118                          * them
8119                          */
8120                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8121                                 if (i == msg->pr.pr_info.residx ||
8122                                     ctl_get_prkey(lun, i) == 0)
8123                                         continue;
8124
8125                                 ctl_clr_prkey(lun, i);
8126                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8127                         }
8128
8129                         lun->pr_key_count = 1;
8130                         lun->pr_res_type = msg->pr.pr_info.res_type;
8131                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8132                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8133                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8134                 } else {
8135                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8136                                 if (sa_res_key == ctl_get_prkey(lun, i))
8137                                         continue;
8138
8139                                 ctl_clr_prkey(lun, i);
8140                                 lun->pr_key_count--;
8141                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8142                         }
8143                 }
8144         } else {
8145                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8146                         if (i == msg->pr.pr_info.residx ||
8147                             ctl_get_prkey(lun, i) == 0)
8148                                 continue;
8149
8150                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8151                                 ctl_clr_prkey(lun, i);
8152                                 lun->pr_key_count--;
8153                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8154                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8155                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8156                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8157                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8158                         }
8159                 }
8160                 lun->pr_res_type = msg->pr.pr_info.res_type;
8161                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8162                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8163                         lun->pr_res_idx = msg->pr.pr_info.residx;
8164                 else
8165                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8166         }
8167         lun->pr_generation++;
8168
8169 }
8170
8171
8172 int
8173 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8174 {
8175         int retval;
8176         u_int32_t param_len;
8177         struct scsi_per_res_out *cdb;
8178         struct ctl_lun *lun;
8179         struct scsi_per_res_out_parms* param;
8180         struct ctl_softc *softc;
8181         uint32_t residx;
8182         uint64_t res_key, sa_res_key, key;
8183         uint8_t type;
8184         union ctl_ha_msg persis_io;
8185         int    i;
8186
8187         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8188
8189         retval = CTL_RETVAL_COMPLETE;
8190
8191         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8192         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8193         softc = lun->ctl_softc;
8194
8195         /*
8196          * We only support whole-LUN scope.  The scope & type are ignored for
8197          * register, register and ignore existing key and clear.
8198          * We sometimes ignore scope and type on preempts too!!
8199          * Verify reservation type here as well.
8200          */
8201         type = cdb->scope_type & SPR_TYPE_MASK;
8202         if ((cdb->action == SPRO_RESERVE)
8203          || (cdb->action == SPRO_RELEASE)) {
8204                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8205                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8206                                               /*sks_valid*/ 1,
8207                                               /*command*/ 1,
8208                                               /*field*/ 2,
8209                                               /*bit_valid*/ 1,
8210                                               /*bit*/ 4);
8211                         ctl_done((union ctl_io *)ctsio);
8212                         return (CTL_RETVAL_COMPLETE);
8213                 }
8214
8215                 if (type>8 || type==2 || type==4 || type==0) {
8216                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8217                                               /*sks_valid*/ 1,
8218                                               /*command*/ 1,
8219                                               /*field*/ 2,
8220                                               /*bit_valid*/ 1,
8221                                               /*bit*/ 0);
8222                         ctl_done((union ctl_io *)ctsio);
8223                         return (CTL_RETVAL_COMPLETE);
8224                 }
8225         }
8226
8227         param_len = scsi_4btoul(cdb->length);
8228
8229         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8230                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8231                 ctsio->kern_data_len = param_len;
8232                 ctsio->kern_total_len = param_len;
8233                 ctsio->kern_data_resid = 0;
8234                 ctsio->kern_rel_offset = 0;
8235                 ctsio->kern_sg_entries = 0;
8236                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8237                 ctsio->be_move_done = ctl_config_move_done;
8238                 ctl_datamove((union ctl_io *)ctsio);
8239
8240                 return (CTL_RETVAL_COMPLETE);
8241         }
8242
8243         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8244
8245         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8246         res_key = scsi_8btou64(param->res_key.key);
8247         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8248
8249         /*
8250          * Validate the reservation key here except for SPRO_REG_IGNO
8251          * This must be done for all other service actions
8252          */
8253         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8254                 mtx_lock(&lun->lun_lock);
8255                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8256                         if (res_key != key) {
8257                                 /*
8258                                  * The current key passed in doesn't match
8259                                  * the one the initiator previously
8260                                  * registered.
8261                                  */
8262                                 mtx_unlock(&lun->lun_lock);
8263                                 free(ctsio->kern_data_ptr, M_CTL);
8264                                 ctl_set_reservation_conflict(ctsio);
8265                                 ctl_done((union ctl_io *)ctsio);
8266                                 return (CTL_RETVAL_COMPLETE);
8267                         }
8268                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8269                         /*
8270                          * We are not registered
8271                          */
8272                         mtx_unlock(&lun->lun_lock);
8273                         free(ctsio->kern_data_ptr, M_CTL);
8274                         ctl_set_reservation_conflict(ctsio);
8275                         ctl_done((union ctl_io *)ctsio);
8276                         return (CTL_RETVAL_COMPLETE);
8277                 } else if (res_key != 0) {
8278                         /*
8279                          * We are not registered and trying to register but
8280                          * the register key isn't zero.
8281                          */
8282                         mtx_unlock(&lun->lun_lock);
8283                         free(ctsio->kern_data_ptr, M_CTL);
8284                         ctl_set_reservation_conflict(ctsio);
8285                         ctl_done((union ctl_io *)ctsio);
8286                         return (CTL_RETVAL_COMPLETE);
8287                 }
8288                 mtx_unlock(&lun->lun_lock);
8289         }
8290
8291         switch (cdb->action & SPRO_ACTION_MASK) {
8292         case SPRO_REGISTER:
8293         case SPRO_REG_IGNO: {
8294
8295 #if 0
8296                 printf("Registration received\n");
8297 #endif
8298
8299                 /*
8300                  * We don't support any of these options, as we report in
8301                  * the read capabilities request (see
8302                  * ctl_persistent_reserve_in(), above).
8303                  */
8304                 if ((param->flags & SPR_SPEC_I_PT)
8305                  || (param->flags & SPR_ALL_TG_PT)
8306                  || (param->flags & SPR_APTPL)) {
8307                         int bit_ptr;
8308
8309                         if (param->flags & SPR_APTPL)
8310                                 bit_ptr = 0;
8311                         else if (param->flags & SPR_ALL_TG_PT)
8312                                 bit_ptr = 2;
8313                         else /* SPR_SPEC_I_PT */
8314                                 bit_ptr = 3;
8315
8316                         free(ctsio->kern_data_ptr, M_CTL);
8317                         ctl_set_invalid_field(ctsio,
8318                                               /*sks_valid*/ 1,
8319                                               /*command*/ 0,
8320                                               /*field*/ 20,
8321                                               /*bit_valid*/ 1,
8322                                               /*bit*/ bit_ptr);
8323                         ctl_done((union ctl_io *)ctsio);
8324                         return (CTL_RETVAL_COMPLETE);
8325                 }
8326
8327                 mtx_lock(&lun->lun_lock);
8328
8329                 /*
8330                  * The initiator wants to clear the
8331                  * key/unregister.
8332                  */
8333                 if (sa_res_key == 0) {
8334                         if ((res_key == 0
8335                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8336                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8337                           && ctl_get_prkey(lun, residx) == 0)) {
8338                                 mtx_unlock(&lun->lun_lock);
8339                                 goto done;
8340                         }
8341
8342                         ctl_clr_prkey(lun, residx);
8343                         lun->pr_key_count--;
8344
8345                         if (residx == lun->pr_res_idx) {
8346                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8347                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8348
8349                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8350                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8351                                     lun->pr_key_count) {
8352                                         /*
8353                                          * If the reservation is a registrants
8354                                          * only type we need to generate a UA
8355                                          * for other registered inits.  The
8356                                          * sense code should be RESERVATIONS
8357                                          * RELEASED
8358                                          */
8359
8360                                         for (i = softc->init_min; i < softc->init_max; i++){
8361                                                 if (ctl_get_prkey(lun, i) == 0)
8362                                                         continue;
8363                                                 ctl_est_ua(lun, i,
8364                                                     CTL_UA_RES_RELEASE);
8365                                         }
8366                                 }
8367                                 lun->pr_res_type = 0;
8368                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8369                                 if (lun->pr_key_count==0) {
8370                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8371                                         lun->pr_res_type = 0;
8372                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8373                                 }
8374                         }
8375                         lun->pr_generation++;
8376                         mtx_unlock(&lun->lun_lock);
8377
8378                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8379                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8380                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8381                         persis_io.pr.pr_info.residx = residx;
8382                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8383                             sizeof(persis_io.pr), M_WAITOK);
8384                 } else /* sa_res_key != 0 */ {
8385
8386                         /*
8387                          * If we aren't registered currently then increment
8388                          * the key count and set the registered flag.
8389                          */
8390                         ctl_alloc_prkey(lun, residx);
8391                         if (ctl_get_prkey(lun, residx) == 0)
8392                                 lun->pr_key_count++;
8393                         ctl_set_prkey(lun, residx, sa_res_key);
8394                         lun->pr_generation++;
8395                         mtx_unlock(&lun->lun_lock);
8396
8397                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8398                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8399                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8400                         persis_io.pr.pr_info.residx = residx;
8401                         memcpy(persis_io.pr.pr_info.sa_res_key,
8402                                param->serv_act_res_key,
8403                                sizeof(param->serv_act_res_key));
8404                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8405                             sizeof(persis_io.pr), M_WAITOK);
8406                 }
8407
8408                 break;
8409         }
8410         case SPRO_RESERVE:
8411 #if 0
8412                 printf("Reserve executed type %d\n", type);
8413 #endif
8414                 mtx_lock(&lun->lun_lock);
8415                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8416                         /*
8417                          * if this isn't the reservation holder and it's
8418                          * not a "all registrants" type or if the type is
8419                          * different then we have a conflict
8420                          */
8421                         if ((lun->pr_res_idx != residx
8422                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8423                          || lun->pr_res_type != type) {
8424                                 mtx_unlock(&lun->lun_lock);
8425                                 free(ctsio->kern_data_ptr, M_CTL);
8426                                 ctl_set_reservation_conflict(ctsio);
8427                                 ctl_done((union ctl_io *)ctsio);
8428                                 return (CTL_RETVAL_COMPLETE);
8429                         }
8430                         mtx_unlock(&lun->lun_lock);
8431                 } else /* create a reservation */ {
8432                         /*
8433                          * If it's not an "all registrants" type record
8434                          * reservation holder
8435                          */
8436                         if (type != SPR_TYPE_WR_EX_AR
8437                          && type != SPR_TYPE_EX_AC_AR)
8438                                 lun->pr_res_idx = residx; /* Res holder */
8439                         else
8440                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8441
8442                         lun->flags |= CTL_LUN_PR_RESERVED;
8443                         lun->pr_res_type = type;
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_RESERVE;
8451                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8452                         persis_io.pr.pr_info.res_type = type;
8453                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8454                             sizeof(persis_io.pr), M_WAITOK);
8455                 }
8456                 break;
8457
8458         case SPRO_RELEASE:
8459                 mtx_lock(&lun->lun_lock);
8460                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8461                         /* No reservation exists return good status */
8462                         mtx_unlock(&lun->lun_lock);
8463                         goto done;
8464                 }
8465                 /*
8466                  * Is this nexus a reservation holder?
8467                  */
8468                 if (lun->pr_res_idx != residx
8469                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8470                         /*
8471                          * not a res holder return good status but
8472                          * do nothing
8473                          */
8474                         mtx_unlock(&lun->lun_lock);
8475                         goto done;
8476                 }
8477
8478                 if (lun->pr_res_type != type) {
8479                         mtx_unlock(&lun->lun_lock);
8480                         free(ctsio->kern_data_ptr, M_CTL);
8481                         ctl_set_illegal_pr_release(ctsio);
8482                         ctl_done((union ctl_io *)ctsio);
8483                         return (CTL_RETVAL_COMPLETE);
8484                 }
8485
8486                 /* okay to release */
8487                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8488                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8489                 lun->pr_res_type = 0;
8490
8491                 /*
8492                  * if this isn't an exclusive access
8493                  * res generate UA for all other
8494                  * registrants.
8495                  */
8496                 if (type != SPR_TYPE_EX_AC
8497                  && type != SPR_TYPE_WR_EX) {
8498                         for (i = softc->init_min; i < softc->init_max; i++) {
8499                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8500                                         continue;
8501                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8502                         }
8503                 }
8504                 mtx_unlock(&lun->lun_lock);
8505
8506                 /* Send msg to other side */
8507                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8508                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8509                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8510                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8511                      sizeof(persis_io.pr), M_WAITOK);
8512                 break;
8513
8514         case SPRO_CLEAR:
8515                 /* send msg to other side */
8516
8517                 mtx_lock(&lun->lun_lock);
8518                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8519                 lun->pr_res_type = 0;
8520                 lun->pr_key_count = 0;
8521                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8522
8523                 ctl_clr_prkey(lun, residx);
8524                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8525                         if (ctl_get_prkey(lun, i) != 0) {
8526                                 ctl_clr_prkey(lun, i);
8527                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8528                         }
8529                 lun->pr_generation++;
8530                 mtx_unlock(&lun->lun_lock);
8531
8532                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8533                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8534                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8535                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8536                      sizeof(persis_io.pr), M_WAITOK);
8537                 break;
8538
8539         case SPRO_PREEMPT:
8540         case SPRO_PRE_ABO: {
8541                 int nretval;
8542
8543                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8544                                           residx, ctsio, cdb, param);
8545                 if (nretval != 0)
8546                         return (CTL_RETVAL_COMPLETE);
8547                 break;
8548         }
8549         default:
8550                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8551         }
8552
8553 done:
8554         free(ctsio->kern_data_ptr, M_CTL);
8555         ctl_set_success(ctsio);
8556         ctl_done((union ctl_io *)ctsio);
8557
8558         return (retval);
8559 }
8560
8561 /*
8562  * This routine is for handling a message from the other SC pertaining to
8563  * persistent reserve out. All the error checking will have been done
8564  * so only perorming the action need be done here to keep the two
8565  * in sync.
8566  */
8567 static void
8568 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8569 {
8570         struct ctl_softc *softc = control_softc;
8571         struct ctl_lun *lun;
8572         int i;
8573         uint32_t residx, targ_lun;
8574
8575         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8576         mtx_lock(&softc->ctl_lock);
8577         if ((targ_lun >= CTL_MAX_LUNS) ||
8578             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8579                 mtx_unlock(&softc->ctl_lock);
8580                 return;
8581         }
8582         mtx_lock(&lun->lun_lock);
8583         mtx_unlock(&softc->ctl_lock);
8584         if (lun->flags & CTL_LUN_DISABLED) {
8585                 mtx_unlock(&lun->lun_lock);
8586                 return;
8587         }
8588         residx = ctl_get_initindex(&msg->hdr.nexus);
8589         switch(msg->pr.pr_info.action) {
8590         case CTL_PR_REG_KEY:
8591                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8592                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8593                         lun->pr_key_count++;
8594                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8595                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8596                 lun->pr_generation++;
8597                 break;
8598
8599         case CTL_PR_UNREG_KEY:
8600                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8601                 lun->pr_key_count--;
8602
8603                 /* XXX Need to see if the reservation has been released */
8604                 /* if so do we need to generate UA? */
8605                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8606                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8607                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8608
8609                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8610                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8611                             lun->pr_key_count) {
8612                                 /*
8613                                  * If the reservation is a registrants
8614                                  * only type we need to generate a UA
8615                                  * for other registered inits.  The
8616                                  * sense code should be RESERVATIONS
8617                                  * RELEASED
8618                                  */
8619
8620                                 for (i = softc->init_min; i < softc->init_max; i++) {
8621                                         if (ctl_get_prkey(lun, i) == 0)
8622                                                 continue;
8623
8624                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8625                                 }
8626                         }
8627                         lun->pr_res_type = 0;
8628                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8629                         if (lun->pr_key_count==0) {
8630                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8631                                 lun->pr_res_type = 0;
8632                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8633                         }
8634                 }
8635                 lun->pr_generation++;
8636                 break;
8637
8638         case CTL_PR_RESERVE:
8639                 lun->flags |= CTL_LUN_PR_RESERVED;
8640                 lun->pr_res_type = msg->pr.pr_info.res_type;
8641                 lun->pr_res_idx = msg->pr.pr_info.residx;
8642
8643                 break;
8644
8645         case CTL_PR_RELEASE:
8646                 /*
8647                  * if this isn't an exclusive access res generate UA for all
8648                  * other registrants.
8649                  */
8650                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8651                     lun->pr_res_type != SPR_TYPE_WR_EX) {
8652                         for (i = softc->init_min; i < softc->init_max; i++)
8653                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8654                                         continue;
8655                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8656                 }
8657
8658                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8659                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8660                 lun->pr_res_type = 0;
8661                 break;
8662
8663         case CTL_PR_PREEMPT:
8664                 ctl_pro_preempt_other(lun, msg);
8665                 break;
8666         case CTL_PR_CLEAR:
8667                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8668                 lun->pr_res_type = 0;
8669                 lun->pr_key_count = 0;
8670                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8671
8672                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8673                         if (ctl_get_prkey(lun, i) == 0)
8674                                 continue;
8675                         ctl_clr_prkey(lun, i);
8676                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8677                 }
8678                 lun->pr_generation++;
8679                 break;
8680         }
8681
8682         mtx_unlock(&lun->lun_lock);
8683 }
8684
8685 int
8686 ctl_read_write(struct ctl_scsiio *ctsio)
8687 {
8688         struct ctl_lun *lun;
8689         struct ctl_lba_len_flags *lbalen;
8690         uint64_t lba;
8691         uint32_t num_blocks;
8692         int flags, retval;
8693         int isread;
8694
8695         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8696
8697         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8698
8699         flags = 0;
8700         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8701               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8702         switch (ctsio->cdb[0]) {
8703         case READ_6:
8704         case WRITE_6: {
8705                 struct scsi_rw_6 *cdb;
8706
8707                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8708
8709                 lba = scsi_3btoul(cdb->addr);
8710                 /* only 5 bits are valid in the most significant address byte */
8711                 lba &= 0x1fffff;
8712                 num_blocks = cdb->length;
8713                 /*
8714                  * This is correct according to SBC-2.
8715                  */
8716                 if (num_blocks == 0)
8717                         num_blocks = 256;
8718                 break;
8719         }
8720         case READ_10:
8721         case WRITE_10: {
8722                 struct scsi_rw_10 *cdb;
8723
8724                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8725                 if (cdb->byte2 & SRW10_FUA)
8726                         flags |= CTL_LLF_FUA;
8727                 if (cdb->byte2 & SRW10_DPO)
8728                         flags |= CTL_LLF_DPO;
8729                 lba = scsi_4btoul(cdb->addr);
8730                 num_blocks = scsi_2btoul(cdb->length);
8731                 break;
8732         }
8733         case WRITE_VERIFY_10: {
8734                 struct scsi_write_verify_10 *cdb;
8735
8736                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8737                 flags |= CTL_LLF_FUA;
8738                 if (cdb->byte2 & SWV_DPO)
8739                         flags |= CTL_LLF_DPO;
8740                 lba = scsi_4btoul(cdb->addr);
8741                 num_blocks = scsi_2btoul(cdb->length);
8742                 break;
8743         }
8744         case READ_12:
8745         case WRITE_12: {
8746                 struct scsi_rw_12 *cdb;
8747
8748                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8749                 if (cdb->byte2 & SRW12_FUA)
8750                         flags |= CTL_LLF_FUA;
8751                 if (cdb->byte2 & SRW12_DPO)
8752                         flags |= CTL_LLF_DPO;
8753                 lba = scsi_4btoul(cdb->addr);
8754                 num_blocks = scsi_4btoul(cdb->length);
8755                 break;
8756         }
8757         case WRITE_VERIFY_12: {
8758                 struct scsi_write_verify_12 *cdb;
8759
8760                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8761                 flags |= CTL_LLF_FUA;
8762                 if (cdb->byte2 & SWV_DPO)
8763                         flags |= CTL_LLF_DPO;
8764                 lba = scsi_4btoul(cdb->addr);
8765                 num_blocks = scsi_4btoul(cdb->length);
8766                 break;
8767         }
8768         case READ_16:
8769         case WRITE_16: {
8770                 struct scsi_rw_16 *cdb;
8771
8772                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8773                 if (cdb->byte2 & SRW12_FUA)
8774                         flags |= CTL_LLF_FUA;
8775                 if (cdb->byte2 & SRW12_DPO)
8776                         flags |= CTL_LLF_DPO;
8777                 lba = scsi_8btou64(cdb->addr);
8778                 num_blocks = scsi_4btoul(cdb->length);
8779                 break;
8780         }
8781         case WRITE_ATOMIC_16: {
8782                 struct scsi_write_atomic_16 *cdb;
8783
8784                 if (lun->be_lun->atomicblock == 0) {
8785                         ctl_set_invalid_opcode(ctsio);
8786                         ctl_done((union ctl_io *)ctsio);
8787                         return (CTL_RETVAL_COMPLETE);
8788                 }
8789
8790                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8791                 if (cdb->byte2 & SRW12_FUA)
8792                         flags |= CTL_LLF_FUA;
8793                 if (cdb->byte2 & SRW12_DPO)
8794                         flags |= CTL_LLF_DPO;
8795                 lba = scsi_8btou64(cdb->addr);
8796                 num_blocks = scsi_2btoul(cdb->length);
8797                 if (num_blocks > lun->be_lun->atomicblock) {
8798                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8799                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8800                             /*bit*/ 0);
8801                         ctl_done((union ctl_io *)ctsio);
8802                         return (CTL_RETVAL_COMPLETE);
8803                 }
8804                 break;
8805         }
8806         case WRITE_VERIFY_16: {
8807                 struct scsi_write_verify_16 *cdb;
8808
8809                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8810                 flags |= CTL_LLF_FUA;
8811                 if (cdb->byte2 & SWV_DPO)
8812                         flags |= CTL_LLF_DPO;
8813                 lba = scsi_8btou64(cdb->addr);
8814                 num_blocks = scsi_4btoul(cdb->length);
8815                 break;
8816         }
8817         default:
8818                 /*
8819                  * We got a command we don't support.  This shouldn't
8820                  * happen, commands should be filtered out above us.
8821                  */
8822                 ctl_set_invalid_opcode(ctsio);
8823                 ctl_done((union ctl_io *)ctsio);
8824
8825                 return (CTL_RETVAL_COMPLETE);
8826                 break; /* NOTREACHED */
8827         }
8828
8829         /*
8830          * The first check is to make sure we're in bounds, the second
8831          * check is to catch wrap-around problems.  If the lba + num blocks
8832          * is less than the lba, then we've wrapped around and the block
8833          * range is invalid anyway.
8834          */
8835         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8836          || ((lba + num_blocks) < lba)) {
8837                 ctl_set_lba_out_of_range(ctsio);
8838                 ctl_done((union ctl_io *)ctsio);
8839                 return (CTL_RETVAL_COMPLETE);
8840         }
8841
8842         /*
8843          * According to SBC-3, a transfer length of 0 is not an error.
8844          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8845          * translates to 256 blocks for those commands.
8846          */
8847         if (num_blocks == 0) {
8848                 ctl_set_success(ctsio);
8849                 ctl_done((union ctl_io *)ctsio);
8850                 return (CTL_RETVAL_COMPLETE);
8851         }
8852
8853         /* Set FUA and/or DPO if caches are disabled. */
8854         if (isread) {
8855                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8856                     SCP_RCD) != 0)
8857                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8858         } else {
8859                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8860                     SCP_WCE) == 0)
8861                         flags |= CTL_LLF_FUA;
8862         }
8863
8864         lbalen = (struct ctl_lba_len_flags *)
8865             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8866         lbalen->lba = lba;
8867         lbalen->len = num_blocks;
8868         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8869
8870         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8871         ctsio->kern_rel_offset = 0;
8872
8873         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8874
8875         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8876         return (retval);
8877 }
8878
8879 static int
8880 ctl_cnw_cont(union ctl_io *io)
8881 {
8882         struct ctl_scsiio *ctsio;
8883         struct ctl_lun *lun;
8884         struct ctl_lba_len_flags *lbalen;
8885         int retval;
8886
8887         ctsio = &io->scsiio;
8888         ctsio->io_hdr.status = CTL_STATUS_NONE;
8889         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8890         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8891         lbalen = (struct ctl_lba_len_flags *)
8892             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8893         lbalen->flags &= ~CTL_LLF_COMPARE;
8894         lbalen->flags |= CTL_LLF_WRITE;
8895
8896         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8897         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8898         return (retval);
8899 }
8900
8901 int
8902 ctl_cnw(struct ctl_scsiio *ctsio)
8903 {
8904         struct ctl_lun *lun;
8905         struct ctl_lba_len_flags *lbalen;
8906         uint64_t lba;
8907         uint32_t num_blocks;
8908         int flags, retval;
8909
8910         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8911
8912         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8913
8914         flags = 0;
8915         switch (ctsio->cdb[0]) {
8916         case COMPARE_AND_WRITE: {
8917                 struct scsi_compare_and_write *cdb;
8918
8919                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8920                 if (cdb->byte2 & SRW10_FUA)
8921                         flags |= CTL_LLF_FUA;
8922                 if (cdb->byte2 & SRW10_DPO)
8923                         flags |= CTL_LLF_DPO;
8924                 lba = scsi_8btou64(cdb->addr);
8925                 num_blocks = cdb->length;
8926                 break;
8927         }
8928         default:
8929                 /*
8930                  * We got a command we don't support.  This shouldn't
8931                  * happen, commands should be filtered out above us.
8932                  */
8933                 ctl_set_invalid_opcode(ctsio);
8934                 ctl_done((union ctl_io *)ctsio);
8935
8936                 return (CTL_RETVAL_COMPLETE);
8937                 break; /* NOTREACHED */
8938         }
8939
8940         /*
8941          * The first check is to make sure we're in bounds, the second
8942          * check is to catch wrap-around problems.  If the lba + num blocks
8943          * is less than the lba, then we've wrapped around and the block
8944          * range is invalid anyway.
8945          */
8946         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8947          || ((lba + num_blocks) < lba)) {
8948                 ctl_set_lba_out_of_range(ctsio);
8949                 ctl_done((union ctl_io *)ctsio);
8950                 return (CTL_RETVAL_COMPLETE);
8951         }
8952
8953         /*
8954          * According to SBC-3, a transfer length of 0 is not an error.
8955          */
8956         if (num_blocks == 0) {
8957                 ctl_set_success(ctsio);
8958                 ctl_done((union ctl_io *)ctsio);
8959                 return (CTL_RETVAL_COMPLETE);
8960         }
8961
8962         /* Set FUA if write cache is disabled. */
8963         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8964             SCP_WCE) == 0)
8965                 flags |= CTL_LLF_FUA;
8966
8967         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8968         ctsio->kern_rel_offset = 0;
8969
8970         /*
8971          * Set the IO_CONT flag, so that if this I/O gets passed to
8972          * ctl_data_submit_done(), it'll get passed back to
8973          * ctl_ctl_cnw_cont() for further processing.
8974          */
8975         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8976         ctsio->io_cont = ctl_cnw_cont;
8977
8978         lbalen = (struct ctl_lba_len_flags *)
8979             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8980         lbalen->lba = lba;
8981         lbalen->len = num_blocks;
8982         lbalen->flags = CTL_LLF_COMPARE | flags;
8983
8984         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8985         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8986         return (retval);
8987 }
8988
8989 int
8990 ctl_verify(struct ctl_scsiio *ctsio)
8991 {
8992         struct ctl_lun *lun;
8993         struct ctl_lba_len_flags *lbalen;
8994         uint64_t lba;
8995         uint32_t num_blocks;
8996         int bytchk, flags;
8997         int retval;
8998
8999         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9000
9001         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9002
9003         bytchk = 0;
9004         flags = CTL_LLF_FUA;
9005         switch (ctsio->cdb[0]) {
9006         case VERIFY_10: {
9007                 struct scsi_verify_10 *cdb;
9008
9009                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9010                 if (cdb->byte2 & SVFY_BYTCHK)
9011                         bytchk = 1;
9012                 if (cdb->byte2 & SVFY_DPO)
9013                         flags |= CTL_LLF_DPO;
9014                 lba = scsi_4btoul(cdb->addr);
9015                 num_blocks = scsi_2btoul(cdb->length);
9016                 break;
9017         }
9018         case VERIFY_12: {
9019                 struct scsi_verify_12 *cdb;
9020
9021                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9022                 if (cdb->byte2 & SVFY_BYTCHK)
9023                         bytchk = 1;
9024                 if (cdb->byte2 & SVFY_DPO)
9025                         flags |= CTL_LLF_DPO;
9026                 lba = scsi_4btoul(cdb->addr);
9027                 num_blocks = scsi_4btoul(cdb->length);
9028                 break;
9029         }
9030         case VERIFY_16: {
9031                 struct scsi_rw_16 *cdb;
9032
9033                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9034                 if (cdb->byte2 & SVFY_BYTCHK)
9035                         bytchk = 1;
9036                 if (cdb->byte2 & SVFY_DPO)
9037                         flags |= CTL_LLF_DPO;
9038                 lba = scsi_8btou64(cdb->addr);
9039                 num_blocks = scsi_4btoul(cdb->length);
9040                 break;
9041         }
9042         default:
9043                 /*
9044                  * We got a command we don't support.  This shouldn't
9045                  * happen, commands should be filtered out above us.
9046                  */
9047                 ctl_set_invalid_opcode(ctsio);
9048                 ctl_done((union ctl_io *)ctsio);
9049                 return (CTL_RETVAL_COMPLETE);
9050         }
9051
9052         /*
9053          * The first check is to make sure we're in bounds, the second
9054          * check is to catch wrap-around problems.  If the lba + num blocks
9055          * is less than the lba, then we've wrapped around and the block
9056          * range is invalid anyway.
9057          */
9058         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9059          || ((lba + num_blocks) < lba)) {
9060                 ctl_set_lba_out_of_range(ctsio);
9061                 ctl_done((union ctl_io *)ctsio);
9062                 return (CTL_RETVAL_COMPLETE);
9063         }
9064
9065         /*
9066          * According to SBC-3, a transfer length of 0 is not an error.
9067          */
9068         if (num_blocks == 0) {
9069                 ctl_set_success(ctsio);
9070                 ctl_done((union ctl_io *)ctsio);
9071                 return (CTL_RETVAL_COMPLETE);
9072         }
9073
9074         lbalen = (struct ctl_lba_len_flags *)
9075             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9076         lbalen->lba = lba;
9077         lbalen->len = num_blocks;
9078         if (bytchk) {
9079                 lbalen->flags = CTL_LLF_COMPARE | flags;
9080                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9081         } else {
9082                 lbalen->flags = CTL_LLF_VERIFY | flags;
9083                 ctsio->kern_total_len = 0;
9084         }
9085         ctsio->kern_rel_offset = 0;
9086
9087         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9088         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9089         return (retval);
9090 }
9091
9092 int
9093 ctl_report_luns(struct ctl_scsiio *ctsio)
9094 {
9095         struct ctl_softc *softc;
9096         struct scsi_report_luns *cdb;
9097         struct scsi_report_luns_data *lun_data;
9098         struct ctl_lun *lun, *request_lun;
9099         struct ctl_port *port;
9100         int num_luns, retval;
9101         uint32_t alloc_len, lun_datalen;
9102         int num_filled;
9103         uint32_t initidx, targ_lun_id, lun_id;
9104
9105         retval = CTL_RETVAL_COMPLETE;
9106         cdb = (struct scsi_report_luns *)ctsio->cdb;
9107         port = ctl_io_port(&ctsio->io_hdr);
9108         softc = port->ctl_softc;
9109
9110         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9111
9112         mtx_lock(&softc->ctl_lock);
9113         num_luns = 0;
9114         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9115                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9116                         num_luns++;
9117         }
9118         mtx_unlock(&softc->ctl_lock);
9119
9120         switch (cdb->select_report) {
9121         case RPL_REPORT_DEFAULT:
9122         case RPL_REPORT_ALL:
9123         case RPL_REPORT_NONSUBSID:
9124                 break;
9125         case RPL_REPORT_WELLKNOWN:
9126         case RPL_REPORT_ADMIN:
9127         case RPL_REPORT_CONGLOM:
9128                 num_luns = 0;
9129                 break;
9130         default:
9131                 ctl_set_invalid_field(ctsio,
9132                                       /*sks_valid*/ 1,
9133                                       /*command*/ 1,
9134                                       /*field*/ 2,
9135                                       /*bit_valid*/ 0,
9136                                       /*bit*/ 0);
9137                 ctl_done((union ctl_io *)ctsio);
9138                 return (retval);
9139                 break; /* NOTREACHED */
9140         }
9141
9142         alloc_len = scsi_4btoul(cdb->length);
9143         /*
9144          * The initiator has to allocate at least 16 bytes for this request,
9145          * so he can at least get the header and the first LUN.  Otherwise
9146          * we reject the request (per SPC-3 rev 14, section 6.21).
9147          */
9148         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9149             sizeof(struct scsi_report_luns_lundata))) {
9150                 ctl_set_invalid_field(ctsio,
9151                                       /*sks_valid*/ 1,
9152                                       /*command*/ 1,
9153                                       /*field*/ 6,
9154                                       /*bit_valid*/ 0,
9155                                       /*bit*/ 0);
9156                 ctl_done((union ctl_io *)ctsio);
9157                 return (retval);
9158         }
9159
9160         request_lun = (struct ctl_lun *)
9161                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9162
9163         lun_datalen = sizeof(*lun_data) +
9164                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9165
9166         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9167         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9168         ctsio->kern_sg_entries = 0;
9169
9170         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9171
9172         mtx_lock(&softc->ctl_lock);
9173         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9174                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9175                 if (lun_id >= CTL_MAX_LUNS)
9176                         continue;
9177                 lun = softc->ctl_luns[lun_id];
9178                 if (lun == NULL)
9179                         continue;
9180
9181                 be64enc(lun_data->luns[num_filled++].lundata,
9182                     ctl_encode_lun(targ_lun_id));
9183
9184                 /*
9185                  * According to SPC-3, rev 14 section 6.21:
9186                  *
9187                  * "The execution of a REPORT LUNS command to any valid and
9188                  * installed logical unit shall clear the REPORTED LUNS DATA
9189                  * HAS CHANGED unit attention condition for all logical
9190                  * units of that target with respect to the requesting
9191                  * initiator. A valid and installed logical unit is one
9192                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9193                  * INQUIRY data (see 6.4.2)."
9194                  *
9195                  * If request_lun is NULL, the LUN this report luns command
9196                  * was issued to is either disabled or doesn't exist. In that
9197                  * case, we shouldn't clear any pending lun change unit
9198                  * attention.
9199                  */
9200                 if (request_lun != NULL) {
9201                         mtx_lock(&lun->lun_lock);
9202                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9203                         mtx_unlock(&lun->lun_lock);
9204                 }
9205         }
9206         mtx_unlock(&softc->ctl_lock);
9207
9208         /*
9209          * It's quite possible that we've returned fewer LUNs than we allocated
9210          * space for.  Trim it.
9211          */
9212         lun_datalen = sizeof(*lun_data) +
9213                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9214
9215         if (lun_datalen < alloc_len) {
9216                 ctsio->residual = alloc_len - lun_datalen;
9217                 ctsio->kern_data_len = lun_datalen;
9218                 ctsio->kern_total_len = lun_datalen;
9219         } else {
9220                 ctsio->residual = 0;
9221                 ctsio->kern_data_len = alloc_len;
9222                 ctsio->kern_total_len = alloc_len;
9223         }
9224         ctsio->kern_data_resid = 0;
9225         ctsio->kern_rel_offset = 0;
9226         ctsio->kern_sg_entries = 0;
9227
9228         /*
9229          * We set this to the actual data length, regardless of how much
9230          * space we actually have to return results.  If the user looks at
9231          * this value, he'll know whether or not he allocated enough space
9232          * and reissue the command if necessary.  We don't support well
9233          * known logical units, so if the user asks for that, return none.
9234          */
9235         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9236
9237         /*
9238          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9239          * this request.
9240          */
9241         ctl_set_success(ctsio);
9242         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9243         ctsio->be_move_done = ctl_config_move_done;
9244         ctl_datamove((union ctl_io *)ctsio);
9245         return (retval);
9246 }
9247
9248 int
9249 ctl_request_sense(struct ctl_scsiio *ctsio)
9250 {
9251         struct scsi_request_sense *cdb;
9252         struct scsi_sense_data *sense_ptr;
9253         struct ctl_softc *ctl_softc;
9254         struct ctl_lun *lun;
9255         uint32_t initidx;
9256         int have_error;
9257         scsi_sense_data_type sense_format;
9258         ctl_ua_type ua_type;
9259
9260         cdb = (struct scsi_request_sense *)ctsio->cdb;
9261
9262         ctl_softc = control_softc;
9263         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9264
9265         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9266
9267         /*
9268          * Determine which sense format the user wants.
9269          */
9270         if (cdb->byte2 & SRS_DESC)
9271                 sense_format = SSD_TYPE_DESC;
9272         else
9273                 sense_format = SSD_TYPE_FIXED;
9274
9275         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9276         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9277         ctsio->kern_sg_entries = 0;
9278
9279         /*
9280          * struct scsi_sense_data, which is currently set to 256 bytes, is
9281          * larger than the largest allowed value for the length field in the
9282          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9283          */
9284         ctsio->residual = 0;
9285         ctsio->kern_data_len = cdb->length;
9286         ctsio->kern_total_len = cdb->length;
9287
9288         ctsio->kern_data_resid = 0;
9289         ctsio->kern_rel_offset = 0;
9290         ctsio->kern_sg_entries = 0;
9291
9292         /*
9293          * If we don't have a LUN, we don't have any pending sense.
9294          */
9295         if (lun == NULL)
9296                 goto no_sense;
9297
9298         have_error = 0;
9299         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9300         /*
9301          * Check for pending sense, and then for pending unit attentions.
9302          * Pending sense gets returned first, then pending unit attentions.
9303          */
9304         mtx_lock(&lun->lun_lock);
9305 #ifdef CTL_WITH_CA
9306         if (ctl_is_set(lun->have_ca, initidx)) {
9307                 scsi_sense_data_type stored_format;
9308
9309                 /*
9310                  * Check to see which sense format was used for the stored
9311                  * sense data.
9312                  */
9313                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9314
9315                 /*
9316                  * If the user requested a different sense format than the
9317                  * one we stored, then we need to convert it to the other
9318                  * format.  If we're going from descriptor to fixed format
9319                  * sense data, we may lose things in translation, depending
9320                  * on what options were used.
9321                  *
9322                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9323                  * for some reason we'll just copy it out as-is.
9324                  */
9325                 if ((stored_format == SSD_TYPE_FIXED)
9326                  && (sense_format == SSD_TYPE_DESC))
9327                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9328                             &lun->pending_sense[initidx],
9329                             (struct scsi_sense_data_desc *)sense_ptr);
9330                 else if ((stored_format == SSD_TYPE_DESC)
9331                       && (sense_format == SSD_TYPE_FIXED))
9332                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9333                             &lun->pending_sense[initidx],
9334                             (struct scsi_sense_data_fixed *)sense_ptr);
9335                 else
9336                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9337                                MIN(sizeof(*sense_ptr),
9338                                sizeof(lun->pending_sense[initidx])));
9339
9340                 ctl_clear_mask(lun->have_ca, initidx);
9341                 have_error = 1;
9342         } else
9343 #endif
9344         {
9345                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9346                 if (ua_type != CTL_UA_NONE)
9347                         have_error = 1;
9348                 if (ua_type == CTL_UA_LUN_CHANGE) {
9349                         mtx_unlock(&lun->lun_lock);
9350                         mtx_lock(&ctl_softc->ctl_lock);
9351                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9352                         mtx_unlock(&ctl_softc->ctl_lock);
9353                         mtx_lock(&lun->lun_lock);
9354                 }
9355
9356         }
9357         mtx_unlock(&lun->lun_lock);
9358
9359         /*
9360          * We already have a pending error, return it.
9361          */
9362         if (have_error != 0) {
9363                 /*
9364                  * We report the SCSI status as OK, since the status of the
9365                  * request sense command itself is OK.
9366                  * We report 0 for the sense length, because we aren't doing
9367                  * autosense in this case.  We're reporting sense as
9368                  * parameter data.
9369                  */
9370                 ctl_set_success(ctsio);
9371                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9372                 ctsio->be_move_done = ctl_config_move_done;
9373                 ctl_datamove((union ctl_io *)ctsio);
9374                 return (CTL_RETVAL_COMPLETE);
9375         }
9376
9377 no_sense:
9378
9379         /*
9380          * No sense information to report, so we report that everything is
9381          * okay.
9382          */
9383         ctl_set_sense_data(sense_ptr,
9384                            lun,
9385                            sense_format,
9386                            /*current_error*/ 1,
9387                            /*sense_key*/ SSD_KEY_NO_SENSE,
9388                            /*asc*/ 0x00,
9389                            /*ascq*/ 0x00,
9390                            SSD_ELEM_NONE);
9391
9392         /*
9393          * We report 0 for the sense length, because we aren't doing
9394          * autosense in this case.  We're reporting sense as parameter data.
9395          */
9396         ctl_set_success(ctsio);
9397         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9398         ctsio->be_move_done = ctl_config_move_done;
9399         ctl_datamove((union ctl_io *)ctsio);
9400         return (CTL_RETVAL_COMPLETE);
9401 }
9402
9403 int
9404 ctl_tur(struct ctl_scsiio *ctsio)
9405 {
9406
9407         CTL_DEBUG_PRINT(("ctl_tur\n"));
9408
9409         ctl_set_success(ctsio);
9410         ctl_done((union ctl_io *)ctsio);
9411
9412         return (CTL_RETVAL_COMPLETE);
9413 }
9414
9415 /*
9416  * SCSI VPD page 0x00, the Supported VPD Pages page.
9417  */
9418 static int
9419 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9420 {
9421         struct scsi_vpd_supported_pages *pages;
9422         int sup_page_size;
9423         struct ctl_lun *lun;
9424         int p;
9425
9426         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9427
9428         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9429             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9430         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9431         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9432         ctsio->kern_sg_entries = 0;
9433
9434         if (sup_page_size < alloc_len) {
9435                 ctsio->residual = alloc_len - sup_page_size;
9436                 ctsio->kern_data_len = sup_page_size;
9437                 ctsio->kern_total_len = sup_page_size;
9438         } else {
9439                 ctsio->residual = 0;
9440                 ctsio->kern_data_len = alloc_len;
9441                 ctsio->kern_total_len = alloc_len;
9442         }
9443         ctsio->kern_data_resid = 0;
9444         ctsio->kern_rel_offset = 0;
9445         ctsio->kern_sg_entries = 0;
9446
9447         /*
9448          * The control device is always connected.  The disk device, on the
9449          * other hand, may not be online all the time.  Need to change this
9450          * to figure out whether the disk device is actually online or not.
9451          */
9452         if (lun != NULL)
9453                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9454                                 lun->be_lun->lun_type;
9455         else
9456                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9457
9458         p = 0;
9459         /* Supported VPD pages */
9460         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9461         /* Serial Number */
9462         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9463         /* Device Identification */
9464         pages->page_list[p++] = SVPD_DEVICE_ID;
9465         /* Extended INQUIRY Data */
9466         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9467         /* Mode Page Policy */
9468         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9469         /* SCSI Ports */
9470         pages->page_list[p++] = SVPD_SCSI_PORTS;
9471         /* Third-party Copy */
9472         pages->page_list[p++] = SVPD_SCSI_TPC;
9473         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9474                 /* Block limits */
9475                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9476                 /* Block Device Characteristics */
9477                 pages->page_list[p++] = SVPD_BDC;
9478                 /* Logical Block Provisioning */
9479                 pages->page_list[p++] = SVPD_LBP;
9480         }
9481         pages->length = p;
9482
9483         ctl_set_success(ctsio);
9484         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9485         ctsio->be_move_done = ctl_config_move_done;
9486         ctl_datamove((union ctl_io *)ctsio);
9487         return (CTL_RETVAL_COMPLETE);
9488 }
9489
9490 /*
9491  * SCSI VPD page 0x80, the Unit Serial Number page.
9492  */
9493 static int
9494 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9495 {
9496         struct scsi_vpd_unit_serial_number *sn_ptr;
9497         struct ctl_lun *lun;
9498         int data_len;
9499
9500         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9501
9502         data_len = 4 + CTL_SN_LEN;
9503         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9504         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9505         if (data_len < alloc_len) {
9506                 ctsio->residual = alloc_len - data_len;
9507                 ctsio->kern_data_len = data_len;
9508                 ctsio->kern_total_len = data_len;
9509         } else {
9510                 ctsio->residual = 0;
9511                 ctsio->kern_data_len = alloc_len;
9512                 ctsio->kern_total_len = alloc_len;
9513         }
9514         ctsio->kern_data_resid = 0;
9515         ctsio->kern_rel_offset = 0;
9516         ctsio->kern_sg_entries = 0;
9517
9518         /*
9519          * The control device is always connected.  The disk device, on the
9520          * other hand, may not be online all the time.  Need to change this
9521          * to figure out whether the disk device is actually online or not.
9522          */
9523         if (lun != NULL)
9524                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9525                                   lun->be_lun->lun_type;
9526         else
9527                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9528
9529         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9530         sn_ptr->length = CTL_SN_LEN;
9531         /*
9532          * If we don't have a LUN, we just leave the serial number as
9533          * all spaces.
9534          */
9535         if (lun != NULL) {
9536                 strncpy((char *)sn_ptr->serial_num,
9537                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9538         } else
9539                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9540
9541         ctl_set_success(ctsio);
9542         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9543         ctsio->be_move_done = ctl_config_move_done;
9544         ctl_datamove((union ctl_io *)ctsio);
9545         return (CTL_RETVAL_COMPLETE);
9546 }
9547
9548
9549 /*
9550  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9551  */
9552 static int
9553 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9554 {
9555         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9556         struct ctl_lun *lun;
9557         int data_len;
9558
9559         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9560
9561         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9562         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9563         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9564         ctsio->kern_sg_entries = 0;
9565
9566         if (data_len < alloc_len) {
9567                 ctsio->residual = alloc_len - data_len;
9568                 ctsio->kern_data_len = data_len;
9569                 ctsio->kern_total_len = data_len;
9570         } else {
9571                 ctsio->residual = 0;
9572                 ctsio->kern_data_len = alloc_len;
9573                 ctsio->kern_total_len = alloc_len;
9574         }
9575         ctsio->kern_data_resid = 0;
9576         ctsio->kern_rel_offset = 0;
9577         ctsio->kern_sg_entries = 0;
9578
9579         /*
9580          * The control device is always connected.  The disk device, on the
9581          * other hand, may not be online all the time.
9582          */
9583         if (lun != NULL)
9584                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9585                                      lun->be_lun->lun_type;
9586         else
9587                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9588         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9589         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9590         /*
9591          * We support head of queue, ordered and simple tags.
9592          */
9593         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9594         /*
9595          * Volatile cache supported.
9596          */
9597         eid_ptr->flags3 = SVPD_EID_V_SUP;
9598
9599         /*
9600          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9601          * attention for a particular IT nexus on all LUNs once we report
9602          * it to that nexus once.  This bit is required as of SPC-4.
9603          */
9604         eid_ptr->flags4 = SVPD_EID_LUICLT;
9605
9606         /*
9607          * XXX KDM in order to correctly answer this, we would need
9608          * information from the SIM to determine how much sense data it
9609          * can send.  So this would really be a path inquiry field, most
9610          * likely.  This can be set to a maximum of 252 according to SPC-4,
9611          * but the hardware may or may not be able to support that much.
9612          * 0 just means that the maximum sense data length is not reported.
9613          */
9614         eid_ptr->max_sense_length = 0;
9615
9616         ctl_set_success(ctsio);
9617         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9618         ctsio->be_move_done = ctl_config_move_done;
9619         ctl_datamove((union ctl_io *)ctsio);
9620         return (CTL_RETVAL_COMPLETE);
9621 }
9622
9623 static int
9624 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9625 {
9626         struct scsi_vpd_mode_page_policy *mpp_ptr;
9627         struct ctl_lun *lun;
9628         int data_len;
9629
9630         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9631
9632         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9633             sizeof(struct scsi_vpd_mode_page_policy_descr);
9634
9635         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9636         mpp_ptr = (struct scsi_vpd_mode_page_policy *)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                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9658                                      lun->be_lun->lun_type;
9659         else
9660                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9661         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9662         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9663         mpp_ptr->descr[0].page_code = 0x3f;
9664         mpp_ptr->descr[0].subpage_code = 0xff;
9665         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9666
9667         ctl_set_success(ctsio);
9668         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9669         ctsio->be_move_done = ctl_config_move_done;
9670         ctl_datamove((union ctl_io *)ctsio);
9671         return (CTL_RETVAL_COMPLETE);
9672 }
9673
9674 /*
9675  * SCSI VPD page 0x83, the Device Identification page.
9676  */
9677 static int
9678 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9679 {
9680         struct scsi_vpd_device_id *devid_ptr;
9681         struct scsi_vpd_id_descriptor *desc;
9682         struct ctl_softc *softc;
9683         struct ctl_lun *lun;
9684         struct ctl_port *port;
9685         int data_len, g;
9686         uint8_t proto;
9687
9688         softc = control_softc;
9689
9690         port = ctl_io_port(&ctsio->io_hdr);
9691         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9692
9693         data_len = sizeof(struct scsi_vpd_device_id) +
9694             sizeof(struct scsi_vpd_id_descriptor) +
9695                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9696             sizeof(struct scsi_vpd_id_descriptor) +
9697                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9698         if (lun && lun->lun_devid)
9699                 data_len += lun->lun_devid->len;
9700         if (port && port->port_devid)
9701                 data_len += port->port_devid->len;
9702         if (port && port->target_devid)
9703                 data_len += port->target_devid->len;
9704
9705         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9706         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9707         ctsio->kern_sg_entries = 0;
9708
9709         if (data_len < alloc_len) {
9710                 ctsio->residual = alloc_len - data_len;
9711                 ctsio->kern_data_len = data_len;
9712                 ctsio->kern_total_len = data_len;
9713         } else {
9714                 ctsio->residual = 0;
9715                 ctsio->kern_data_len = alloc_len;
9716                 ctsio->kern_total_len = alloc_len;
9717         }
9718         ctsio->kern_data_resid = 0;
9719         ctsio->kern_rel_offset = 0;
9720         ctsio->kern_sg_entries = 0;
9721
9722         /*
9723          * The control device is always connected.  The disk device, on the
9724          * other hand, may not be online all the time.
9725          */
9726         if (lun != NULL)
9727                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9728                                      lun->be_lun->lun_type;
9729         else
9730                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9731         devid_ptr->page_code = SVPD_DEVICE_ID;
9732         scsi_ulto2b(data_len - 4, devid_ptr->length);
9733
9734         if (port && port->port_type == CTL_PORT_FC)
9735                 proto = SCSI_PROTO_FC << 4;
9736         else if (port && port->port_type == CTL_PORT_ISCSI)
9737                 proto = SCSI_PROTO_ISCSI << 4;
9738         else
9739                 proto = SCSI_PROTO_SPI << 4;
9740         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9741
9742         /*
9743          * We're using a LUN association here.  i.e., this device ID is a
9744          * per-LUN identifier.
9745          */
9746         if (lun && lun->lun_devid) {
9747                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9748                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9749                     lun->lun_devid->len);
9750         }
9751
9752         /*
9753          * This is for the WWPN which is a port association.
9754          */
9755         if (port && port->port_devid) {
9756                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9757                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9758                     port->port_devid->len);
9759         }
9760
9761         /*
9762          * This is for the Relative Target Port(type 4h) identifier
9763          */
9764         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9765         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9766             SVPD_ID_TYPE_RELTARG;
9767         desc->length = 4;
9768         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9769         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9770             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9771
9772         /*
9773          * This is for the Target Port Group(type 5h) identifier
9774          */
9775         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9776         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9777             SVPD_ID_TYPE_TPORTGRP;
9778         desc->length = 4;
9779         if (softc->is_single ||
9780             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9781                 g = 1;
9782         else
9783                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9784         scsi_ulto2b(g, &desc->identifier[2]);
9785         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9786             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9787
9788         /*
9789          * This is for the Target identifier
9790          */
9791         if (port && port->target_devid) {
9792                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9793         }
9794
9795         ctl_set_success(ctsio);
9796         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9797         ctsio->be_move_done = ctl_config_move_done;
9798         ctl_datamove((union ctl_io *)ctsio);
9799         return (CTL_RETVAL_COMPLETE);
9800 }
9801
9802 static int
9803 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9804 {
9805         struct ctl_softc *softc = control_softc;
9806         struct scsi_vpd_scsi_ports *sp;
9807         struct scsi_vpd_port_designation *pd;
9808         struct scsi_vpd_port_designation_cont *pdc;
9809         struct ctl_lun *lun;
9810         struct ctl_port *port;
9811         int data_len, num_target_ports, iid_len, id_len;
9812
9813         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9814
9815         num_target_ports = 0;
9816         iid_len = 0;
9817         id_len = 0;
9818         mtx_lock(&softc->ctl_lock);
9819         STAILQ_FOREACH(port, &softc->port_list, links) {
9820                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9821                         continue;
9822                 if (lun != NULL &&
9823                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9824                         continue;
9825                 num_target_ports++;
9826                 if (port->init_devid)
9827                         iid_len += port->init_devid->len;
9828                 if (port->port_devid)
9829                         id_len += port->port_devid->len;
9830         }
9831         mtx_unlock(&softc->ctl_lock);
9832
9833         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9834             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9835              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9836         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9837         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9838         ctsio->kern_sg_entries = 0;
9839
9840         if (data_len < alloc_len) {
9841                 ctsio->residual = alloc_len - data_len;
9842                 ctsio->kern_data_len = data_len;
9843                 ctsio->kern_total_len = data_len;
9844         } else {
9845                 ctsio->residual = 0;
9846                 ctsio->kern_data_len = alloc_len;
9847                 ctsio->kern_total_len = alloc_len;
9848         }
9849         ctsio->kern_data_resid = 0;
9850         ctsio->kern_rel_offset = 0;
9851         ctsio->kern_sg_entries = 0;
9852
9853         /*
9854          * The control device is always connected.  The disk device, on the
9855          * other hand, may not be online all the time.  Need to change this
9856          * to figure out whether the disk device is actually online or not.
9857          */
9858         if (lun != NULL)
9859                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9860                                   lun->be_lun->lun_type;
9861         else
9862                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9863
9864         sp->page_code = SVPD_SCSI_PORTS;
9865         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9866             sp->page_length);
9867         pd = &sp->design[0];
9868
9869         mtx_lock(&softc->ctl_lock);
9870         STAILQ_FOREACH(port, &softc->port_list, links) {
9871                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9872                         continue;
9873                 if (lun != NULL &&
9874                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9875                         continue;
9876                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9877                 if (port->init_devid) {
9878                         iid_len = port->init_devid->len;
9879                         memcpy(pd->initiator_transportid,
9880                             port->init_devid->data, port->init_devid->len);
9881                 } else
9882                         iid_len = 0;
9883                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9884                 pdc = (struct scsi_vpd_port_designation_cont *)
9885                     (&pd->initiator_transportid[iid_len]);
9886                 if (port->port_devid) {
9887                         id_len = port->port_devid->len;
9888                         memcpy(pdc->target_port_descriptors,
9889                             port->port_devid->data, port->port_devid->len);
9890                 } else
9891                         id_len = 0;
9892                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9893                 pd = (struct scsi_vpd_port_designation *)
9894                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9895         }
9896         mtx_unlock(&softc->ctl_lock);
9897
9898         ctl_set_success(ctsio);
9899         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9900         ctsio->be_move_done = ctl_config_move_done;
9901         ctl_datamove((union ctl_io *)ctsio);
9902         return (CTL_RETVAL_COMPLETE);
9903 }
9904
9905 static int
9906 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9907 {
9908         struct scsi_vpd_block_limits *bl_ptr;
9909         struct ctl_lun *lun;
9910         uint64_t ival;
9911
9912         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9913
9914         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9915         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9916         ctsio->kern_sg_entries = 0;
9917
9918         if (sizeof(*bl_ptr) < alloc_len) {
9919                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9920                 ctsio->kern_data_len = sizeof(*bl_ptr);
9921                 ctsio->kern_total_len = sizeof(*bl_ptr);
9922         } else {
9923                 ctsio->residual = 0;
9924                 ctsio->kern_data_len = alloc_len;
9925                 ctsio->kern_total_len = alloc_len;
9926         }
9927         ctsio->kern_data_resid = 0;
9928         ctsio->kern_rel_offset = 0;
9929         ctsio->kern_sg_entries = 0;
9930
9931         /*
9932          * The control device is always connected.  The disk device, on the
9933          * other hand, may not be online all the time.  Need to change this
9934          * to figure out whether the disk device is actually online or not.
9935          */
9936         if (lun != NULL)
9937                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9938                                   lun->be_lun->lun_type;
9939         else
9940                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9941
9942         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9943         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9944         bl_ptr->max_cmp_write_len = 0xff;
9945         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9946         if (lun != NULL) {
9947                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9948                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9949                         ival = 0xffffffff;
9950                         ctl_get_opt_number(&lun->be_lun->options,
9951                             "unmap_max_lba", &ival);
9952                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9953                         ival = 0xffffffff;
9954                         ctl_get_opt_number(&lun->be_lun->options,
9955                             "unmap_max_descr", &ival);
9956                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9957                         if (lun->be_lun->ublockexp != 0) {
9958                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9959                                     bl_ptr->opt_unmap_grain);
9960                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9961                                     bl_ptr->unmap_grain_align);
9962                         }
9963                 }
9964                 scsi_ulto4b(lun->be_lun->atomicblock,
9965                     bl_ptr->max_atomic_transfer_length);
9966                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9967                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9968                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9969                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9970                 ival = UINT64_MAX;
9971                 ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9972                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9973         }
9974
9975         ctl_set_success(ctsio);
9976         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9977         ctsio->be_move_done = ctl_config_move_done;
9978         ctl_datamove((union ctl_io *)ctsio);
9979         return (CTL_RETVAL_COMPLETE);
9980 }
9981
9982 static int
9983 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9984 {
9985         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9986         struct ctl_lun *lun;
9987         const char *value;
9988         u_int i;
9989
9990         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9991
9992         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9993         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9994         ctsio->kern_sg_entries = 0;
9995
9996         if (sizeof(*bdc_ptr) < alloc_len) {
9997                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9998                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9999                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10000         } else {
10001                 ctsio->residual = 0;
10002                 ctsio->kern_data_len = alloc_len;
10003                 ctsio->kern_total_len = alloc_len;
10004         }
10005         ctsio->kern_data_resid = 0;
10006         ctsio->kern_rel_offset = 0;
10007         ctsio->kern_sg_entries = 0;
10008
10009         /*
10010          * The control device is always connected.  The disk device, on the
10011          * other hand, may not be online all the time.  Need to change this
10012          * to figure out whether the disk device is actually online or not.
10013          */
10014         if (lun != NULL)
10015                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10016                                   lun->be_lun->lun_type;
10017         else
10018                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10019         bdc_ptr->page_code = SVPD_BDC;
10020         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10021         if (lun != NULL &&
10022             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10023                 i = strtol(value, NULL, 0);
10024         else
10025                 i = CTL_DEFAULT_ROTATION_RATE;
10026         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10027         if (lun != NULL &&
10028             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10029                 i = strtol(value, NULL, 0);
10030         else
10031                 i = 0;
10032         bdc_ptr->wab_wac_ff = (i & 0x0f);
10033         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10034
10035         ctl_set_success(ctsio);
10036         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10037         ctsio->be_move_done = ctl_config_move_done;
10038         ctl_datamove((union ctl_io *)ctsio);
10039         return (CTL_RETVAL_COMPLETE);
10040 }
10041
10042 static int
10043 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10044 {
10045         struct scsi_vpd_logical_block_prov *lbp_ptr;
10046         struct ctl_lun *lun;
10047
10048         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10049
10050         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10051         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10052         ctsio->kern_sg_entries = 0;
10053
10054         if (sizeof(*lbp_ptr) < alloc_len) {
10055                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10056                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10057                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10058         } else {
10059                 ctsio->residual = 0;
10060                 ctsio->kern_data_len = alloc_len;
10061                 ctsio->kern_total_len = alloc_len;
10062         }
10063         ctsio->kern_data_resid = 0;
10064         ctsio->kern_rel_offset = 0;
10065         ctsio->kern_sg_entries = 0;
10066
10067         /*
10068          * The control device is always connected.  The disk device, on the
10069          * other hand, may not be online all the time.  Need to change this
10070          * to figure out whether the disk device is actually online or not.
10071          */
10072         if (lun != NULL)
10073                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10074                                   lun->be_lun->lun_type;
10075         else
10076                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10077
10078         lbp_ptr->page_code = SVPD_LBP;
10079         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10080         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10081         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10082                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10083                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10084                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10085         }
10086
10087         ctl_set_success(ctsio);
10088         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10089         ctsio->be_move_done = ctl_config_move_done;
10090         ctl_datamove((union ctl_io *)ctsio);
10091         return (CTL_RETVAL_COMPLETE);
10092 }
10093
10094 /*
10095  * INQUIRY with the EVPD bit set.
10096  */
10097 static int
10098 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10099 {
10100         struct ctl_lun *lun;
10101         struct scsi_inquiry *cdb;
10102         int alloc_len, retval;
10103
10104         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10105         cdb = (struct scsi_inquiry *)ctsio->cdb;
10106         alloc_len = scsi_2btoul(cdb->length);
10107
10108         switch (cdb->page_code) {
10109         case SVPD_SUPPORTED_PAGES:
10110                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10111                 break;
10112         case SVPD_UNIT_SERIAL_NUMBER:
10113                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10114                 break;
10115         case SVPD_DEVICE_ID:
10116                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10117                 break;
10118         case SVPD_EXTENDED_INQUIRY_DATA:
10119                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10120                 break;
10121         case SVPD_MODE_PAGE_POLICY:
10122                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10123                 break;
10124         case SVPD_SCSI_PORTS:
10125                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10126                 break;
10127         case SVPD_SCSI_TPC:
10128                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10129                 break;
10130         case SVPD_BLOCK_LIMITS:
10131                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10132                         goto err;
10133                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10134                 break;
10135         case SVPD_BDC:
10136                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10137                         goto err;
10138                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10139                 break;
10140         case SVPD_LBP:
10141                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10142                         goto err;
10143                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10144                 break;
10145         default:
10146 err:
10147                 ctl_set_invalid_field(ctsio,
10148                                       /*sks_valid*/ 1,
10149                                       /*command*/ 1,
10150                                       /*field*/ 2,
10151                                       /*bit_valid*/ 0,
10152                                       /*bit*/ 0);
10153                 ctl_done((union ctl_io *)ctsio);
10154                 retval = CTL_RETVAL_COMPLETE;
10155                 break;
10156         }
10157
10158         return (retval);
10159 }
10160
10161 /*
10162  * Standard INQUIRY data.
10163  */
10164 static int
10165 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10166 {
10167         struct scsi_inquiry_data *inq_ptr;
10168         struct scsi_inquiry *cdb;
10169         struct ctl_softc *softc = control_softc;
10170         struct ctl_port *port;
10171         struct ctl_lun *lun;
10172         char *val;
10173         uint32_t alloc_len, data_len;
10174         ctl_port_type port_type;
10175
10176         port = ctl_io_port(&ctsio->io_hdr);
10177         port_type = port->port_type;
10178         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10179                 port_type = CTL_PORT_SCSI;
10180
10181         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10182         cdb = (struct scsi_inquiry *)ctsio->cdb;
10183         alloc_len = scsi_2btoul(cdb->length);
10184
10185         /*
10186          * We malloc the full inquiry data size here and fill it
10187          * in.  If the user only asks for less, we'll give him
10188          * that much.
10189          */
10190         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10191         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10192         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10193         ctsio->kern_sg_entries = 0;
10194         ctsio->kern_data_resid = 0;
10195         ctsio->kern_rel_offset = 0;
10196
10197         if (data_len < alloc_len) {
10198                 ctsio->residual = alloc_len - data_len;
10199                 ctsio->kern_data_len = data_len;
10200                 ctsio->kern_total_len = data_len;
10201         } else {
10202                 ctsio->residual = 0;
10203                 ctsio->kern_data_len = alloc_len;
10204                 ctsio->kern_total_len = alloc_len;
10205         }
10206
10207         if (lun != NULL) {
10208                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10209                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10210                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10211                             lun->be_lun->lun_type;
10212                 } else {
10213                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10214                             lun->be_lun->lun_type;
10215                 }
10216                 if (lun->flags & CTL_LUN_REMOVABLE)
10217                         inq_ptr->dev_qual2 |= SID_RMB;
10218         } else
10219                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10220
10221         /* RMB in byte 2 is 0 */
10222         inq_ptr->version = SCSI_REV_SPC4;
10223
10224         /*
10225          * According to SAM-3, even if a device only supports a single
10226          * level of LUN addressing, it should still set the HISUP bit:
10227          *
10228          * 4.9.1 Logical unit numbers overview
10229          *
10230          * All logical unit number formats described in this standard are
10231          * hierarchical in structure even when only a single level in that
10232          * hierarchy is used. The HISUP bit shall be set to one in the
10233          * standard INQUIRY data (see SPC-2) when any logical unit number
10234          * format described in this standard is used.  Non-hierarchical
10235          * formats are outside the scope of this standard.
10236          *
10237          * Therefore we set the HiSup bit here.
10238          *
10239          * The reponse format is 2, per SPC-3.
10240          */
10241         inq_ptr->response_format = SID_HiSup | 2;
10242
10243         inq_ptr->additional_length = data_len -
10244             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10245         CTL_DEBUG_PRINT(("additional_length = %d\n",
10246                          inq_ptr->additional_length));
10247
10248         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10249         if (port_type == CTL_PORT_SCSI)
10250                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10251         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10252         inq_ptr->flags = SID_CmdQue;
10253         if (port_type == CTL_PORT_SCSI)
10254                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10255
10256         /*
10257          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10258          * We have 8 bytes for the vendor name, and 16 bytes for the device
10259          * name and 4 bytes for the revision.
10260          */
10261         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10262             "vendor")) == NULL) {
10263                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10264         } else {
10265                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10266                 strncpy(inq_ptr->vendor, val,
10267                     min(sizeof(inq_ptr->vendor), strlen(val)));
10268         }
10269         if (lun == NULL) {
10270                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10271                     sizeof(inq_ptr->product));
10272         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10273                 switch (lun->be_lun->lun_type) {
10274                 case T_DIRECT:
10275                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10276                             sizeof(inq_ptr->product));
10277                         break;
10278                 case T_PROCESSOR:
10279                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10280                             sizeof(inq_ptr->product));
10281                         break;
10282                 case T_CDROM:
10283                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10284                             sizeof(inq_ptr->product));
10285                         break;
10286                 default:
10287                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10288                             sizeof(inq_ptr->product));
10289                         break;
10290                 }
10291         } else {
10292                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10293                 strncpy(inq_ptr->product, val,
10294                     min(sizeof(inq_ptr->product), strlen(val)));
10295         }
10296
10297         /*
10298          * XXX make this a macro somewhere so it automatically gets
10299          * incremented when we make changes.
10300          */
10301         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10302             "revision")) == NULL) {
10303                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10304         } else {
10305                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10306                 strncpy(inq_ptr->revision, val,
10307                     min(sizeof(inq_ptr->revision), strlen(val)));
10308         }
10309
10310         /*
10311          * For parallel SCSI, we support double transition and single
10312          * transition clocking.  We also support QAS (Quick Arbitration
10313          * and Selection) and Information Unit transfers on both the
10314          * control and array devices.
10315          */
10316         if (port_type == CTL_PORT_SCSI)
10317                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10318                                     SID_SPI_IUS;
10319
10320         /* SAM-5 (no version claimed) */
10321         scsi_ulto2b(0x00A0, inq_ptr->version1);
10322         /* SPC-4 (no version claimed) */
10323         scsi_ulto2b(0x0460, inq_ptr->version2);
10324         if (port_type == CTL_PORT_FC) {
10325                 /* FCP-2 ANSI INCITS.350:2003 */
10326                 scsi_ulto2b(0x0917, inq_ptr->version3);
10327         } else if (port_type == CTL_PORT_SCSI) {
10328                 /* SPI-4 ANSI INCITS.362:200x */
10329                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10330         } else if (port_type == CTL_PORT_ISCSI) {
10331                 /* iSCSI (no version claimed) */
10332                 scsi_ulto2b(0x0960, inq_ptr->version3);
10333         } else if (port_type == CTL_PORT_SAS) {
10334                 /* SAS (no version claimed) */
10335                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10336         }
10337
10338         if (lun == NULL) {
10339                 /* SBC-4 (no version claimed) */
10340                 scsi_ulto2b(0x0600, inq_ptr->version4);
10341         } else {
10342                 switch (lun->be_lun->lun_type) {
10343                 case T_DIRECT:
10344                         /* SBC-4 (no version claimed) */
10345                         scsi_ulto2b(0x0600, inq_ptr->version4);
10346                         break;
10347                 case T_PROCESSOR:
10348                         break;
10349                 case T_CDROM:
10350                         /* MMC-6 (no version claimed) */
10351                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10352                         break;
10353                 default:
10354                         break;
10355                 }
10356         }
10357
10358         ctl_set_success(ctsio);
10359         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10360         ctsio->be_move_done = ctl_config_move_done;
10361         ctl_datamove((union ctl_io *)ctsio);
10362         return (CTL_RETVAL_COMPLETE);
10363 }
10364
10365 int
10366 ctl_inquiry(struct ctl_scsiio *ctsio)
10367 {
10368         struct scsi_inquiry *cdb;
10369         int retval;
10370
10371         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10372
10373         cdb = (struct scsi_inquiry *)ctsio->cdb;
10374         if (cdb->byte2 & SI_EVPD)
10375                 retval = ctl_inquiry_evpd(ctsio);
10376         else if (cdb->page_code == 0)
10377                 retval = ctl_inquiry_std(ctsio);
10378         else {
10379                 ctl_set_invalid_field(ctsio,
10380                                       /*sks_valid*/ 1,
10381                                       /*command*/ 1,
10382                                       /*field*/ 2,
10383                                       /*bit_valid*/ 0,
10384                                       /*bit*/ 0);
10385                 ctl_done((union ctl_io *)ctsio);
10386                 return (CTL_RETVAL_COMPLETE);
10387         }
10388
10389         return (retval);
10390 }
10391
10392 int
10393 ctl_get_config(struct ctl_scsiio *ctsio)
10394 {
10395         struct scsi_get_config_header *hdr;
10396         struct scsi_get_config_feature *feature;
10397         struct scsi_get_config *cdb;
10398         struct ctl_lun *lun;
10399         uint32_t alloc_len, data_len;
10400         int rt, starting;
10401
10402         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10403         cdb = (struct scsi_get_config *)ctsio->cdb;
10404         rt = (cdb->rt & SGC_RT_MASK);
10405         starting = scsi_2btoul(cdb->starting_feature);
10406         alloc_len = scsi_2btoul(cdb->length);
10407
10408         data_len = sizeof(struct scsi_get_config_header) +
10409             sizeof(struct scsi_get_config_feature) + 8 +
10410             sizeof(struct scsi_get_config_feature) + 8 +
10411             sizeof(struct scsi_get_config_feature) + 4 +
10412             sizeof(struct scsi_get_config_feature) + 4 +
10413             sizeof(struct scsi_get_config_feature) + 8 +
10414             sizeof(struct scsi_get_config_feature) +
10415             sizeof(struct scsi_get_config_feature) + 4 +
10416             sizeof(struct scsi_get_config_feature) + 4 +
10417             sizeof(struct scsi_get_config_feature) + 4 +
10418             sizeof(struct scsi_get_config_feature) + 4 +
10419             sizeof(struct scsi_get_config_feature) + 4 +
10420             sizeof(struct scsi_get_config_feature) + 4;
10421         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10422         ctsio->kern_sg_entries = 0;
10423         ctsio->kern_data_resid = 0;
10424         ctsio->kern_rel_offset = 0;
10425
10426         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10427         if (lun->flags & CTL_LUN_NO_MEDIA)
10428                 scsi_ulto2b(0x0000, hdr->current_profile);
10429         else
10430                 scsi_ulto2b(0x0010, hdr->current_profile);
10431         feature = (struct scsi_get_config_feature *)(hdr + 1);
10432
10433         if (starting > 0x003b)
10434                 goto done;
10435         if (starting > 0x003a)
10436                 goto f3b;
10437         if (starting > 0x002b)
10438                 goto f3a;
10439         if (starting > 0x002a)
10440                 goto f2b;
10441         if (starting > 0x001f)
10442                 goto f2a;
10443         if (starting > 0x001e)
10444                 goto f1f;
10445         if (starting > 0x001d)
10446                 goto f1e;
10447         if (starting > 0x0010)
10448                 goto f1d;
10449         if (starting > 0x0003)
10450                 goto f10;
10451         if (starting > 0x0002)
10452                 goto f3;
10453         if (starting > 0x0001)
10454                 goto f2;
10455         if (starting > 0x0000)
10456                 goto f1;
10457
10458         /* Profile List */
10459         scsi_ulto2b(0x0000, feature->feature_code);
10460         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10461         feature->add_length = 8;
10462         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10463         feature->feature_data[2] = 0x00;
10464         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10465         feature->feature_data[6] = 0x01;
10466         feature = (struct scsi_get_config_feature *)
10467             &feature->feature_data[feature->add_length];
10468
10469 f1:     /* Core */
10470         scsi_ulto2b(0x0001, feature->feature_code);
10471         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10472         feature->add_length = 8;
10473         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10474         feature->feature_data[4] = 0x03;
10475         feature = (struct scsi_get_config_feature *)
10476             &feature->feature_data[feature->add_length];
10477
10478 f2:     /* Morphing */
10479         scsi_ulto2b(0x0002, feature->feature_code);
10480         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10481         feature->add_length = 4;
10482         feature->feature_data[0] = 0x02;
10483         feature = (struct scsi_get_config_feature *)
10484             &feature->feature_data[feature->add_length];
10485
10486 f3:     /* Removable Medium */
10487         scsi_ulto2b(0x0003, feature->feature_code);
10488         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10489         feature->add_length = 4;
10490         feature->feature_data[0] = 0x39;
10491         feature = (struct scsi_get_config_feature *)
10492             &feature->feature_data[feature->add_length];
10493
10494         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10495                 goto done;
10496
10497 f10:    /* Random Read */
10498         scsi_ulto2b(0x0010, feature->feature_code);
10499         feature->flags = 0x00;
10500         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10501                 feature->flags |= SGC_F_CURRENT;
10502         feature->add_length = 8;
10503         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10504         scsi_ulto2b(1, &feature->feature_data[4]);
10505         feature->feature_data[6] = 0x00;
10506         feature = (struct scsi_get_config_feature *)
10507             &feature->feature_data[feature->add_length];
10508
10509 f1d:    /* Multi-Read */
10510         scsi_ulto2b(0x001D, 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 = 0;
10515         feature = (struct scsi_get_config_feature *)
10516             &feature->feature_data[feature->add_length];
10517
10518 f1e:    /* CD Read */
10519         scsi_ulto2b(0x001E, feature->feature_code);
10520         feature->flags = 0x00;
10521         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10522                 feature->flags |= SGC_F_CURRENT;
10523         feature->add_length = 4;
10524         feature->feature_data[0] = 0x00;
10525         feature = (struct scsi_get_config_feature *)
10526             &feature->feature_data[feature->add_length];
10527
10528 f1f:    /* DVD Read */
10529         scsi_ulto2b(0x001F, feature->feature_code);
10530         feature->flags = 0x08;
10531         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10532                 feature->flags |= SGC_F_CURRENT;
10533         feature->add_length = 4;
10534         feature->feature_data[0] = 0x01;
10535         feature->feature_data[2] = 0x03;
10536         feature = (struct scsi_get_config_feature *)
10537             &feature->feature_data[feature->add_length];
10538
10539 f2a:    /* DVD+RW */
10540         scsi_ulto2b(0x002A, feature->feature_code);
10541         feature->flags = 0x04;
10542         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10543                 feature->flags |= SGC_F_CURRENT;
10544         feature->add_length = 4;
10545         feature->feature_data[0] = 0x00;
10546         feature->feature_data[1] = 0x00;
10547         feature = (struct scsi_get_config_feature *)
10548             &feature->feature_data[feature->add_length];
10549
10550 f2b:    /* DVD+R */
10551         scsi_ulto2b(0x002B, feature->feature_code);
10552         feature->flags = 0x00;
10553         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10554                 feature->flags |= SGC_F_CURRENT;
10555         feature->add_length = 4;
10556         feature->feature_data[0] = 0x00;
10557         feature = (struct scsi_get_config_feature *)
10558             &feature->feature_data[feature->add_length];
10559
10560 f3a:    /* DVD+RW Dual Layer */
10561         scsi_ulto2b(0x003A, feature->feature_code);
10562         feature->flags = 0x00;
10563         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10564                 feature->flags |= SGC_F_CURRENT;
10565         feature->add_length = 4;
10566         feature->feature_data[0] = 0x00;
10567         feature->feature_data[1] = 0x00;
10568         feature = (struct scsi_get_config_feature *)
10569             &feature->feature_data[feature->add_length];
10570
10571 f3b:    /* DVD+R Dual Layer */
10572         scsi_ulto2b(0x003B, feature->feature_code);
10573         feature->flags = 0x00;
10574         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10575                 feature->flags |= SGC_F_CURRENT;
10576         feature->add_length = 4;
10577         feature->feature_data[0] = 0x00;
10578         feature = (struct scsi_get_config_feature *)
10579             &feature->feature_data[feature->add_length];
10580
10581 done:
10582         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10583         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10584                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10585                 if (scsi_2btoul(feature->feature_code) == starting)
10586                         feature = (struct scsi_get_config_feature *)
10587                             &feature->feature_data[feature->add_length];
10588                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10589         }
10590         scsi_ulto4b(data_len - 4, hdr->data_length);
10591         if (data_len < alloc_len) {
10592                 ctsio->residual = alloc_len - data_len;
10593                 ctsio->kern_data_len = data_len;
10594                 ctsio->kern_total_len = data_len;
10595         } else {
10596                 ctsio->residual = 0;
10597                 ctsio->kern_data_len = alloc_len;
10598                 ctsio->kern_total_len = alloc_len;
10599         }
10600
10601         ctl_set_success(ctsio);
10602         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10603         ctsio->be_move_done = ctl_config_move_done;
10604         ctl_datamove((union ctl_io *)ctsio);
10605         return (CTL_RETVAL_COMPLETE);
10606 }
10607
10608 int
10609 ctl_get_event_status(struct ctl_scsiio *ctsio)
10610 {
10611         struct scsi_get_event_status_header *hdr;
10612         struct scsi_get_event_status *cdb;
10613         struct ctl_lun *lun;
10614         uint32_t alloc_len, data_len;
10615         int notif_class;
10616
10617         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10618         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10619         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10620                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10621                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10622                 ctl_done((union ctl_io *)ctsio);
10623                 return (CTL_RETVAL_COMPLETE);
10624         }
10625         notif_class = cdb->notif_class;
10626         alloc_len = scsi_2btoul(cdb->length);
10627
10628         data_len = sizeof(struct scsi_get_event_status_header);
10629         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10630         ctsio->kern_sg_entries = 0;
10631         ctsio->kern_data_resid = 0;
10632         ctsio->kern_rel_offset = 0;
10633
10634         if (data_len < alloc_len) {
10635                 ctsio->residual = alloc_len - data_len;
10636                 ctsio->kern_data_len = data_len;
10637                 ctsio->kern_total_len = data_len;
10638         } else {
10639                 ctsio->residual = 0;
10640                 ctsio->kern_data_len = alloc_len;
10641                 ctsio->kern_total_len = alloc_len;
10642         }
10643
10644         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10645         scsi_ulto2b(0, hdr->descr_length);
10646         hdr->nea_class = SGESN_NEA;
10647         hdr->supported_class = 0;
10648
10649         ctl_set_success(ctsio);
10650         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10651         ctsio->be_move_done = ctl_config_move_done;
10652         ctl_datamove((union ctl_io *)ctsio);
10653         return (CTL_RETVAL_COMPLETE);
10654 }
10655
10656 int
10657 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10658 {
10659         struct scsi_mechanism_status_header *hdr;
10660         struct scsi_mechanism_status *cdb;
10661         struct ctl_lun *lun;
10662         uint32_t alloc_len, data_len;
10663
10664         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10665         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10666         alloc_len = scsi_2btoul(cdb->length);
10667
10668         data_len = sizeof(struct scsi_mechanism_status_header);
10669         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10670         ctsio->kern_sg_entries = 0;
10671         ctsio->kern_data_resid = 0;
10672         ctsio->kern_rel_offset = 0;
10673
10674         if (data_len < alloc_len) {
10675                 ctsio->residual = alloc_len - data_len;
10676                 ctsio->kern_data_len = data_len;
10677                 ctsio->kern_total_len = data_len;
10678         } else {
10679                 ctsio->residual = 0;
10680                 ctsio->kern_data_len = alloc_len;
10681                 ctsio->kern_total_len = alloc_len;
10682         }
10683
10684         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10685         hdr->state1 = 0x00;
10686         hdr->state2 = 0xe0;
10687         scsi_ulto3b(0, hdr->lba);
10688         hdr->slots_num = 0;
10689         scsi_ulto2b(0, hdr->slots_length);
10690
10691         ctl_set_success(ctsio);
10692         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10693         ctsio->be_move_done = ctl_config_move_done;
10694         ctl_datamove((union ctl_io *)ctsio);
10695         return (CTL_RETVAL_COMPLETE);
10696 }
10697
10698 static void
10699 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10700 {
10701
10702         lba += 150;
10703         buf[0] = 0;
10704         buf[1] = bin2bcd((lba / 75) / 60);
10705         buf[2] = bin2bcd((lba / 75) % 60);
10706         buf[3] = bin2bcd(lba % 75);
10707 }
10708
10709 int
10710 ctl_read_toc(struct ctl_scsiio *ctsio)
10711 {
10712         struct scsi_read_toc_hdr *hdr;
10713         struct scsi_read_toc_type01_descr *descr;
10714         struct scsi_read_toc *cdb;
10715         struct ctl_lun *lun;
10716         uint32_t alloc_len, data_len;
10717         int format, msf;
10718
10719         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10720         cdb = (struct scsi_read_toc *)ctsio->cdb;
10721         msf = (cdb->byte2 & CD_MSF) != 0;
10722         format = cdb->format;
10723         alloc_len = scsi_2btoul(cdb->data_len);
10724
10725         data_len = sizeof(struct scsi_read_toc_hdr);
10726         if (format == 0)
10727                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10728         else
10729                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10730         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10731         ctsio->kern_sg_entries = 0;
10732         ctsio->kern_data_resid = 0;
10733         ctsio->kern_rel_offset = 0;
10734
10735         if (data_len < alloc_len) {
10736                 ctsio->residual = alloc_len - data_len;
10737                 ctsio->kern_data_len = data_len;
10738                 ctsio->kern_total_len = data_len;
10739         } else {
10740                 ctsio->residual = 0;
10741                 ctsio->kern_data_len = alloc_len;
10742                 ctsio->kern_total_len = alloc_len;
10743         }
10744
10745         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10746         if (format == 0) {
10747                 scsi_ulto2b(0x12, hdr->data_length);
10748                 hdr->first = 1;
10749                 hdr->last = 1;
10750                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10751                 descr->addr_ctl = 0x14;
10752                 descr->track_number = 1;
10753                 if (msf)
10754                         ctl_ultomsf(0, descr->track_start);
10755                 else
10756                         scsi_ulto4b(0, descr->track_start);
10757                 descr++;
10758                 descr->addr_ctl = 0x14;
10759                 descr->track_number = 0xaa;
10760                 if (msf)
10761                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10762                 else
10763                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10764         } else {
10765                 scsi_ulto2b(0x0a, hdr->data_length);
10766                 hdr->first = 1;
10767                 hdr->last = 1;
10768                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10769                 descr->addr_ctl = 0x14;
10770                 descr->track_number = 1;
10771                 if (msf)
10772                         ctl_ultomsf(0, descr->track_start);
10773                 else
10774                         scsi_ulto4b(0, descr->track_start);
10775         }
10776
10777         ctl_set_success(ctsio);
10778         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10779         ctsio->be_move_done = ctl_config_move_done;
10780         ctl_datamove((union ctl_io *)ctsio);
10781         return (CTL_RETVAL_COMPLETE);
10782 }
10783
10784 /*
10785  * For known CDB types, parse the LBA and length.
10786  */
10787 static int
10788 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10789 {
10790         if (io->io_hdr.io_type != CTL_IO_SCSI)
10791                 return (1);
10792
10793         switch (io->scsiio.cdb[0]) {
10794         case COMPARE_AND_WRITE: {
10795                 struct scsi_compare_and_write *cdb;
10796
10797                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10798
10799                 *lba = scsi_8btou64(cdb->addr);
10800                 *len = cdb->length;
10801                 break;
10802         }
10803         case READ_6:
10804         case WRITE_6: {
10805                 struct scsi_rw_6 *cdb;
10806
10807                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10808
10809                 *lba = scsi_3btoul(cdb->addr);
10810                 /* only 5 bits are valid in the most significant address byte */
10811                 *lba &= 0x1fffff;
10812                 *len = cdb->length;
10813                 break;
10814         }
10815         case READ_10:
10816         case WRITE_10: {
10817                 struct scsi_rw_10 *cdb;
10818
10819                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10820
10821                 *lba = scsi_4btoul(cdb->addr);
10822                 *len = scsi_2btoul(cdb->length);
10823                 break;
10824         }
10825         case WRITE_VERIFY_10: {
10826                 struct scsi_write_verify_10 *cdb;
10827
10828                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10829
10830                 *lba = scsi_4btoul(cdb->addr);
10831                 *len = scsi_2btoul(cdb->length);
10832                 break;
10833         }
10834         case READ_12:
10835         case WRITE_12: {
10836                 struct scsi_rw_12 *cdb;
10837
10838                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10839
10840                 *lba = scsi_4btoul(cdb->addr);
10841                 *len = scsi_4btoul(cdb->length);
10842                 break;
10843         }
10844         case WRITE_VERIFY_12: {
10845                 struct scsi_write_verify_12 *cdb;
10846
10847                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10848
10849                 *lba = scsi_4btoul(cdb->addr);
10850                 *len = scsi_4btoul(cdb->length);
10851                 break;
10852         }
10853         case READ_16:
10854         case WRITE_16: {
10855                 struct scsi_rw_16 *cdb;
10856
10857                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10858
10859                 *lba = scsi_8btou64(cdb->addr);
10860                 *len = scsi_4btoul(cdb->length);
10861                 break;
10862         }
10863         case WRITE_ATOMIC_16: {
10864                 struct scsi_write_atomic_16 *cdb;
10865
10866                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10867
10868                 *lba = scsi_8btou64(cdb->addr);
10869                 *len = scsi_2btoul(cdb->length);
10870                 break;
10871         }
10872         case WRITE_VERIFY_16: {
10873                 struct scsi_write_verify_16 *cdb;
10874
10875                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10876
10877                 *lba = scsi_8btou64(cdb->addr);
10878                 *len = scsi_4btoul(cdb->length);
10879                 break;
10880         }
10881         case WRITE_SAME_10: {
10882                 struct scsi_write_same_10 *cdb;
10883
10884                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10885
10886                 *lba = scsi_4btoul(cdb->addr);
10887                 *len = scsi_2btoul(cdb->length);
10888                 break;
10889         }
10890         case WRITE_SAME_16: {
10891                 struct scsi_write_same_16 *cdb;
10892
10893                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10894
10895                 *lba = scsi_8btou64(cdb->addr);
10896                 *len = scsi_4btoul(cdb->length);
10897                 break;
10898         }
10899         case VERIFY_10: {
10900                 struct scsi_verify_10 *cdb;
10901
10902                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10903
10904                 *lba = scsi_4btoul(cdb->addr);
10905                 *len = scsi_2btoul(cdb->length);
10906                 break;
10907         }
10908         case VERIFY_12: {
10909                 struct scsi_verify_12 *cdb;
10910
10911                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10912
10913                 *lba = scsi_4btoul(cdb->addr);
10914                 *len = scsi_4btoul(cdb->length);
10915                 break;
10916         }
10917         case VERIFY_16: {
10918                 struct scsi_verify_16 *cdb;
10919
10920                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10921
10922                 *lba = scsi_8btou64(cdb->addr);
10923                 *len = scsi_4btoul(cdb->length);
10924                 break;
10925         }
10926         case UNMAP: {
10927                 *lba = 0;
10928                 *len = UINT64_MAX;
10929                 break;
10930         }
10931         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10932                 struct scsi_get_lba_status *cdb;
10933
10934                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10935                 *lba = scsi_8btou64(cdb->addr);
10936                 *len = UINT32_MAX;
10937                 break;
10938         }
10939         default:
10940                 return (1);
10941                 break; /* NOTREACHED */
10942         }
10943
10944         return (0);
10945 }
10946
10947 static ctl_action
10948 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10949     bool seq)
10950 {
10951         uint64_t endlba1, endlba2;
10952
10953         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10954         endlba2 = lba2 + len2 - 1;
10955
10956         if ((endlba1 < lba2) || (endlba2 < lba1))
10957                 return (CTL_ACTION_PASS);
10958         else
10959                 return (CTL_ACTION_BLOCK);
10960 }
10961
10962 static int
10963 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10964 {
10965         struct ctl_ptr_len_flags *ptrlen;
10966         struct scsi_unmap_desc *buf, *end, *range;
10967         uint64_t lba;
10968         uint32_t len;
10969
10970         /* If not UNMAP -- go other way. */
10971         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10972             io->scsiio.cdb[0] != UNMAP)
10973                 return (CTL_ACTION_ERROR);
10974
10975         /* If UNMAP without data -- block and wait for data. */
10976         ptrlen = (struct ctl_ptr_len_flags *)
10977             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10978         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10979             ptrlen->ptr == NULL)
10980                 return (CTL_ACTION_BLOCK);
10981
10982         /* UNMAP with data -- check for collision. */
10983         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10984         end = buf + ptrlen->len / sizeof(*buf);
10985         for (range = buf; range < end; range++) {
10986                 lba = scsi_8btou64(range->lba);
10987                 len = scsi_4btoul(range->length);
10988                 if ((lba < lba2 + len2) && (lba + len > lba2))
10989                         return (CTL_ACTION_BLOCK);
10990         }
10991         return (CTL_ACTION_PASS);
10992 }
10993
10994 static ctl_action
10995 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10996 {
10997         uint64_t lba1, lba2;
10998         uint64_t len1, len2;
10999         int retval;
11000
11001         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11002                 return (CTL_ACTION_ERROR);
11003
11004         retval = ctl_extent_check_unmap(io1, lba2, len2);
11005         if (retval != CTL_ACTION_ERROR)
11006                 return (retval);
11007
11008         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11009                 return (CTL_ACTION_ERROR);
11010
11011         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11012                 seq = FALSE;
11013         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11014 }
11015
11016 static ctl_action
11017 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
11018 {
11019         uint64_t lba1, lba2;
11020         uint64_t len1, len2;
11021
11022         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11023                 return (CTL_ACTION_PASS);
11024         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11025                 return (CTL_ACTION_ERROR);
11026         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11027                 return (CTL_ACTION_ERROR);
11028
11029         if (lba1 + len1 == lba2)
11030                 return (CTL_ACTION_BLOCK);
11031         return (CTL_ACTION_PASS);
11032 }
11033
11034 static ctl_action
11035 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11036     union ctl_io *ooa_io)
11037 {
11038         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11039         const ctl_serialize_action *serialize_row;
11040
11041         /*
11042          * The initiator attempted multiple untagged commands at the same
11043          * time.  Can't do that.
11044          */
11045         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11046          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11047          && ((pending_io->io_hdr.nexus.targ_port ==
11048               ooa_io->io_hdr.nexus.targ_port)
11049           && (pending_io->io_hdr.nexus.initid ==
11050               ooa_io->io_hdr.nexus.initid))
11051          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11052               CTL_FLAG_STATUS_SENT)) == 0))
11053                 return (CTL_ACTION_OVERLAP);
11054
11055         /*
11056          * The initiator attempted to send multiple tagged commands with
11057          * the same ID.  (It's fine if different initiators have the same
11058          * tag ID.)
11059          *
11060          * Even if all of those conditions are true, we don't kill the I/O
11061          * if the command ahead of us has been aborted.  We won't end up
11062          * sending it to the FETD, and it's perfectly legal to resend a
11063          * command with the same tag number as long as the previous
11064          * instance of this tag number has been aborted somehow.
11065          */
11066         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11067          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11068          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11069          && ((pending_io->io_hdr.nexus.targ_port ==
11070               ooa_io->io_hdr.nexus.targ_port)
11071           && (pending_io->io_hdr.nexus.initid ==
11072               ooa_io->io_hdr.nexus.initid))
11073          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11074               CTL_FLAG_STATUS_SENT)) == 0))
11075                 return (CTL_ACTION_OVERLAP_TAG);
11076
11077         /*
11078          * If we get a head of queue tag, SAM-3 says that we should
11079          * immediately execute it.
11080          *
11081          * What happens if this command would normally block for some other
11082          * reason?  e.g. a request sense with a head of queue tag
11083          * immediately after a write.  Normally that would block, but this
11084          * will result in its getting executed immediately...
11085          *
11086          * We currently return "pass" instead of "skip", so we'll end up
11087          * going through the rest of the queue to check for overlapped tags.
11088          *
11089          * XXX KDM check for other types of blockage first??
11090          */
11091         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11092                 return (CTL_ACTION_PASS);
11093
11094         /*
11095          * Ordered tags have to block until all items ahead of them
11096          * have completed.  If we get called with an ordered tag, we always
11097          * block, if something else is ahead of us in the queue.
11098          */
11099         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11100                 return (CTL_ACTION_BLOCK);
11101
11102         /*
11103          * Simple tags get blocked until all head of queue and ordered tags
11104          * ahead of them have completed.  I'm lumping untagged commands in
11105          * with simple tags here.  XXX KDM is that the right thing to do?
11106          */
11107         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11108           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11109          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11110           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11111                 return (CTL_ACTION_BLOCK);
11112
11113         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11114         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11115             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11116              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11117              pending_io->scsiio.cdb[1], pending_io));
11118         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11119         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11120                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11121         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11122             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11123              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11124              ooa_io->scsiio.cdb[1], ooa_io));
11125
11126         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11127
11128         switch (serialize_row[pending_entry->seridx]) {
11129         case CTL_SER_BLOCK:
11130                 return (CTL_ACTION_BLOCK);
11131         case CTL_SER_EXTENT:
11132                 return (ctl_extent_check(ooa_io, pending_io,
11133                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11134         case CTL_SER_EXTENTOPT:
11135                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11136                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11137                         return (ctl_extent_check(ooa_io, pending_io,
11138                             (lun->be_lun &&
11139                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11140                 return (CTL_ACTION_PASS);
11141         case CTL_SER_EXTENTSEQ:
11142                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11143                         return (ctl_extent_check_seq(ooa_io, pending_io));
11144                 return (CTL_ACTION_PASS);
11145         case CTL_SER_PASS:
11146                 return (CTL_ACTION_PASS);
11147         case CTL_SER_BLOCKOPT:
11148                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11149                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11150                         return (CTL_ACTION_BLOCK);
11151                 return (CTL_ACTION_PASS);
11152         case CTL_SER_SKIP:
11153                 return (CTL_ACTION_SKIP);
11154         default:
11155                 panic("%s: Invalid serialization value %d for %d => %d",
11156                     __func__, serialize_row[pending_entry->seridx],
11157                     pending_entry->seridx, ooa_entry->seridx);
11158         }
11159
11160         return (CTL_ACTION_ERROR);
11161 }
11162
11163 /*
11164  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11165  * Assumptions:
11166  * - pending_io is generally either incoming, or on the blocked queue
11167  * - starting I/O is the I/O we want to start the check with.
11168  */
11169 static ctl_action
11170 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11171               union ctl_io *starting_io)
11172 {
11173         union ctl_io *ooa_io;
11174         ctl_action action;
11175
11176         mtx_assert(&lun->lun_lock, MA_OWNED);
11177
11178         /*
11179          * Run back along the OOA queue, starting with the current
11180          * blocked I/O and going through every I/O before it on the
11181          * queue.  If starting_io is NULL, we'll just end up returning
11182          * CTL_ACTION_PASS.
11183          */
11184         for (ooa_io = starting_io; ooa_io != NULL;
11185              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11186              ooa_links)){
11187
11188                 /*
11189                  * This routine just checks to see whether
11190                  * cur_blocked is blocked by ooa_io, which is ahead
11191                  * of it in the queue.  It doesn't queue/dequeue
11192                  * cur_blocked.
11193                  */
11194                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11195                 switch (action) {
11196                 case CTL_ACTION_BLOCK:
11197                 case CTL_ACTION_OVERLAP:
11198                 case CTL_ACTION_OVERLAP_TAG:
11199                 case CTL_ACTION_SKIP:
11200                 case CTL_ACTION_ERROR:
11201                         return (action);
11202                         break; /* NOTREACHED */
11203                 case CTL_ACTION_PASS:
11204                         break;
11205                 default:
11206                         panic("%s: Invalid action %d\n", __func__, action);
11207                 }
11208         }
11209
11210         return (CTL_ACTION_PASS);
11211 }
11212
11213 /*
11214  * Assumptions:
11215  * - An I/O has just completed, and has been removed from the per-LUN OOA
11216  *   queue, so some items on the blocked queue may now be unblocked.
11217  */
11218 static int
11219 ctl_check_blocked(struct ctl_lun *lun)
11220 {
11221         struct ctl_softc *softc = lun->ctl_softc;
11222         union ctl_io *cur_blocked, *next_blocked;
11223
11224         mtx_assert(&lun->lun_lock, MA_OWNED);
11225
11226         /*
11227          * Run forward from the head of the blocked queue, checking each
11228          * entry against the I/Os prior to it on the OOA queue to see if
11229          * there is still any blockage.
11230          *
11231          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11232          * with our removing a variable on it while it is traversing the
11233          * list.
11234          */
11235         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11236              cur_blocked != NULL; cur_blocked = next_blocked) {
11237                 union ctl_io *prev_ooa;
11238                 ctl_action action;
11239
11240                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11241                                                           blocked_links);
11242
11243                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11244                                                       ctl_ooaq, ooa_links);
11245
11246                 /*
11247                  * If cur_blocked happens to be the first item in the OOA
11248                  * queue now, prev_ooa will be NULL, and the action
11249                  * returned will just be CTL_ACTION_PASS.
11250                  */
11251                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11252
11253                 switch (action) {
11254                 case CTL_ACTION_BLOCK:
11255                         /* Nothing to do here, still blocked */
11256                         break;
11257                 case CTL_ACTION_OVERLAP:
11258                 case CTL_ACTION_OVERLAP_TAG:
11259                         /*
11260                          * This shouldn't happen!  In theory we've already
11261                          * checked this command for overlap...
11262                          */
11263                         break;
11264                 case CTL_ACTION_PASS:
11265                 case CTL_ACTION_SKIP: {
11266                         const struct ctl_cmd_entry *entry;
11267
11268                         /*
11269                          * The skip case shouldn't happen, this transaction
11270                          * should have never made it onto the blocked queue.
11271                          */
11272                         /*
11273                          * This I/O is no longer blocked, we can remove it
11274                          * from the blocked queue.  Since this is a TAILQ
11275                          * (doubly linked list), we can do O(1) removals
11276                          * from any place on the list.
11277                          */
11278                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11279                                      blocked_links);
11280                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11281
11282                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11283                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11284                                 /*
11285                                  * Need to send IO back to original side to
11286                                  * run
11287                                  */
11288                                 union ctl_ha_msg msg_info;
11289
11290                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11291                                 msg_info.hdr.original_sc =
11292                                         cur_blocked->io_hdr.original_sc;
11293                                 msg_info.hdr.serializing_sc = cur_blocked;
11294                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11295                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11296                                     sizeof(msg_info.hdr), M_NOWAIT);
11297                                 break;
11298                         }
11299                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11300
11301                         /*
11302                          * Check this I/O for LUN state changes that may
11303                          * have happened while this command was blocked.
11304                          * The LUN state may have been changed by a command
11305                          * ahead of us in the queue, so we need to re-check
11306                          * for any states that can be caused by SCSI
11307                          * commands.
11308                          */
11309                         if (ctl_scsiio_lun_check(lun, entry,
11310                                                  &cur_blocked->scsiio) == 0) {
11311                                 cur_blocked->io_hdr.flags |=
11312                                                       CTL_FLAG_IS_WAS_ON_RTR;
11313                                 ctl_enqueue_rtr(cur_blocked);
11314                         } else
11315                                 ctl_done(cur_blocked);
11316                         break;
11317                 }
11318                 default:
11319                         /*
11320                          * This probably shouldn't happen -- we shouldn't
11321                          * get CTL_ACTION_ERROR, or anything else.
11322                          */
11323                         break;
11324                 }
11325         }
11326
11327         return (CTL_RETVAL_COMPLETE);
11328 }
11329
11330 /*
11331  * This routine (with one exception) checks LUN flags that can be set by
11332  * commands ahead of us in the OOA queue.  These flags have to be checked
11333  * when a command initially comes in, and when we pull a command off the
11334  * blocked queue and are preparing to execute it.  The reason we have to
11335  * check these flags for commands on the blocked queue is that the LUN
11336  * state may have been changed by a command ahead of us while we're on the
11337  * blocked queue.
11338  *
11339  * Ordering is somewhat important with these checks, so please pay
11340  * careful attention to the placement of any new checks.
11341  */
11342 static int
11343 ctl_scsiio_lun_check(struct ctl_lun *lun,
11344     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11345 {
11346         struct ctl_softc *softc = lun->ctl_softc;
11347         int retval;
11348         uint32_t residx;
11349
11350         retval = 0;
11351
11352         mtx_assert(&lun->lun_lock, MA_OWNED);
11353
11354         /*
11355          * If this shelf is a secondary shelf controller, we may have to
11356          * reject some commands disallowed by HA mode and link state.
11357          */
11358         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11359                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11360                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11361                         ctl_set_lun_unavail(ctsio);
11362                         retval = 1;
11363                         goto bailout;
11364                 }
11365                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11366                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11367                         ctl_set_lun_transit(ctsio);
11368                         retval = 1;
11369                         goto bailout;
11370                 }
11371                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11372                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11373                         ctl_set_lun_standby(ctsio);
11374                         retval = 1;
11375                         goto bailout;
11376                 }
11377
11378                 /* The rest of checks are only done on executing side */
11379                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11380                         goto bailout;
11381         }
11382
11383         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11384                 if (lun->be_lun &&
11385                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11386                         ctl_set_hw_write_protected(ctsio);
11387                         retval = 1;
11388                         goto bailout;
11389                 }
11390                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11391                     .eca_and_aen & SCP_SWP) != 0) {
11392                         ctl_set_sense(ctsio, /*current_error*/ 1,
11393                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11394                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11395                         retval = 1;
11396                         goto bailout;
11397                 }
11398         }
11399
11400         /*
11401          * Check for a reservation conflict.  If this command isn't allowed
11402          * even on reserved LUNs, and if this initiator isn't the one who
11403          * reserved us, reject the command with a reservation conflict.
11404          */
11405         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11406         if ((lun->flags & CTL_LUN_RESERVED)
11407          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11408                 if (lun->res_idx != residx) {
11409                         ctl_set_reservation_conflict(ctsio);
11410                         retval = 1;
11411                         goto bailout;
11412                 }
11413         }
11414
11415         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11416             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11417                 /* No reservation or command is allowed. */;
11418         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11419             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11420              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11421              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11422                 /* The command is allowed for Write Exclusive resv. */;
11423         } else {
11424                 /*
11425                  * if we aren't registered or it's a res holder type
11426                  * reservation and this isn't the res holder then set a
11427                  * conflict.
11428                  */
11429                 if (ctl_get_prkey(lun, residx) == 0 ||
11430                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11431                         ctl_set_reservation_conflict(ctsio);
11432                         retval = 1;
11433                         goto bailout;
11434                 }
11435         }
11436
11437         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11438                 if (lun->flags & CTL_LUN_EJECTED)
11439                         ctl_set_lun_ejected(ctsio);
11440                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11441                         if (lun->flags & CTL_LUN_REMOVABLE)
11442                                 ctl_set_lun_no_media(ctsio);
11443                         else
11444                                 ctl_set_lun_int_reqd(ctsio);
11445                 } else if (lun->flags & CTL_LUN_STOPPED)
11446                         ctl_set_lun_stopped(ctsio);
11447                 else
11448                         goto bailout;
11449                 retval = 1;
11450                 goto bailout;
11451         }
11452
11453 bailout:
11454         return (retval);
11455 }
11456
11457 static void
11458 ctl_failover_io(union ctl_io *io, int have_lock)
11459 {
11460         ctl_set_busy(&io->scsiio);
11461         ctl_done(io);
11462 }
11463
11464 static void
11465 ctl_failover_lun(union ctl_io *rio)
11466 {
11467         struct ctl_softc *softc = control_softc;
11468         struct ctl_lun *lun;
11469         struct ctl_io_hdr *io, *next_io;
11470         uint32_t targ_lun;
11471
11472         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11473         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11474
11475         /* Find and lock the LUN. */
11476         mtx_lock(&softc->ctl_lock);
11477         if ((targ_lun < CTL_MAX_LUNS) &&
11478             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11479                 mtx_lock(&lun->lun_lock);
11480                 mtx_unlock(&softc->ctl_lock);
11481                 if (lun->flags & CTL_LUN_DISABLED) {
11482                         mtx_unlock(&lun->lun_lock);
11483                         return;
11484                 }
11485         } else {
11486                 mtx_unlock(&softc->ctl_lock);
11487                 return;
11488         }
11489
11490         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11491                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11492                         /* We are master */
11493                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11494                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11495                                         io->flags |= CTL_FLAG_ABORT;
11496                                         io->flags |= CTL_FLAG_FAILOVER;
11497                                 } else { /* This can be only due to DATAMOVE */
11498                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11499                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11500                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11501                                         io->port_status = 31340;
11502                                         ctl_enqueue_isc((union ctl_io *)io);
11503                                 }
11504                         }
11505                         /* We are slave */
11506                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11507                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11508                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11509                                         io->flags |= CTL_FLAG_FAILOVER;
11510                                 } else {
11511                                         ctl_set_busy(&((union ctl_io *)io)->
11512                                             scsiio);
11513                                         ctl_done((union ctl_io *)io);
11514                                 }
11515                         }
11516                 }
11517         } else { /* SERIALIZE modes */
11518                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11519                     next_io) {
11520                         /* We are master */
11521                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11522                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11523                                     blocked_links);
11524                                 io->flags &= ~CTL_FLAG_BLOCKED;
11525                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11526                                 ctl_free_io((union ctl_io *)io);
11527                         }
11528                 }
11529                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11530                         /* We are master */
11531                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11532                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11533                                 ctl_free_io((union ctl_io *)io);
11534                         }
11535                         /* We are slave */
11536                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11537                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11538                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11539                                         ctl_set_busy(&((union ctl_io *)io)->
11540                                             scsiio);
11541                                         ctl_done((union ctl_io *)io);
11542                                 }
11543                         }
11544                 }
11545                 ctl_check_blocked(lun);
11546         }
11547         mtx_unlock(&lun->lun_lock);
11548 }
11549
11550 static int
11551 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11552 {
11553         struct ctl_lun *lun;
11554         const struct ctl_cmd_entry *entry;
11555         uint32_t initidx, targ_lun;
11556         int retval;
11557
11558         retval = 0;
11559
11560         lun = NULL;
11561
11562         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11563         if ((targ_lun < CTL_MAX_LUNS)
11564          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11565                 /*
11566                  * If the LUN is invalid, pretend that it doesn't exist.
11567                  * It will go away as soon as all pending I/O has been
11568                  * completed.
11569                  */
11570                 mtx_lock(&lun->lun_lock);
11571                 if (lun->flags & CTL_LUN_DISABLED) {
11572                         mtx_unlock(&lun->lun_lock);
11573                         lun = NULL;
11574                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11575                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11576                 } else {
11577                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11578                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11579                                 lun->be_lun;
11580
11581                         /*
11582                          * Every I/O goes into the OOA queue for a
11583                          * particular LUN, and stays there until completion.
11584                          */
11585 #ifdef CTL_TIME_IO
11586                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11587                                 lun->idle_time += getsbinuptime() -
11588                                     lun->last_busy;
11589                         }
11590 #endif
11591                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11592                             ooa_links);
11593                 }
11594         } else {
11595                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11596                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11597         }
11598
11599         /* Get command entry and return error if it is unsuppotyed. */
11600         entry = ctl_validate_command(ctsio);
11601         if (entry == NULL) {
11602                 if (lun)
11603                         mtx_unlock(&lun->lun_lock);
11604                 return (retval);
11605         }
11606
11607         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11608         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11609
11610         /*
11611          * Check to see whether we can send this command to LUNs that don't
11612          * exist.  This should pretty much only be the case for inquiry
11613          * and request sense.  Further checks, below, really require having
11614          * a LUN, so we can't really check the command anymore.  Just put
11615          * it on the rtr queue.
11616          */
11617         if (lun == NULL) {
11618                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11619                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11620                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11621                         return (retval);
11622                 }
11623
11624                 ctl_set_unsupported_lun(ctsio);
11625                 ctl_done((union ctl_io *)ctsio);
11626                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11627                 return (retval);
11628         } else {
11629                 /*
11630                  * Make sure we support this particular command on this LUN.
11631                  * e.g., we don't support writes to the control LUN.
11632                  */
11633                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11634                         mtx_unlock(&lun->lun_lock);
11635                         ctl_set_invalid_opcode(ctsio);
11636                         ctl_done((union ctl_io *)ctsio);
11637                         return (retval);
11638                 }
11639         }
11640
11641         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11642
11643 #ifdef CTL_WITH_CA
11644         /*
11645          * If we've got a request sense, it'll clear the contingent
11646          * allegiance condition.  Otherwise, if we have a CA condition for
11647          * this initiator, clear it, because it sent down a command other
11648          * than request sense.
11649          */
11650         if ((ctsio->cdb[0] != REQUEST_SENSE)
11651          && (ctl_is_set(lun->have_ca, initidx)))
11652                 ctl_clear_mask(lun->have_ca, initidx);
11653 #endif
11654
11655         /*
11656          * If the command has this flag set, it handles its own unit
11657          * attention reporting, we shouldn't do anything.  Otherwise we
11658          * check for any pending unit attentions, and send them back to the
11659          * initiator.  We only do this when a command initially comes in,
11660          * not when we pull it off the blocked queue.
11661          *
11662          * According to SAM-3, section 5.3.2, the order that things get
11663          * presented back to the host is basically unit attentions caused
11664          * by some sort of reset event, busy status, reservation conflicts
11665          * or task set full, and finally any other status.
11666          *
11667          * One issue here is that some of the unit attentions we report
11668          * don't fall into the "reset" category (e.g. "reported luns data
11669          * has changed").  So reporting it here, before the reservation
11670          * check, may be technically wrong.  I guess the only thing to do
11671          * would be to check for and report the reset events here, and then
11672          * check for the other unit attention types after we check for a
11673          * reservation conflict.
11674          *
11675          * XXX KDM need to fix this
11676          */
11677         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11678                 ctl_ua_type ua_type;
11679
11680                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11681                     SSD_TYPE_NONE);
11682                 if (ua_type != CTL_UA_NONE) {
11683                         mtx_unlock(&lun->lun_lock);
11684                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11685                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11686                         ctsio->sense_len = SSD_FULL_SIZE;
11687                         ctl_done((union ctl_io *)ctsio);
11688                         return (retval);
11689                 }
11690         }
11691
11692
11693         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11694                 mtx_unlock(&lun->lun_lock);
11695                 ctl_done((union ctl_io *)ctsio);
11696                 return (retval);
11697         }
11698
11699         /*
11700          * XXX CHD this is where we want to send IO to other side if
11701          * this LUN is secondary on this SC. We will need to make a copy
11702          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11703          * the copy we send as FROM_OTHER.
11704          * We also need to stuff the address of the original IO so we can
11705          * find it easily. Something similar will need be done on the other
11706          * side so when we are done we can find the copy.
11707          */
11708         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11709             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11710             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11711                 union ctl_ha_msg msg_info;
11712                 int isc_retval;
11713
11714                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11715                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11716                 mtx_unlock(&lun->lun_lock);
11717
11718                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11719                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11720                 msg_info.hdr.serializing_sc = NULL;
11721                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11722                 msg_info.scsi.tag_num = ctsio->tag_num;
11723                 msg_info.scsi.tag_type = ctsio->tag_type;
11724                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11725                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11726
11727                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11728                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11729                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11730                         ctl_set_busy(ctsio);
11731                         ctl_done((union ctl_io *)ctsio);
11732                         return (retval);
11733                 }
11734                 return (retval);
11735         }
11736
11737         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11738                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11739                               ctl_ooaq, ooa_links))) {
11740         case CTL_ACTION_BLOCK:
11741                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11742                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11743                                   blocked_links);
11744                 mtx_unlock(&lun->lun_lock);
11745                 return (retval);
11746         case CTL_ACTION_PASS:
11747         case CTL_ACTION_SKIP:
11748                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11749                 mtx_unlock(&lun->lun_lock);
11750                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11751                 break;
11752         case CTL_ACTION_OVERLAP:
11753                 mtx_unlock(&lun->lun_lock);
11754                 ctl_set_overlapped_cmd(ctsio);
11755                 ctl_done((union ctl_io *)ctsio);
11756                 break;
11757         case CTL_ACTION_OVERLAP_TAG:
11758                 mtx_unlock(&lun->lun_lock);
11759                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11760                 ctl_done((union ctl_io *)ctsio);
11761                 break;
11762         case CTL_ACTION_ERROR:
11763         default:
11764                 mtx_unlock(&lun->lun_lock);
11765                 ctl_set_internal_failure(ctsio,
11766                                          /*sks_valid*/ 0,
11767                                          /*retry_count*/ 0);
11768                 ctl_done((union ctl_io *)ctsio);
11769                 break;
11770         }
11771         return (retval);
11772 }
11773
11774 const struct ctl_cmd_entry *
11775 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11776 {
11777         const struct ctl_cmd_entry *entry;
11778         int service_action;
11779
11780         entry = &ctl_cmd_table[ctsio->cdb[0]];
11781         if (sa)
11782                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11783         if (entry->flags & CTL_CMD_FLAG_SA5) {
11784                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11785                 entry = &((const struct ctl_cmd_entry *)
11786                     entry->execute)[service_action];
11787         }
11788         return (entry);
11789 }
11790
11791 const struct ctl_cmd_entry *
11792 ctl_validate_command(struct ctl_scsiio *ctsio)
11793 {
11794         const struct ctl_cmd_entry *entry;
11795         int i, sa;
11796         uint8_t diff;
11797
11798         entry = ctl_get_cmd_entry(ctsio, &sa);
11799         if (entry->execute == NULL) {
11800                 if (sa)
11801                         ctl_set_invalid_field(ctsio,
11802                                               /*sks_valid*/ 1,
11803                                               /*command*/ 1,
11804                                               /*field*/ 1,
11805                                               /*bit_valid*/ 1,
11806                                               /*bit*/ 4);
11807                 else
11808                         ctl_set_invalid_opcode(ctsio);
11809                 ctl_done((union ctl_io *)ctsio);
11810                 return (NULL);
11811         }
11812         KASSERT(entry->length > 0,
11813             ("Not defined length for command 0x%02x/0x%02x",
11814              ctsio->cdb[0], ctsio->cdb[1]));
11815         for (i = 1; i < entry->length; i++) {
11816                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11817                 if (diff == 0)
11818                         continue;
11819                 ctl_set_invalid_field(ctsio,
11820                                       /*sks_valid*/ 1,
11821                                       /*command*/ 1,
11822                                       /*field*/ i,
11823                                       /*bit_valid*/ 1,
11824                                       /*bit*/ fls(diff) - 1);
11825                 ctl_done((union ctl_io *)ctsio);
11826                 return (NULL);
11827         }
11828         return (entry);
11829 }
11830
11831 static int
11832 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11833 {
11834
11835         switch (lun_type) {
11836         case T_DIRECT:
11837                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11838                         return (0);
11839                 break;
11840         case T_PROCESSOR:
11841                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11842                         return (0);
11843                 break;
11844         case T_CDROM:
11845                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11846                         return (0);
11847                 break;
11848         default:
11849                 return (0);
11850         }
11851         return (1);
11852 }
11853
11854 static int
11855 ctl_scsiio(struct ctl_scsiio *ctsio)
11856 {
11857         int retval;
11858         const struct ctl_cmd_entry *entry;
11859
11860         retval = CTL_RETVAL_COMPLETE;
11861
11862         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11863
11864         entry = ctl_get_cmd_entry(ctsio, NULL);
11865
11866         /*
11867          * If this I/O has been aborted, just send it straight to
11868          * ctl_done() without executing it.
11869          */
11870         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11871                 ctl_done((union ctl_io *)ctsio);
11872                 goto bailout;
11873         }
11874
11875         /*
11876          * All the checks should have been handled by ctl_scsiio_precheck().
11877          * We should be clear now to just execute the I/O.
11878          */
11879         retval = entry->execute(ctsio);
11880
11881 bailout:
11882         return (retval);
11883 }
11884
11885 /*
11886  * Since we only implement one target right now, a bus reset simply resets
11887  * our single target.
11888  */
11889 static int
11890 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11891 {
11892         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11893 }
11894
11895 static int
11896 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11897                  ctl_ua_type ua_type)
11898 {
11899         struct ctl_port *port;
11900         struct ctl_lun *lun;
11901         int retval;
11902
11903         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11904                 union ctl_ha_msg msg_info;
11905
11906                 msg_info.hdr.nexus = io->io_hdr.nexus;
11907                 if (ua_type==CTL_UA_TARG_RESET)
11908                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11909                 else
11910                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11911                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11912                 msg_info.hdr.original_sc = NULL;
11913                 msg_info.hdr.serializing_sc = NULL;
11914                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11915                     sizeof(msg_info.task), M_WAITOK);
11916         }
11917         retval = 0;
11918
11919         mtx_lock(&softc->ctl_lock);
11920         port = ctl_io_port(&io->io_hdr);
11921         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11922                 if (port != NULL &&
11923                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11924                         continue;
11925                 retval += ctl_do_lun_reset(lun, io, ua_type);
11926         }
11927         mtx_unlock(&softc->ctl_lock);
11928         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11929         return (retval);
11930 }
11931
11932 /*
11933  * The LUN should always be set.  The I/O is optional, and is used to
11934  * distinguish between I/Os sent by this initiator, and by other
11935  * initiators.  We set unit attention for initiators other than this one.
11936  * SAM-3 is vague on this point.  It does say that a unit attention should
11937  * be established for other initiators when a LUN is reset (see section
11938  * 5.7.3), but it doesn't specifically say that the unit attention should
11939  * be established for this particular initiator when a LUN is reset.  Here
11940  * is the relevant text, from SAM-3 rev 8:
11941  *
11942  * 5.7.2 When a SCSI initiator port aborts its own tasks
11943  *
11944  * When a SCSI initiator port causes its own task(s) to be aborted, no
11945  * notification that the task(s) have been aborted shall be returned to
11946  * the SCSI initiator port other than the completion response for the
11947  * command or task management function action that caused the task(s) to
11948  * be aborted and notification(s) associated with related effects of the
11949  * action (e.g., a reset unit attention condition).
11950  *
11951  * XXX KDM for now, we're setting unit attention for all initiators.
11952  */
11953 static int
11954 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11955 {
11956         union ctl_io *xio;
11957 #if 0
11958         uint32_t initidx;
11959 #endif
11960         int i;
11961
11962         mtx_lock(&lun->lun_lock);
11963         /*
11964          * Run through the OOA queue and abort each I/O.
11965          */
11966         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11967              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11968                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11969         }
11970
11971         /*
11972          * This version sets unit attention for every
11973          */
11974 #if 0
11975         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11976         ctl_est_ua_all(lun, initidx, ua_type);
11977 #else
11978         ctl_est_ua_all(lun, -1, ua_type);
11979 #endif
11980
11981         /*
11982          * A reset (any kind, really) clears reservations established with
11983          * RESERVE/RELEASE.  It does not clear reservations established
11984          * with PERSISTENT RESERVE OUT, but we don't support that at the
11985          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11986          * reservations made with the RESERVE/RELEASE commands, because
11987          * those commands are obsolete in SPC-3.
11988          */
11989         lun->flags &= ~CTL_LUN_RESERVED;
11990
11991 #ifdef CTL_WITH_CA
11992         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11993                 ctl_clear_mask(lun->have_ca, i);
11994 #endif
11995         lun->prevent_count = 0;
11996         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11997                 ctl_clear_mask(lun->prevent, i);
11998         mtx_unlock(&lun->lun_lock);
11999
12000         return (0);
12001 }
12002
12003 static int
12004 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
12005 {
12006         struct ctl_lun *lun;
12007         uint32_t targ_lun;
12008         int retval;
12009
12010         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12011         mtx_lock(&softc->ctl_lock);
12012         if ((targ_lun >= CTL_MAX_LUNS) ||
12013             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12014                 mtx_unlock(&softc->ctl_lock);
12015                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12016                 return (1);
12017         }
12018         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
12019         mtx_unlock(&softc->ctl_lock);
12020         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12021
12022         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
12023                 union ctl_ha_msg msg_info;
12024
12025                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12026                 msg_info.hdr.nexus = io->io_hdr.nexus;
12027                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
12028                 msg_info.hdr.original_sc = NULL;
12029                 msg_info.hdr.serializing_sc = NULL;
12030                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12031                     sizeof(msg_info.task), M_WAITOK);
12032         }
12033         return (retval);
12034 }
12035
12036 static void
12037 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12038     int other_sc)
12039 {
12040         union ctl_io *xio;
12041
12042         mtx_assert(&lun->lun_lock, MA_OWNED);
12043
12044         /*
12045          * Run through the OOA queue and attempt to find the given I/O.
12046          * The target port, initiator ID, tag type and tag number have to
12047          * match the values that we got from the initiator.  If we have an
12048          * untagged command to abort, simply abort the first untagged command
12049          * we come to.  We only allow one untagged command at a time of course.
12050          */
12051         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12052              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12053
12054                 if ((targ_port == UINT32_MAX ||
12055                      targ_port == xio->io_hdr.nexus.targ_port) &&
12056                     (init_id == UINT32_MAX ||
12057                      init_id == xio->io_hdr.nexus.initid)) {
12058                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12059                             init_id != xio->io_hdr.nexus.initid)
12060                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12061                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12062                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12063                                 union ctl_ha_msg msg_info;
12064
12065                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12066                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12067                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12068                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12069                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12070                                 msg_info.hdr.original_sc = NULL;
12071                                 msg_info.hdr.serializing_sc = NULL;
12072                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12073                                     sizeof(msg_info.task), M_NOWAIT);
12074                         }
12075                 }
12076         }
12077 }
12078
12079 static int
12080 ctl_abort_task_set(union ctl_io *io)
12081 {
12082         struct ctl_softc *softc = control_softc;
12083         struct ctl_lun *lun;
12084         uint32_t targ_lun;
12085
12086         /*
12087          * Look up the LUN.
12088          */
12089         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12090         mtx_lock(&softc->ctl_lock);
12091         if ((targ_lun >= CTL_MAX_LUNS) ||
12092             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12093                 mtx_unlock(&softc->ctl_lock);
12094                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12095                 return (1);
12096         }
12097
12098         mtx_lock(&lun->lun_lock);
12099         mtx_unlock(&softc->ctl_lock);
12100         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12101                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12102                     io->io_hdr.nexus.initid,
12103                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12104         } else { /* CTL_TASK_CLEAR_TASK_SET */
12105                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12106                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12107         }
12108         mtx_unlock(&lun->lun_lock);
12109         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12110         return (0);
12111 }
12112
12113 static int
12114 ctl_i_t_nexus_reset(union ctl_io *io)
12115 {
12116         struct ctl_softc *softc = control_softc;
12117         struct ctl_lun *lun;
12118         uint32_t initidx;
12119
12120         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12121                 union ctl_ha_msg msg_info;
12122
12123                 msg_info.hdr.nexus = io->io_hdr.nexus;
12124                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12125                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12126                 msg_info.hdr.original_sc = NULL;
12127                 msg_info.hdr.serializing_sc = NULL;
12128                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12129                     sizeof(msg_info.task), M_WAITOK);
12130         }
12131
12132         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12133         mtx_lock(&softc->ctl_lock);
12134         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12135                 mtx_lock(&lun->lun_lock);
12136                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12137                     io->io_hdr.nexus.initid, 1);
12138 #ifdef CTL_WITH_CA
12139                 ctl_clear_mask(lun->have_ca, initidx);
12140 #endif
12141                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12142                         lun->flags &= ~CTL_LUN_RESERVED;
12143                 if (ctl_is_set(lun->prevent, initidx)) {
12144                         ctl_clear_mask(lun->prevent, initidx);
12145                         lun->prevent_count--;
12146                 }
12147                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12148                 mtx_unlock(&lun->lun_lock);
12149         }
12150         mtx_unlock(&softc->ctl_lock);
12151         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12152         return (0);
12153 }
12154
12155 static int
12156 ctl_abort_task(union ctl_io *io)
12157 {
12158         union ctl_io *xio;
12159         struct ctl_lun *lun;
12160         struct ctl_softc *softc;
12161 #if 0
12162         struct sbuf sb;
12163         char printbuf[128];
12164 #endif
12165         int found;
12166         uint32_t targ_lun;
12167
12168         softc = control_softc;
12169         found = 0;
12170
12171         /*
12172          * Look up the LUN.
12173          */
12174         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12175         mtx_lock(&softc->ctl_lock);
12176         if ((targ_lun >= CTL_MAX_LUNS) ||
12177             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12178                 mtx_unlock(&softc->ctl_lock);
12179                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12180                 return (1);
12181         }
12182
12183 #if 0
12184         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12185                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12186 #endif
12187
12188         mtx_lock(&lun->lun_lock);
12189         mtx_unlock(&softc->ctl_lock);
12190         /*
12191          * Run through the OOA queue and attempt to find the given I/O.
12192          * The target port, initiator ID, tag type and tag number have to
12193          * match the values that we got from the initiator.  If we have an
12194          * untagged command to abort, simply abort the first untagged command
12195          * we come to.  We only allow one untagged command at a time of course.
12196          */
12197         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12198              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12199 #if 0
12200                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12201
12202                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12203                             lun->lun, xio->scsiio.tag_num,
12204                             xio->scsiio.tag_type,
12205                             (xio->io_hdr.blocked_links.tqe_prev
12206                             == NULL) ? "" : " BLOCKED",
12207                             (xio->io_hdr.flags &
12208                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12209                             (xio->io_hdr.flags &
12210                             CTL_FLAG_ABORT) ? " ABORT" : "",
12211                             (xio->io_hdr.flags &
12212                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12213                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12214                 sbuf_finish(&sb);
12215                 printf("%s\n", sbuf_data(&sb));
12216 #endif
12217
12218                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12219                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12220                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12221                         continue;
12222
12223                 /*
12224                  * If the abort says that the task is untagged, the
12225                  * task in the queue must be untagged.  Otherwise,
12226                  * we just check to see whether the tag numbers
12227                  * match.  This is because the QLogic firmware
12228                  * doesn't pass back the tag type in an abort
12229                  * request.
12230                  */
12231 #if 0
12232                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12233                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12234                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12235 #endif
12236                 /*
12237                  * XXX KDM we've got problems with FC, because it
12238                  * doesn't send down a tag type with aborts.  So we
12239                  * can only really go by the tag number...
12240                  * This may cause problems with parallel SCSI.
12241                  * Need to figure that out!!
12242                  */
12243                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12244                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12245                         found = 1;
12246                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12247                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12248                                 union ctl_ha_msg msg_info;
12249
12250                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12251                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12252                                 msg_info.task.tag_num = io->taskio.tag_num;
12253                                 msg_info.task.tag_type = io->taskio.tag_type;
12254                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12255                                 msg_info.hdr.original_sc = NULL;
12256                                 msg_info.hdr.serializing_sc = NULL;
12257 #if 0
12258                                 printf("Sent Abort to other side\n");
12259 #endif
12260                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12261                                     sizeof(msg_info.task), M_NOWAIT);
12262                         }
12263 #if 0
12264                         printf("ctl_abort_task: found I/O to abort\n");
12265 #endif
12266                 }
12267         }
12268         mtx_unlock(&lun->lun_lock);
12269
12270         if (found == 0) {
12271                 /*
12272                  * This isn't really an error.  It's entirely possible for
12273                  * the abort and command completion to cross on the wire.
12274                  * This is more of an informative/diagnostic error.
12275                  */
12276 #if 0
12277                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12278                        "%u:%u:%u tag %d type %d\n",
12279                        io->io_hdr.nexus.initid,
12280                        io->io_hdr.nexus.targ_port,
12281                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12282                        io->taskio.tag_type);
12283 #endif
12284         }
12285         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12286         return (0);
12287 }
12288
12289 static int
12290 ctl_query_task(union ctl_io *io, int task_set)
12291 {
12292         union ctl_io *xio;
12293         struct ctl_lun *lun;
12294         struct ctl_softc *softc;
12295         int found = 0;
12296         uint32_t targ_lun;
12297
12298         softc = control_softc;
12299         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12300         mtx_lock(&softc->ctl_lock);
12301         if ((targ_lun >= CTL_MAX_LUNS) ||
12302             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12303                 mtx_unlock(&softc->ctl_lock);
12304                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12305                 return (1);
12306         }
12307         mtx_lock(&lun->lun_lock);
12308         mtx_unlock(&softc->ctl_lock);
12309         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12310              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12311
12312                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12313                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12314                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12315                         continue;
12316
12317                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12318                         found = 1;
12319                         break;
12320                 }
12321         }
12322         mtx_unlock(&lun->lun_lock);
12323         if (found)
12324                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12325         else
12326                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12327         return (0);
12328 }
12329
12330 static int
12331 ctl_query_async_event(union ctl_io *io)
12332 {
12333         struct ctl_lun *lun;
12334         struct ctl_softc *softc;
12335         ctl_ua_type ua;
12336         uint32_t targ_lun, initidx;
12337
12338         softc = control_softc;
12339         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12340         mtx_lock(&softc->ctl_lock);
12341         if ((targ_lun >= CTL_MAX_LUNS) ||
12342             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12343                 mtx_unlock(&softc->ctl_lock);
12344                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12345                 return (1);
12346         }
12347         mtx_lock(&lun->lun_lock);
12348         mtx_unlock(&softc->ctl_lock);
12349         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12350         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12351         mtx_unlock(&lun->lun_lock);
12352         if (ua != CTL_UA_NONE)
12353                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12354         else
12355                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12356         return (0);
12357 }
12358
12359 static void
12360 ctl_run_task(union ctl_io *io)
12361 {
12362         struct ctl_softc *softc = control_softc;
12363         int retval = 1;
12364
12365         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12366         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12367             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12368         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12369         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12370         switch (io->taskio.task_action) {
12371         case CTL_TASK_ABORT_TASK:
12372                 retval = ctl_abort_task(io);
12373                 break;
12374         case CTL_TASK_ABORT_TASK_SET:
12375         case CTL_TASK_CLEAR_TASK_SET:
12376                 retval = ctl_abort_task_set(io);
12377                 break;
12378         case CTL_TASK_CLEAR_ACA:
12379                 break;
12380         case CTL_TASK_I_T_NEXUS_RESET:
12381                 retval = ctl_i_t_nexus_reset(io);
12382                 break;
12383         case CTL_TASK_LUN_RESET:
12384                 retval = ctl_lun_reset(softc, io);
12385                 break;
12386         case CTL_TASK_TARGET_RESET:
12387                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12388                 break;
12389         case CTL_TASK_BUS_RESET:
12390                 retval = ctl_bus_reset(softc, io);
12391                 break;
12392         case CTL_TASK_PORT_LOGIN:
12393                 break;
12394         case CTL_TASK_PORT_LOGOUT:
12395                 break;
12396         case CTL_TASK_QUERY_TASK:
12397                 retval = ctl_query_task(io, 0);
12398                 break;
12399         case CTL_TASK_QUERY_TASK_SET:
12400                 retval = ctl_query_task(io, 1);
12401                 break;
12402         case CTL_TASK_QUERY_ASYNC_EVENT:
12403                 retval = ctl_query_async_event(io);
12404                 break;
12405         default:
12406                 printf("%s: got unknown task management event %d\n",
12407                        __func__, io->taskio.task_action);
12408                 break;
12409         }
12410         if (retval == 0)
12411                 io->io_hdr.status = CTL_SUCCESS;
12412         else
12413                 io->io_hdr.status = CTL_ERROR;
12414         ctl_done(io);
12415 }
12416
12417 /*
12418  * For HA operation.  Handle commands that come in from the other
12419  * controller.
12420  */
12421 static void
12422 ctl_handle_isc(union ctl_io *io)
12423 {
12424         int free_io;
12425         struct ctl_lun *lun;
12426         struct ctl_softc *softc = control_softc;
12427         uint32_t targ_lun;
12428
12429         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12430         lun = softc->ctl_luns[targ_lun];
12431
12432         switch (io->io_hdr.msg_type) {
12433         case CTL_MSG_SERIALIZE:
12434                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12435                 break;
12436         case CTL_MSG_R2R: {
12437                 const struct ctl_cmd_entry *entry;
12438
12439                 /*
12440                  * This is only used in SER_ONLY mode.
12441                  */
12442                 free_io = 0;
12443                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12444                 mtx_lock(&lun->lun_lock);
12445                 if (ctl_scsiio_lun_check(lun,
12446                     entry, (struct ctl_scsiio *)io) != 0) {
12447                         mtx_unlock(&lun->lun_lock);
12448                         ctl_done(io);
12449                         break;
12450                 }
12451                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12452                 mtx_unlock(&lun->lun_lock);
12453                 ctl_enqueue_rtr(io);
12454                 break;
12455         }
12456         case CTL_MSG_FINISH_IO:
12457                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12458                         free_io = 0;
12459                         ctl_done(io);
12460                 } else {
12461                         free_io = 1;
12462                         mtx_lock(&lun->lun_lock);
12463                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12464                                      ooa_links);
12465                         ctl_check_blocked(lun);
12466                         mtx_unlock(&lun->lun_lock);
12467                 }
12468                 break;
12469         case CTL_MSG_PERS_ACTION:
12470                 ctl_hndl_per_res_out_on_other_sc(
12471                         (union ctl_ha_msg *)&io->presio.pr_msg);
12472                 free_io = 1;
12473                 break;
12474         case CTL_MSG_BAD_JUJU:
12475                 free_io = 0;
12476                 ctl_done(io);
12477                 break;
12478         case CTL_MSG_DATAMOVE:
12479                 /* Only used in XFER mode */
12480                 free_io = 0;
12481                 ctl_datamove_remote(io);
12482                 break;
12483         case CTL_MSG_DATAMOVE_DONE:
12484                 /* Only used in XFER mode */
12485                 free_io = 0;
12486                 io->scsiio.be_move_done(io);
12487                 break;
12488         case CTL_MSG_FAILOVER:
12489                 ctl_failover_lun(io);
12490                 free_io = 1;
12491                 break;
12492         default:
12493                 free_io = 1;
12494                 printf("%s: Invalid message type %d\n",
12495                        __func__, io->io_hdr.msg_type);
12496                 break;
12497         }
12498         if (free_io)
12499                 ctl_free_io(io);
12500
12501 }
12502
12503
12504 /*
12505  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12506  * there is no match.
12507  */
12508 static ctl_lun_error_pattern
12509 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12510 {
12511         const struct ctl_cmd_entry *entry;
12512         ctl_lun_error_pattern filtered_pattern, pattern;
12513
12514         pattern = desc->error_pattern;
12515
12516         /*
12517          * XXX KDM we need more data passed into this function to match a
12518          * custom pattern, and we actually need to implement custom pattern
12519          * matching.
12520          */
12521         if (pattern & CTL_LUN_PAT_CMD)
12522                 return (CTL_LUN_PAT_CMD);
12523
12524         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12525                 return (CTL_LUN_PAT_ANY);
12526
12527         entry = ctl_get_cmd_entry(ctsio, NULL);
12528
12529         filtered_pattern = entry->pattern & pattern;
12530
12531         /*
12532          * If the user requested specific flags in the pattern (e.g.
12533          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12534          * flags.
12535          *
12536          * If the user did not specify any flags, it doesn't matter whether
12537          * or not the command supports the flags.
12538          */
12539         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12540              (pattern & ~CTL_LUN_PAT_MASK))
12541                 return (CTL_LUN_PAT_NONE);
12542
12543         /*
12544          * If the user asked for a range check, see if the requested LBA
12545          * range overlaps with this command's LBA range.
12546          */
12547         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12548                 uint64_t lba1;
12549                 uint64_t len1;
12550                 ctl_action action;
12551                 int retval;
12552
12553                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12554                 if (retval != 0)
12555                         return (CTL_LUN_PAT_NONE);
12556
12557                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12558                                               desc->lba_range.len, FALSE);
12559                 /*
12560                  * A "pass" means that the LBA ranges don't overlap, so
12561                  * this doesn't match the user's range criteria.
12562                  */
12563                 if (action == CTL_ACTION_PASS)
12564                         return (CTL_LUN_PAT_NONE);
12565         }
12566
12567         return (filtered_pattern);
12568 }
12569
12570 static void
12571 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12572 {
12573         struct ctl_error_desc *desc, *desc2;
12574
12575         mtx_assert(&lun->lun_lock, MA_OWNED);
12576
12577         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12578                 ctl_lun_error_pattern pattern;
12579                 /*
12580                  * Check to see whether this particular command matches
12581                  * the pattern in the descriptor.
12582                  */
12583                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12584                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12585                         continue;
12586
12587                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12588                 case CTL_LUN_INJ_ABORTED:
12589                         ctl_set_aborted(&io->scsiio);
12590                         break;
12591                 case CTL_LUN_INJ_MEDIUM_ERR:
12592                         ctl_set_medium_error(&io->scsiio,
12593                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12594                              CTL_FLAG_DATA_OUT);
12595                         break;
12596                 case CTL_LUN_INJ_UA:
12597                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12598                          * OCCURRED */
12599                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12600                         break;
12601                 case CTL_LUN_INJ_CUSTOM:
12602                         /*
12603                          * We're assuming the user knows what he is doing.
12604                          * Just copy the sense information without doing
12605                          * checks.
12606                          */
12607                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12608                               MIN(sizeof(desc->custom_sense),
12609                                   sizeof(io->scsiio.sense_data)));
12610                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12611                         io->scsiio.sense_len = SSD_FULL_SIZE;
12612                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12613                         break;
12614                 case CTL_LUN_INJ_NONE:
12615                 default:
12616                         /*
12617                          * If this is an error injection type we don't know
12618                          * about, clear the continuous flag (if it is set)
12619                          * so it will get deleted below.
12620                          */
12621                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12622                         break;
12623                 }
12624                 /*
12625                  * By default, each error injection action is a one-shot
12626                  */
12627                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12628                         continue;
12629
12630                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12631
12632                 free(desc, M_CTL);
12633         }
12634 }
12635
12636 #ifdef CTL_IO_DELAY
12637 static void
12638 ctl_datamove_timer_wakeup(void *arg)
12639 {
12640         union ctl_io *io;
12641
12642         io = (union ctl_io *)arg;
12643
12644         ctl_datamove(io);
12645 }
12646 #endif /* CTL_IO_DELAY */
12647
12648 void
12649 ctl_datamove(union ctl_io *io)
12650 {
12651         struct ctl_lun *lun;
12652         void (*fe_datamove)(union ctl_io *io);
12653
12654         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12655
12656         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12657
12658         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12659 #ifdef CTL_TIME_IO
12660         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12661                 char str[256];
12662                 char path_str[64];
12663                 struct sbuf sb;
12664
12665                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12666                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12667
12668                 sbuf_cat(&sb, path_str);
12669                 switch (io->io_hdr.io_type) {
12670                 case CTL_IO_SCSI:
12671                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12672                         sbuf_printf(&sb, "\n");
12673                         sbuf_cat(&sb, path_str);
12674                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12675                                     io->scsiio.tag_num, io->scsiio.tag_type);
12676                         break;
12677                 case CTL_IO_TASK:
12678                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12679                                     "Tag Type: %d\n", io->taskio.task_action,
12680                                     io->taskio.tag_num, io->taskio.tag_type);
12681                         break;
12682                 default:
12683                         panic("%s: Invalid CTL I/O type %d\n",
12684                             __func__, io->io_hdr.io_type);
12685                 }
12686                 sbuf_cat(&sb, path_str);
12687                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12688                             (intmax_t)time_uptime - io->io_hdr.start_time);
12689                 sbuf_finish(&sb);
12690                 printf("%s", sbuf_data(&sb));
12691         }
12692 #endif /* CTL_TIME_IO */
12693
12694 #ifdef CTL_IO_DELAY
12695         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12696                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12697         } else {
12698                 if ((lun != NULL)
12699                  && (lun->delay_info.datamove_delay > 0)) {
12700
12701                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12702                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12703                         callout_reset(&io->io_hdr.delay_callout,
12704                                       lun->delay_info.datamove_delay * hz,
12705                                       ctl_datamove_timer_wakeup, io);
12706                         if (lun->delay_info.datamove_type ==
12707                             CTL_DELAY_TYPE_ONESHOT)
12708                                 lun->delay_info.datamove_delay = 0;
12709                         return;
12710                 }
12711         }
12712 #endif
12713
12714         /*
12715          * This command has been aborted.  Set the port status, so we fail
12716          * the data move.
12717          */
12718         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12719                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12720                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12721                        io->io_hdr.nexus.targ_port,
12722                        io->io_hdr.nexus.targ_lun);
12723                 io->io_hdr.port_status = 31337;
12724                 /*
12725                  * Note that the backend, in this case, will get the
12726                  * callback in its context.  In other cases it may get
12727                  * called in the frontend's interrupt thread context.
12728                  */
12729                 io->scsiio.be_move_done(io);
12730                 return;
12731         }
12732
12733         /* Don't confuse frontend with zero length data move. */
12734         if (io->scsiio.kern_data_len == 0) {
12735                 io->scsiio.be_move_done(io);
12736                 return;
12737         }
12738
12739         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12740         fe_datamove(io);
12741 }
12742
12743 static void
12744 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12745 {
12746         union ctl_ha_msg msg;
12747 #ifdef CTL_TIME_IO
12748         struct bintime cur_bt;
12749 #endif
12750
12751         memset(&msg, 0, sizeof(msg));
12752         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12753         msg.hdr.original_sc = io;
12754         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12755         msg.hdr.nexus = io->io_hdr.nexus;
12756         msg.hdr.status = io->io_hdr.status;
12757         msg.scsi.tag_num = io->scsiio.tag_num;
12758         msg.scsi.tag_type = io->scsiio.tag_type;
12759         msg.scsi.scsi_status = io->scsiio.scsi_status;
12760         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12761                io->scsiio.sense_len);
12762         msg.scsi.sense_len = io->scsiio.sense_len;
12763         msg.scsi.sense_residual = io->scsiio.sense_residual;
12764         msg.scsi.fetd_status = io->io_hdr.port_status;
12765         msg.scsi.residual = io->scsiio.residual;
12766         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12767         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12768                 ctl_failover_io(io, /*have_lock*/ have_lock);
12769                 return;
12770         }
12771         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12772             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12773             msg.scsi.sense_len, M_WAITOK);
12774
12775 #ifdef CTL_TIME_IO
12776         getbinuptime(&cur_bt);
12777         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12778         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12779 #endif
12780         io->io_hdr.num_dmas++;
12781 }
12782
12783 /*
12784  * The DMA to the remote side is done, now we need to tell the other side
12785  * we're done so it can continue with its data movement.
12786  */
12787 static void
12788 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12789 {
12790         union ctl_io *io;
12791         uint32_t i;
12792
12793         io = rq->context;
12794
12795         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12796                 printf("%s: ISC DMA write failed with error %d", __func__,
12797                        rq->ret);
12798                 ctl_set_internal_failure(&io->scsiio,
12799                                          /*sks_valid*/ 1,
12800                                          /*retry_count*/ rq->ret);
12801         }
12802
12803         ctl_dt_req_free(rq);
12804
12805         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12806                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12807         free(io->io_hdr.remote_sglist, M_CTL);
12808         io->io_hdr.remote_sglist = NULL;
12809         io->io_hdr.local_sglist = NULL;
12810
12811         /*
12812          * The data is in local and remote memory, so now we need to send
12813          * status (good or back) back to the other side.
12814          */
12815         ctl_send_datamove_done(io, /*have_lock*/ 0);
12816 }
12817
12818 /*
12819  * We've moved the data from the host/controller into local memory.  Now we
12820  * need to push it over to the remote controller's memory.
12821  */
12822 static int
12823 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12824 {
12825         int retval;
12826
12827         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12828                                           ctl_datamove_remote_write_cb);
12829         return (retval);
12830 }
12831
12832 static void
12833 ctl_datamove_remote_write(union ctl_io *io)
12834 {
12835         int retval;
12836         void (*fe_datamove)(union ctl_io *io);
12837
12838         /*
12839          * - Get the data from the host/HBA into local memory.
12840          * - DMA memory from the local controller to the remote controller.
12841          * - Send status back to the remote controller.
12842          */
12843
12844         retval = ctl_datamove_remote_sgl_setup(io);
12845         if (retval != 0)
12846                 return;
12847
12848         /* Switch the pointer over so the FETD knows what to do */
12849         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12850
12851         /*
12852          * Use a custom move done callback, since we need to send completion
12853          * back to the other controller, not to the backend on this side.
12854          */
12855         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12856
12857         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12858         fe_datamove(io);
12859 }
12860
12861 static int
12862 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12863 {
12864 #if 0
12865         char str[256];
12866         char path_str[64];
12867         struct sbuf sb;
12868 #endif
12869         uint32_t i;
12870
12871         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12872                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12873         free(io->io_hdr.remote_sglist, M_CTL);
12874         io->io_hdr.remote_sglist = NULL;
12875         io->io_hdr.local_sglist = NULL;
12876
12877 #if 0
12878         scsi_path_string(io, path_str, sizeof(path_str));
12879         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12880         sbuf_cat(&sb, path_str);
12881         scsi_command_string(&io->scsiio, NULL, &sb);
12882         sbuf_printf(&sb, "\n");
12883         sbuf_cat(&sb, path_str);
12884         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12885                     io->scsiio.tag_num, io->scsiio.tag_type);
12886         sbuf_cat(&sb, path_str);
12887         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12888                     io->io_hdr.flags, io->io_hdr.status);
12889         sbuf_finish(&sb);
12890         printk("%s", sbuf_data(&sb));
12891 #endif
12892
12893
12894         /*
12895          * The read is done, now we need to send status (good or bad) back
12896          * to the other side.
12897          */
12898         ctl_send_datamove_done(io, /*have_lock*/ 0);
12899
12900         return (0);
12901 }
12902
12903 static void
12904 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12905 {
12906         union ctl_io *io;
12907         void (*fe_datamove)(union ctl_io *io);
12908
12909         io = rq->context;
12910
12911         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12912                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12913                        rq->ret);
12914                 ctl_set_internal_failure(&io->scsiio,
12915                                          /*sks_valid*/ 1,
12916                                          /*retry_count*/ rq->ret);
12917         }
12918
12919         ctl_dt_req_free(rq);
12920
12921         /* Switch the pointer over so the FETD knows what to do */
12922         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12923
12924         /*
12925          * Use a custom move done callback, since we need to send completion
12926          * back to the other controller, not to the backend on this side.
12927          */
12928         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12929
12930         /* XXX KDM add checks like the ones in ctl_datamove? */
12931
12932         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12933         fe_datamove(io);
12934 }
12935
12936 static int
12937 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12938 {
12939         struct ctl_sg_entry *local_sglist;
12940         uint32_t len_to_go;
12941         int retval;
12942         int i;
12943
12944         retval = 0;
12945         local_sglist = io->io_hdr.local_sglist;
12946         len_to_go = io->scsiio.kern_data_len;
12947
12948         /*
12949          * The difficult thing here is that the size of the various
12950          * S/G segments may be different than the size from the
12951          * remote controller.  That'll make it harder when DMAing
12952          * the data back to the other side.
12953          */
12954         for (i = 0; len_to_go > 0; i++) {
12955                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12956                 local_sglist[i].addr =
12957                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12958
12959                 len_to_go -= local_sglist[i].len;
12960         }
12961         /*
12962          * Reset the number of S/G entries accordingly.  The original
12963          * number of S/G entries is available in rem_sg_entries.
12964          */
12965         io->scsiio.kern_sg_entries = i;
12966
12967 #if 0
12968         printf("%s: kern_sg_entries = %d\n", __func__,
12969                io->scsiio.kern_sg_entries);
12970         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12971                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12972                        local_sglist[i].addr, local_sglist[i].len);
12973 #endif
12974
12975         return (retval);
12976 }
12977
12978 static int
12979 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12980                          ctl_ha_dt_cb callback)
12981 {
12982         struct ctl_ha_dt_req *rq;
12983         struct ctl_sg_entry *remote_sglist, *local_sglist;
12984         uint32_t local_used, remote_used, total_used;
12985         int i, j, isc_ret;
12986
12987         rq = ctl_dt_req_alloc();
12988
12989         /*
12990          * If we failed to allocate the request, and if the DMA didn't fail
12991          * anyway, set busy status.  This is just a resource allocation
12992          * failure.
12993          */
12994         if ((rq == NULL)
12995          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12996              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12997                 ctl_set_busy(&io->scsiio);
12998
12999         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
13000             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
13001
13002                 if (rq != NULL)
13003                         ctl_dt_req_free(rq);
13004
13005                 /*
13006                  * The data move failed.  We need to return status back
13007                  * to the other controller.  No point in trying to DMA
13008                  * data to the remote controller.
13009                  */
13010
13011                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13012
13013                 return (1);
13014         }
13015
13016         local_sglist = io->io_hdr.local_sglist;
13017         remote_sglist = io->io_hdr.remote_sglist;
13018         local_used = 0;
13019         remote_used = 0;
13020         total_used = 0;
13021
13022         /*
13023          * Pull/push the data over the wire from/to the other controller.
13024          * This takes into account the possibility that the local and
13025          * remote sglists may not be identical in terms of the size of
13026          * the elements and the number of elements.
13027          *
13028          * One fundamental assumption here is that the length allocated for
13029          * both the local and remote sglists is identical.  Otherwise, we've
13030          * essentially got a coding error of some sort.
13031          */
13032         isc_ret = CTL_HA_STATUS_SUCCESS;
13033         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13034                 uint32_t cur_len;
13035                 uint8_t *tmp_ptr;
13036
13037                 rq->command = command;
13038                 rq->context = io;
13039
13040                 /*
13041                  * Both pointers should be aligned.  But it is possible
13042                  * that the allocation length is not.  They should both
13043                  * also have enough slack left over at the end, though,
13044                  * to round up to the next 8 byte boundary.
13045                  */
13046                 cur_len = MIN(local_sglist[i].len - local_used,
13047                               remote_sglist[j].len - remote_used);
13048                 rq->size = cur_len;
13049
13050                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13051                 tmp_ptr += local_used;
13052
13053 #if 0
13054                 /* Use physical addresses when talking to ISC hardware */
13055                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13056                         /* XXX KDM use busdma */
13057                         rq->local = vtophys(tmp_ptr);
13058                 } else
13059                         rq->local = tmp_ptr;
13060 #else
13061                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13062                     ("HA does not support BUS_ADDR"));
13063                 rq->local = tmp_ptr;
13064 #endif
13065
13066                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13067                 tmp_ptr += remote_used;
13068                 rq->remote = tmp_ptr;
13069
13070                 rq->callback = NULL;
13071
13072                 local_used += cur_len;
13073                 if (local_used >= local_sglist[i].len) {
13074                         i++;
13075                         local_used = 0;
13076                 }
13077
13078                 remote_used += cur_len;
13079                 if (remote_used >= remote_sglist[j].len) {
13080                         j++;
13081                         remote_used = 0;
13082                 }
13083                 total_used += cur_len;
13084
13085                 if (total_used >= io->scsiio.kern_data_len)
13086                         rq->callback = callback;
13087
13088 #if 0
13089                 printf("%s: %s: local %p remote %p size %d\n", __func__,
13090                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13091                        rq->local, rq->remote, rq->size);
13092 #endif
13093
13094                 isc_ret = ctl_dt_single(rq);
13095                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
13096                         break;
13097         }
13098         if (isc_ret != CTL_HA_STATUS_WAIT) {
13099                 rq->ret = isc_ret;
13100                 callback(rq);
13101         }
13102
13103         return (0);
13104 }
13105
13106 static void
13107 ctl_datamove_remote_read(union ctl_io *io)
13108 {
13109         int retval;
13110         uint32_t i;
13111
13112         /*
13113          * This will send an error to the other controller in the case of a
13114          * failure.
13115          */
13116         retval = ctl_datamove_remote_sgl_setup(io);
13117         if (retval != 0)
13118                 return;
13119
13120         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13121                                           ctl_datamove_remote_read_cb);
13122         if (retval != 0) {
13123                 /*
13124                  * Make sure we free memory if there was an error..  The
13125                  * ctl_datamove_remote_xfer() function will send the
13126                  * datamove done message, or call the callback with an
13127                  * error if there is a problem.
13128                  */
13129                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13130                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13131                 free(io->io_hdr.remote_sglist, M_CTL);
13132                 io->io_hdr.remote_sglist = NULL;
13133                 io->io_hdr.local_sglist = NULL;
13134         }
13135 }
13136
13137 /*
13138  * Process a datamove request from the other controller.  This is used for
13139  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13140  * first.  Once that is complete, the data gets DMAed into the remote
13141  * controller's memory.  For reads, we DMA from the remote controller's
13142  * memory into our memory first, and then move it out to the FETD.
13143  */
13144 static void
13145 ctl_datamove_remote(union ctl_io *io)
13146 {
13147
13148         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13149
13150         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13151                 ctl_failover_io(io, /*have_lock*/ 0);
13152                 return;
13153         }
13154
13155         /*
13156          * Note that we look for an aborted I/O here, but don't do some of
13157          * the other checks that ctl_datamove() normally does.
13158          * We don't need to run the datamove delay code, since that should
13159          * have been done if need be on the other controller.
13160          */
13161         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13162                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13163                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13164                        io->io_hdr.nexus.targ_port,
13165                        io->io_hdr.nexus.targ_lun);
13166                 io->io_hdr.port_status = 31338;
13167                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13168                 return;
13169         }
13170
13171         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13172                 ctl_datamove_remote_write(io);
13173         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13174                 ctl_datamove_remote_read(io);
13175         else {
13176                 io->io_hdr.port_status = 31339;
13177                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13178         }
13179 }
13180
13181 static void
13182 ctl_process_done(union ctl_io *io)
13183 {
13184         struct ctl_lun *lun;
13185         struct ctl_softc *softc = control_softc;
13186         void (*fe_done)(union ctl_io *io);
13187         union ctl_ha_msg msg;
13188         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13189
13190         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13191         fe_done = softc->ctl_ports[targ_port]->fe_done;
13192
13193 #ifdef CTL_TIME_IO
13194         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13195                 char str[256];
13196                 char path_str[64];
13197                 struct sbuf sb;
13198
13199                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13200                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13201
13202                 sbuf_cat(&sb, path_str);
13203                 switch (io->io_hdr.io_type) {
13204                 case CTL_IO_SCSI:
13205                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13206                         sbuf_printf(&sb, "\n");
13207                         sbuf_cat(&sb, path_str);
13208                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13209                                     io->scsiio.tag_num, io->scsiio.tag_type);
13210                         break;
13211                 case CTL_IO_TASK:
13212                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13213                                     "Tag Type: %d\n", io->taskio.task_action,
13214                                     io->taskio.tag_num, io->taskio.tag_type);
13215                         break;
13216                 default:
13217                         panic("%s: Invalid CTL I/O type %d\n",
13218                             __func__, io->io_hdr.io_type);
13219                 }
13220                 sbuf_cat(&sb, path_str);
13221                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13222                             (intmax_t)time_uptime - io->io_hdr.start_time);
13223                 sbuf_finish(&sb);
13224                 printf("%s", sbuf_data(&sb));
13225         }
13226 #endif /* CTL_TIME_IO */
13227
13228         switch (io->io_hdr.io_type) {
13229         case CTL_IO_SCSI:
13230                 break;
13231         case CTL_IO_TASK:
13232                 if (ctl_debug & CTL_DEBUG_INFO)
13233                         ctl_io_error_print(io, NULL);
13234                 fe_done(io);
13235                 return;
13236         default:
13237                 panic("%s: Invalid CTL I/O type %d\n",
13238                     __func__, io->io_hdr.io_type);
13239         }
13240
13241         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13242         if (lun == NULL) {
13243                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13244                                  io->io_hdr.nexus.targ_mapped_lun));
13245                 goto bailout;
13246         }
13247
13248         mtx_lock(&lun->lun_lock);
13249
13250         /*
13251          * Check to see if we have any errors to inject here.  We only
13252          * inject errors for commands that don't already have errors set.
13253          */
13254         if (!STAILQ_EMPTY(&lun->error_list) &&
13255             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13256             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13257                 ctl_inject_error(lun, io);
13258
13259         /*
13260          * XXX KDM how do we treat commands that aren't completed
13261          * successfully?
13262          *
13263          * XXX KDM should we also track I/O latency?
13264          */
13265         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13266             io->io_hdr.io_type == CTL_IO_SCSI) {
13267 #ifdef CTL_TIME_IO
13268                 struct bintime cur_bt;
13269 #endif
13270                 int type;
13271
13272                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13273                     CTL_FLAG_DATA_IN)
13274                         type = CTL_STATS_READ;
13275                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13276                     CTL_FLAG_DATA_OUT)
13277                         type = CTL_STATS_WRITE;
13278                 else
13279                         type = CTL_STATS_NO_IO;
13280
13281                 lun->stats.ports[targ_port].bytes[type] +=
13282                     io->scsiio.kern_total_len;
13283                 lun->stats.ports[targ_port].operations[type]++;
13284 #ifdef CTL_TIME_IO
13285                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13286                    &io->io_hdr.dma_bt);
13287                 getbinuptime(&cur_bt);
13288                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13289                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13290 #endif
13291                 lun->stats.ports[targ_port].num_dmas[type] +=
13292                     io->io_hdr.num_dmas;
13293         }
13294
13295         /*
13296          * Remove this from the OOA queue.
13297          */
13298         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13299 #ifdef CTL_TIME_IO
13300         if (TAILQ_EMPTY(&lun->ooa_queue))
13301                 lun->last_busy = getsbinuptime();
13302 #endif
13303
13304         /*
13305          * Run through the blocked queue on this LUN and see if anything
13306          * has become unblocked, now that this transaction is done.
13307          */
13308         ctl_check_blocked(lun);
13309
13310         /*
13311          * If the LUN has been invalidated, free it if there is nothing
13312          * left on its OOA queue.
13313          */
13314         if ((lun->flags & CTL_LUN_INVALID)
13315          && TAILQ_EMPTY(&lun->ooa_queue)) {
13316                 mtx_unlock(&lun->lun_lock);
13317                 mtx_lock(&softc->ctl_lock);
13318                 ctl_free_lun(lun);
13319                 mtx_unlock(&softc->ctl_lock);
13320         } else
13321                 mtx_unlock(&lun->lun_lock);
13322
13323 bailout:
13324
13325         /*
13326          * If this command has been aborted, make sure we set the status
13327          * properly.  The FETD is responsible for freeing the I/O and doing
13328          * whatever it needs to do to clean up its state.
13329          */
13330         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13331                 ctl_set_task_aborted(&io->scsiio);
13332
13333         /*
13334          * If enabled, print command error status.
13335          */
13336         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13337             (ctl_debug & CTL_DEBUG_INFO) != 0)
13338                 ctl_io_error_print(io, NULL);
13339
13340         /*
13341          * Tell the FETD or the other shelf controller we're done with this
13342          * command.  Note that only SCSI commands get to this point.  Task
13343          * management commands are completed above.
13344          */
13345         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13346             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13347                 memset(&msg, 0, sizeof(msg));
13348                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13349                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13350                 msg.hdr.nexus = io->io_hdr.nexus;
13351                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13352                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13353                     M_WAITOK);
13354         }
13355
13356         fe_done(io);
13357 }
13358
13359 #ifdef CTL_WITH_CA
13360 /*
13361  * Front end should call this if it doesn't do autosense.  When the request
13362  * sense comes back in from the initiator, we'll dequeue this and send it.
13363  */
13364 int
13365 ctl_queue_sense(union ctl_io *io)
13366 {
13367         struct ctl_lun *lun;
13368         struct ctl_port *port;
13369         struct ctl_softc *softc;
13370         uint32_t initidx, targ_lun;
13371
13372         softc = control_softc;
13373
13374         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13375
13376         /*
13377          * LUN lookup will likely move to the ctl_work_thread() once we
13378          * have our new queueing infrastructure (that doesn't put things on
13379          * a per-LUN queue initially).  That is so that we can handle
13380          * things like an INQUIRY to a LUN that we don't have enabled.  We
13381          * can't deal with that right now.
13382          */
13383         mtx_lock(&softc->ctl_lock);
13384
13385         /*
13386          * If we don't have a LUN for this, just toss the sense
13387          * information.
13388          */
13389         port = ctl_io_port(&ctsio->io_hdr);
13390         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13391         if ((targ_lun < CTL_MAX_LUNS)
13392          && (softc->ctl_luns[targ_lun] != NULL))
13393                 lun = softc->ctl_luns[targ_lun];
13394         else
13395                 goto bailout;
13396
13397         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13398
13399         mtx_lock(&lun->lun_lock);
13400         /*
13401          * Already have CA set for this LUN...toss the sense information.
13402          */
13403         if (ctl_is_set(lun->have_ca, initidx)) {
13404                 mtx_unlock(&lun->lun_lock);
13405                 goto bailout;
13406         }
13407
13408         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13409                MIN(sizeof(lun->pending_sense[initidx]),
13410                sizeof(io->scsiio.sense_data)));
13411         ctl_set_mask(lun->have_ca, initidx);
13412         mtx_unlock(&lun->lun_lock);
13413
13414 bailout:
13415         mtx_unlock(&softc->ctl_lock);
13416
13417         ctl_free_io(io);
13418
13419         return (CTL_RETVAL_COMPLETE);
13420 }
13421 #endif
13422
13423 /*
13424  * Primary command inlet from frontend ports.  All SCSI and task I/O
13425  * requests must go through this function.
13426  */
13427 int
13428 ctl_queue(union ctl_io *io)
13429 {
13430         struct ctl_port *port;
13431
13432         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13433
13434 #ifdef CTL_TIME_IO
13435         io->io_hdr.start_time = time_uptime;
13436         getbinuptime(&io->io_hdr.start_bt);
13437 #endif /* CTL_TIME_IO */
13438
13439         /* Map FE-specific LUN ID into global one. */
13440         port = ctl_io_port(&io->io_hdr);
13441         io->io_hdr.nexus.targ_mapped_lun =
13442             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13443
13444         switch (io->io_hdr.io_type) {
13445         case CTL_IO_SCSI:
13446         case CTL_IO_TASK:
13447                 if (ctl_debug & CTL_DEBUG_CDB)
13448                         ctl_io_print(io);
13449                 ctl_enqueue_incoming(io);
13450                 break;
13451         default:
13452                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13453                 return (EINVAL);
13454         }
13455
13456         return (CTL_RETVAL_COMPLETE);
13457 }
13458
13459 #ifdef CTL_IO_DELAY
13460 static void
13461 ctl_done_timer_wakeup(void *arg)
13462 {
13463         union ctl_io *io;
13464
13465         io = (union ctl_io *)arg;
13466         ctl_done(io);
13467 }
13468 #endif /* CTL_IO_DELAY */
13469
13470 void
13471 ctl_serseq_done(union ctl_io *io)
13472 {
13473         struct ctl_lun *lun;
13474
13475         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13476         if (lun->be_lun == NULL ||
13477             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13478                 return;
13479         mtx_lock(&lun->lun_lock);
13480         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13481         ctl_check_blocked(lun);
13482         mtx_unlock(&lun->lun_lock);
13483 }
13484
13485 void
13486 ctl_done(union ctl_io *io)
13487 {
13488
13489         /*
13490          * Enable this to catch duplicate completion issues.
13491          */
13492 #if 0
13493         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13494                 printf("%s: type %d msg %d cdb %x iptl: "
13495                        "%u:%u:%u tag 0x%04x "
13496                        "flag %#x status %x\n",
13497                         __func__,
13498                         io->io_hdr.io_type,
13499                         io->io_hdr.msg_type,
13500                         io->scsiio.cdb[0],
13501                         io->io_hdr.nexus.initid,
13502                         io->io_hdr.nexus.targ_port,
13503                         io->io_hdr.nexus.targ_lun,
13504                         (io->io_hdr.io_type ==
13505                         CTL_IO_TASK) ?
13506                         io->taskio.tag_num :
13507                         io->scsiio.tag_num,
13508                         io->io_hdr.flags,
13509                         io->io_hdr.status);
13510         } else
13511                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13512 #endif
13513
13514         /*
13515          * This is an internal copy of an I/O, and should not go through
13516          * the normal done processing logic.
13517          */
13518         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13519                 return;
13520
13521 #ifdef CTL_IO_DELAY
13522         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13523                 struct ctl_lun *lun;
13524
13525                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13526
13527                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13528         } else {
13529                 struct ctl_lun *lun;
13530
13531                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13532
13533                 if ((lun != NULL)
13534                  && (lun->delay_info.done_delay > 0)) {
13535
13536                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13537                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13538                         callout_reset(&io->io_hdr.delay_callout,
13539                                       lun->delay_info.done_delay * hz,
13540                                       ctl_done_timer_wakeup, io);
13541                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13542                                 lun->delay_info.done_delay = 0;
13543                         return;
13544                 }
13545         }
13546 #endif /* CTL_IO_DELAY */
13547
13548         ctl_enqueue_done(io);
13549 }
13550
13551 static void
13552 ctl_work_thread(void *arg)
13553 {
13554         struct ctl_thread *thr = (struct ctl_thread *)arg;
13555         struct ctl_softc *softc = thr->ctl_softc;
13556         union ctl_io *io;
13557         int retval;
13558
13559         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13560
13561         for (;;) {
13562                 /*
13563                  * We handle the queues in this order:
13564                  * - ISC
13565                  * - done queue (to free up resources, unblock other commands)
13566                  * - RtR queue
13567                  * - incoming queue
13568                  *
13569                  * If those queues are empty, we break out of the loop and
13570                  * go to sleep.
13571                  */
13572                 mtx_lock(&thr->queue_lock);
13573                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13574                 if (io != NULL) {
13575                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13576                         mtx_unlock(&thr->queue_lock);
13577                         ctl_handle_isc(io);
13578                         continue;
13579                 }
13580                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13581                 if (io != NULL) {
13582                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13583                         /* clear any blocked commands, call fe_done */
13584                         mtx_unlock(&thr->queue_lock);
13585                         ctl_process_done(io);
13586                         continue;
13587                 }
13588                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13589                 if (io != NULL) {
13590                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13591                         mtx_unlock(&thr->queue_lock);
13592                         if (io->io_hdr.io_type == CTL_IO_TASK)
13593                                 ctl_run_task(io);
13594                         else
13595                                 ctl_scsiio_precheck(softc, &io->scsiio);
13596                         continue;
13597                 }
13598                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13599                 if (io != NULL) {
13600                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13601                         mtx_unlock(&thr->queue_lock);
13602                         retval = ctl_scsiio(&io->scsiio);
13603                         if (retval != CTL_RETVAL_COMPLETE)
13604                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13605                         continue;
13606                 }
13607
13608                 /* Sleep until we have something to do. */
13609                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13610         }
13611 }
13612
13613 static void
13614 ctl_lun_thread(void *arg)
13615 {
13616         struct ctl_softc *softc = (struct ctl_softc *)arg;
13617         struct ctl_be_lun *be_lun;
13618
13619         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13620
13621         for (;;) {
13622                 mtx_lock(&softc->ctl_lock);
13623                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13624                 if (be_lun != NULL) {
13625                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13626                         mtx_unlock(&softc->ctl_lock);
13627                         ctl_create_lun(be_lun);
13628                         continue;
13629                 }
13630
13631                 /* Sleep until we have something to do. */
13632                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13633                     PDROP | PRIBIO, "-", 0);
13634         }
13635 }
13636
13637 static void
13638 ctl_thresh_thread(void *arg)
13639 {
13640         struct ctl_softc *softc = (struct ctl_softc *)arg;
13641         struct ctl_lun *lun;
13642         struct scsi_da_rw_recovery_page *rwpage;
13643         struct ctl_logical_block_provisioning_page *page;
13644         const char *attr;
13645         union ctl_ha_msg msg;
13646         uint64_t thres, val;
13647         int i, e, set;
13648
13649         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13650
13651         for (;;) {
13652                 mtx_lock(&softc->ctl_lock);
13653                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13654                         if ((lun->flags & CTL_LUN_DISABLED) ||
13655                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13656                             lun->backend->lun_attr == NULL)
13657                                 continue;
13658                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13659                             softc->ha_mode == CTL_HA_MODE_XFER)
13660                                 continue;
13661                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13662                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13663                                 continue;
13664                         e = 0;
13665                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13666                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13667                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13668                                         continue;
13669                                 thres = scsi_4btoul(page->descr[i].count);
13670                                 thres <<= CTL_LBP_EXPONENT;
13671                                 switch (page->descr[i].resource) {
13672                                 case 0x01:
13673                                         attr = "blocksavail";
13674                                         break;
13675                                 case 0x02:
13676                                         attr = "blocksused";
13677                                         break;
13678                                 case 0xf1:
13679                                         attr = "poolblocksavail";
13680                                         break;
13681                                 case 0xf2:
13682                                         attr = "poolblocksused";
13683                                         break;
13684                                 default:
13685                                         continue;
13686                                 }
13687                                 mtx_unlock(&softc->ctl_lock); // XXX
13688                                 val = lun->backend->lun_attr(
13689                                     lun->be_lun->be_lun, attr);
13690                                 mtx_lock(&softc->ctl_lock);
13691                                 if (val == UINT64_MAX)
13692                                         continue;
13693                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13694                                     == SLBPPD_ARMING_INC)
13695                                         e = (val >= thres);
13696                                 else
13697                                         e = (val <= thres);
13698                                 if (e)
13699                                         break;
13700                         }
13701                         mtx_lock(&lun->lun_lock);
13702                         if (e) {
13703                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13704                                     (uint8_t *)page, lun->ua_tpt_info);
13705                                 if (lun->lasttpt == 0 ||
13706                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13707                                         lun->lasttpt = time_uptime;
13708                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13709                                         set = 1;
13710                                 } else
13711                                         set = 0;
13712                         } else {
13713                                 lun->lasttpt = 0;
13714                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13715                                 set = -1;
13716                         }
13717                         mtx_unlock(&lun->lun_lock);
13718                         if (set != 0 &&
13719                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13720                                 /* Send msg to other side. */
13721                                 bzero(&msg.ua, sizeof(msg.ua));
13722                                 msg.hdr.msg_type = CTL_MSG_UA;
13723                                 msg.hdr.nexus.initid = -1;
13724                                 msg.hdr.nexus.targ_port = -1;
13725                                 msg.hdr.nexus.targ_lun = lun->lun;
13726                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13727                                 msg.ua.ua_all = 1;
13728                                 msg.ua.ua_set = (set > 0);
13729                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13730                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13731                                 mtx_unlock(&softc->ctl_lock); // XXX
13732                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13733                                     sizeof(msg.ua), M_WAITOK);
13734                                 mtx_lock(&softc->ctl_lock);
13735                         }
13736                 }
13737                 mtx_unlock(&softc->ctl_lock);
13738                 pause("-", CTL_LBP_PERIOD * hz);
13739         }
13740 }
13741
13742 static void
13743 ctl_enqueue_incoming(union ctl_io *io)
13744 {
13745         struct ctl_softc *softc = control_softc;
13746         struct ctl_thread *thr;
13747         u_int idx;
13748
13749         idx = (io->io_hdr.nexus.targ_port * 127 +
13750                io->io_hdr.nexus.initid) % worker_threads;
13751         thr = &softc->threads[idx];
13752         mtx_lock(&thr->queue_lock);
13753         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13754         mtx_unlock(&thr->queue_lock);
13755         wakeup(thr);
13756 }
13757
13758 static void
13759 ctl_enqueue_rtr(union ctl_io *io)
13760 {
13761         struct ctl_softc *softc = control_softc;
13762         struct ctl_thread *thr;
13763
13764         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13765         mtx_lock(&thr->queue_lock);
13766         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13767         mtx_unlock(&thr->queue_lock);
13768         wakeup(thr);
13769 }
13770
13771 static void
13772 ctl_enqueue_done(union ctl_io *io)
13773 {
13774         struct ctl_softc *softc = control_softc;
13775         struct ctl_thread *thr;
13776
13777         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13778         mtx_lock(&thr->queue_lock);
13779         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13780         mtx_unlock(&thr->queue_lock);
13781         wakeup(thr);
13782 }
13783
13784 static void
13785 ctl_enqueue_isc(union ctl_io *io)
13786 {
13787         struct ctl_softc *softc = control_softc;
13788         struct ctl_thread *thr;
13789
13790         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13791         mtx_lock(&thr->queue_lock);
13792         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13793         mtx_unlock(&thr->queue_lock);
13794         wakeup(thr);
13795 }
13796
13797 /*
13798  *  vim: ts=8
13799  */