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