]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl.c
Merge compiler-rt release_38 branch r258968.
[FreeBSD/FreeBSD.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 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406     &worker_threads, 1, "Number of worker threads");
407 static int ctl_debug = CTL_DEBUG_NONE;
408 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409     &ctl_debug, 0, "Enabled debug flags");
410
411 /*
412  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
413  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
414  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
415  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
416  */
417 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
418
419 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
420                                   int param);
421 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
422 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
423 static int ctl_init(void);
424 void ctl_shutdown(void);
425 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
426 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
427 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
428 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
429                               struct ctl_ooa *ooa_hdr,
430                               struct ctl_ooa_entry *kern_entries);
431 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
432                      struct thread *td);
433 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
434                          struct ctl_be_lun *be_lun);
435 static int ctl_free_lun(struct ctl_lun *lun);
436 static void ctl_create_lun(struct ctl_be_lun *be_lun);
437 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
438
439 static int ctl_do_mode_select(union ctl_io *io);
440 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
441                            uint64_t res_key, uint64_t sa_res_key,
442                            uint8_t type, uint32_t residx,
443                            struct ctl_scsiio *ctsio,
444                            struct scsi_per_res_out *cdb,
445                            struct scsi_per_res_out_parms* param);
446 static void ctl_pro_preempt_other(struct ctl_lun *lun,
447                                   union ctl_ha_msg *msg);
448 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
449 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
450 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
451 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
455                                          int alloc_len);
456 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
457                                          int alloc_len);
458 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
459 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
460 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
461 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
462 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
463 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
464     bool seq);
465 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
466 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
467     union ctl_io *pending_io, union ctl_io *ooa_io);
468 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
469                                 union ctl_io *starting_io);
470 static int ctl_check_blocked(struct ctl_lun *lun);
471 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
472                                 const struct ctl_cmd_entry *entry,
473                                 struct ctl_scsiio *ctsio);
474 static void ctl_failover_lun(union ctl_io *io);
475 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
476                                struct ctl_scsiio *ctsio);
477 static int ctl_scsiio(struct ctl_scsiio *ctsio);
478
479 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
480 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
481                             ctl_ua_type ua_type);
482 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
483                          ctl_ua_type ua_type);
484 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
485 static int ctl_abort_task(union ctl_io *io);
486 static int ctl_abort_task_set(union ctl_io *io);
487 static int ctl_query_task(union ctl_io *io, int task_set);
488 static int ctl_i_t_nexus_reset(union ctl_io *io);
489 static int ctl_query_async_event(union ctl_io *io);
490 static void ctl_run_task(union ctl_io *io);
491 #ifdef CTL_IO_DELAY
492 static void ctl_datamove_timer_wakeup(void *arg);
493 static void ctl_done_timer_wakeup(void *arg);
494 #endif /* CTL_IO_DELAY */
495
496 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
497 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
498 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
499 static void ctl_datamove_remote_write(union ctl_io *io);
500 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
501 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
502 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
503 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
504                                     ctl_ha_dt_cb callback);
505 static void ctl_datamove_remote_read(union ctl_io *io);
506 static void ctl_datamove_remote(union ctl_io *io);
507 static void ctl_process_done(union ctl_io *io);
508 static void ctl_lun_thread(void *arg);
509 static void ctl_thresh_thread(void *arg);
510 static void ctl_work_thread(void *arg);
511 static void ctl_enqueue_incoming(union ctl_io *io);
512 static void ctl_enqueue_rtr(union ctl_io *io);
513 static void ctl_enqueue_done(union ctl_io *io);
514 static void ctl_enqueue_isc(union ctl_io *io);
515 static const struct ctl_cmd_entry *
516     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
517 static const struct ctl_cmd_entry *
518     ctl_validate_command(struct ctl_scsiio *ctsio);
519 static int ctl_cmd_applicable(uint8_t lun_type,
520     const struct ctl_cmd_entry *entry);
521
522 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
523 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
524 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
525 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
526
527 /*
528  * Load the serialization table.  This isn't very pretty, but is probably
529  * the easiest way to do it.
530  */
531 #include "ctl_ser_table.c"
532
533 /*
534  * We only need to define open, close and ioctl routines for this driver.
535  */
536 static struct cdevsw ctl_cdevsw = {
537         .d_version =    D_VERSION,
538         .d_flags =      0,
539         .d_open =       ctl_open,
540         .d_close =      ctl_close,
541         .d_ioctl =      ctl_ioctl,
542         .d_name =       "ctl",
543 };
544
545
546 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
547
548 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
549
550 static moduledata_t ctl_moduledata = {
551         "ctl",
552         ctl_module_event_handler,
553         NULL
554 };
555
556 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
557 MODULE_VERSION(ctl, 1);
558
559 static struct ctl_frontend ha_frontend =
560 {
561         .name = "ha",
562 };
563
564 static void
565 ctl_ha_datamove(union ctl_io *io)
566 {
567         struct ctl_lun *lun;
568         struct ctl_sg_entry *sgl;
569         union ctl_ha_msg msg;
570         uint32_t sg_entries_sent;
571         int do_sg_copy, i, j;
572
573         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
574         memset(&msg.dt, 0, sizeof(msg.dt));
575         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
576         msg.hdr.original_sc = io->io_hdr.original_sc;
577         msg.hdr.serializing_sc = io;
578         msg.hdr.nexus = io->io_hdr.nexus;
579         msg.hdr.status = io->io_hdr.status;
580         msg.dt.flags = io->io_hdr.flags;
581
582         /*
583          * We convert everything into a S/G list here.  We can't
584          * pass by reference, only by value between controllers.
585          * So we can't pass a pointer to the S/G list, only as many
586          * S/G entries as we can fit in here.  If it's possible for
587          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
588          * then we need to break this up into multiple transfers.
589          */
590         if (io->scsiio.kern_sg_entries == 0) {
591                 msg.dt.kern_sg_entries = 1;
592 #if 0
593                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
594                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
595                 } else {
596                         /* XXX KDM use busdma here! */
597                         msg.dt.sg_list[0].addr =
598                             (void *)vtophys(io->scsiio.kern_data_ptr);
599                 }
600 #else
601                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
602                     ("HA does not support BUS_ADDR"));
603                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
604 #endif
605                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
606                 do_sg_copy = 0;
607         } else {
608                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
609                 do_sg_copy = 1;
610         }
611
612         msg.dt.kern_data_len = io->scsiio.kern_data_len;
613         msg.dt.kern_total_len = io->scsiio.kern_total_len;
614         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
615         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
616         msg.dt.sg_sequence = 0;
617
618         /*
619          * Loop until we've sent all of the S/G entries.  On the
620          * other end, we'll recompose these S/G entries into one
621          * contiguous list before processing.
622          */
623         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
624             msg.dt.sg_sequence++) {
625                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
626                     sizeof(msg.dt.sg_list[0])),
627                     msg.dt.kern_sg_entries - sg_entries_sent);
628                 if (do_sg_copy != 0) {
629                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
630                         for (i = sg_entries_sent, j = 0;
631                              i < msg.dt.cur_sg_entries; i++, j++) {
632 #if 0
633                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
634                                         msg.dt.sg_list[j].addr = sgl[i].addr;
635                                 } else {
636                                         /* XXX KDM use busdma here! */
637                                         msg.dt.sg_list[j].addr =
638                                             (void *)vtophys(sgl[i].addr);
639                                 }
640 #else
641                                 KASSERT((io->io_hdr.flags &
642                                     CTL_FLAG_BUS_ADDR) == 0,
643                                     ("HA does not support BUS_ADDR"));
644                                 msg.dt.sg_list[j].addr = sgl[i].addr;
645 #endif
646                                 msg.dt.sg_list[j].len = sgl[i].len;
647                         }
648                 }
649
650                 sg_entries_sent += msg.dt.cur_sg_entries;
651                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
652                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
653                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
654                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
655                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
656                         io->io_hdr.port_status = 31341;
657                         io->scsiio.be_move_done(io);
658                         return;
659                 }
660                 msg.dt.sent_sg_entries = sg_entries_sent;
661         }
662
663         /*
664          * Officially handover the request from us to peer.
665          * If failover has just happened, then we must return error.
666          * If failover happen just after, then it is not our problem.
667          */
668         if (lun)
669                 mtx_lock(&lun->lun_lock);
670         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
671                 if (lun)
672                         mtx_unlock(&lun->lun_lock);
673                 io->io_hdr.port_status = 31342;
674                 io->scsiio.be_move_done(io);
675                 return;
676         }
677         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
678         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
679         if (lun)
680                 mtx_unlock(&lun->lun_lock);
681 }
682
683 static void
684 ctl_ha_done(union ctl_io *io)
685 {
686         union ctl_ha_msg msg;
687
688         if (io->io_hdr.io_type == CTL_IO_SCSI) {
689                 memset(&msg, 0, sizeof(msg));
690                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
691                 msg.hdr.original_sc = io->io_hdr.original_sc;
692                 msg.hdr.nexus = io->io_hdr.nexus;
693                 msg.hdr.status = io->io_hdr.status;
694                 msg.scsi.scsi_status = io->scsiio.scsi_status;
695                 msg.scsi.tag_num = io->scsiio.tag_num;
696                 msg.scsi.tag_type = io->scsiio.tag_type;
697                 msg.scsi.sense_len = io->scsiio.sense_len;
698                 msg.scsi.sense_residual = io->scsiio.sense_residual;
699                 msg.scsi.residual = io->scsiio.residual;
700                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
701                     io->scsiio.sense_len);
702                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
703                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
704                     msg.scsi.sense_len, M_WAITOK);
705         }
706         ctl_free_io(io);
707 }
708
709 static void
710 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
711                             union ctl_ha_msg *msg_info)
712 {
713         struct ctl_scsiio *ctsio;
714
715         if (msg_info->hdr.original_sc == NULL) {
716                 printf("%s: original_sc == NULL!\n", __func__);
717                 /* XXX KDM now what? */
718                 return;
719         }
720
721         ctsio = &msg_info->hdr.original_sc->scsiio;
722         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
723         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
724         ctsio->io_hdr.status = msg_info->hdr.status;
725         ctsio->scsi_status = msg_info->scsi.scsi_status;
726         ctsio->sense_len = msg_info->scsi.sense_len;
727         ctsio->sense_residual = msg_info->scsi.sense_residual;
728         ctsio->residual = msg_info->scsi.residual;
729         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
730                msg_info->scsi.sense_len);
731         ctl_enqueue_isc((union ctl_io *)ctsio);
732 }
733
734 static void
735 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
736                                 union ctl_ha_msg *msg_info)
737 {
738         struct ctl_scsiio *ctsio;
739
740         if (msg_info->hdr.serializing_sc == NULL) {
741                 printf("%s: serializing_sc == NULL!\n", __func__);
742                 /* XXX KDM now what? */
743                 return;
744         }
745
746         ctsio = &msg_info->hdr.serializing_sc->scsiio;
747         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
748         ctl_enqueue_isc((union ctl_io *)ctsio);
749 }
750
751 void
752 ctl_isc_announce_lun(struct ctl_lun *lun)
753 {
754         struct ctl_softc *softc = lun->ctl_softc;
755         union ctl_ha_msg *msg;
756         struct ctl_ha_msg_lun_pr_key pr_key;
757         int i, k;
758
759         if (softc->ha_link != CTL_HA_LINK_ONLINE)
760                 return;
761         mtx_lock(&lun->lun_lock);
762         i = sizeof(msg->lun);
763         if (lun->lun_devid)
764                 i += lun->lun_devid->len;
765         i += sizeof(pr_key) * lun->pr_key_count;
766 alloc:
767         mtx_unlock(&lun->lun_lock);
768         msg = malloc(i, M_CTL, M_WAITOK);
769         mtx_lock(&lun->lun_lock);
770         k = sizeof(msg->lun);
771         if (lun->lun_devid)
772                 k += lun->lun_devid->len;
773         k += sizeof(pr_key) * lun->pr_key_count;
774         if (i < k) {
775                 free(msg, M_CTL);
776                 i = k;
777                 goto alloc;
778         }
779         bzero(&msg->lun, sizeof(msg->lun));
780         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
781         msg->hdr.nexus.targ_lun = lun->lun;
782         msg->hdr.nexus.targ_mapped_lun = lun->lun;
783         msg->lun.flags = lun->flags;
784         msg->lun.pr_generation = lun->pr_generation;
785         msg->lun.pr_res_idx = lun->pr_res_idx;
786         msg->lun.pr_res_type = lun->pr_res_type;
787         msg->lun.pr_key_count = lun->pr_key_count;
788         i = 0;
789         if (lun->lun_devid) {
790                 msg->lun.lun_devid_len = lun->lun_devid->len;
791                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
792                     msg->lun.lun_devid_len);
793                 i += msg->lun.lun_devid_len;
794         }
795         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
796                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
797                         continue;
798                 pr_key.pr_iid = k;
799                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
800                 i += sizeof(pr_key);
801         }
802         mtx_unlock(&lun->lun_lock);
803         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
804             M_WAITOK);
805         free(msg, M_CTL);
806
807         if (lun->flags & CTL_LUN_PRIMARY_SC) {
808                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
809                         ctl_isc_announce_mode(lun, -1,
810                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
811                             lun->mode_pages.index[i].subpage);
812                 }
813         }
814 }
815
816 void
817 ctl_isc_announce_port(struct ctl_port *port)
818 {
819         struct ctl_softc *softc = port->ctl_softc;
820         union ctl_ha_msg *msg;
821         int i;
822
823         if (port->targ_port < softc->port_min ||
824             port->targ_port >= softc->port_max ||
825             softc->ha_link != CTL_HA_LINK_ONLINE)
826                 return;
827         i = sizeof(msg->port) + strlen(port->port_name) + 1;
828         if (port->lun_map)
829                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
830         if (port->port_devid)
831                 i += port->port_devid->len;
832         if (port->target_devid)
833                 i += port->target_devid->len;
834         if (port->init_devid)
835                 i += port->init_devid->len;
836         msg = malloc(i, M_CTL, M_WAITOK);
837         bzero(&msg->port, sizeof(msg->port));
838         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
839         msg->hdr.nexus.targ_port = port->targ_port;
840         msg->port.port_type = port->port_type;
841         msg->port.physical_port = port->physical_port;
842         msg->port.virtual_port = port->virtual_port;
843         msg->port.status = port->status;
844         i = 0;
845         msg->port.name_len = sprintf(&msg->port.data[i],
846             "%d:%s", softc->ha_id, port->port_name) + 1;
847         i += msg->port.name_len;
848         if (port->lun_map) {
849                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
850                 memcpy(&msg->port.data[i], port->lun_map,
851                     msg->port.lun_map_len);
852                 i += msg->port.lun_map_len;
853         }
854         if (port->port_devid) {
855                 msg->port.port_devid_len = port->port_devid->len;
856                 memcpy(&msg->port.data[i], port->port_devid->data,
857                     msg->port.port_devid_len);
858                 i += msg->port.port_devid_len;
859         }
860         if (port->target_devid) {
861                 msg->port.target_devid_len = port->target_devid->len;
862                 memcpy(&msg->port.data[i], port->target_devid->data,
863                     msg->port.target_devid_len);
864                 i += msg->port.target_devid_len;
865         }
866         if (port->init_devid) {
867                 msg->port.init_devid_len = port->init_devid->len;
868                 memcpy(&msg->port.data[i], port->init_devid->data,
869                     msg->port.init_devid_len);
870                 i += msg->port.init_devid_len;
871         }
872         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
873             M_WAITOK);
874         free(msg, M_CTL);
875 }
876
877 void
878 ctl_isc_announce_iid(struct ctl_port *port, int iid)
879 {
880         struct ctl_softc *softc = port->ctl_softc;
881         union ctl_ha_msg *msg;
882         int i, l;
883
884         if (port->targ_port < softc->port_min ||
885             port->targ_port >= softc->port_max ||
886             softc->ha_link != CTL_HA_LINK_ONLINE)
887                 return;
888         mtx_lock(&softc->ctl_lock);
889         i = sizeof(msg->iid);
890         l = 0;
891         if (port->wwpn_iid[iid].name)
892                 l = strlen(port->wwpn_iid[iid].name) + 1;
893         i += l;
894         msg = malloc(i, M_CTL, M_NOWAIT);
895         if (msg == NULL) {
896                 mtx_unlock(&softc->ctl_lock);
897                 return;
898         }
899         bzero(&msg->iid, sizeof(msg->iid));
900         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
901         msg->hdr.nexus.targ_port = port->targ_port;
902         msg->hdr.nexus.initid = iid;
903         msg->iid.in_use = port->wwpn_iid[iid].in_use;
904         msg->iid.name_len = l;
905         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
906         if (port->wwpn_iid[iid].name)
907                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
908         mtx_unlock(&softc->ctl_lock);
909         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
910         free(msg, M_CTL);
911 }
912
913 void
914 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
915     uint8_t page, uint8_t subpage)
916 {
917         struct ctl_softc *softc = lun->ctl_softc;
918         union ctl_ha_msg msg;
919         int i;
920
921         if (softc->ha_link != CTL_HA_LINK_ONLINE)
922                 return;
923         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
924                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
925                     page && lun->mode_pages.index[i].subpage == subpage)
926                         break;
927         }
928         if (i == CTL_NUM_MODE_PAGES)
929                 return;
930
931         /* Don't try to replicate pages not present on this device. */
932         if (lun->mode_pages.index[i].page_data == NULL)
933                 return;
934
935         bzero(&msg.mode, sizeof(msg.mode));
936         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
937         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
938         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
939         msg.hdr.nexus.targ_lun = lun->lun;
940         msg.hdr.nexus.targ_mapped_lun = lun->lun;
941         msg.mode.page_code = page;
942         msg.mode.subpage = subpage;
943         msg.mode.page_len = lun->mode_pages.index[i].page_len;
944         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
945             msg.mode.page_len);
946         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
947             M_WAITOK);
948 }
949
950 static void
951 ctl_isc_ha_link_up(struct ctl_softc *softc)
952 {
953         struct ctl_port *port;
954         struct ctl_lun *lun;
955         union ctl_ha_msg msg;
956         int i;
957
958         /* Announce this node parameters to peer for validation. */
959         msg.login.msg_type = CTL_MSG_LOGIN;
960         msg.login.version = CTL_HA_VERSION;
961         msg.login.ha_mode = softc->ha_mode;
962         msg.login.ha_id = softc->ha_id;
963         msg.login.max_luns = CTL_MAX_LUNS;
964         msg.login.max_ports = CTL_MAX_PORTS;
965         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
966         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
967             M_WAITOK);
968
969         STAILQ_FOREACH(port, &softc->port_list, links) {
970                 ctl_isc_announce_port(port);
971                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
972                         if (port->wwpn_iid[i].in_use)
973                                 ctl_isc_announce_iid(port, i);
974                 }
975         }
976         STAILQ_FOREACH(lun, &softc->lun_list, links)
977                 ctl_isc_announce_lun(lun);
978 }
979
980 static void
981 ctl_isc_ha_link_down(struct ctl_softc *softc)
982 {
983         struct ctl_port *port;
984         struct ctl_lun *lun;
985         union ctl_io *io;
986         int i;
987
988         mtx_lock(&softc->ctl_lock);
989         STAILQ_FOREACH(lun, &softc->lun_list, links) {
990                 mtx_lock(&lun->lun_lock);
991                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
992                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
993                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
994                 }
995                 mtx_unlock(&lun->lun_lock);
996
997                 mtx_unlock(&softc->ctl_lock);
998                 io = ctl_alloc_io(softc->othersc_pool);
999                 mtx_lock(&softc->ctl_lock);
1000                 ctl_zero_io(io);
1001                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1002                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1003                 ctl_enqueue_isc(io);
1004         }
1005
1006         STAILQ_FOREACH(port, &softc->port_list, links) {
1007                 if (port->targ_port >= softc->port_min &&
1008                     port->targ_port < softc->port_max)
1009                         continue;
1010                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1011                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1012                         port->wwpn_iid[i].in_use = 0;
1013                         free(port->wwpn_iid[i].name, M_CTL);
1014                         port->wwpn_iid[i].name = NULL;
1015                 }
1016         }
1017         mtx_unlock(&softc->ctl_lock);
1018 }
1019
1020 static void
1021 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1022 {
1023         struct ctl_lun *lun;
1024         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1025
1026         mtx_lock(&softc->ctl_lock);
1027         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1028             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1029                 mtx_lock(&lun->lun_lock);
1030                 mtx_unlock(&softc->ctl_lock);
1031                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1032                     msg->ua.ua_set)
1033                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1034                 if (msg->ua.ua_all) {
1035                         if (msg->ua.ua_set)
1036                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1037                         else
1038                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1039                 } else {
1040                         if (msg->ua.ua_set)
1041                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
1042                         else
1043                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
1044                 }
1045                 mtx_unlock(&lun->lun_lock);
1046         } else
1047                 mtx_unlock(&softc->ctl_lock);
1048 }
1049
1050 static void
1051 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1052 {
1053         struct ctl_lun *lun;
1054         struct ctl_ha_msg_lun_pr_key pr_key;
1055         int i, k;
1056         ctl_lun_flags oflags;
1057         uint32_t targ_lun;
1058
1059         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1060         mtx_lock(&softc->ctl_lock);
1061         if ((targ_lun >= CTL_MAX_LUNS) ||
1062             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1063                 mtx_unlock(&softc->ctl_lock);
1064                 return;
1065         }
1066         mtx_lock(&lun->lun_lock);
1067         mtx_unlock(&softc->ctl_lock);
1068         if (lun->flags & CTL_LUN_DISABLED) {
1069                 mtx_unlock(&lun->lun_lock);
1070                 return;
1071         }
1072         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1073         if (msg->lun.lun_devid_len != i || (i > 0 &&
1074             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1075                 mtx_unlock(&lun->lun_lock);
1076                 printf("%s: Received conflicting HA LUN %d\n",
1077                     __func__, msg->hdr.nexus.targ_lun);
1078                 return;
1079         } else {
1080                 /* Record whether peer is primary. */
1081                 oflags = lun->flags;
1082                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1083                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1084                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1085                 else
1086                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1087                 if (oflags != lun->flags)
1088                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1089
1090                 /* If peer is primary and we are not -- use data */
1091                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1092                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1093                         lun->pr_generation = msg->lun.pr_generation;
1094                         lun->pr_res_idx = msg->lun.pr_res_idx;
1095                         lun->pr_res_type = msg->lun.pr_res_type;
1096                         lun->pr_key_count = msg->lun.pr_key_count;
1097                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1098                                 ctl_clr_prkey(lun, k);
1099                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1100                                 memcpy(&pr_key, &msg->lun.data[i],
1101                                     sizeof(pr_key));
1102                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1103                                 ctl_set_prkey(lun, pr_key.pr_iid,
1104                                     pr_key.pr_key);
1105                                 i += sizeof(pr_key);
1106                         }
1107                 }
1108
1109                 mtx_unlock(&lun->lun_lock);
1110                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1111                     __func__, msg->hdr.nexus.targ_lun,
1112                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1113                     "primary" : "secondary"));
1114
1115                 /* If we are primary but peer doesn't know -- notify */
1116                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1117                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1118                         ctl_isc_announce_lun(lun);
1119         }
1120 }
1121
1122 static void
1123 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1124 {
1125         struct ctl_port *port;
1126         struct ctl_lun *lun;
1127         int i, new;
1128
1129         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1130         if (port == NULL) {
1131                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1132                     msg->hdr.nexus.targ_port));
1133                 new = 1;
1134                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1135                 port->frontend = &ha_frontend;
1136                 port->targ_port = msg->hdr.nexus.targ_port;
1137                 port->fe_datamove = ctl_ha_datamove;
1138                 port->fe_done = ctl_ha_done;
1139         } else if (port->frontend == &ha_frontend) {
1140                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1141                     msg->hdr.nexus.targ_port));
1142                 new = 0;
1143         } else {
1144                 printf("%s: Received conflicting HA port %d\n",
1145                     __func__, msg->hdr.nexus.targ_port);
1146                 return;
1147         }
1148         port->port_type = msg->port.port_type;
1149         port->physical_port = msg->port.physical_port;
1150         port->virtual_port = msg->port.virtual_port;
1151         port->status = msg->port.status;
1152         i = 0;
1153         free(port->port_name, M_CTL);
1154         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1155             M_CTL);
1156         i += msg->port.name_len;
1157         if (msg->port.lun_map_len != 0) {
1158                 if (port->lun_map == NULL)
1159                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1160                             M_CTL, M_WAITOK);
1161                 memcpy(port->lun_map, &msg->port.data[i],
1162                     sizeof(uint32_t) * CTL_MAX_LUNS);
1163                 i += msg->port.lun_map_len;
1164         } else {
1165                 free(port->lun_map, M_CTL);
1166                 port->lun_map = NULL;
1167         }
1168         if (msg->port.port_devid_len != 0) {
1169                 if (port->port_devid == NULL ||
1170                     port->port_devid->len != msg->port.port_devid_len) {
1171                         free(port->port_devid, M_CTL);
1172                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1173                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1174                 }
1175                 memcpy(port->port_devid->data, &msg->port.data[i],
1176                     msg->port.port_devid_len);
1177                 port->port_devid->len = msg->port.port_devid_len;
1178                 i += msg->port.port_devid_len;
1179         } else {
1180                 free(port->port_devid, M_CTL);
1181                 port->port_devid = NULL;
1182         }
1183         if (msg->port.target_devid_len != 0) {
1184                 if (port->target_devid == NULL ||
1185                     port->target_devid->len != msg->port.target_devid_len) {
1186                         free(port->target_devid, M_CTL);
1187                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1188                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1189                 }
1190                 memcpy(port->target_devid->data, &msg->port.data[i],
1191                     msg->port.target_devid_len);
1192                 port->target_devid->len = msg->port.target_devid_len;
1193                 i += msg->port.target_devid_len;
1194         } else {
1195                 free(port->target_devid, M_CTL);
1196                 port->target_devid = NULL;
1197         }
1198         if (msg->port.init_devid_len != 0) {
1199                 if (port->init_devid == NULL ||
1200                     port->init_devid->len != msg->port.init_devid_len) {
1201                         free(port->init_devid, M_CTL);
1202                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1203                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1204                 }
1205                 memcpy(port->init_devid->data, &msg->port.data[i],
1206                     msg->port.init_devid_len);
1207                 port->init_devid->len = msg->port.init_devid_len;
1208                 i += msg->port.init_devid_len;
1209         } else {
1210                 free(port->init_devid, M_CTL);
1211                 port->init_devid = NULL;
1212         }
1213         if (new) {
1214                 if (ctl_port_register(port) != 0) {
1215                         printf("%s: ctl_port_register() failed with error\n",
1216                             __func__);
1217                 }
1218         }
1219         mtx_lock(&softc->ctl_lock);
1220         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1221                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1222                         continue;
1223                 mtx_lock(&lun->lun_lock);
1224                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1225                 mtx_unlock(&lun->lun_lock);
1226         }
1227         mtx_unlock(&softc->ctl_lock);
1228 }
1229
1230 static void
1231 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1232 {
1233         struct ctl_port *port;
1234         int iid;
1235
1236         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1237         if (port == NULL) {
1238                 printf("%s: Received IID for unknown port %d\n",
1239                     __func__, msg->hdr.nexus.targ_port);
1240                 return;
1241         }
1242         iid = msg->hdr.nexus.initid;
1243         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1244         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1245         free(port->wwpn_iid[iid].name, M_CTL);
1246         if (msg->iid.name_len) {
1247                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1248                     msg->iid.name_len, M_CTL);
1249         } else
1250                 port->wwpn_iid[iid].name = NULL;
1251 }
1252
1253 static void
1254 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1255 {
1256
1257         if (msg->login.version != CTL_HA_VERSION) {
1258                 printf("CTL HA peers have different versions %d != %d\n",
1259                     msg->login.version, CTL_HA_VERSION);
1260                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1261                 return;
1262         }
1263         if (msg->login.ha_mode != softc->ha_mode) {
1264                 printf("CTL HA peers have different ha_mode %d != %d\n",
1265                     msg->login.ha_mode, softc->ha_mode);
1266                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1267                 return;
1268         }
1269         if (msg->login.ha_id == softc->ha_id) {
1270                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1271                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1272                 return;
1273         }
1274         if (msg->login.max_luns != CTL_MAX_LUNS ||
1275             msg->login.max_ports != CTL_MAX_PORTS ||
1276             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1277                 printf("CTL HA peers have different limits\n");
1278                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1279                 return;
1280         }
1281 }
1282
1283 static void
1284 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1285 {
1286         struct ctl_lun *lun;
1287         int i;
1288         uint32_t initidx, targ_lun;
1289
1290         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1291         mtx_lock(&softc->ctl_lock);
1292         if ((targ_lun >= CTL_MAX_LUNS) ||
1293             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1294                 mtx_unlock(&softc->ctl_lock);
1295                 return;
1296         }
1297         mtx_lock(&lun->lun_lock);
1298         mtx_unlock(&softc->ctl_lock);
1299         if (lun->flags & CTL_LUN_DISABLED) {
1300                 mtx_unlock(&lun->lun_lock);
1301                 return;
1302         }
1303         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1304                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1305                     msg->mode.page_code &&
1306                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1307                         break;
1308         }
1309         if (i == CTL_NUM_MODE_PAGES) {
1310                 mtx_unlock(&lun->lun_lock);
1311                 return;
1312         }
1313         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1314             lun->mode_pages.index[i].page_len);
1315         initidx = ctl_get_initindex(&msg->hdr.nexus);
1316         if (initidx != -1)
1317                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1318         mtx_unlock(&lun->lun_lock);
1319 }
1320
1321 /*
1322  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1323  * subsystem come in here.
1324  */
1325 static void
1326 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1327 {
1328         struct ctl_softc *softc = control_softc;
1329         union ctl_io *io;
1330         struct ctl_prio *presio;
1331         ctl_ha_status isc_status;
1332
1333         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1334         if (event == CTL_HA_EVT_MSG_RECV) {
1335                 union ctl_ha_msg *msg, msgbuf;
1336
1337                 if (param > sizeof(msgbuf))
1338                         msg = malloc(param, M_CTL, M_WAITOK);
1339                 else
1340                         msg = &msgbuf;
1341                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1342                     M_WAITOK);
1343                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1344                         printf("%s: Error receiving message: %d\n",
1345                             __func__, isc_status);
1346                         if (msg != &msgbuf)
1347                                 free(msg, M_CTL);
1348                         return;
1349                 }
1350
1351                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1352                 switch (msg->hdr.msg_type) {
1353                 case CTL_MSG_SERIALIZE:
1354                         io = ctl_alloc_io(softc->othersc_pool);
1355                         ctl_zero_io(io);
1356                         // populate ctsio from msg
1357                         io->io_hdr.io_type = CTL_IO_SCSI;
1358                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1359                         io->io_hdr.original_sc = msg->hdr.original_sc;
1360                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1361                                             CTL_FLAG_IO_ACTIVE;
1362                         /*
1363                          * If we're in serialization-only mode, we don't
1364                          * want to go through full done processing.  Thus
1365                          * the COPY flag.
1366                          *
1367                          * XXX KDM add another flag that is more specific.
1368                          */
1369                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1370                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1371                         io->io_hdr.nexus = msg->hdr.nexus;
1372 #if 0
1373                         printf("port %u, iid %u, lun %u\n",
1374                                io->io_hdr.nexus.targ_port,
1375                                io->io_hdr.nexus.initid,
1376                                io->io_hdr.nexus.targ_lun);
1377 #endif
1378                         io->scsiio.tag_num = msg->scsi.tag_num;
1379                         io->scsiio.tag_type = msg->scsi.tag_type;
1380 #ifdef CTL_TIME_IO
1381                         io->io_hdr.start_time = time_uptime;
1382                         getbinuptime(&io->io_hdr.start_bt);
1383 #endif /* CTL_TIME_IO */
1384                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1385                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1386                                CTL_MAX_CDBLEN);
1387                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1388                                 const struct ctl_cmd_entry *entry;
1389
1390                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1391                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1392                                 io->io_hdr.flags |=
1393                                         entry->flags & CTL_FLAG_DATA_MASK;
1394                         }
1395                         ctl_enqueue_isc(io);
1396                         break;
1397
1398                 /* Performed on the Originating SC, XFER mode only */
1399                 case CTL_MSG_DATAMOVE: {
1400                         struct ctl_sg_entry *sgl;
1401                         int i, j;
1402
1403                         io = msg->hdr.original_sc;
1404                         if (io == NULL) {
1405                                 printf("%s: original_sc == NULL!\n", __func__);
1406                                 /* XXX KDM do something here */
1407                                 break;
1408                         }
1409                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1410                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1411                         /*
1412                          * Keep track of this, we need to send it back over
1413                          * when the datamove is complete.
1414                          */
1415                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1416                         if (msg->hdr.status == CTL_SUCCESS)
1417                                 io->io_hdr.status = msg->hdr.status;
1418
1419                         if (msg->dt.sg_sequence == 0) {
1420 #ifdef CTL_TIME_IO
1421                                 getbinuptime(&io->io_hdr.dma_start_bt);
1422 #endif
1423                                 i = msg->dt.kern_sg_entries +
1424                                     msg->dt.kern_data_len /
1425                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1426                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1427                                     M_WAITOK | M_ZERO);
1428                                 io->io_hdr.remote_sglist = sgl;
1429                                 io->io_hdr.local_sglist =
1430                                     &sgl[msg->dt.kern_sg_entries];
1431
1432                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1433
1434                                 io->scsiio.kern_sg_entries =
1435                                         msg->dt.kern_sg_entries;
1436                                 io->scsiio.rem_sg_entries =
1437                                         msg->dt.kern_sg_entries;
1438                                 io->scsiio.kern_data_len =
1439                                         msg->dt.kern_data_len;
1440                                 io->scsiio.kern_total_len =
1441                                         msg->dt.kern_total_len;
1442                                 io->scsiio.kern_data_resid =
1443                                         msg->dt.kern_data_resid;
1444                                 io->scsiio.kern_rel_offset =
1445                                         msg->dt.kern_rel_offset;
1446                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1447                                 io->io_hdr.flags |= msg->dt.flags &
1448                                     CTL_FLAG_BUS_ADDR;
1449                         } else
1450                                 sgl = (struct ctl_sg_entry *)
1451                                         io->scsiio.kern_data_ptr;
1452
1453                         for (i = msg->dt.sent_sg_entries, j = 0;
1454                              i < (msg->dt.sent_sg_entries +
1455                              msg->dt.cur_sg_entries); i++, j++) {
1456                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1457                                 sgl[i].len = msg->dt.sg_list[j].len;
1458
1459 #if 0
1460                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1461                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1462 #endif
1463                         }
1464
1465                         /*
1466                          * If this is the last piece of the I/O, we've got
1467                          * the full S/G list.  Queue processing in the thread.
1468                          * Otherwise wait for the next piece.
1469                          */
1470                         if (msg->dt.sg_last != 0)
1471                                 ctl_enqueue_isc(io);
1472                         break;
1473                 }
1474                 /* Performed on the Serializing (primary) SC, XFER mode only */
1475                 case CTL_MSG_DATAMOVE_DONE: {
1476                         if (msg->hdr.serializing_sc == NULL) {
1477                                 printf("%s: serializing_sc == NULL!\n",
1478                                        __func__);
1479                                 /* XXX KDM now what? */
1480                                 break;
1481                         }
1482                         /*
1483                          * We grab the sense information here in case
1484                          * there was a failure, so we can return status
1485                          * back to the initiator.
1486                          */
1487                         io = msg->hdr.serializing_sc;
1488                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1489                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1490                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1491                         io->io_hdr.port_status = msg->scsi.fetd_status;
1492                         io->scsiio.residual = msg->scsi.residual;
1493                         if (msg->hdr.status != CTL_STATUS_NONE) {
1494                                 io->io_hdr.status = msg->hdr.status;
1495                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1496                                 io->scsiio.sense_len = msg->scsi.sense_len;
1497                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1498                                 memcpy(&io->scsiio.sense_data,
1499                                     &msg->scsi.sense_data,
1500                                     msg->scsi.sense_len);
1501                                 if (msg->hdr.status == CTL_SUCCESS)
1502                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1503                         }
1504                         ctl_enqueue_isc(io);
1505                         break;
1506                 }
1507
1508                 /* Preformed on Originating SC, SER_ONLY mode */
1509                 case CTL_MSG_R2R:
1510                         io = msg->hdr.original_sc;
1511                         if (io == NULL) {
1512                                 printf("%s: original_sc == NULL!\n",
1513                                     __func__);
1514                                 break;
1515                         }
1516                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1517                         io->io_hdr.msg_type = CTL_MSG_R2R;
1518                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1519                         ctl_enqueue_isc(io);
1520                         break;
1521
1522                 /*
1523                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1524                  * mode.
1525                  * Performed on the Originating (i.e. secondary) SC in XFER
1526                  * mode
1527                  */
1528                 case CTL_MSG_FINISH_IO:
1529                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1530                                 ctl_isc_handler_finish_xfer(softc, msg);
1531                         else
1532                                 ctl_isc_handler_finish_ser_only(softc, msg);
1533                         break;
1534
1535                 /* Preformed on Originating SC */
1536                 case CTL_MSG_BAD_JUJU:
1537                         io = msg->hdr.original_sc;
1538                         if (io == NULL) {
1539                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1540                                        __func__);
1541                                 break;
1542                         }
1543                         ctl_copy_sense_data(msg, io);
1544                         /*
1545                          * IO should have already been cleaned up on other
1546                          * SC so clear this flag so we won't send a message
1547                          * back to finish the IO there.
1548                          */
1549                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1550                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1551
1552                         /* io = msg->hdr.serializing_sc; */
1553                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1554                         ctl_enqueue_isc(io);
1555                         break;
1556
1557                 /* Handle resets sent from the other side */
1558                 case CTL_MSG_MANAGE_TASKS: {
1559                         struct ctl_taskio *taskio;
1560                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1561                             softc->othersc_pool);
1562                         ctl_zero_io((union ctl_io *)taskio);
1563                         taskio->io_hdr.io_type = CTL_IO_TASK;
1564                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1565                         taskio->io_hdr.nexus = msg->hdr.nexus;
1566                         taskio->task_action = msg->task.task_action;
1567                         taskio->tag_num = msg->task.tag_num;
1568                         taskio->tag_type = msg->task.tag_type;
1569 #ifdef CTL_TIME_IO
1570                         taskio->io_hdr.start_time = time_uptime;
1571                         getbinuptime(&taskio->io_hdr.start_bt);
1572 #endif /* CTL_TIME_IO */
1573                         ctl_run_task((union ctl_io *)taskio);
1574                         break;
1575                 }
1576                 /* Persistent Reserve action which needs attention */
1577                 case CTL_MSG_PERS_ACTION:
1578                         presio = (struct ctl_prio *)ctl_alloc_io(
1579                             softc->othersc_pool);
1580                         ctl_zero_io((union ctl_io *)presio);
1581                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1582                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1583                         presio->io_hdr.nexus = msg->hdr.nexus;
1584                         presio->pr_msg = msg->pr;
1585                         ctl_enqueue_isc((union ctl_io *)presio);
1586                         break;
1587                 case CTL_MSG_UA:
1588                         ctl_isc_ua(softc, msg, param);
1589                         break;
1590                 case CTL_MSG_PORT_SYNC:
1591                         ctl_isc_port_sync(softc, msg, param);
1592                         break;
1593                 case CTL_MSG_LUN_SYNC:
1594                         ctl_isc_lun_sync(softc, msg, param);
1595                         break;
1596                 case CTL_MSG_IID_SYNC:
1597                         ctl_isc_iid_sync(softc, msg, param);
1598                         break;
1599                 case CTL_MSG_LOGIN:
1600                         ctl_isc_login(softc, msg, param);
1601                         break;
1602                 case CTL_MSG_MODE_SYNC:
1603                         ctl_isc_mode_sync(softc, msg, param);
1604                         break;
1605                 default:
1606                         printf("Received HA message of unknown type %d\n",
1607                             msg->hdr.msg_type);
1608                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1609                         break;
1610                 }
1611                 if (msg != &msgbuf)
1612                         free(msg, M_CTL);
1613         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1614                 printf("CTL: HA link status changed from %d to %d\n",
1615                     softc->ha_link, param);
1616                 if (param == softc->ha_link)
1617                         return;
1618                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1619                         softc->ha_link = param;
1620                         ctl_isc_ha_link_down(softc);
1621                 } else {
1622                         softc->ha_link = param;
1623                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1624                                 ctl_isc_ha_link_up(softc);
1625                 }
1626                 return;
1627         } else {
1628                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1629                 return;
1630         }
1631 }
1632
1633 static void
1634 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1635 {
1636
1637         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1638             src->scsi.sense_len);
1639         dest->scsiio.scsi_status = src->scsi.scsi_status;
1640         dest->scsiio.sense_len = src->scsi.sense_len;
1641         dest->io_hdr.status = src->hdr.status;
1642 }
1643
1644 static void
1645 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1646 {
1647
1648         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1649             src->scsiio.sense_len);
1650         dest->scsi.scsi_status = src->scsiio.scsi_status;
1651         dest->scsi.sense_len = src->scsiio.sense_len;
1652         dest->hdr.status = src->io_hdr.status;
1653 }
1654
1655 void
1656 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1657 {
1658         struct ctl_softc *softc = lun->ctl_softc;
1659         ctl_ua_type *pu;
1660
1661         if (initidx < softc->init_min || initidx >= softc->init_max)
1662                 return;
1663         mtx_assert(&lun->lun_lock, MA_OWNED);
1664         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1665         if (pu == NULL)
1666                 return;
1667         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1668 }
1669
1670 void
1671 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1672 {
1673         int i;
1674
1675         mtx_assert(&lun->lun_lock, MA_OWNED);
1676         if (lun->pending_ua[port] == NULL)
1677                 return;
1678         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1679                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1680                         continue;
1681                 lun->pending_ua[port][i] |= ua;
1682         }
1683 }
1684
1685 void
1686 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1687 {
1688         struct ctl_softc *softc = lun->ctl_softc;
1689         int i;
1690
1691         mtx_assert(&lun->lun_lock, MA_OWNED);
1692         for (i = softc->port_min; i < softc->port_max; i++)
1693                 ctl_est_ua_port(lun, i, except, ua);
1694 }
1695
1696 void
1697 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1698 {
1699         struct ctl_softc *softc = lun->ctl_softc;
1700         ctl_ua_type *pu;
1701
1702         if (initidx < softc->init_min || initidx >= softc->init_max)
1703                 return;
1704         mtx_assert(&lun->lun_lock, MA_OWNED);
1705         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1706         if (pu == NULL)
1707                 return;
1708         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1709 }
1710
1711 void
1712 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1713 {
1714         struct ctl_softc *softc = lun->ctl_softc;
1715         int i, j;
1716
1717         mtx_assert(&lun->lun_lock, MA_OWNED);
1718         for (i = softc->port_min; i < softc->port_max; i++) {
1719                 if (lun->pending_ua[i] == NULL)
1720                         continue;
1721                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1722                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1723                                 continue;
1724                         lun->pending_ua[i][j] &= ~ua;
1725                 }
1726         }
1727 }
1728
1729 void
1730 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1731     ctl_ua_type ua_type)
1732 {
1733         struct ctl_lun *lun;
1734
1735         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1736         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1737                 mtx_lock(&lun->lun_lock);
1738                 ctl_clr_ua(lun, initidx, ua_type);
1739                 mtx_unlock(&lun->lun_lock);
1740         }
1741 }
1742
1743 static int
1744 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1745 {
1746         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1747         struct ctl_lun *lun;
1748         struct ctl_lun_req ireq;
1749         int error, value;
1750
1751         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1752         error = sysctl_handle_int(oidp, &value, 0, req);
1753         if ((error != 0) || (req->newptr == NULL))
1754                 return (error);
1755
1756         mtx_lock(&softc->ctl_lock);
1757         if (value == 0)
1758                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1759         else
1760                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1761         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1762                 mtx_unlock(&softc->ctl_lock);
1763                 bzero(&ireq, sizeof(ireq));
1764                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1765                 ireq.reqdata.modify.lun_id = lun->lun;
1766                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1767                     curthread);
1768                 if (ireq.status != CTL_LUN_OK) {
1769                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1770                             __func__, ireq.status, ireq.error_str);
1771                 }
1772                 mtx_lock(&softc->ctl_lock);
1773         }
1774         mtx_unlock(&softc->ctl_lock);
1775         return (0);
1776 }
1777
1778 static int
1779 ctl_init(void)
1780 {
1781         struct make_dev_args args;
1782         struct ctl_softc *softc;
1783         void *other_pool;
1784         int i, error;
1785
1786         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1787                                M_WAITOK | M_ZERO);
1788
1789         make_dev_args_init(&args);
1790         args.mda_devsw = &ctl_cdevsw;
1791         args.mda_uid = UID_ROOT;
1792         args.mda_gid = GID_OPERATOR;
1793         args.mda_mode = 0600;
1794         args.mda_si_drv1 = softc;
1795         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1796         if (error != 0) {
1797                 free(control_softc, M_DEVBUF);
1798                 return (error);
1799         }
1800
1801         sysctl_ctx_init(&softc->sysctl_ctx);
1802         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1803                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1804                 CTLFLAG_RD, 0, "CAM Target Layer");
1805
1806         if (softc->sysctl_tree == NULL) {
1807                 printf("%s: unable to allocate sysctl tree\n", __func__);
1808                 destroy_dev(softc->dev);
1809                 free(control_softc, M_DEVBUF);
1810                 control_softc = NULL;
1811                 return (ENOMEM);
1812         }
1813
1814         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1815         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1816             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1817         softc->flags = 0;
1818
1819         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1820             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1821             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1822
1823         /*
1824          * In Copan's HA scheme, the "master" and "slave" roles are
1825          * figured out through the slot the controller is in.  Although it
1826          * is an active/active system, someone has to be in charge.
1827          */
1828         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1829             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1830             "HA head ID (0 - no HA)");
1831         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1832                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1833                 softc->is_single = 1;
1834                 softc->port_cnt = CTL_MAX_PORTS;
1835                 softc->port_min = 0;
1836         } else {
1837                 softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1838                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1839         }
1840         softc->port_max = softc->port_min + softc->port_cnt;
1841         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1842         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1843
1844         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1845             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1846             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1847
1848         STAILQ_INIT(&softc->lun_list);
1849         STAILQ_INIT(&softc->pending_lun_queue);
1850         STAILQ_INIT(&softc->fe_list);
1851         STAILQ_INIT(&softc->port_list);
1852         STAILQ_INIT(&softc->be_list);
1853         ctl_tpc_init(softc);
1854
1855         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1856                             &other_pool) != 0)
1857         {
1858                 printf("ctl: can't allocate %d entry other SC pool, "
1859                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1860                 return (ENOMEM);
1861         }
1862         softc->othersc_pool = other_pool;
1863
1864         if (worker_threads <= 0)
1865                 worker_threads = max(1, mp_ncpus / 4);
1866         if (worker_threads > CTL_MAX_THREADS)
1867                 worker_threads = CTL_MAX_THREADS;
1868
1869         for (i = 0; i < worker_threads; i++) {
1870                 struct ctl_thread *thr = &softc->threads[i];
1871
1872                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1873                 thr->ctl_softc = softc;
1874                 STAILQ_INIT(&thr->incoming_queue);
1875                 STAILQ_INIT(&thr->rtr_queue);
1876                 STAILQ_INIT(&thr->done_queue);
1877                 STAILQ_INIT(&thr->isc_queue);
1878
1879                 error = kproc_kthread_add(ctl_work_thread, thr,
1880                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1881                 if (error != 0) {
1882                         printf("error creating CTL work thread!\n");
1883                         ctl_pool_free(other_pool);
1884                         return (error);
1885                 }
1886         }
1887         error = kproc_kthread_add(ctl_lun_thread, softc,
1888             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1889         if (error != 0) {
1890                 printf("error creating CTL lun thread!\n");
1891                 ctl_pool_free(other_pool);
1892                 return (error);
1893         }
1894         error = kproc_kthread_add(ctl_thresh_thread, softc,
1895             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1896         if (error != 0) {
1897                 printf("error creating CTL threshold thread!\n");
1898                 ctl_pool_free(other_pool);
1899                 return (error);
1900         }
1901
1902         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1903             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1904             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1905
1906         if (softc->is_single == 0) {
1907                 ctl_frontend_register(&ha_frontend);
1908                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1909                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1910                         softc->is_single = 1;
1911                 } else
1912                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1913                     != CTL_HA_STATUS_SUCCESS) {
1914                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1915                         softc->is_single = 1;
1916                 }
1917         }
1918         return (0);
1919 }
1920
1921 void
1922 ctl_shutdown(void)
1923 {
1924         struct ctl_softc *softc = control_softc;
1925         struct ctl_lun *lun, *next_lun;
1926
1927         if (softc->is_single == 0) {
1928                 ctl_ha_msg_shutdown(softc);
1929                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1930                     != CTL_HA_STATUS_SUCCESS)
1931                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1932                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1933                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1934                 ctl_frontend_deregister(&ha_frontend);
1935         }
1936
1937         mtx_lock(&softc->ctl_lock);
1938
1939         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1940                 ctl_free_lun(lun);
1941
1942         mtx_unlock(&softc->ctl_lock);
1943
1944 #if 0
1945         ctl_shutdown_thread(softc->work_thread);
1946         mtx_destroy(&softc->queue_lock);
1947 #endif
1948
1949         ctl_tpc_shutdown(softc);
1950         uma_zdestroy(softc->io_zone);
1951         mtx_destroy(&softc->ctl_lock);
1952
1953         destroy_dev(softc->dev);
1954
1955         sysctl_ctx_free(&softc->sysctl_ctx);
1956
1957         free(control_softc, M_DEVBUF);
1958         control_softc = NULL;
1959 }
1960
1961 static int
1962 ctl_module_event_handler(module_t mod, int what, void *arg)
1963 {
1964
1965         switch (what) {
1966         case MOD_LOAD:
1967                 return (ctl_init());
1968         case MOD_UNLOAD:
1969                 return (EBUSY);
1970         default:
1971                 return (EOPNOTSUPP);
1972         }
1973 }
1974
1975 /*
1976  * XXX KDM should we do some access checks here?  Bump a reference count to
1977  * prevent a CTL module from being unloaded while someone has it open?
1978  */
1979 static int
1980 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1981 {
1982         return (0);
1983 }
1984
1985 static int
1986 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1987 {
1988         return (0);
1989 }
1990
1991 /*
1992  * Remove an initiator by port number and initiator ID.
1993  * Returns 0 for success, -1 for failure.
1994  */
1995 int
1996 ctl_remove_initiator(struct ctl_port *port, int iid)
1997 {
1998         struct ctl_softc *softc = port->ctl_softc;
1999
2000         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2001
2002         if (iid > CTL_MAX_INIT_PER_PORT) {
2003                 printf("%s: initiator ID %u > maximun %u!\n",
2004                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2005                 return (-1);
2006         }
2007
2008         mtx_lock(&softc->ctl_lock);
2009         port->wwpn_iid[iid].in_use--;
2010         port->wwpn_iid[iid].last_use = time_uptime;
2011         mtx_unlock(&softc->ctl_lock);
2012         ctl_isc_announce_iid(port, iid);
2013
2014         return (0);
2015 }
2016
2017 /*
2018  * Add an initiator to the initiator map.
2019  * Returns iid for success, < 0 for failure.
2020  */
2021 int
2022 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2023 {
2024         struct ctl_softc *softc = port->ctl_softc;
2025         time_t best_time;
2026         int i, best;
2027
2028         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2029
2030         if (iid >= CTL_MAX_INIT_PER_PORT) {
2031                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2032                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2033                 free(name, M_CTL);
2034                 return (-1);
2035         }
2036
2037         mtx_lock(&softc->ctl_lock);
2038
2039         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2040                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2041                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2042                                 iid = i;
2043                                 break;
2044                         }
2045                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2046                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2047                                 iid = i;
2048                                 break;
2049                         }
2050                 }
2051         }
2052
2053         if (iid < 0) {
2054                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2055                         if (port->wwpn_iid[i].in_use == 0 &&
2056                             port->wwpn_iid[i].wwpn == 0 &&
2057                             port->wwpn_iid[i].name == NULL) {
2058                                 iid = i;
2059                                 break;
2060                         }
2061                 }
2062         }
2063
2064         if (iid < 0) {
2065                 best = -1;
2066                 best_time = INT32_MAX;
2067                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2068                         if (port->wwpn_iid[i].in_use == 0) {
2069                                 if (port->wwpn_iid[i].last_use < best_time) {
2070                                         best = i;
2071                                         best_time = port->wwpn_iid[i].last_use;
2072                                 }
2073                         }
2074                 }
2075                 iid = best;
2076         }
2077
2078         if (iid < 0) {
2079                 mtx_unlock(&softc->ctl_lock);
2080                 free(name, M_CTL);
2081                 return (-2);
2082         }
2083
2084         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2085                 /*
2086                  * This is not an error yet.
2087                  */
2088                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2089 #if 0
2090                         printf("%s: port %d iid %u WWPN %#jx arrived"
2091                             " again\n", __func__, port->targ_port,
2092                             iid, (uintmax_t)wwpn);
2093 #endif
2094                         goto take;
2095                 }
2096                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2097                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2098 #if 0
2099                         printf("%s: port %d iid %u name '%s' arrived"
2100                             " again\n", __func__, port->targ_port,
2101                             iid, name);
2102 #endif
2103                         goto take;
2104                 }
2105
2106                 /*
2107                  * This is an error, but what do we do about it?  The
2108                  * driver is telling us we have a new WWPN for this
2109                  * initiator ID, so we pretty much need to use it.
2110                  */
2111                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2112                     " but WWPN %#jx '%s' is still at that address\n",
2113                     __func__, port->targ_port, iid, wwpn, name,
2114                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2115                     port->wwpn_iid[iid].name);
2116
2117                 /*
2118                  * XXX KDM clear have_ca and ua_pending on each LUN for
2119                  * this initiator.
2120                  */
2121         }
2122 take:
2123         free(port->wwpn_iid[iid].name, M_CTL);
2124         port->wwpn_iid[iid].name = name;
2125         port->wwpn_iid[iid].wwpn = wwpn;
2126         port->wwpn_iid[iid].in_use++;
2127         mtx_unlock(&softc->ctl_lock);
2128         ctl_isc_announce_iid(port, iid);
2129
2130         return (iid);
2131 }
2132
2133 static int
2134 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2135 {
2136         int len;
2137
2138         switch (port->port_type) {
2139         case CTL_PORT_FC:
2140         {
2141                 struct scsi_transportid_fcp *id =
2142                     (struct scsi_transportid_fcp *)buf;
2143                 if (port->wwpn_iid[iid].wwpn == 0)
2144                         return (0);
2145                 memset(id, 0, sizeof(*id));
2146                 id->format_protocol = SCSI_PROTO_FC;
2147                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2148                 return (sizeof(*id));
2149         }
2150         case CTL_PORT_ISCSI:
2151         {
2152                 struct scsi_transportid_iscsi_port *id =
2153                     (struct scsi_transportid_iscsi_port *)buf;
2154                 if (port->wwpn_iid[iid].name == NULL)
2155                         return (0);
2156                 memset(id, 0, 256);
2157                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2158                     SCSI_PROTO_ISCSI;
2159                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2160                 len = roundup2(min(len, 252), 4);
2161                 scsi_ulto2b(len, id->additional_length);
2162                 return (sizeof(*id) + len);
2163         }
2164         case CTL_PORT_SAS:
2165         {
2166                 struct scsi_transportid_sas *id =
2167                     (struct scsi_transportid_sas *)buf;
2168                 if (port->wwpn_iid[iid].wwpn == 0)
2169                         return (0);
2170                 memset(id, 0, sizeof(*id));
2171                 id->format_protocol = SCSI_PROTO_SAS;
2172                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2173                 return (sizeof(*id));
2174         }
2175         default:
2176         {
2177                 struct scsi_transportid_spi *id =
2178                     (struct scsi_transportid_spi *)buf;
2179                 memset(id, 0, sizeof(*id));
2180                 id->format_protocol = SCSI_PROTO_SPI;
2181                 scsi_ulto2b(iid, id->scsi_addr);
2182                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2183                 return (sizeof(*id));
2184         }
2185         }
2186 }
2187
2188 /*
2189  * Serialize a command that went down the "wrong" side, and so was sent to
2190  * this controller for execution.  The logic is a little different than the
2191  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2192  * sent back to the other side, but in the success case, we execute the
2193  * command on this side (XFER mode) or tell the other side to execute it
2194  * (SER_ONLY mode).
2195  */
2196 static int
2197 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2198 {
2199         struct ctl_softc *softc = control_softc;
2200         union ctl_ha_msg msg_info;
2201         struct ctl_port *port;
2202         struct ctl_lun *lun;
2203         const struct ctl_cmd_entry *entry;
2204         int retval = 0;
2205         uint32_t targ_lun;
2206
2207         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2208         mtx_lock(&softc->ctl_lock);
2209
2210         /* Make sure that we know about this port. */
2211         port = ctl_io_port(&ctsio->io_hdr);
2212         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2213                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2214                                          /*retry_count*/ 1);
2215                 goto badjuju;
2216         }
2217
2218         /* Make sure that we know about this LUN. */
2219         if ((targ_lun < CTL_MAX_LUNS) &&
2220             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2221                 mtx_lock(&lun->lun_lock);
2222                 mtx_unlock(&softc->ctl_lock);
2223                 /*
2224                  * If the LUN is invalid, pretend that it doesn't exist.
2225                  * It will go away as soon as all pending I/O has been
2226                  * completed.
2227                  */
2228                 if (lun->flags & CTL_LUN_DISABLED) {
2229                         mtx_unlock(&lun->lun_lock);
2230                         lun = NULL;
2231                 }
2232         } else {
2233                 mtx_unlock(&softc->ctl_lock);
2234                 lun = NULL;
2235         }
2236         if (lun == NULL) {
2237                 /*
2238                  * The other node would not send this request to us unless
2239                  * received announce that we are primary node for this LUN.
2240                  * If this LUN does not exist now, it is probably result of
2241                  * a race, so respond to initiator in the most opaque way.
2242                  */
2243                 ctl_set_busy(ctsio);
2244                 goto badjuju;
2245         }
2246
2247         entry = ctl_get_cmd_entry(ctsio, NULL);
2248         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2249                 mtx_unlock(&lun->lun_lock);
2250                 goto badjuju;
2251         }
2252
2253         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2254         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2255
2256         /*
2257          * Every I/O goes into the OOA queue for a
2258          * particular LUN, and stays there until completion.
2259          */
2260 #ifdef CTL_TIME_IO
2261         if (TAILQ_EMPTY(&lun->ooa_queue))
2262                 lun->idle_time += getsbinuptime() - lun->last_busy;
2263 #endif
2264         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2265
2266         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2267                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2268                  ooa_links))) {
2269         case CTL_ACTION_BLOCK:
2270                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2271                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2272                                   blocked_links);
2273                 mtx_unlock(&lun->lun_lock);
2274                 break;
2275         case CTL_ACTION_PASS:
2276         case CTL_ACTION_SKIP:
2277                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2278                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2279                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2280                         mtx_unlock(&lun->lun_lock);
2281                 } else {
2282                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2283                         mtx_unlock(&lun->lun_lock);
2284
2285                         /* send msg back to other side */
2286                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2287                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2288                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2289                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2290                             sizeof(msg_info.hdr), M_WAITOK);
2291                 }
2292                 break;
2293         case CTL_ACTION_OVERLAP:
2294                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2295                 mtx_unlock(&lun->lun_lock);
2296                 ctl_set_overlapped_cmd(ctsio);
2297                 goto badjuju;
2298         case CTL_ACTION_OVERLAP_TAG:
2299                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2300                 mtx_unlock(&lun->lun_lock);
2301                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2302                 goto badjuju;
2303         case CTL_ACTION_ERROR:
2304         default:
2305                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2306                 mtx_unlock(&lun->lun_lock);
2307
2308                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2309                                          /*retry_count*/ 0);
2310 badjuju:
2311                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2312                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2313                 msg_info.hdr.serializing_sc = NULL;
2314                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2315                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2316                     sizeof(msg_info.scsi), M_WAITOK);
2317                 retval = 1;
2318                 break;
2319         }
2320         return (retval);
2321 }
2322
2323 /*
2324  * Returns 0 for success, errno for failure.
2325  */
2326 static void
2327 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2328                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2329 {
2330         union ctl_io *io;
2331
2332         mtx_lock(&lun->lun_lock);
2333         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2334              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2335              ooa_links)) {
2336                 struct ctl_ooa_entry *entry;
2337
2338                 /*
2339                  * If we've got more than we can fit, just count the
2340                  * remaining entries.
2341                  */
2342                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2343                         continue;
2344
2345                 entry = &kern_entries[*cur_fill_num];
2346
2347                 entry->tag_num = io->scsiio.tag_num;
2348                 entry->lun_num = lun->lun;
2349 #ifdef CTL_TIME_IO
2350                 entry->start_bt = io->io_hdr.start_bt;
2351 #endif
2352                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2353                 entry->cdb_len = io->scsiio.cdb_len;
2354                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2355                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2356
2357                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2358                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2359
2360                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2361                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2362
2363                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2364                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2365
2366                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2367                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2368         }
2369         mtx_unlock(&lun->lun_lock);
2370 }
2371
2372 static void *
2373 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2374                  size_t error_str_len)
2375 {
2376         void *kptr;
2377
2378         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2379
2380         if (copyin(user_addr, kptr, len) != 0) {
2381                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2382                          "from user address %p to kernel address %p", len,
2383                          user_addr, kptr);
2384                 free(kptr, M_CTL);
2385                 return (NULL);
2386         }
2387
2388         return (kptr);
2389 }
2390
2391 static void
2392 ctl_free_args(int num_args, struct ctl_be_arg *args)
2393 {
2394         int i;
2395
2396         if (args == NULL)
2397                 return;
2398
2399         for (i = 0; i < num_args; i++) {
2400                 free(args[i].kname, M_CTL);
2401                 free(args[i].kvalue, M_CTL);
2402         }
2403
2404         free(args, M_CTL);
2405 }
2406
2407 static struct ctl_be_arg *
2408 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2409                 char *error_str, size_t error_str_len)
2410 {
2411         struct ctl_be_arg *args;
2412         int i;
2413
2414         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2415                                 error_str, error_str_len);
2416
2417         if (args == NULL)
2418                 goto bailout;
2419
2420         for (i = 0; i < num_args; i++) {
2421                 args[i].kname = NULL;
2422                 args[i].kvalue = NULL;
2423         }
2424
2425         for (i = 0; i < num_args; i++) {
2426                 uint8_t *tmpptr;
2427
2428                 args[i].kname = ctl_copyin_alloc(args[i].name,
2429                         args[i].namelen, error_str, error_str_len);
2430                 if (args[i].kname == NULL)
2431                         goto bailout;
2432
2433                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2434                         snprintf(error_str, error_str_len, "Argument %d "
2435                                  "name is not NUL-terminated", i);
2436                         goto bailout;
2437                 }
2438
2439                 if (args[i].flags & CTL_BEARG_RD) {
2440                         tmpptr = ctl_copyin_alloc(args[i].value,
2441                                 args[i].vallen, error_str, error_str_len);
2442                         if (tmpptr == NULL)
2443                                 goto bailout;
2444                         if ((args[i].flags & CTL_BEARG_ASCII)
2445                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2446                                 snprintf(error_str, error_str_len, "Argument "
2447                                     "%d value is not NUL-terminated", i);
2448                                 goto bailout;
2449                         }
2450                         args[i].kvalue = tmpptr;
2451                 } else {
2452                         args[i].kvalue = malloc(args[i].vallen,
2453                             M_CTL, M_WAITOK | M_ZERO);
2454                 }
2455         }
2456
2457         return (args);
2458 bailout:
2459
2460         ctl_free_args(num_args, args);
2461
2462         return (NULL);
2463 }
2464
2465 static void
2466 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2467 {
2468         int i;
2469
2470         for (i = 0; i < num_args; i++) {
2471                 if (args[i].flags & CTL_BEARG_WR)
2472                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2473         }
2474 }
2475
2476 /*
2477  * Escape characters that are illegal or not recommended in XML.
2478  */
2479 int
2480 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2481 {
2482         char *end = str + size;
2483         int retval;
2484
2485         retval = 0;
2486
2487         for (; *str && str < end; str++) {
2488                 switch (*str) {
2489                 case '&':
2490                         retval = sbuf_printf(sb, "&amp;");
2491                         break;
2492                 case '>':
2493                         retval = sbuf_printf(sb, "&gt;");
2494                         break;
2495                 case '<':
2496                         retval = sbuf_printf(sb, "&lt;");
2497                         break;
2498                 default:
2499                         retval = sbuf_putc(sb, *str);
2500                         break;
2501                 }
2502
2503                 if (retval != 0)
2504                         break;
2505
2506         }
2507
2508         return (retval);
2509 }
2510
2511 static void
2512 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2513 {
2514         struct scsi_vpd_id_descriptor *desc;
2515         int i;
2516
2517         if (id == NULL || id->len < 4)
2518                 return;
2519         desc = (struct scsi_vpd_id_descriptor *)id->data;
2520         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2521         case SVPD_ID_TYPE_T10:
2522                 sbuf_printf(sb, "t10.");
2523                 break;
2524         case SVPD_ID_TYPE_EUI64:
2525                 sbuf_printf(sb, "eui.");
2526                 break;
2527         case SVPD_ID_TYPE_NAA:
2528                 sbuf_printf(sb, "naa.");
2529                 break;
2530         case SVPD_ID_TYPE_SCSI_NAME:
2531                 break;
2532         }
2533         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2534         case SVPD_ID_CODESET_BINARY:
2535                 for (i = 0; i < desc->length; i++)
2536                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2537                 break;
2538         case SVPD_ID_CODESET_ASCII:
2539                 sbuf_printf(sb, "%.*s", (int)desc->length,
2540                     (char *)desc->identifier);
2541                 break;
2542         case SVPD_ID_CODESET_UTF8:
2543                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2544                 break;
2545         }
2546 }
2547
2548 static int
2549 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2550           struct thread *td)
2551 {
2552         struct ctl_softc *softc = dev->si_drv1;
2553         struct ctl_lun *lun;
2554         int retval;
2555
2556         retval = 0;
2557
2558         switch (cmd) {
2559         case CTL_IO:
2560                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2561                 break;
2562         case CTL_ENABLE_PORT:
2563         case CTL_DISABLE_PORT:
2564         case CTL_SET_PORT_WWNS: {
2565                 struct ctl_port *port;
2566                 struct ctl_port_entry *entry;
2567
2568                 entry = (struct ctl_port_entry *)addr;
2569                 
2570                 mtx_lock(&softc->ctl_lock);
2571                 STAILQ_FOREACH(port, &softc->port_list, links) {
2572                         int action, done;
2573
2574                         if (port->targ_port < softc->port_min ||
2575                             port->targ_port >= softc->port_max)
2576                                 continue;
2577
2578                         action = 0;
2579                         done = 0;
2580                         if ((entry->port_type == CTL_PORT_NONE)
2581                          && (entry->targ_port == port->targ_port)) {
2582                                 /*
2583                                  * If the user only wants to enable or
2584                                  * disable or set WWNs on a specific port,
2585                                  * do the operation and we're done.
2586                                  */
2587                                 action = 1;
2588                                 done = 1;
2589                         } else if (entry->port_type & port->port_type) {
2590                                 /*
2591                                  * Compare the user's type mask with the
2592                                  * particular frontend type to see if we
2593                                  * have a match.
2594                                  */
2595                                 action = 1;
2596                                 done = 0;
2597
2598                                 /*
2599                                  * Make sure the user isn't trying to set
2600                                  * WWNs on multiple ports at the same time.
2601                                  */
2602                                 if (cmd == CTL_SET_PORT_WWNS) {
2603                                         printf("%s: Can't set WWNs on "
2604                                                "multiple ports\n", __func__);
2605                                         retval = EINVAL;
2606                                         break;
2607                                 }
2608                         }
2609                         if (action == 0)
2610                                 continue;
2611
2612                         /*
2613                          * XXX KDM we have to drop the lock here, because
2614                          * the online/offline operations can potentially
2615                          * block.  We need to reference count the frontends
2616                          * so they can't go away,
2617                          */
2618                         if (cmd == CTL_ENABLE_PORT) {
2619                                 mtx_unlock(&softc->ctl_lock);
2620                                 ctl_port_online(port);
2621                                 mtx_lock(&softc->ctl_lock);
2622                         } else if (cmd == CTL_DISABLE_PORT) {
2623                                 mtx_unlock(&softc->ctl_lock);
2624                                 ctl_port_offline(port);
2625                                 mtx_lock(&softc->ctl_lock);
2626                         } else if (cmd == CTL_SET_PORT_WWNS) {
2627                                 ctl_port_set_wwns(port,
2628                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2629                                     1 : 0, entry->wwnn,
2630                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2631                                     1 : 0, entry->wwpn);
2632                         }
2633                         if (done != 0)
2634                                 break;
2635                 }
2636                 mtx_unlock(&softc->ctl_lock);
2637                 break;
2638         }
2639         case CTL_GET_OOA: {
2640                 struct ctl_ooa *ooa_hdr;
2641                 struct ctl_ooa_entry *entries;
2642                 uint32_t cur_fill_num;
2643
2644                 ooa_hdr = (struct ctl_ooa *)addr;
2645
2646                 if ((ooa_hdr->alloc_len == 0)
2647                  || (ooa_hdr->alloc_num == 0)) {
2648                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2649                                "must be non-zero\n", __func__,
2650                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2651                         retval = EINVAL;
2652                         break;
2653                 }
2654
2655                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2656                     sizeof(struct ctl_ooa_entry))) {
2657                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2658                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2659                                __func__, ooa_hdr->alloc_len,
2660                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2661                         retval = EINVAL;
2662                         break;
2663                 }
2664
2665                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2666                 if (entries == NULL) {
2667                         printf("%s: could not allocate %d bytes for OOA "
2668                                "dump\n", __func__, ooa_hdr->alloc_len);
2669                         retval = ENOMEM;
2670                         break;
2671                 }
2672
2673                 mtx_lock(&softc->ctl_lock);
2674                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2675                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2676                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2677                         mtx_unlock(&softc->ctl_lock);
2678                         free(entries, M_CTL);
2679                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2680                                __func__, (uintmax_t)ooa_hdr->lun_num);
2681                         retval = EINVAL;
2682                         break;
2683                 }
2684
2685                 cur_fill_num = 0;
2686
2687                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2688                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2689                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2690                                     ooa_hdr, entries);
2691                         }
2692                 } else {
2693                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2694                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2695                             entries);
2696                 }
2697                 mtx_unlock(&softc->ctl_lock);
2698
2699                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2700                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2701                         sizeof(struct ctl_ooa_entry);
2702                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2703                 if (retval != 0) {
2704                         printf("%s: error copying out %d bytes for OOA dump\n", 
2705                                __func__, ooa_hdr->fill_len);
2706                 }
2707
2708                 getbinuptime(&ooa_hdr->cur_bt);
2709
2710                 if (cur_fill_num > ooa_hdr->alloc_num) {
2711                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2712                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2713                 } else {
2714                         ooa_hdr->dropped_num = 0;
2715                         ooa_hdr->status = CTL_OOA_OK;
2716                 }
2717
2718                 free(entries, M_CTL);
2719                 break;
2720         }
2721         case CTL_DELAY_IO: {
2722                 struct ctl_io_delay_info *delay_info;
2723
2724                 delay_info = (struct ctl_io_delay_info *)addr;
2725
2726 #ifdef CTL_IO_DELAY
2727                 mtx_lock(&softc->ctl_lock);
2728
2729                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2730                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2731                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2732                 } else {
2733                         lun = softc->ctl_luns[delay_info->lun_id];
2734                         mtx_lock(&lun->lun_lock);
2735
2736                         delay_info->status = CTL_DELAY_STATUS_OK;
2737
2738                         switch (delay_info->delay_type) {
2739                         case CTL_DELAY_TYPE_CONT:
2740                                 break;
2741                         case CTL_DELAY_TYPE_ONESHOT:
2742                                 break;
2743                         default:
2744                                 delay_info->status =
2745                                         CTL_DELAY_STATUS_INVALID_TYPE;
2746                                 break;
2747                         }
2748
2749                         switch (delay_info->delay_loc) {
2750                         case CTL_DELAY_LOC_DATAMOVE:
2751                                 lun->delay_info.datamove_type =
2752                                         delay_info->delay_type;
2753                                 lun->delay_info.datamove_delay =
2754                                         delay_info->delay_secs;
2755                                 break;
2756                         case CTL_DELAY_LOC_DONE:
2757                                 lun->delay_info.done_type =
2758                                         delay_info->delay_type;
2759                                 lun->delay_info.done_delay =
2760                                         delay_info->delay_secs;
2761                                 break;
2762                         default:
2763                                 delay_info->status =
2764                                         CTL_DELAY_STATUS_INVALID_LOC;
2765                                 break;
2766                         }
2767                         mtx_unlock(&lun->lun_lock);
2768                 }
2769
2770                 mtx_unlock(&softc->ctl_lock);
2771 #else
2772                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2773 #endif /* CTL_IO_DELAY */
2774                 break;
2775         }
2776         case CTL_GETSTATS: {
2777                 struct ctl_stats *stats;
2778                 int i;
2779
2780                 stats = (struct ctl_stats *)addr;
2781
2782                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2783                      stats->alloc_len) {
2784                         stats->status = CTL_SS_NEED_MORE_SPACE;
2785                         stats->num_luns = softc->num_luns;
2786                         break;
2787                 }
2788                 /*
2789                  * XXX KDM no locking here.  If the LUN list changes,
2790                  * things can blow up.
2791                  */
2792                 i = 0;
2793                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2794                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2795                                          sizeof(lun->stats));
2796                         if (retval != 0)
2797                                 break;
2798                 }
2799                 stats->num_luns = softc->num_luns;
2800                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2801                                  softc->num_luns;
2802                 stats->status = CTL_SS_OK;
2803 #ifdef CTL_TIME_IO
2804                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2805 #else
2806                 stats->flags = CTL_STATS_FLAG_NONE;
2807 #endif
2808                 getnanouptime(&stats->timestamp);
2809                 break;
2810         }
2811         case CTL_ERROR_INJECT: {
2812                 struct ctl_error_desc *err_desc, *new_err_desc;
2813
2814                 err_desc = (struct ctl_error_desc *)addr;
2815
2816                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2817                                       M_WAITOK | M_ZERO);
2818                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2819
2820                 mtx_lock(&softc->ctl_lock);
2821                 lun = softc->ctl_luns[err_desc->lun_id];
2822                 if (lun == NULL) {
2823                         mtx_unlock(&softc->ctl_lock);
2824                         free(new_err_desc, M_CTL);
2825                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2826                                __func__, (uintmax_t)err_desc->lun_id);
2827                         retval = EINVAL;
2828                         break;
2829                 }
2830                 mtx_lock(&lun->lun_lock);
2831                 mtx_unlock(&softc->ctl_lock);
2832
2833                 /*
2834                  * We could do some checking here to verify the validity
2835                  * of the request, but given the complexity of error
2836                  * injection requests, the checking logic would be fairly
2837                  * complex.
2838                  *
2839                  * For now, if the request is invalid, it just won't get
2840                  * executed and might get deleted.
2841                  */
2842                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2843
2844                 /*
2845                  * XXX KDM check to make sure the serial number is unique,
2846                  * in case we somehow manage to wrap.  That shouldn't
2847                  * happen for a very long time, but it's the right thing to
2848                  * do.
2849                  */
2850                 new_err_desc->serial = lun->error_serial;
2851                 err_desc->serial = lun->error_serial;
2852                 lun->error_serial++;
2853
2854                 mtx_unlock(&lun->lun_lock);
2855                 break;
2856         }
2857         case CTL_ERROR_INJECT_DELETE: {
2858                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2859                 int delete_done;
2860
2861                 delete_desc = (struct ctl_error_desc *)addr;
2862                 delete_done = 0;
2863
2864                 mtx_lock(&softc->ctl_lock);
2865                 lun = softc->ctl_luns[delete_desc->lun_id];
2866                 if (lun == NULL) {
2867                         mtx_unlock(&softc->ctl_lock);
2868                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2869                                __func__, (uintmax_t)delete_desc->lun_id);
2870                         retval = EINVAL;
2871                         break;
2872                 }
2873                 mtx_lock(&lun->lun_lock);
2874                 mtx_unlock(&softc->ctl_lock);
2875                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2876                         if (desc->serial != delete_desc->serial)
2877                                 continue;
2878
2879                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2880                                       links);
2881                         free(desc, M_CTL);
2882                         delete_done = 1;
2883                 }
2884                 mtx_unlock(&lun->lun_lock);
2885                 if (delete_done == 0) {
2886                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2887                                "error serial %ju on LUN %u\n", __func__, 
2888                                delete_desc->serial, delete_desc->lun_id);
2889                         retval = EINVAL;
2890                         break;
2891                 }
2892                 break;
2893         }
2894         case CTL_DUMP_STRUCTS: {
2895                 int i, j, k;
2896                 struct ctl_port *port;
2897                 struct ctl_frontend *fe;
2898
2899                 mtx_lock(&softc->ctl_lock);
2900                 printf("CTL Persistent Reservation information start:\n");
2901                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2902                         lun = softc->ctl_luns[i];
2903
2904                         if ((lun == NULL)
2905                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2906                                 continue;
2907
2908                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2909                                 if (lun->pr_keys[j] == NULL)
2910                                         continue;
2911                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2912                                         if (lun->pr_keys[j][k] == 0)
2913                                                 continue;
2914                                         printf("  LUN %d port %d iid %d key "
2915                                                "%#jx\n", i, j, k,
2916                                                (uintmax_t)lun->pr_keys[j][k]);
2917                                 }
2918                         }
2919                 }
2920                 printf("CTL Persistent Reservation information end\n");
2921                 printf("CTL Ports:\n");
2922                 STAILQ_FOREACH(port, &softc->port_list, links) {
2923                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2924                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2925                                port->frontend->name, port->port_type,
2926                                port->physical_port, port->virtual_port,
2927                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2928                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2929                                 if (port->wwpn_iid[j].in_use == 0 &&
2930                                     port->wwpn_iid[j].wwpn == 0 &&
2931                                     port->wwpn_iid[j].name == NULL)
2932                                         continue;
2933
2934                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2935                                     j, port->wwpn_iid[j].in_use,
2936                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2937                                     port->wwpn_iid[j].name);
2938                         }
2939                 }
2940                 printf("CTL Port information end\n");
2941                 mtx_unlock(&softc->ctl_lock);
2942                 /*
2943                  * XXX KDM calling this without a lock.  We'd likely want
2944                  * to drop the lock before calling the frontend's dump
2945                  * routine anyway.
2946                  */
2947                 printf("CTL Frontends:\n");
2948                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2949                         printf("  Frontend '%s'\n", fe->name);
2950                         if (fe->fe_dump != NULL)
2951                                 fe->fe_dump();
2952                 }
2953                 printf("CTL Frontend information end\n");
2954                 break;
2955         }
2956         case CTL_LUN_REQ: {
2957                 struct ctl_lun_req *lun_req;
2958                 struct ctl_backend_driver *backend;
2959
2960                 lun_req = (struct ctl_lun_req *)addr;
2961
2962                 backend = ctl_backend_find(lun_req->backend);
2963                 if (backend == NULL) {
2964                         lun_req->status = CTL_LUN_ERROR;
2965                         snprintf(lun_req->error_str,
2966                                  sizeof(lun_req->error_str),
2967                                  "Backend \"%s\" not found.",
2968                                  lun_req->backend);
2969                         break;
2970                 }
2971                 if (lun_req->num_be_args > 0) {
2972                         lun_req->kern_be_args = ctl_copyin_args(
2973                                 lun_req->num_be_args,
2974                                 lun_req->be_args,
2975                                 lun_req->error_str,
2976                                 sizeof(lun_req->error_str));
2977                         if (lun_req->kern_be_args == NULL) {
2978                                 lun_req->status = CTL_LUN_ERROR;
2979                                 break;
2980                         }
2981                 }
2982
2983                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2984
2985                 if (lun_req->num_be_args > 0) {
2986                         ctl_copyout_args(lun_req->num_be_args,
2987                                       lun_req->kern_be_args);
2988                         ctl_free_args(lun_req->num_be_args,
2989                                       lun_req->kern_be_args);
2990                 }
2991                 break;
2992         }
2993         case CTL_LUN_LIST: {
2994                 struct sbuf *sb;
2995                 struct ctl_lun_list *list;
2996                 struct ctl_option *opt;
2997
2998                 list = (struct ctl_lun_list *)addr;
2999
3000                 /*
3001                  * Allocate a fixed length sbuf here, based on the length
3002                  * of the user's buffer.  We could allocate an auto-extending
3003                  * buffer, and then tell the user how much larger our
3004                  * amount of data is than his buffer, but that presents
3005                  * some problems:
3006                  *
3007                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3008                  *     we can't hold a lock while calling them with an
3009                  *     auto-extending buffer.
3010                  *
3011                  * 2.  There is not currently a LUN reference counting
3012                  *     mechanism, outside of outstanding transactions on
3013                  *     the LUN's OOA queue.  So a LUN could go away on us
3014                  *     while we're getting the LUN number, backend-specific
3015                  *     information, etc.  Thus, given the way things
3016                  *     currently work, we need to hold the CTL lock while
3017                  *     grabbing LUN information.
3018                  *
3019                  * So, from the user's standpoint, the best thing to do is
3020                  * allocate what he thinks is a reasonable buffer length,
3021                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3022                  * double the buffer length and try again.  (And repeat
3023                  * that until he succeeds.)
3024                  */
3025                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3026                 if (sb == NULL) {
3027                         list->status = CTL_LUN_LIST_ERROR;
3028                         snprintf(list->error_str, sizeof(list->error_str),
3029                                  "Unable to allocate %d bytes for LUN list",
3030                                  list->alloc_len);
3031                         break;
3032                 }
3033
3034                 sbuf_printf(sb, "<ctllunlist>\n");
3035
3036                 mtx_lock(&softc->ctl_lock);
3037                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3038                         mtx_lock(&lun->lun_lock);
3039                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3040                                              (uintmax_t)lun->lun);
3041
3042                         /*
3043                          * Bail out as soon as we see that we've overfilled
3044                          * the buffer.
3045                          */
3046                         if (retval != 0)
3047                                 break;
3048
3049                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3050                                              "</backend_type>\n",
3051                                              (lun->backend == NULL) ?  "none" :
3052                                              lun->backend->name);
3053
3054                         if (retval != 0)
3055                                 break;
3056
3057                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3058                                              lun->be_lun->lun_type);
3059
3060                         if (retval != 0)
3061                                 break;
3062
3063                         if (lun->backend == NULL) {
3064                                 retval = sbuf_printf(sb, "</lun>\n");
3065                                 if (retval != 0)
3066                                         break;
3067                                 continue;
3068                         }
3069
3070                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3071                                              (lun->be_lun->maxlba > 0) ?
3072                                              lun->be_lun->maxlba + 1 : 0);
3073
3074                         if (retval != 0)
3075                                 break;
3076
3077                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3078                                              lun->be_lun->blocksize);
3079
3080                         if (retval != 0)
3081                                 break;
3082
3083                         retval = sbuf_printf(sb, "\t<serial_number>");
3084
3085                         if (retval != 0)
3086                                 break;
3087
3088                         retval = ctl_sbuf_printf_esc(sb,
3089                             lun->be_lun->serial_num,
3090                             sizeof(lun->be_lun->serial_num));
3091
3092                         if (retval != 0)
3093                                 break;
3094
3095                         retval = sbuf_printf(sb, "</serial_number>\n");
3096                 
3097                         if (retval != 0)
3098                                 break;
3099
3100                         retval = sbuf_printf(sb, "\t<device_id>");
3101
3102                         if (retval != 0)
3103                                 break;
3104
3105                         retval = ctl_sbuf_printf_esc(sb,
3106                             lun->be_lun->device_id,
3107                             sizeof(lun->be_lun->device_id));
3108
3109                         if (retval != 0)
3110                                 break;
3111
3112                         retval = sbuf_printf(sb, "</device_id>\n");
3113
3114                         if (retval != 0)
3115                                 break;
3116
3117                         if (lun->backend->lun_info != NULL) {
3118                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3119                                 if (retval != 0)
3120                                         break;
3121                         }
3122                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3123                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3124                                     opt->name, opt->value, opt->name);
3125                                 if (retval != 0)
3126                                         break;
3127                         }
3128
3129                         retval = sbuf_printf(sb, "</lun>\n");
3130
3131                         if (retval != 0)
3132                                 break;
3133                         mtx_unlock(&lun->lun_lock);
3134                 }
3135                 if (lun != NULL)
3136                         mtx_unlock(&lun->lun_lock);
3137                 mtx_unlock(&softc->ctl_lock);
3138
3139                 if ((retval != 0)
3140                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3141                         retval = 0;
3142                         sbuf_delete(sb);
3143                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3144                         snprintf(list->error_str, sizeof(list->error_str),
3145                                  "Out of space, %d bytes is too small",
3146                                  list->alloc_len);
3147                         break;
3148                 }
3149
3150                 sbuf_finish(sb);
3151
3152                 retval = copyout(sbuf_data(sb), list->lun_xml,
3153                                  sbuf_len(sb) + 1);
3154
3155                 list->fill_len = sbuf_len(sb) + 1;
3156                 list->status = CTL_LUN_LIST_OK;
3157                 sbuf_delete(sb);
3158                 break;
3159         }
3160         case CTL_ISCSI: {
3161                 struct ctl_iscsi *ci;
3162                 struct ctl_frontend *fe;
3163
3164                 ci = (struct ctl_iscsi *)addr;
3165
3166                 fe = ctl_frontend_find("iscsi");
3167                 if (fe == NULL) {
3168                         ci->status = CTL_ISCSI_ERROR;
3169                         snprintf(ci->error_str, sizeof(ci->error_str),
3170                             "Frontend \"iscsi\" not found.");
3171                         break;
3172                 }
3173
3174                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3175                 break;
3176         }
3177         case CTL_PORT_REQ: {
3178                 struct ctl_req *req;
3179                 struct ctl_frontend *fe;
3180
3181                 req = (struct ctl_req *)addr;
3182
3183                 fe = ctl_frontend_find(req->driver);
3184                 if (fe == NULL) {
3185                         req->status = CTL_LUN_ERROR;
3186                         snprintf(req->error_str, sizeof(req->error_str),
3187                             "Frontend \"%s\" not found.", req->driver);
3188                         break;
3189                 }
3190                 if (req->num_args > 0) {
3191                         req->kern_args = ctl_copyin_args(req->num_args,
3192                             req->args, req->error_str, sizeof(req->error_str));
3193                         if (req->kern_args == NULL) {
3194                                 req->status = CTL_LUN_ERROR;
3195                                 break;
3196                         }
3197                 }
3198
3199                 if (fe->ioctl)
3200                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3201                 else
3202                         retval = ENODEV;
3203
3204                 if (req->num_args > 0) {
3205                         ctl_copyout_args(req->num_args, req->kern_args);
3206                         ctl_free_args(req->num_args, req->kern_args);
3207                 }
3208                 break;
3209         }
3210         case CTL_PORT_LIST: {
3211                 struct sbuf *sb;
3212                 struct ctl_port *port;
3213                 struct ctl_lun_list *list;
3214                 struct ctl_option *opt;
3215                 int j;
3216                 uint32_t plun;
3217
3218                 list = (struct ctl_lun_list *)addr;
3219
3220                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3221                 if (sb == NULL) {
3222                         list->status = CTL_LUN_LIST_ERROR;
3223                         snprintf(list->error_str, sizeof(list->error_str),
3224                                  "Unable to allocate %d bytes for LUN list",
3225                                  list->alloc_len);
3226                         break;
3227                 }
3228
3229                 sbuf_printf(sb, "<ctlportlist>\n");
3230
3231                 mtx_lock(&softc->ctl_lock);
3232                 STAILQ_FOREACH(port, &softc->port_list, links) {
3233                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3234                                              (uintmax_t)port->targ_port);
3235
3236                         /*
3237                          * Bail out as soon as we see that we've overfilled
3238                          * the buffer.
3239                          */
3240                         if (retval != 0)
3241                                 break;
3242
3243                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3244                             "</frontend_type>\n", port->frontend->name);
3245                         if (retval != 0)
3246                                 break;
3247
3248                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3249                                              port->port_type);
3250                         if (retval != 0)
3251                                 break;
3252
3253                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3254                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3255                         if (retval != 0)
3256                                 break;
3257
3258                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3259                             port->port_name);
3260                         if (retval != 0)
3261                                 break;
3262
3263                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3264                             port->physical_port);
3265                         if (retval != 0)
3266                                 break;
3267
3268                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3269                             port->virtual_port);
3270                         if (retval != 0)
3271                                 break;
3272
3273                         if (port->target_devid != NULL) {
3274                                 sbuf_printf(sb, "\t<target>");
3275                                 ctl_id_sbuf(port->target_devid, sb);
3276                                 sbuf_printf(sb, "</target>\n");
3277                         }
3278
3279                         if (port->port_devid != NULL) {
3280                                 sbuf_printf(sb, "\t<port>");
3281                                 ctl_id_sbuf(port->port_devid, sb);
3282                                 sbuf_printf(sb, "</port>\n");
3283                         }
3284
3285                         if (port->port_info != NULL) {
3286                                 retval = port->port_info(port->onoff_arg, sb);
3287                                 if (retval != 0)
3288                                         break;
3289                         }
3290                         STAILQ_FOREACH(opt, &port->options, links) {
3291                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3292                                     opt->name, opt->value, opt->name);
3293                                 if (retval != 0)
3294                                         break;
3295                         }
3296
3297                         if (port->lun_map != NULL) {
3298                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3299                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3300                                         plun = ctl_lun_map_from_port(port, j);
3301                                         if (plun >= CTL_MAX_LUNS)
3302                                                 continue;
3303                                         sbuf_printf(sb,
3304                                             "\t<lun id=\"%u\">%u</lun>\n",
3305                                             j, plun);
3306                                 }
3307                         }
3308
3309                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3310                                 if (port->wwpn_iid[j].in_use == 0 ||
3311                                     (port->wwpn_iid[j].wwpn == 0 &&
3312                                      port->wwpn_iid[j].name == NULL))
3313                                         continue;
3314
3315                                 if (port->wwpn_iid[j].name != NULL)
3316                                         retval = sbuf_printf(sb,
3317                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3318                                             j, port->wwpn_iid[j].name);
3319                                 else
3320                                         retval = sbuf_printf(sb,
3321                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3322                                             j, port->wwpn_iid[j].wwpn);
3323                                 if (retval != 0)
3324                                         break;
3325                         }
3326                         if (retval != 0)
3327                                 break;
3328
3329                         retval = sbuf_printf(sb, "</targ_port>\n");
3330                         if (retval != 0)
3331                                 break;
3332                 }
3333                 mtx_unlock(&softc->ctl_lock);
3334
3335                 if ((retval != 0)
3336                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3337                         retval = 0;
3338                         sbuf_delete(sb);
3339                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3340                         snprintf(list->error_str, sizeof(list->error_str),
3341                                  "Out of space, %d bytes is too small",
3342                                  list->alloc_len);
3343                         break;
3344                 }
3345
3346                 sbuf_finish(sb);
3347
3348                 retval = copyout(sbuf_data(sb), list->lun_xml,
3349                                  sbuf_len(sb) + 1);
3350
3351                 list->fill_len = sbuf_len(sb) + 1;
3352                 list->status = CTL_LUN_LIST_OK;
3353                 sbuf_delete(sb);
3354                 break;
3355         }
3356         case CTL_LUN_MAP: {
3357                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3358                 struct ctl_port *port;
3359
3360                 mtx_lock(&softc->ctl_lock);
3361                 if (lm->port < softc->port_min ||
3362                     lm->port >= softc->port_max ||
3363                     (port = softc->ctl_ports[lm->port]) == NULL) {
3364                         mtx_unlock(&softc->ctl_lock);
3365                         return (ENXIO);
3366                 }
3367                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3368                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3369                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3370                                     CTL_MAX_LUNS)
3371                                         continue;
3372                                 mtx_lock(&lun->lun_lock);
3373                                 ctl_est_ua_port(lun, lm->port, -1,
3374                                     CTL_UA_LUN_CHANGE);
3375                                 mtx_unlock(&lun->lun_lock);
3376                         }
3377                 }
3378                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3379                 if (lm->plun < CTL_MAX_LUNS) {
3380                         if (lm->lun == UINT32_MAX)
3381                                 retval = ctl_lun_map_unset(port, lm->plun);
3382                         else if (lm->lun < CTL_MAX_LUNS &&
3383                             softc->ctl_luns[lm->lun] != NULL)
3384                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3385                         else
3386                                 return (ENXIO);
3387                 } else if (lm->plun == UINT32_MAX) {
3388                         if (lm->lun == UINT32_MAX)
3389                                 retval = ctl_lun_map_deinit(port);
3390                         else
3391                                 retval = ctl_lun_map_init(port);
3392                 } else
3393                         return (ENXIO);
3394                 if (port->status & CTL_PORT_STATUS_ONLINE)
3395                         ctl_isc_announce_port(port);
3396                 break;
3397         }
3398         default: {
3399                 /* XXX KDM should we fix this? */
3400 #if 0
3401                 struct ctl_backend_driver *backend;
3402                 unsigned int type;
3403                 int found;
3404
3405                 found = 0;
3406
3407                 /*
3408                  * We encode the backend type as the ioctl type for backend
3409                  * ioctls.  So parse it out here, and then search for a
3410                  * backend of this type.
3411                  */
3412                 type = _IOC_TYPE(cmd);
3413
3414                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3415                         if (backend->type == type) {
3416                                 found = 1;
3417                                 break;
3418                         }
3419                 }
3420                 if (found == 0) {
3421                         printf("ctl: unknown ioctl command %#lx or backend "
3422                                "%d\n", cmd, type);
3423                         retval = EINVAL;
3424                         break;
3425                 }
3426                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3427 #endif
3428                 retval = ENOTTY;
3429                 break;
3430         }
3431         }
3432         return (retval);
3433 }
3434
3435 uint32_t
3436 ctl_get_initindex(struct ctl_nexus *nexus)
3437 {
3438         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3439 }
3440
3441 int
3442 ctl_lun_map_init(struct ctl_port *port)
3443 {
3444         struct ctl_softc *softc = port->ctl_softc;
3445         struct ctl_lun *lun;
3446         uint32_t i;
3447
3448         if (port->lun_map == NULL)
3449                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3450                     M_CTL, M_NOWAIT);
3451         if (port->lun_map == NULL)
3452                 return (ENOMEM);
3453         for (i = 0; i < CTL_MAX_LUNS; i++)
3454                 port->lun_map[i] = UINT32_MAX;
3455         if (port->status & CTL_PORT_STATUS_ONLINE) {
3456                 if (port->lun_disable != NULL) {
3457                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3458                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3459                 }
3460                 ctl_isc_announce_port(port);
3461         }
3462         return (0);
3463 }
3464
3465 int
3466 ctl_lun_map_deinit(struct ctl_port *port)
3467 {
3468         struct ctl_softc *softc = port->ctl_softc;
3469         struct ctl_lun *lun;
3470
3471         if (port->lun_map == NULL)
3472                 return (0);
3473         free(port->lun_map, M_CTL);
3474         port->lun_map = NULL;
3475         if (port->status & CTL_PORT_STATUS_ONLINE) {
3476                 if (port->lun_enable != NULL) {
3477                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3478                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3479                 }
3480                 ctl_isc_announce_port(port);
3481         }
3482         return (0);
3483 }
3484
3485 int
3486 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3487 {
3488         int status;
3489         uint32_t old;
3490
3491         if (port->lun_map == NULL) {
3492                 status = ctl_lun_map_init(port);
3493                 if (status != 0)
3494                         return (status);
3495         }
3496         old = port->lun_map[plun];
3497         port->lun_map[plun] = glun;
3498         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3499                 if (port->lun_enable != NULL)
3500                         port->lun_enable(port->targ_lun_arg, plun);
3501                 ctl_isc_announce_port(port);
3502         }
3503         return (0);
3504 }
3505
3506 int
3507 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3508 {
3509         uint32_t old;
3510
3511         if (port->lun_map == NULL)
3512                 return (0);
3513         old = port->lun_map[plun];
3514         port->lun_map[plun] = UINT32_MAX;
3515         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3516                 if (port->lun_disable != NULL)
3517                         port->lun_disable(port->targ_lun_arg, plun);
3518                 ctl_isc_announce_port(port);
3519         }
3520         return (0);
3521 }
3522
3523 uint32_t
3524 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3525 {
3526
3527         if (port == NULL)
3528                 return (UINT32_MAX);
3529         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3530                 return (lun_id);
3531         return (port->lun_map[lun_id]);
3532 }
3533
3534 uint32_t
3535 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3536 {
3537         uint32_t i;
3538
3539         if (port == NULL)
3540                 return (UINT32_MAX);
3541         if (port->lun_map == NULL)
3542                 return (lun_id);
3543         for (i = 0; i < CTL_MAX_LUNS; i++) {
3544                 if (port->lun_map[i] == lun_id)
3545                         return (i);
3546         }
3547         return (UINT32_MAX);
3548 }
3549
3550 uint32_t
3551 ctl_decode_lun(uint64_t encoded)
3552 {
3553         uint8_t lun[8];
3554         uint32_t result = 0xffffffff;
3555
3556         be64enc(lun, encoded);
3557         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3558         case RPL_LUNDATA_ATYP_PERIPH:
3559                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3560                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3561                         result = lun[1];
3562                 break;
3563         case RPL_LUNDATA_ATYP_FLAT:
3564                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3565                     lun[6] == 0 && lun[7] == 0)
3566                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3567                 break;
3568         case RPL_LUNDATA_ATYP_EXTLUN:
3569                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3570                 case 0x02:
3571                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3572                         case 0x00:
3573                                 result = lun[1];
3574                                 break;
3575                         case 0x10:
3576                                 result = (lun[1] << 16) + (lun[2] << 8) +
3577                                     lun[3];
3578                                 break;
3579                         case 0x20:
3580                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3581                                         result = (lun[2] << 24) +
3582                                             (lun[3] << 16) + (lun[4] << 8) +
3583                                             lun[5];
3584                                 break;
3585                         }
3586                         break;
3587                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3588                         result = 0xffffffff;
3589                         break;
3590                 }
3591                 break;
3592         }
3593         return (result);
3594 }
3595
3596 uint64_t
3597 ctl_encode_lun(uint32_t decoded)
3598 {
3599         uint64_t l = decoded;
3600
3601         if (l <= 0xff)
3602                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3603         if (l <= 0x3fff)
3604                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3605         if (l <= 0xffffff)
3606                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3607                     (l << 32));
3608         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3609 }
3610
3611 static struct ctl_port *
3612 ctl_io_port(struct ctl_io_hdr *io_hdr)
3613 {
3614
3615         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3616 }
3617
3618 int
3619 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3620 {
3621         int i;
3622
3623         for (i = first; i < last; i++) {
3624                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3625                         return (i);
3626         }
3627         return (-1);
3628 }
3629
3630 int
3631 ctl_set_mask(uint32_t *mask, uint32_t bit)
3632 {
3633         uint32_t chunk, piece;
3634
3635         chunk = bit >> 5;
3636         piece = bit % (sizeof(uint32_t) * 8);
3637
3638         if ((mask[chunk] & (1 << piece)) != 0)
3639                 return (-1);
3640         else
3641                 mask[chunk] |= (1 << piece);
3642
3643         return (0);
3644 }
3645
3646 int
3647 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3648 {
3649         uint32_t chunk, piece;
3650
3651         chunk = bit >> 5;
3652         piece = bit % (sizeof(uint32_t) * 8);
3653
3654         if ((mask[chunk] & (1 << piece)) == 0)
3655                 return (-1);
3656         else
3657                 mask[chunk] &= ~(1 << piece);
3658
3659         return (0);
3660 }
3661
3662 int
3663 ctl_is_set(uint32_t *mask, uint32_t bit)
3664 {
3665         uint32_t chunk, piece;
3666
3667         chunk = bit >> 5;
3668         piece = bit % (sizeof(uint32_t) * 8);
3669
3670         if ((mask[chunk] & (1 << piece)) == 0)
3671                 return (0);
3672         else
3673                 return (1);
3674 }
3675
3676 static uint64_t
3677 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3678 {
3679         uint64_t *t;
3680
3681         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3682         if (t == NULL)
3683                 return (0);
3684         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3685 }
3686
3687 static void
3688 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3689 {
3690         uint64_t *t;
3691
3692         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3693         if (t == NULL)
3694                 return;
3695         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3696 }
3697
3698 static void
3699 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3700 {
3701         uint64_t *p;
3702         u_int i;
3703
3704         i = residx/CTL_MAX_INIT_PER_PORT;
3705         if (lun->pr_keys[i] != NULL)
3706                 return;
3707         mtx_unlock(&lun->lun_lock);
3708         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3709             M_WAITOK | M_ZERO);
3710         mtx_lock(&lun->lun_lock);
3711         if (lun->pr_keys[i] == NULL)
3712                 lun->pr_keys[i] = p;
3713         else
3714                 free(p, M_CTL);
3715 }
3716
3717 static void
3718 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3719 {
3720         uint64_t *t;
3721
3722         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3723         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3724         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3725 }
3726
3727 /*
3728  * ctl_softc, pool_name, total_ctl_io are passed in.
3729  * npool is passed out.
3730  */
3731 int
3732 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3733                 uint32_t total_ctl_io, void **npool)
3734 {
3735 #ifdef IO_POOLS
3736         struct ctl_io_pool *pool;
3737
3738         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3739                                             M_NOWAIT | M_ZERO);
3740         if (pool == NULL)
3741                 return (ENOMEM);
3742
3743         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3744         pool->ctl_softc = ctl_softc;
3745         pool->zone = uma_zsecond_create(pool->name, NULL,
3746             NULL, NULL, NULL, ctl_softc->io_zone);
3747         /* uma_prealloc(pool->zone, total_ctl_io); */
3748
3749         *npool = pool;
3750 #else
3751         *npool = ctl_softc->io_zone;
3752 #endif
3753         return (0);
3754 }
3755
3756 void
3757 ctl_pool_free(struct ctl_io_pool *pool)
3758 {
3759
3760         if (pool == NULL)
3761                 return;
3762
3763 #ifdef IO_POOLS
3764         uma_zdestroy(pool->zone);
3765         free(pool, M_CTL);
3766 #endif
3767 }
3768
3769 union ctl_io *
3770 ctl_alloc_io(void *pool_ref)
3771 {
3772         union ctl_io *io;
3773 #ifdef IO_POOLS
3774         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3775
3776         io = uma_zalloc(pool->zone, M_WAITOK);
3777 #else
3778         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3779 #endif
3780         if (io != NULL)
3781                 io->io_hdr.pool = pool_ref;
3782         return (io);
3783 }
3784
3785 union ctl_io *
3786 ctl_alloc_io_nowait(void *pool_ref)
3787 {
3788         union ctl_io *io;
3789 #ifdef IO_POOLS
3790         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3791
3792         io = uma_zalloc(pool->zone, M_NOWAIT);
3793 #else
3794         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3795 #endif
3796         if (io != NULL)
3797                 io->io_hdr.pool = pool_ref;
3798         return (io);
3799 }
3800
3801 void
3802 ctl_free_io(union ctl_io *io)
3803 {
3804 #ifdef IO_POOLS
3805         struct ctl_io_pool *pool;
3806 #endif
3807
3808         if (io == NULL)
3809                 return;
3810
3811 #ifdef IO_POOLS
3812         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3813         uma_zfree(pool->zone, io);
3814 #else
3815         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3816 #endif
3817 }
3818
3819 void
3820 ctl_zero_io(union ctl_io *io)
3821 {
3822         void *pool_ref;
3823
3824         if (io == NULL)
3825                 return;
3826
3827         /*
3828          * May need to preserve linked list pointers at some point too.
3829          */
3830         pool_ref = io->io_hdr.pool;
3831         memset(io, 0, sizeof(*io));
3832         io->io_hdr.pool = pool_ref;
3833 }
3834
3835 int
3836 ctl_expand_number(const char *buf, uint64_t *num)
3837 {
3838         char *endptr;
3839         uint64_t number;
3840         unsigned shift;
3841
3842         number = strtoq(buf, &endptr, 0);
3843
3844         switch (tolower((unsigned char)*endptr)) {
3845         case 'e':
3846                 shift = 60;
3847                 break;
3848         case 'p':
3849                 shift = 50;
3850                 break;
3851         case 't':
3852                 shift = 40;
3853                 break;
3854         case 'g':
3855                 shift = 30;
3856                 break;
3857         case 'm':
3858                 shift = 20;
3859                 break;
3860         case 'k':
3861                 shift = 10;
3862                 break;
3863         case 'b':
3864         case '\0': /* No unit. */
3865                 *num = number;
3866                 return (0);
3867         default:
3868                 /* Unrecognized unit. */
3869                 return (-1);
3870         }
3871
3872         if ((number << shift) >> shift != number) {
3873                 /* Overflow */
3874                 return (-1);
3875         }
3876         *num = number << shift;
3877         return (0);
3878 }
3879
3880
3881 /*
3882  * This routine could be used in the future to load default and/or saved
3883  * mode page parameters for a particuar lun.
3884  */
3885 static int
3886 ctl_init_page_index(struct ctl_lun *lun)
3887 {
3888         int i, page_code;
3889         struct ctl_page_index *page_index;
3890         const char *value;
3891         uint64_t ival;
3892
3893         memcpy(&lun->mode_pages.index, page_index_template,
3894                sizeof(page_index_template));
3895
3896         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3897
3898                 page_index = &lun->mode_pages.index[i];
3899                 if (lun->be_lun->lun_type == T_DIRECT &&
3900                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3901                         continue;
3902                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3903                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3904                         continue;
3905                 if (lun->be_lun->lun_type == T_CDROM &&
3906                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3907                         continue;
3908
3909                 page_code = page_index->page_code & SMPH_PC_MASK;
3910                 switch (page_code) {
3911                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3912                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3913                             ("subpage %#x for page %#x is incorrect!",
3914                             page_index->subpage, page_code));
3915                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3916                                &rw_er_page_default,
3917                                sizeof(rw_er_page_default));
3918                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3919                                &rw_er_page_changeable,
3920                                sizeof(rw_er_page_changeable));
3921                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3922                                &rw_er_page_default,
3923                                sizeof(rw_er_page_default));
3924                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3925                                &rw_er_page_default,
3926                                sizeof(rw_er_page_default));
3927                         page_index->page_data =
3928                                 (uint8_t *)lun->mode_pages.rw_er_page;
3929                         break;
3930                 }
3931                 case SMS_FORMAT_DEVICE_PAGE: {
3932                         struct scsi_format_page *format_page;
3933
3934                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3935                             ("subpage %#x for page %#x is incorrect!",
3936                             page_index->subpage, page_code));
3937
3938                         /*
3939                          * Sectors per track are set above.  Bytes per
3940                          * sector need to be set here on a per-LUN basis.
3941                          */
3942                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3943                                &format_page_default,
3944                                sizeof(format_page_default));
3945                         memcpy(&lun->mode_pages.format_page[
3946                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3947                                sizeof(format_page_changeable));
3948                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3949                                &format_page_default,
3950                                sizeof(format_page_default));
3951                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3952                                &format_page_default,
3953                                sizeof(format_page_default));
3954
3955                         format_page = &lun->mode_pages.format_page[
3956                                 CTL_PAGE_CURRENT];
3957                         scsi_ulto2b(lun->be_lun->blocksize,
3958                                     format_page->bytes_per_sector);
3959
3960                         format_page = &lun->mode_pages.format_page[
3961                                 CTL_PAGE_DEFAULT];
3962                         scsi_ulto2b(lun->be_lun->blocksize,
3963                                     format_page->bytes_per_sector);
3964
3965                         format_page = &lun->mode_pages.format_page[
3966                                 CTL_PAGE_SAVED];
3967                         scsi_ulto2b(lun->be_lun->blocksize,
3968                                     format_page->bytes_per_sector);
3969
3970                         page_index->page_data =
3971                                 (uint8_t *)lun->mode_pages.format_page;
3972                         break;
3973                 }
3974                 case SMS_RIGID_DISK_PAGE: {
3975                         struct scsi_rigid_disk_page *rigid_disk_page;
3976                         uint32_t sectors_per_cylinder;
3977                         uint64_t cylinders;
3978 #ifndef __XSCALE__
3979                         int shift;
3980 #endif /* !__XSCALE__ */
3981
3982                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3983                             ("subpage %#x for page %#x is incorrect!",
3984                             page_index->subpage, page_code));
3985
3986                         /*
3987                          * Rotation rate and sectors per track are set
3988                          * above.  We calculate the cylinders here based on
3989                          * capacity.  Due to the number of heads and
3990                          * sectors per track we're using, smaller arrays
3991                          * may turn out to have 0 cylinders.  Linux and
3992                          * FreeBSD don't pay attention to these mode pages
3993                          * to figure out capacity, but Solaris does.  It
3994                          * seems to deal with 0 cylinders just fine, and
3995                          * works out a fake geometry based on the capacity.
3996                          */
3997                         memcpy(&lun->mode_pages.rigid_disk_page[
3998                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3999                                sizeof(rigid_disk_page_default));
4000                         memcpy(&lun->mode_pages.rigid_disk_page[
4001                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4002                                sizeof(rigid_disk_page_changeable));
4003
4004                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4005                                 CTL_DEFAULT_HEADS;
4006
4007                         /*
4008                          * The divide method here will be more accurate,
4009                          * probably, but results in floating point being
4010                          * used in the kernel on i386 (__udivdi3()).  On the
4011                          * XScale, though, __udivdi3() is implemented in
4012                          * software.
4013                          *
4014                          * The shift method for cylinder calculation is
4015                          * accurate if sectors_per_cylinder is a power of
4016                          * 2.  Otherwise it might be slightly off -- you
4017                          * might have a bit of a truncation problem.
4018                          */
4019 #ifdef  __XSCALE__
4020                         cylinders = (lun->be_lun->maxlba + 1) /
4021                                 sectors_per_cylinder;
4022 #else
4023                         for (shift = 31; shift > 0; shift--) {
4024                                 if (sectors_per_cylinder & (1 << shift))
4025                                         break;
4026                         }
4027                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4028 #endif
4029
4030                         /*
4031                          * We've basically got 3 bytes, or 24 bits for the
4032                          * cylinder size in the mode page.  If we're over,
4033                          * just round down to 2^24.
4034                          */
4035                         if (cylinders > 0xffffff)
4036                                 cylinders = 0xffffff;
4037
4038                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4039                                 CTL_PAGE_DEFAULT];
4040                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4041
4042                         if ((value = ctl_get_opt(&lun->be_lun->options,
4043                             "rpm")) != NULL) {
4044                                 scsi_ulto2b(strtol(value, NULL, 0),
4045                                      rigid_disk_page->rotation_rate);
4046                         }
4047
4048                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4049                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4050                                sizeof(rigid_disk_page_default));
4051                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4052                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4053                                sizeof(rigid_disk_page_default));
4054
4055                         page_index->page_data =
4056                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4057                         break;
4058                 }
4059                 case SMS_CACHING_PAGE: {
4060                         struct scsi_caching_page *caching_page;
4061
4062                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4063                             ("subpage %#x for page %#x is incorrect!",
4064                             page_index->subpage, page_code));
4065                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4066                                &caching_page_default,
4067                                sizeof(caching_page_default));
4068                         memcpy(&lun->mode_pages.caching_page[
4069                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4070                                sizeof(caching_page_changeable));
4071                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4072                                &caching_page_default,
4073                                sizeof(caching_page_default));
4074                         caching_page = &lun->mode_pages.caching_page[
4075                             CTL_PAGE_SAVED];
4076                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4077                         if (value != NULL && strcmp(value, "off") == 0)
4078                                 caching_page->flags1 &= ~SCP_WCE;
4079                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4080                         if (value != NULL && strcmp(value, "off") == 0)
4081                                 caching_page->flags1 |= SCP_RCD;
4082                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4083                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4084                                sizeof(caching_page_default));
4085                         page_index->page_data =
4086                                 (uint8_t *)lun->mode_pages.caching_page;
4087                         break;
4088                 }
4089                 case SMS_CONTROL_MODE_PAGE: {
4090                         switch (page_index->subpage) {
4091                         case SMS_SUBPAGE_PAGE_0: {
4092                                 struct scsi_control_page *control_page;
4093
4094                                 memcpy(&lun->mode_pages.control_page[
4095                                     CTL_PAGE_DEFAULT],
4096                                        &control_page_default,
4097                                        sizeof(control_page_default));
4098                                 memcpy(&lun->mode_pages.control_page[
4099                                     CTL_PAGE_CHANGEABLE],
4100                                        &control_page_changeable,
4101                                        sizeof(control_page_changeable));
4102                                 memcpy(&lun->mode_pages.control_page[
4103                                     CTL_PAGE_SAVED],
4104                                        &control_page_default,
4105                                        sizeof(control_page_default));
4106                                 control_page = &lun->mode_pages.control_page[
4107                                     CTL_PAGE_SAVED];
4108                                 value = ctl_get_opt(&lun->be_lun->options,
4109                                     "reordering");
4110                                 if (value != NULL &&
4111                                     strcmp(value, "unrestricted") == 0) {
4112                                         control_page->queue_flags &=
4113                                             ~SCP_QUEUE_ALG_MASK;
4114                                         control_page->queue_flags |=
4115                                             SCP_QUEUE_ALG_UNRESTRICTED;
4116                                 }
4117                                 memcpy(&lun->mode_pages.control_page[
4118                                     CTL_PAGE_CURRENT],
4119                                        &lun->mode_pages.control_page[
4120                                     CTL_PAGE_SAVED],
4121                                        sizeof(control_page_default));
4122                                 page_index->page_data =
4123                                     (uint8_t *)lun->mode_pages.control_page;
4124                                 break;
4125                         }
4126                         case 0x01:
4127                                 memcpy(&lun->mode_pages.control_ext_page[
4128                                     CTL_PAGE_DEFAULT],
4129                                        &control_ext_page_default,
4130                                        sizeof(control_ext_page_default));
4131                                 memcpy(&lun->mode_pages.control_ext_page[
4132                                     CTL_PAGE_CHANGEABLE],
4133                                        &control_ext_page_changeable,
4134                                        sizeof(control_ext_page_changeable));
4135                                 memcpy(&lun->mode_pages.control_ext_page[
4136                                     CTL_PAGE_SAVED],
4137                                        &control_ext_page_default,
4138                                        sizeof(control_ext_page_default));
4139                                 memcpy(&lun->mode_pages.control_ext_page[
4140                                     CTL_PAGE_CURRENT],
4141                                        &lun->mode_pages.control_ext_page[
4142                                     CTL_PAGE_SAVED],
4143                                        sizeof(control_ext_page_default));
4144                                 page_index->page_data =
4145                                     (uint8_t *)lun->mode_pages.control_ext_page;
4146                                 break;
4147                         default:
4148                                 panic("subpage %#x for page %#x is incorrect!",
4149                                       page_index->subpage, page_code);
4150                         }
4151                         break;
4152                 }
4153                 case SMS_INFO_EXCEPTIONS_PAGE: {
4154                         switch (page_index->subpage) {
4155                         case SMS_SUBPAGE_PAGE_0:
4156                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4157                                        &ie_page_default,
4158                                        sizeof(ie_page_default));
4159                                 memcpy(&lun->mode_pages.ie_page[
4160                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4161                                        sizeof(ie_page_changeable));
4162                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4163                                        &ie_page_default,
4164                                        sizeof(ie_page_default));
4165                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4166                                        &ie_page_default,
4167                                        sizeof(ie_page_default));
4168                                 page_index->page_data =
4169                                         (uint8_t *)lun->mode_pages.ie_page;
4170                                 break;
4171                         case 0x02: {
4172                                 struct ctl_logical_block_provisioning_page *page;
4173
4174                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4175                                        &lbp_page_default,
4176                                        sizeof(lbp_page_default));
4177                                 memcpy(&lun->mode_pages.lbp_page[
4178                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4179                                        sizeof(lbp_page_changeable));
4180                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4181                                        &lbp_page_default,
4182                                        sizeof(lbp_page_default));
4183                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4184                                 value = ctl_get_opt(&lun->be_lun->options,
4185                                     "avail-threshold");
4186                                 if (value != NULL &&
4187                                     ctl_expand_number(value, &ival) == 0) {
4188                                         page->descr[0].flags |= SLBPPD_ENABLED |
4189                                             SLBPPD_ARMING_DEC;
4190                                         if (lun->be_lun->blocksize)
4191                                                 ival /= lun->be_lun->blocksize;
4192                                         else
4193                                                 ival /= 512;
4194                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4195                                             page->descr[0].count);
4196                                 }
4197                                 value = ctl_get_opt(&lun->be_lun->options,
4198                                     "used-threshold");
4199                                 if (value != NULL &&
4200                                     ctl_expand_number(value, &ival) == 0) {
4201                                         page->descr[1].flags |= SLBPPD_ENABLED |
4202                                             SLBPPD_ARMING_INC;
4203                                         if (lun->be_lun->blocksize)
4204                                                 ival /= lun->be_lun->blocksize;
4205                                         else
4206                                                 ival /= 512;
4207                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4208                                             page->descr[1].count);
4209                                 }
4210                                 value = ctl_get_opt(&lun->be_lun->options,
4211                                     "pool-avail-threshold");
4212                                 if (value != NULL &&
4213                                     ctl_expand_number(value, &ival) == 0) {
4214                                         page->descr[2].flags |= SLBPPD_ENABLED |
4215                                             SLBPPD_ARMING_DEC;
4216                                         if (lun->be_lun->blocksize)
4217                                                 ival /= lun->be_lun->blocksize;
4218                                         else
4219                                                 ival /= 512;
4220                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4221                                             page->descr[2].count);
4222                                 }
4223                                 value = ctl_get_opt(&lun->be_lun->options,
4224                                     "pool-used-threshold");
4225                                 if (value != NULL &&
4226                                     ctl_expand_number(value, &ival) == 0) {
4227                                         page->descr[3].flags |= SLBPPD_ENABLED |
4228                                             SLBPPD_ARMING_INC;
4229                                         if (lun->be_lun->blocksize)
4230                                                 ival /= lun->be_lun->blocksize;
4231                                         else
4232                                                 ival /= 512;
4233                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4234                                             page->descr[3].count);
4235                                 }
4236                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4237                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4238                                        sizeof(lbp_page_default));
4239                                 page_index->page_data =
4240                                         (uint8_t *)lun->mode_pages.lbp_page;
4241                                 break;
4242                         }
4243                         default:
4244                                 panic("subpage %#x for page %#x is incorrect!",
4245                                       page_index->subpage, page_code);
4246                         }
4247                         break;
4248                 }
4249                 case SMS_CDDVD_CAPS_PAGE:{
4250                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4251                             ("subpage %#x for page %#x is incorrect!",
4252                             page_index->subpage, page_code));
4253                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4254                                &cddvd_page_default,
4255                                sizeof(cddvd_page_default));
4256                         memcpy(&lun->mode_pages.cddvd_page[
4257                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4258                                sizeof(cddvd_page_changeable));
4259                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4260                                &cddvd_page_default,
4261                                sizeof(cddvd_page_default));
4262                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4263                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4264                                sizeof(cddvd_page_default));
4265                         page_index->page_data =
4266                                 (uint8_t *)lun->mode_pages.cddvd_page;
4267                         break;
4268                 }
4269                 case SMS_VENDOR_SPECIFIC_PAGE:{
4270                         switch (page_index->subpage) {
4271                         case DBGCNF_SUBPAGE_CODE: {
4272                                 memcpy(&lun->mode_pages.debugconf_subpage[
4273                                        CTL_PAGE_CURRENT],
4274                                        &debugconf_page_default,
4275                                        sizeof(debugconf_page_default));
4276                                 memcpy(&lun->mode_pages.debugconf_subpage[
4277                                        CTL_PAGE_CHANGEABLE],
4278                                        &debugconf_page_changeable,
4279                                        sizeof(debugconf_page_changeable));
4280                                 memcpy(&lun->mode_pages.debugconf_subpage[
4281                                        CTL_PAGE_DEFAULT],
4282                                        &debugconf_page_default,
4283                                        sizeof(debugconf_page_default));
4284                                 memcpy(&lun->mode_pages.debugconf_subpage[
4285                                        CTL_PAGE_SAVED],
4286                                        &debugconf_page_default,
4287                                        sizeof(debugconf_page_default));
4288                                 page_index->page_data =
4289                                     (uint8_t *)lun->mode_pages.debugconf_subpage;
4290                                 break;
4291                         }
4292                         default:
4293                                 panic("subpage %#x for page %#x is incorrect!",
4294                                       page_index->subpage, page_code);
4295                         }
4296                         break;
4297                 }
4298                 default:
4299                         panic("invalid page code value %#x", page_code);
4300                 }
4301         }
4302
4303         return (CTL_RETVAL_COMPLETE);
4304 }
4305
4306 static int
4307 ctl_init_log_page_index(struct ctl_lun *lun)
4308 {
4309         struct ctl_page_index *page_index;
4310         int i, j, k, prev;
4311
4312         memcpy(&lun->log_pages.index, log_page_index_template,
4313                sizeof(log_page_index_template));
4314
4315         prev = -1;
4316         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4317
4318                 page_index = &lun->log_pages.index[i];
4319                 if (lun->be_lun->lun_type == T_DIRECT &&
4320                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4321                         continue;
4322                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4323                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4324                         continue;
4325                 if (lun->be_lun->lun_type == T_CDROM &&
4326                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4327                         continue;
4328
4329                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4330                     lun->backend->lun_attr == NULL)
4331                         continue;
4332
4333                 if (page_index->page_code != prev) {
4334                         lun->log_pages.pages_page[j] = page_index->page_code;
4335                         prev = page_index->page_code;
4336                         j++;
4337                 }
4338                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4339                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4340                 k++;
4341         }
4342         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4343         lun->log_pages.index[0].page_len = j;
4344         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4345         lun->log_pages.index[1].page_len = k * 2;
4346         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4347         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4348         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4349         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4350
4351         return (CTL_RETVAL_COMPLETE);
4352 }
4353
4354 static int
4355 hex2bin(const char *str, uint8_t *buf, int buf_size)
4356 {
4357         int i;
4358         u_char c;
4359
4360         memset(buf, 0, buf_size);
4361         while (isspace(str[0]))
4362                 str++;
4363         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4364                 str += 2;
4365         buf_size *= 2;
4366         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4367                 c = str[i];
4368                 if (isdigit(c))
4369                         c -= '0';
4370                 else if (isalpha(c))
4371                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4372                 else
4373                         break;
4374                 if (c >= 16)
4375                         break;
4376                 if ((i & 1) == 0)
4377                         buf[i / 2] |= (c << 4);
4378                 else
4379                         buf[i / 2] |= c;
4380         }
4381         return ((i + 1) / 2);
4382 }
4383
4384 /*
4385  * LUN allocation.
4386  *
4387  * Requirements:
4388  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4389  *   wants us to allocate the LUN and he can block.
4390  * - ctl_softc is always set
4391  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4392  *
4393  * Returns 0 for success, non-zero (errno) for failure.
4394  */
4395 static int
4396 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4397               struct ctl_be_lun *const be_lun)
4398 {
4399         struct ctl_lun *nlun, *lun;
4400         struct scsi_vpd_id_descriptor *desc;
4401         struct scsi_vpd_id_t10 *t10id;
4402         const char *eui, *naa, *scsiname, *vendor, *value;
4403         int lun_number, i, lun_malloced;
4404         int devidlen, idlen1, idlen2 = 0, len;
4405
4406         if (be_lun == NULL)
4407                 return (EINVAL);
4408
4409         /*
4410          * We currently only support Direct Access or Processor LUN types.
4411          */
4412         switch (be_lun->lun_type) {
4413         case T_DIRECT:
4414         case T_PROCESSOR:
4415         case T_CDROM:
4416                 break;
4417         case T_SEQUENTIAL:
4418         case T_CHANGER:
4419         default:
4420                 be_lun->lun_config_status(be_lun->be_lun,
4421                                           CTL_LUN_CONFIG_FAILURE);
4422                 break;
4423         }
4424         if (ctl_lun == NULL) {
4425                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4426                 lun_malloced = 1;
4427         } else {
4428                 lun_malloced = 0;
4429                 lun = ctl_lun;
4430         }
4431
4432         memset(lun, 0, sizeof(*lun));
4433         if (lun_malloced)
4434                 lun->flags = CTL_LUN_MALLOCED;
4435
4436         /* Generate LUN ID. */
4437         devidlen = max(CTL_DEVID_MIN_LEN,
4438             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4439         idlen1 = sizeof(*t10id) + devidlen;
4440         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4441         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4442         if (scsiname != NULL) {
4443                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4444                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4445         }
4446         eui = ctl_get_opt(&be_lun->options, "eui");
4447         if (eui != NULL) {
4448                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4449         }
4450         naa = ctl_get_opt(&be_lun->options, "naa");
4451         if (naa != NULL) {
4452                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4453         }
4454         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4455             M_CTL, M_WAITOK | M_ZERO);
4456         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4457         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4458         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4459         desc->length = idlen1;
4460         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4461         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4462         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4463                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4464         } else {
4465                 strncpy(t10id->vendor, vendor,
4466                     min(sizeof(t10id->vendor), strlen(vendor)));
4467         }
4468         strncpy((char *)t10id->vendor_spec_id,
4469             (char *)be_lun->device_id, devidlen);
4470         if (scsiname != NULL) {
4471                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4472                     desc->length);
4473                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4474                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4475                     SVPD_ID_TYPE_SCSI_NAME;
4476                 desc->length = idlen2;
4477                 strlcpy(desc->identifier, scsiname, idlen2);
4478         }
4479         if (eui != NULL) {
4480                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4481                     desc->length);
4482                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4483                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4484                     SVPD_ID_TYPE_EUI64;
4485                 desc->length = hex2bin(eui, desc->identifier, 16);
4486                 desc->length = desc->length > 12 ? 16 :
4487                     (desc->length > 8 ? 12 : 8);
4488                 len -= 16 - desc->length;
4489         }
4490         if (naa != NULL) {
4491                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4492                     desc->length);
4493                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4494                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4495                     SVPD_ID_TYPE_NAA;
4496                 desc->length = hex2bin(naa, desc->identifier, 16);
4497                 desc->length = desc->length > 8 ? 16 : 8;
4498                 len -= 16 - desc->length;
4499         }
4500         lun->lun_devid->len = len;
4501
4502         mtx_lock(&ctl_softc->ctl_lock);
4503         /*
4504          * See if the caller requested a particular LUN number.  If so, see
4505          * if it is available.  Otherwise, allocate the first available LUN.
4506          */
4507         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4508                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4509                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4510                         mtx_unlock(&ctl_softc->ctl_lock);
4511                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4512                                 printf("ctl: requested LUN ID %d is higher "
4513                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4514                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4515                         } else {
4516                                 /*
4517                                  * XXX KDM return an error, or just assign
4518                                  * another LUN ID in this case??
4519                                  */
4520                                 printf("ctl: requested LUN ID %d is already "
4521                                        "in use\n", be_lun->req_lun_id);
4522                         }
4523                         if (lun->flags & CTL_LUN_MALLOCED)
4524                                 free(lun, M_CTL);
4525                         be_lun->lun_config_status(be_lun->be_lun,
4526                                                   CTL_LUN_CONFIG_FAILURE);
4527                         return (ENOSPC);
4528                 }
4529                 lun_number = be_lun->req_lun_id;
4530         } else {
4531                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4532                 if (lun_number == -1) {
4533                         mtx_unlock(&ctl_softc->ctl_lock);
4534                         printf("ctl: can't allocate LUN, out of LUNs\n");
4535                         if (lun->flags & CTL_LUN_MALLOCED)
4536                                 free(lun, M_CTL);
4537                         be_lun->lun_config_status(be_lun->be_lun,
4538                                                   CTL_LUN_CONFIG_FAILURE);
4539                         return (ENOSPC);
4540                 }
4541         }
4542         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4543
4544         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4545         lun->lun = lun_number;
4546         lun->be_lun = be_lun;
4547         /*
4548          * The processor LUN is always enabled.  Disk LUNs come on line
4549          * disabled, and must be enabled by the backend.
4550          */
4551         lun->flags |= CTL_LUN_DISABLED;
4552         lun->backend = be_lun->be;
4553         be_lun->ctl_lun = lun;
4554         be_lun->lun_id = lun_number;
4555         atomic_add_int(&be_lun->be->num_luns, 1);
4556         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4557                 lun->flags |= CTL_LUN_EJECTED;
4558         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4559                 lun->flags |= CTL_LUN_NO_MEDIA;
4560         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4561                 lun->flags |= CTL_LUN_STOPPED;
4562
4563         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4564                 lun->flags |= CTL_LUN_PRIMARY_SC;
4565
4566         value = ctl_get_opt(&be_lun->options, "removable");
4567         if (value != NULL) {
4568                 if (strcmp(value, "on") == 0)
4569                         lun->flags |= CTL_LUN_REMOVABLE;
4570         } else if (be_lun->lun_type == T_CDROM)
4571                 lun->flags |= CTL_LUN_REMOVABLE;
4572
4573         lun->ctl_softc = ctl_softc;
4574 #ifdef CTL_TIME_IO
4575         lun->last_busy = getsbinuptime();
4576 #endif
4577         TAILQ_INIT(&lun->ooa_queue);
4578         TAILQ_INIT(&lun->blocked_queue);
4579         STAILQ_INIT(&lun->error_list);
4580         ctl_tpc_lun_init(lun);
4581
4582         /*
4583          * Initialize the mode and log page index.
4584          */
4585         ctl_init_page_index(lun);
4586         ctl_init_log_page_index(lun);
4587
4588         /*
4589          * Now, before we insert this lun on the lun list, set the lun
4590          * inventory changed UA for all other luns.
4591          */
4592         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4593                 mtx_lock(&nlun->lun_lock);
4594                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4595                 mtx_unlock(&nlun->lun_lock);
4596         }
4597
4598         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4599
4600         ctl_softc->ctl_luns[lun_number] = lun;
4601
4602         ctl_softc->num_luns++;
4603
4604         /* Setup statistics gathering */
4605         lun->stats.device_type = be_lun->lun_type;
4606         lun->stats.lun_number = lun_number;
4607         lun->stats.blocksize = be_lun->blocksize;
4608         if (be_lun->blocksize == 0)
4609                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4610         for (i = 0;i < CTL_MAX_PORTS;i++)
4611                 lun->stats.ports[i].targ_port = i;
4612
4613         mtx_unlock(&ctl_softc->ctl_lock);
4614
4615         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4616         return (0);
4617 }
4618
4619 /*
4620  * Delete a LUN.
4621  * Assumptions:
4622  * - LUN has already been marked invalid and any pending I/O has been taken
4623  *   care of.
4624  */
4625 static int
4626 ctl_free_lun(struct ctl_lun *lun)
4627 {
4628         struct ctl_softc *softc;
4629         struct ctl_lun *nlun;
4630         int i;
4631
4632         softc = lun->ctl_softc;
4633
4634         mtx_assert(&softc->ctl_lock, MA_OWNED);
4635
4636         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4637
4638         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4639
4640         softc->ctl_luns[lun->lun] = NULL;
4641
4642         if (!TAILQ_EMPTY(&lun->ooa_queue))
4643                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4644
4645         softc->num_luns--;
4646
4647         /*
4648          * Tell the backend to free resources, if this LUN has a backend.
4649          */
4650         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4651         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4652
4653         ctl_tpc_lun_shutdown(lun);
4654         mtx_destroy(&lun->lun_lock);
4655         free(lun->lun_devid, M_CTL);
4656         for (i = 0; i < CTL_MAX_PORTS; i++)
4657                 free(lun->pending_ua[i], M_CTL);
4658         for (i = 0; i < CTL_MAX_PORTS; i++)
4659                 free(lun->pr_keys[i], M_CTL);
4660         free(lun->write_buffer, M_CTL);
4661         if (lun->flags & CTL_LUN_MALLOCED)
4662                 free(lun, M_CTL);
4663
4664         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4665                 mtx_lock(&nlun->lun_lock);
4666                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4667                 mtx_unlock(&nlun->lun_lock);
4668         }
4669
4670         return (0);
4671 }
4672
4673 static void
4674 ctl_create_lun(struct ctl_be_lun *be_lun)
4675 {
4676
4677         /*
4678          * ctl_alloc_lun() should handle all potential failure cases.
4679          */
4680         ctl_alloc_lun(control_softc, NULL, be_lun);
4681 }
4682
4683 int
4684 ctl_add_lun(struct ctl_be_lun *be_lun)
4685 {
4686         struct ctl_softc *softc = control_softc;
4687
4688         mtx_lock(&softc->ctl_lock);
4689         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4690         mtx_unlock(&softc->ctl_lock);
4691         wakeup(&softc->pending_lun_queue);
4692
4693         return (0);
4694 }
4695
4696 int
4697 ctl_enable_lun(struct ctl_be_lun *be_lun)
4698 {
4699         struct ctl_softc *softc;
4700         struct ctl_port *port, *nport;
4701         struct ctl_lun *lun;
4702         int retval;
4703
4704         lun = (struct ctl_lun *)be_lun->ctl_lun;
4705         softc = lun->ctl_softc;
4706
4707         mtx_lock(&softc->ctl_lock);
4708         mtx_lock(&lun->lun_lock);
4709         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4710                 /*
4711                  * eh?  Why did we get called if the LUN is already
4712                  * enabled?
4713                  */
4714                 mtx_unlock(&lun->lun_lock);
4715                 mtx_unlock(&softc->ctl_lock);
4716                 return (0);
4717         }
4718         lun->flags &= ~CTL_LUN_DISABLED;
4719         mtx_unlock(&lun->lun_lock);
4720
4721         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4722                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4723                     port->lun_map != NULL || port->lun_enable == NULL)
4724                         continue;
4725
4726                 /*
4727                  * Drop the lock while we call the FETD's enable routine.
4728                  * This can lead to a callback into CTL (at least in the
4729                  * case of the internal initiator frontend.
4730                  */
4731                 mtx_unlock(&softc->ctl_lock);
4732                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4733                 mtx_lock(&softc->ctl_lock);
4734                 if (retval != 0) {
4735                         printf("%s: FETD %s port %d returned error "
4736                                "%d for lun_enable on lun %jd\n",
4737                                __func__, port->port_name, port->targ_port,
4738                                retval, (intmax_t)lun->lun);
4739                 }
4740         }
4741
4742         mtx_unlock(&softc->ctl_lock);
4743         ctl_isc_announce_lun(lun);
4744
4745         return (0);
4746 }
4747
4748 int
4749 ctl_disable_lun(struct ctl_be_lun *be_lun)
4750 {
4751         struct ctl_softc *softc;
4752         struct ctl_port *port;
4753         struct ctl_lun *lun;
4754         int retval;
4755
4756         lun = (struct ctl_lun *)be_lun->ctl_lun;
4757         softc = lun->ctl_softc;
4758
4759         mtx_lock(&softc->ctl_lock);
4760         mtx_lock(&lun->lun_lock);
4761         if (lun->flags & CTL_LUN_DISABLED) {
4762                 mtx_unlock(&lun->lun_lock);
4763                 mtx_unlock(&softc->ctl_lock);
4764                 return (0);
4765         }
4766         lun->flags |= CTL_LUN_DISABLED;
4767         mtx_unlock(&lun->lun_lock);
4768
4769         STAILQ_FOREACH(port, &softc->port_list, links) {
4770                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4771                     port->lun_map != NULL || port->lun_disable == NULL)
4772                         continue;
4773
4774                 /*
4775                  * Drop the lock before we call the frontend's disable
4776                  * routine, to avoid lock order reversals.
4777                  *
4778                  * XXX KDM what happens if the frontend list changes while
4779                  * we're traversing it?  It's unlikely, but should be handled.
4780                  */
4781                 mtx_unlock(&softc->ctl_lock);
4782                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4783                 mtx_lock(&softc->ctl_lock);
4784                 if (retval != 0) {
4785                         printf("%s: FETD %s port %d returned error "
4786                                "%d for lun_disable on lun %jd\n",
4787                                __func__, port->port_name, port->targ_port,
4788                                retval, (intmax_t)lun->lun);
4789                 }
4790         }
4791
4792         mtx_unlock(&softc->ctl_lock);
4793         ctl_isc_announce_lun(lun);
4794
4795         return (0);
4796 }
4797
4798 int
4799 ctl_start_lun(struct ctl_be_lun *be_lun)
4800 {
4801         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4802
4803         mtx_lock(&lun->lun_lock);
4804         lun->flags &= ~CTL_LUN_STOPPED;
4805         mtx_unlock(&lun->lun_lock);
4806         return (0);
4807 }
4808
4809 int
4810 ctl_stop_lun(struct ctl_be_lun *be_lun)
4811 {
4812         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4813
4814         mtx_lock(&lun->lun_lock);
4815         lun->flags |= CTL_LUN_STOPPED;
4816         mtx_unlock(&lun->lun_lock);
4817         return (0);
4818 }
4819
4820 int
4821 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4822 {
4823         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4824
4825         mtx_lock(&lun->lun_lock);
4826         lun->flags |= CTL_LUN_NO_MEDIA;
4827         mtx_unlock(&lun->lun_lock);
4828         return (0);
4829 }
4830
4831 int
4832 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4833 {
4834         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4835         union ctl_ha_msg msg;
4836
4837         mtx_lock(&lun->lun_lock);
4838         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4839         if (lun->flags & CTL_LUN_REMOVABLE)
4840                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4841         mtx_unlock(&lun->lun_lock);
4842         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4843             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4844                 bzero(&msg.ua, sizeof(msg.ua));
4845                 msg.hdr.msg_type = CTL_MSG_UA;
4846                 msg.hdr.nexus.initid = -1;
4847                 msg.hdr.nexus.targ_port = -1;
4848                 msg.hdr.nexus.targ_lun = lun->lun;
4849                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4850                 msg.ua.ua_all = 1;
4851                 msg.ua.ua_set = 1;
4852                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4853                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4854                     M_WAITOK);
4855         }
4856         return (0);
4857 }
4858
4859 int
4860 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4861 {
4862         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4863
4864         mtx_lock(&lun->lun_lock);
4865         lun->flags |= CTL_LUN_EJECTED;
4866         mtx_unlock(&lun->lun_lock);
4867         return (0);
4868 }
4869
4870 int
4871 ctl_lun_primary(struct ctl_be_lun *be_lun)
4872 {
4873         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4874
4875         mtx_lock(&lun->lun_lock);
4876         lun->flags |= CTL_LUN_PRIMARY_SC;
4877         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4878         mtx_unlock(&lun->lun_lock);
4879         ctl_isc_announce_lun(lun);
4880         return (0);
4881 }
4882
4883 int
4884 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4885 {
4886         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4887
4888         mtx_lock(&lun->lun_lock);
4889         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4890         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4891         mtx_unlock(&lun->lun_lock);
4892         ctl_isc_announce_lun(lun);
4893         return (0);
4894 }
4895
4896 int
4897 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4898 {
4899         struct ctl_softc *softc;
4900         struct ctl_lun *lun;
4901
4902         lun = (struct ctl_lun *)be_lun->ctl_lun;
4903         softc = lun->ctl_softc;
4904
4905         mtx_lock(&lun->lun_lock);
4906
4907         /*
4908          * The LUN needs to be disabled before it can be marked invalid.
4909          */
4910         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4911                 mtx_unlock(&lun->lun_lock);
4912                 return (-1);
4913         }
4914         /*
4915          * Mark the LUN invalid.
4916          */
4917         lun->flags |= CTL_LUN_INVALID;
4918
4919         /*
4920          * If there is nothing in the OOA queue, go ahead and free the LUN.
4921          * If we have something in the OOA queue, we'll free it when the
4922          * last I/O completes.
4923          */
4924         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4925                 mtx_unlock(&lun->lun_lock);
4926                 mtx_lock(&softc->ctl_lock);
4927                 ctl_free_lun(lun);
4928                 mtx_unlock(&softc->ctl_lock);
4929         } else
4930                 mtx_unlock(&lun->lun_lock);
4931
4932         return (0);
4933 }
4934
4935 void
4936 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4937 {
4938         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4939         union ctl_ha_msg msg;
4940
4941         mtx_lock(&lun->lun_lock);
4942         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4943         mtx_unlock(&lun->lun_lock);
4944         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4945                 /* Send msg to other side. */
4946                 bzero(&msg.ua, sizeof(msg.ua));
4947                 msg.hdr.msg_type = CTL_MSG_UA;
4948                 msg.hdr.nexus.initid = -1;
4949                 msg.hdr.nexus.targ_port = -1;
4950                 msg.hdr.nexus.targ_lun = lun->lun;
4951                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4952                 msg.ua.ua_all = 1;
4953                 msg.ua.ua_set = 1;
4954                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4955                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4956                     M_WAITOK);
4957         }
4958 }
4959
4960 /*
4961  * Backend "memory move is complete" callback for requests that never
4962  * make it down to say RAIDCore's configuration code.
4963  */
4964 int
4965 ctl_config_move_done(union ctl_io *io)
4966 {
4967         int retval;
4968
4969         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4970         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4971             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4972
4973         if ((io->io_hdr.port_status != 0) &&
4974             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4975              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4976                 /*
4977                  * For hardware error sense keys, the sense key
4978                  * specific value is defined to be a retry count,
4979                  * but we use it to pass back an internal FETD
4980                  * error code.  XXX KDM  Hopefully the FETD is only
4981                  * using 16 bits for an error code, since that's
4982                  * all the space we have in the sks field.
4983                  */
4984                 ctl_set_internal_failure(&io->scsiio,
4985                                          /*sks_valid*/ 1,
4986                                          /*retry_count*/
4987                                          io->io_hdr.port_status);
4988         }
4989
4990         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4991                 ctl_data_print(io);
4992         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4993             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4994              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4995             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4996                 /*
4997                  * XXX KDM just assuming a single pointer here, and not a
4998                  * S/G list.  If we start using S/G lists for config data,
4999                  * we'll need to know how to clean them up here as well.
5000                  */
5001                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5002                         free(io->scsiio.kern_data_ptr, M_CTL);
5003                 ctl_done(io);
5004                 retval = CTL_RETVAL_COMPLETE;
5005         } else {
5006                 /*
5007                  * XXX KDM now we need to continue data movement.  Some
5008                  * options:
5009                  * - call ctl_scsiio() again?  We don't do this for data
5010                  *   writes, because for those at least we know ahead of
5011                  *   time where the write will go and how long it is.  For
5012                  *   config writes, though, that information is largely
5013                  *   contained within the write itself, thus we need to
5014                  *   parse out the data again.
5015                  *
5016                  * - Call some other function once the data is in?
5017                  */
5018
5019                 /*
5020                  * XXX KDM call ctl_scsiio() again for now, and check flag
5021                  * bits to see whether we're allocated or not.
5022                  */
5023                 retval = ctl_scsiio(&io->scsiio);
5024         }
5025         return (retval);
5026 }
5027
5028 /*
5029  * This gets called by a backend driver when it is done with a
5030  * data_submit method.
5031  */
5032 void
5033 ctl_data_submit_done(union ctl_io *io)
5034 {
5035         /*
5036          * If the IO_CONT flag is set, we need to call the supplied
5037          * function to continue processing the I/O, instead of completing
5038          * the I/O just yet.
5039          *
5040          * If there is an error, though, we don't want to keep processing.
5041          * Instead, just send status back to the initiator.
5042          */
5043         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5044             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5045             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5046              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5047                 io->scsiio.io_cont(io);
5048                 return;
5049         }
5050         ctl_done(io);
5051 }
5052
5053 /*
5054  * This gets called by a backend driver when it is done with a
5055  * configuration write.
5056  */
5057 void
5058 ctl_config_write_done(union ctl_io *io)
5059 {
5060         uint8_t *buf;
5061
5062         /*
5063          * If the IO_CONT flag is set, we need to call the supplied
5064          * function to continue processing the I/O, instead of completing
5065          * the I/O just yet.
5066          *
5067          * If there is an error, though, we don't want to keep processing.
5068          * Instead, just send status back to the initiator.
5069          */
5070         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5071             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5072             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5073              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5074                 io->scsiio.io_cont(io);
5075                 return;
5076         }
5077         /*
5078          * Since a configuration write can be done for commands that actually
5079          * have data allocated, like write buffer, and commands that have
5080          * no data, like start/stop unit, we need to check here.
5081          */
5082         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5083                 buf = io->scsiio.kern_data_ptr;
5084         else
5085                 buf = NULL;
5086         ctl_done(io);
5087         if (buf)
5088                 free(buf, M_CTL);
5089 }
5090
5091 void
5092 ctl_config_read_done(union ctl_io *io)
5093 {
5094         uint8_t *buf;
5095
5096         /*
5097          * If there is some error -- we are done, skip data transfer.
5098          */
5099         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5100             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5101              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5102                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5103                         buf = io->scsiio.kern_data_ptr;
5104                 else
5105                         buf = NULL;
5106                 ctl_done(io);
5107                 if (buf)
5108                         free(buf, M_CTL);
5109                 return;
5110         }
5111
5112         /*
5113          * If the IO_CONT flag is set, we need to call the supplied
5114          * function to continue processing the I/O, instead of completing
5115          * the I/O just yet.
5116          */
5117         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5118                 io->scsiio.io_cont(io);
5119                 return;
5120         }
5121
5122         ctl_datamove(io);
5123 }
5124
5125 /*
5126  * SCSI release command.
5127  */
5128 int
5129 ctl_scsi_release(struct ctl_scsiio *ctsio)
5130 {
5131         struct ctl_lun *lun;
5132         uint32_t residx;
5133
5134         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5135
5136         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5137         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5138
5139         /*
5140          * XXX KDM right now, we only support LUN reservation.  We don't
5141          * support 3rd party reservations, or extent reservations, which
5142          * might actually need the parameter list.  If we've gotten this
5143          * far, we've got a LUN reservation.  Anything else got kicked out
5144          * above.  So, according to SPC, ignore the length.
5145          */
5146
5147         mtx_lock(&lun->lun_lock);
5148
5149         /*
5150          * According to SPC, it is not an error for an intiator to attempt
5151          * to release a reservation on a LUN that isn't reserved, or that
5152          * is reserved by another initiator.  The reservation can only be
5153          * released, though, by the initiator who made it or by one of
5154          * several reset type events.
5155          */
5156         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5157                         lun->flags &= ~CTL_LUN_RESERVED;
5158
5159         mtx_unlock(&lun->lun_lock);
5160
5161         ctl_set_success(ctsio);
5162         ctl_done((union ctl_io *)ctsio);
5163         return (CTL_RETVAL_COMPLETE);
5164 }
5165
5166 int
5167 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5168 {
5169         struct ctl_lun *lun;
5170         uint32_t residx;
5171
5172         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5173
5174         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5175         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5176
5177         /*
5178          * XXX KDM right now, we only support LUN reservation.  We don't
5179          * support 3rd party reservations, or extent reservations, which
5180          * might actually need the parameter list.  If we've gotten this
5181          * far, we've got a LUN reservation.  Anything else got kicked out
5182          * above.  So, according to SPC, ignore the length.
5183          */
5184
5185         mtx_lock(&lun->lun_lock);
5186         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5187                 ctl_set_reservation_conflict(ctsio);
5188                 goto bailout;
5189         }
5190
5191         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5192         if (lun->flags & CTL_LUN_PR_RESERVED) {
5193                 ctl_set_success(ctsio);
5194                 goto bailout;
5195         }
5196
5197         lun->flags |= CTL_LUN_RESERVED;
5198         lun->res_idx = residx;
5199         ctl_set_success(ctsio);
5200
5201 bailout:
5202         mtx_unlock(&lun->lun_lock);
5203         ctl_done((union ctl_io *)ctsio);
5204         return (CTL_RETVAL_COMPLETE);
5205 }
5206
5207 int
5208 ctl_start_stop(struct ctl_scsiio *ctsio)
5209 {
5210         struct scsi_start_stop_unit *cdb;
5211         struct ctl_lun *lun;
5212         int retval;
5213
5214         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5215
5216         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5217         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5218
5219         if ((cdb->how & SSS_PC_MASK) == 0) {
5220                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5221                     (cdb->how & SSS_START) == 0) {
5222                         uint32_t residx;
5223
5224                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5225                         if (ctl_get_prkey(lun, residx) == 0 ||
5226                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5227
5228                                 ctl_set_reservation_conflict(ctsio);
5229                                 ctl_done((union ctl_io *)ctsio);
5230                                 return (CTL_RETVAL_COMPLETE);
5231                         }
5232                 }
5233
5234                 if ((cdb->how & SSS_LOEJ) &&
5235                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5236                         ctl_set_invalid_field(ctsio,
5237                                               /*sks_valid*/ 1,
5238                                               /*command*/ 1,
5239                                               /*field*/ 4,
5240                                               /*bit_valid*/ 1,
5241                                               /*bit*/ 1);
5242                         ctl_done((union ctl_io *)ctsio);
5243                         return (CTL_RETVAL_COMPLETE);
5244                 }
5245
5246                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5247                     lun->prevent_count > 0) {
5248                         /* "Medium removal prevented" */
5249                         ctl_set_sense(ctsio, /*current_error*/ 1,
5250                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5251                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5252                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5253                         ctl_done((union ctl_io *)ctsio);
5254                         return (CTL_RETVAL_COMPLETE);
5255                 }
5256         }
5257
5258         retval = lun->backend->config_write((union ctl_io *)ctsio);
5259         return (retval);
5260 }
5261
5262 int
5263 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5264 {
5265         struct ctl_lun *lun;
5266         struct scsi_prevent *cdb;
5267         int retval;
5268         uint32_t initidx;
5269
5270         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5271
5272         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5273         cdb = (struct scsi_prevent *)ctsio->cdb;
5274
5275         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5276                 ctl_set_invalid_opcode(ctsio);
5277                 ctl_done((union ctl_io *)ctsio);
5278                 return (CTL_RETVAL_COMPLETE);
5279         }
5280
5281         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5282         mtx_lock(&lun->lun_lock);
5283         if ((cdb->how & PR_PREVENT) &&
5284             ctl_is_set(lun->prevent, initidx) == 0) {
5285                 ctl_set_mask(lun->prevent, initidx);
5286                 lun->prevent_count++;
5287         } else if ((cdb->how & PR_PREVENT) == 0 &&
5288             ctl_is_set(lun->prevent, initidx)) {
5289                 ctl_clear_mask(lun->prevent, initidx);
5290                 lun->prevent_count--;
5291         }
5292         mtx_unlock(&lun->lun_lock);
5293         retval = lun->backend->config_write((union ctl_io *)ctsio);
5294         return (retval);
5295 }
5296
5297 /*
5298  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5299  * we don't really do anything with the LBA and length fields if the user
5300  * passes them in.  Instead we'll just flush out the cache for the entire
5301  * LUN.
5302  */
5303 int
5304 ctl_sync_cache(struct ctl_scsiio *ctsio)
5305 {
5306         struct ctl_lun *lun;
5307         struct ctl_softc *softc;
5308         struct ctl_lba_len_flags *lbalen;
5309         uint64_t starting_lba;
5310         uint32_t block_count;
5311         int retval;
5312         uint8_t byte2;
5313
5314         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5315
5316         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5317         softc = lun->ctl_softc;
5318         retval = 0;
5319
5320         switch (ctsio->cdb[0]) {
5321         case SYNCHRONIZE_CACHE: {
5322                 struct scsi_sync_cache *cdb;
5323                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5324
5325                 starting_lba = scsi_4btoul(cdb->begin_lba);
5326                 block_count = scsi_2btoul(cdb->lb_count);
5327                 byte2 = cdb->byte2;
5328                 break;
5329         }
5330         case SYNCHRONIZE_CACHE_16: {
5331                 struct scsi_sync_cache_16 *cdb;
5332                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5333
5334                 starting_lba = scsi_8btou64(cdb->begin_lba);
5335                 block_count = scsi_4btoul(cdb->lb_count);
5336                 byte2 = cdb->byte2;
5337                 break;
5338         }
5339         default:
5340                 ctl_set_invalid_opcode(ctsio);
5341                 ctl_done((union ctl_io *)ctsio);
5342                 goto bailout;
5343                 break; /* NOTREACHED */
5344         }
5345
5346         /*
5347          * We check the LBA and length, but don't do anything with them.
5348          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5349          * get flushed.  This check will just help satisfy anyone who wants
5350          * to see an error for an out of range LBA.
5351          */
5352         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5353                 ctl_set_lba_out_of_range(ctsio);
5354                 ctl_done((union ctl_io *)ctsio);
5355                 goto bailout;
5356         }
5357
5358         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5359         lbalen->lba = starting_lba;
5360         lbalen->len = block_count;
5361         lbalen->flags = byte2;
5362         retval = lun->backend->config_write((union ctl_io *)ctsio);
5363
5364 bailout:
5365         return (retval);
5366 }
5367
5368 int
5369 ctl_format(struct ctl_scsiio *ctsio)
5370 {
5371         struct scsi_format *cdb;
5372         struct ctl_lun *lun;
5373         int length, defect_list_len;
5374
5375         CTL_DEBUG_PRINT(("ctl_format\n"));
5376
5377         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5378
5379         cdb = (struct scsi_format *)ctsio->cdb;
5380
5381         length = 0;
5382         if (cdb->byte2 & SF_FMTDATA) {
5383                 if (cdb->byte2 & SF_LONGLIST)
5384                         length = sizeof(struct scsi_format_header_long);
5385                 else
5386                         length = sizeof(struct scsi_format_header_short);
5387         }
5388
5389         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5390          && (length > 0)) {
5391                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5392                 ctsio->kern_data_len = length;
5393                 ctsio->kern_total_len = length;
5394                 ctsio->kern_data_resid = 0;
5395                 ctsio->kern_rel_offset = 0;
5396                 ctsio->kern_sg_entries = 0;
5397                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5398                 ctsio->be_move_done = ctl_config_move_done;
5399                 ctl_datamove((union ctl_io *)ctsio);
5400
5401                 return (CTL_RETVAL_COMPLETE);
5402         }
5403
5404         defect_list_len = 0;
5405
5406         if (cdb->byte2 & SF_FMTDATA) {
5407                 if (cdb->byte2 & SF_LONGLIST) {
5408                         struct scsi_format_header_long *header;
5409
5410                         header = (struct scsi_format_header_long *)
5411                                 ctsio->kern_data_ptr;
5412
5413                         defect_list_len = scsi_4btoul(header->defect_list_len);
5414                         if (defect_list_len != 0) {
5415                                 ctl_set_invalid_field(ctsio,
5416                                                       /*sks_valid*/ 1,
5417                                                       /*command*/ 0,
5418                                                       /*field*/ 2,
5419                                                       /*bit_valid*/ 0,
5420                                                       /*bit*/ 0);
5421                                 goto bailout;
5422                         }
5423                 } else {
5424                         struct scsi_format_header_short *header;
5425
5426                         header = (struct scsi_format_header_short *)
5427                                 ctsio->kern_data_ptr;
5428
5429                         defect_list_len = scsi_2btoul(header->defect_list_len);
5430                         if (defect_list_len != 0) {
5431                                 ctl_set_invalid_field(ctsio,
5432                                                       /*sks_valid*/ 1,
5433                                                       /*command*/ 0,
5434                                                       /*field*/ 2,
5435                                                       /*bit_valid*/ 0,
5436                                                       /*bit*/ 0);
5437                                 goto bailout;
5438                         }
5439                 }
5440         }
5441
5442         ctl_set_success(ctsio);
5443 bailout:
5444
5445         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5446                 free(ctsio->kern_data_ptr, M_CTL);
5447                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5448         }
5449
5450         ctl_done((union ctl_io *)ctsio);
5451         return (CTL_RETVAL_COMPLETE);
5452 }
5453
5454 int
5455 ctl_read_buffer(struct ctl_scsiio *ctsio)
5456 {
5457         struct ctl_lun *lun;
5458         uint64_t buffer_offset;
5459         uint32_t len;
5460         uint8_t byte2;
5461         static uint8_t descr[4];
5462         static uint8_t echo_descr[4] = { 0 };
5463
5464         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5465         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5466         switch (ctsio->cdb[0]) {
5467         case READ_BUFFER: {
5468                 struct scsi_read_buffer *cdb;
5469
5470                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5471                 buffer_offset = scsi_3btoul(cdb->offset);
5472                 len = scsi_3btoul(cdb->length);
5473                 byte2 = cdb->byte2;
5474                 break;
5475         }
5476         case READ_BUFFER_16: {
5477                 struct scsi_read_buffer_16 *cdb;
5478
5479                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5480                 buffer_offset = scsi_8btou64(cdb->offset);
5481                 len = scsi_4btoul(cdb->length);
5482                 byte2 = cdb->byte2;
5483                 break;
5484         }
5485         default: /* This shouldn't happen. */
5486                 ctl_set_invalid_opcode(ctsio);
5487                 ctl_done((union ctl_io *)ctsio);
5488                 return (CTL_RETVAL_COMPLETE);
5489         }
5490
5491         if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5492             (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5493             (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5494                 ctl_set_invalid_field(ctsio,
5495                                       /*sks_valid*/ 1,
5496                                       /*command*/ 1,
5497                                       /*field*/ 1,
5498                                       /*bit_valid*/ 1,
5499                                       /*bit*/ 4);
5500                 ctl_done((union ctl_io *)ctsio);
5501                 return (CTL_RETVAL_COMPLETE);
5502         }
5503
5504         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5505             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5506                 ctl_set_invalid_field(ctsio,
5507                                       /*sks_valid*/ 1,
5508                                       /*command*/ 1,
5509                                       /*field*/ 6,
5510                                       /*bit_valid*/ 0,
5511                                       /*bit*/ 0);
5512                 ctl_done((union ctl_io *)ctsio);
5513                 return (CTL_RETVAL_COMPLETE);
5514         }
5515
5516         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5517                 descr[0] = 0;
5518                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5519                 ctsio->kern_data_ptr = descr;
5520                 len = min(len, sizeof(descr));
5521         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5522                 ctsio->kern_data_ptr = echo_descr;
5523                 len = min(len, sizeof(echo_descr));
5524         } else {
5525                 if (lun->write_buffer == NULL) {
5526                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5527                             M_CTL, M_WAITOK);
5528                 }
5529                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5530         }
5531         ctsio->kern_data_len = len;
5532         ctsio->kern_total_len = len;
5533         ctsio->kern_data_resid = 0;
5534         ctsio->kern_rel_offset = 0;
5535         ctsio->kern_sg_entries = 0;
5536         ctl_set_success(ctsio);
5537         ctsio->be_move_done = ctl_config_move_done;
5538         ctl_datamove((union ctl_io *)ctsio);
5539         return (CTL_RETVAL_COMPLETE);
5540 }
5541
5542 int
5543 ctl_write_buffer(struct ctl_scsiio *ctsio)
5544 {
5545         struct scsi_write_buffer *cdb;
5546         struct ctl_lun *lun;
5547         int buffer_offset, len;
5548
5549         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5550
5551         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5552         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5553
5554         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5555                 ctl_set_invalid_field(ctsio,
5556                                       /*sks_valid*/ 1,
5557                                       /*command*/ 1,
5558                                       /*field*/ 1,
5559                                       /*bit_valid*/ 1,
5560                                       /*bit*/ 4);
5561                 ctl_done((union ctl_io *)ctsio);
5562                 return (CTL_RETVAL_COMPLETE);
5563         }
5564
5565         len = scsi_3btoul(cdb->length);
5566         buffer_offset = scsi_3btoul(cdb->offset);
5567
5568         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5569                 ctl_set_invalid_field(ctsio,
5570                                       /*sks_valid*/ 1,
5571                                       /*command*/ 1,
5572                                       /*field*/ 6,
5573                                       /*bit_valid*/ 0,
5574                                       /*bit*/ 0);
5575                 ctl_done((union ctl_io *)ctsio);
5576                 return (CTL_RETVAL_COMPLETE);
5577         }
5578
5579         /*
5580          * If we've got a kernel request that hasn't been malloced yet,
5581          * malloc it and tell the caller the data buffer is here.
5582          */
5583         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5584                 if (lun->write_buffer == NULL) {
5585                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5586                             M_CTL, M_WAITOK);
5587                 }
5588                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5589                 ctsio->kern_data_len = len;
5590                 ctsio->kern_total_len = len;
5591                 ctsio->kern_data_resid = 0;
5592                 ctsio->kern_rel_offset = 0;
5593                 ctsio->kern_sg_entries = 0;
5594                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5595                 ctsio->be_move_done = ctl_config_move_done;
5596                 ctl_datamove((union ctl_io *)ctsio);
5597
5598                 return (CTL_RETVAL_COMPLETE);
5599         }
5600
5601         ctl_set_success(ctsio);
5602         ctl_done((union ctl_io *)ctsio);
5603         return (CTL_RETVAL_COMPLETE);
5604 }
5605
5606 int
5607 ctl_write_same(struct ctl_scsiio *ctsio)
5608 {
5609         struct ctl_lun *lun;
5610         struct ctl_lba_len_flags *lbalen;
5611         uint64_t lba;
5612         uint32_t num_blocks;
5613         int len, retval;
5614         uint8_t byte2;
5615
5616         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5617
5618         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5619
5620         switch (ctsio->cdb[0]) {
5621         case WRITE_SAME_10: {
5622                 struct scsi_write_same_10 *cdb;
5623
5624                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5625
5626                 lba = scsi_4btoul(cdb->addr);
5627                 num_blocks = scsi_2btoul(cdb->length);
5628                 byte2 = cdb->byte2;
5629                 break;
5630         }
5631         case WRITE_SAME_16: {
5632                 struct scsi_write_same_16 *cdb;
5633
5634                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5635
5636                 lba = scsi_8btou64(cdb->addr);
5637                 num_blocks = scsi_4btoul(cdb->length);
5638                 byte2 = cdb->byte2;
5639                 break;
5640         }
5641         default:
5642                 /*
5643                  * We got a command we don't support.  This shouldn't
5644                  * happen, commands should be filtered out above us.
5645                  */
5646                 ctl_set_invalid_opcode(ctsio);
5647                 ctl_done((union ctl_io *)ctsio);
5648
5649                 return (CTL_RETVAL_COMPLETE);
5650                 break; /* NOTREACHED */
5651         }
5652
5653         /* ANCHOR flag can be used only together with UNMAP */
5654         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5655                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5656                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5657                 ctl_done((union ctl_io *)ctsio);
5658                 return (CTL_RETVAL_COMPLETE);
5659         }
5660
5661         /*
5662          * The first check is to make sure we're in bounds, the second
5663          * check is to catch wrap-around problems.  If the lba + num blocks
5664          * is less than the lba, then we've wrapped around and the block
5665          * range is invalid anyway.
5666          */
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
5674         /* Zero number of blocks means "to the last logical block" */
5675         if (num_blocks == 0) {
5676                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5677                         ctl_set_invalid_field(ctsio,
5678                                               /*sks_valid*/ 0,
5679                                               /*command*/ 1,
5680                                               /*field*/ 0,
5681                                               /*bit_valid*/ 0,
5682                                               /*bit*/ 0);
5683                         ctl_done((union ctl_io *)ctsio);
5684                         return (CTL_RETVAL_COMPLETE);
5685                 }
5686                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5687         }
5688
5689         len = lun->be_lun->blocksize;
5690
5691         /*
5692          * If we've got a kernel request that hasn't been malloced yet,
5693          * malloc it and tell the caller the data buffer is here.
5694          */
5695         if ((byte2 & SWS_NDOB) == 0 &&
5696             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5697                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5698                 ctsio->kern_data_len = len;
5699                 ctsio->kern_total_len = len;
5700                 ctsio->kern_data_resid = 0;
5701                 ctsio->kern_rel_offset = 0;
5702                 ctsio->kern_sg_entries = 0;
5703                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5704                 ctsio->be_move_done = ctl_config_move_done;
5705                 ctl_datamove((union ctl_io *)ctsio);
5706
5707                 return (CTL_RETVAL_COMPLETE);
5708         }
5709
5710         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5711         lbalen->lba = lba;
5712         lbalen->len = num_blocks;
5713         lbalen->flags = byte2;
5714         retval = lun->backend->config_write((union ctl_io *)ctsio);
5715
5716         return (retval);
5717 }
5718
5719 int
5720 ctl_unmap(struct ctl_scsiio *ctsio)
5721 {
5722         struct ctl_lun *lun;
5723         struct scsi_unmap *cdb;
5724         struct ctl_ptr_len_flags *ptrlen;
5725         struct scsi_unmap_header *hdr;
5726         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5727         uint64_t lba;
5728         uint32_t num_blocks;
5729         int len, retval;
5730         uint8_t byte2;
5731
5732         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5733
5734         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5735         cdb = (struct scsi_unmap *)ctsio->cdb;
5736
5737         len = scsi_2btoul(cdb->length);
5738         byte2 = cdb->byte2;
5739
5740         /*
5741          * If we've got a kernel request that hasn't been malloced yet,
5742          * malloc it and tell the caller the data buffer is here.
5743          */
5744         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5745                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5746                 ctsio->kern_data_len = len;
5747                 ctsio->kern_total_len = len;
5748                 ctsio->kern_data_resid = 0;
5749                 ctsio->kern_rel_offset = 0;
5750                 ctsio->kern_sg_entries = 0;
5751                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5752                 ctsio->be_move_done = ctl_config_move_done;
5753                 ctl_datamove((union ctl_io *)ctsio);
5754
5755                 return (CTL_RETVAL_COMPLETE);
5756         }
5757
5758         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5759         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5760         if (len < sizeof (*hdr) ||
5761             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5762             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5763             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5764                 ctl_set_invalid_field(ctsio,
5765                                       /*sks_valid*/ 0,
5766                                       /*command*/ 0,
5767                                       /*field*/ 0,
5768                                       /*bit_valid*/ 0,
5769                                       /*bit*/ 0);
5770                 goto done;
5771         }
5772         len = scsi_2btoul(hdr->desc_length);
5773         buf = (struct scsi_unmap_desc *)(hdr + 1);
5774         end = buf + len / sizeof(*buf);
5775
5776         endnz = buf;
5777         for (range = buf; range < end; range++) {
5778                 lba = scsi_8btou64(range->lba);
5779                 num_blocks = scsi_4btoul(range->length);
5780                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5781                  || ((lba + num_blocks) < lba)) {
5782                         ctl_set_lba_out_of_range(ctsio);
5783                         ctl_done((union ctl_io *)ctsio);
5784                         return (CTL_RETVAL_COMPLETE);
5785                 }
5786                 if (num_blocks != 0)
5787                         endnz = range + 1;
5788         }
5789
5790         /*
5791          * Block backend can not handle zero last range.
5792          * Filter it out and return if there is nothing left.
5793          */
5794         len = (uint8_t *)endnz - (uint8_t *)buf;
5795         if (len == 0) {
5796                 ctl_set_success(ctsio);
5797                 goto done;
5798         }
5799
5800         mtx_lock(&lun->lun_lock);
5801         ptrlen = (struct ctl_ptr_len_flags *)
5802             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5803         ptrlen->ptr = (void *)buf;
5804         ptrlen->len = len;
5805         ptrlen->flags = byte2;
5806         ctl_check_blocked(lun);
5807         mtx_unlock(&lun->lun_lock);
5808
5809         retval = lun->backend->config_write((union ctl_io *)ctsio);
5810         return (retval);
5811
5812 done:
5813         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5814                 free(ctsio->kern_data_ptr, M_CTL);
5815                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5816         }
5817         ctl_done((union ctl_io *)ctsio);
5818         return (CTL_RETVAL_COMPLETE);
5819 }
5820
5821 /*
5822  * Note that this function currently doesn't actually do anything inside
5823  * CTL to enforce things if the DQue bit is turned on.
5824  *
5825  * Also note that this function can't be used in the default case, because
5826  * the DQue bit isn't set in the changeable mask for the control mode page
5827  * anyway.  This is just here as an example for how to implement a page
5828  * handler, and a placeholder in case we want to allow the user to turn
5829  * tagged queueing on and off.
5830  *
5831  * The D_SENSE bit handling is functional, however, and will turn
5832  * descriptor sense on and off for a given LUN.
5833  */
5834 int
5835 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5836                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5837 {
5838         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5839         struct ctl_lun *lun;
5840         int set_ua;
5841         uint32_t initidx;
5842
5843         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5844         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5845         set_ua = 0;
5846
5847         user_cp = (struct scsi_control_page *)page_ptr;
5848         current_cp = (struct scsi_control_page *)
5849                 (page_index->page_data + (page_index->page_len *
5850                 CTL_PAGE_CURRENT));
5851         saved_cp = (struct scsi_control_page *)
5852                 (page_index->page_data + (page_index->page_len *
5853                 CTL_PAGE_SAVED));
5854
5855         mtx_lock(&lun->lun_lock);
5856         if (((current_cp->rlec & SCP_DSENSE) == 0)
5857          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5858                 /*
5859                  * Descriptor sense is currently turned off and the user
5860                  * wants to turn it on.
5861                  */
5862                 current_cp->rlec |= SCP_DSENSE;
5863                 saved_cp->rlec |= SCP_DSENSE;
5864                 lun->flags |= CTL_LUN_SENSE_DESC;
5865                 set_ua = 1;
5866         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5867                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5868                 /*
5869                  * Descriptor sense is currently turned on, and the user
5870                  * wants to turn it off.
5871                  */
5872                 current_cp->rlec &= ~SCP_DSENSE;
5873                 saved_cp->rlec &= ~SCP_DSENSE;
5874                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5875                 set_ua = 1;
5876         }
5877         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5878             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5879                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5880                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5881                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5882                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5883                 set_ua = 1;
5884         }
5885         if ((current_cp->eca_and_aen & SCP_SWP) !=
5886             (user_cp->eca_and_aen & SCP_SWP)) {
5887                 current_cp->eca_and_aen &= ~SCP_SWP;
5888                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5889                 saved_cp->eca_and_aen &= ~SCP_SWP;
5890                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5891                 set_ua = 1;
5892         }
5893         if (set_ua != 0)
5894                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5895         mtx_unlock(&lun->lun_lock);
5896         if (set_ua) {
5897                 ctl_isc_announce_mode(lun,
5898                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5899                     page_index->page_code, page_index->subpage);
5900         }
5901         return (0);
5902 }
5903
5904 int
5905 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5906                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5907 {
5908         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5909         struct ctl_lun *lun;
5910         int set_ua;
5911         uint32_t initidx;
5912
5913         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5914         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5915         set_ua = 0;
5916
5917         user_cp = (struct scsi_caching_page *)page_ptr;
5918         current_cp = (struct scsi_caching_page *)
5919                 (page_index->page_data + (page_index->page_len *
5920                 CTL_PAGE_CURRENT));
5921         saved_cp = (struct scsi_caching_page *)
5922                 (page_index->page_data + (page_index->page_len *
5923                 CTL_PAGE_SAVED));
5924
5925         mtx_lock(&lun->lun_lock);
5926         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5927             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5928                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5929                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5930                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5931                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5932                 set_ua = 1;
5933         }
5934         if (set_ua != 0)
5935                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5936         mtx_unlock(&lun->lun_lock);
5937         if (set_ua) {
5938                 ctl_isc_announce_mode(lun,
5939                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5940                     page_index->page_code, page_index->subpage);
5941         }
5942         return (0);
5943 }
5944
5945 int
5946 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5947                                 struct ctl_page_index *page_index,
5948                                 uint8_t *page_ptr)
5949 {
5950         uint8_t *c;
5951         int i;
5952
5953         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5954         ctl_time_io_secs =
5955                 (c[0] << 8) |
5956                 (c[1] << 0) |
5957                 0;
5958         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5959         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5960         printf("page data:");
5961         for (i=0; i<8; i++)
5962                 printf(" %.2x",page_ptr[i]);
5963         printf("\n");
5964         return (0);
5965 }
5966
5967 int
5968 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5969                                struct ctl_page_index *page_index,
5970                                int pc)
5971 {
5972         struct copan_debugconf_subpage *page;
5973
5974         page = (struct copan_debugconf_subpage *)page_index->page_data +
5975                 (page_index->page_len * pc);
5976
5977         switch (pc) {
5978         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5979         case SMS_PAGE_CTRL_DEFAULT >> 6:
5980         case SMS_PAGE_CTRL_SAVED >> 6:
5981                 /*
5982                  * We don't update the changable or default bits for this page.
5983                  */
5984                 break;
5985         case SMS_PAGE_CTRL_CURRENT >> 6:
5986                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5987                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5988                 break;
5989         default:
5990                 break;
5991         }
5992         return (0);
5993 }
5994
5995
5996 static int
5997 ctl_do_mode_select(union ctl_io *io)
5998 {
5999         struct scsi_mode_page_header *page_header;
6000         struct ctl_page_index *page_index;
6001         struct ctl_scsiio *ctsio;
6002         int page_len, page_len_offset, page_len_size;
6003         union ctl_modepage_info *modepage_info;
6004         struct ctl_lun *lun;
6005         int *len_left, *len_used;
6006         int retval, i;
6007
6008         ctsio = &io->scsiio;
6009         page_index = NULL;
6010         page_len = 0;
6011         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6012
6013         modepage_info = (union ctl_modepage_info *)
6014                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6015         len_left = &modepage_info->header.len_left;
6016         len_used = &modepage_info->header.len_used;
6017
6018 do_next_page:
6019
6020         page_header = (struct scsi_mode_page_header *)
6021                 (ctsio->kern_data_ptr + *len_used);
6022
6023         if (*len_left == 0) {
6024                 free(ctsio->kern_data_ptr, M_CTL);
6025                 ctl_set_success(ctsio);
6026                 ctl_done((union ctl_io *)ctsio);
6027                 return (CTL_RETVAL_COMPLETE);
6028         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6029
6030                 free(ctsio->kern_data_ptr, M_CTL);
6031                 ctl_set_param_len_error(ctsio);
6032                 ctl_done((union ctl_io *)ctsio);
6033                 return (CTL_RETVAL_COMPLETE);
6034
6035         } else if ((page_header->page_code & SMPH_SPF)
6036                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6037
6038                 free(ctsio->kern_data_ptr, M_CTL);
6039                 ctl_set_param_len_error(ctsio);
6040                 ctl_done((union ctl_io *)ctsio);
6041                 return (CTL_RETVAL_COMPLETE);
6042         }
6043
6044
6045         /*
6046          * XXX KDM should we do something with the block descriptor?
6047          */
6048         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6049                 page_index = &lun->mode_pages.index[i];
6050                 if (lun->be_lun->lun_type == T_DIRECT &&
6051                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6052                         continue;
6053                 if (lun->be_lun->lun_type == T_PROCESSOR &&
6054                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6055                         continue;
6056                 if (lun->be_lun->lun_type == T_CDROM &&
6057                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6058                         continue;
6059
6060                 if ((page_index->page_code & SMPH_PC_MASK) !=
6061                     (page_header->page_code & SMPH_PC_MASK))
6062                         continue;
6063
6064                 /*
6065                  * If neither page has a subpage code, then we've got a
6066                  * match.
6067                  */
6068                 if (((page_index->page_code & SMPH_SPF) == 0)
6069                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6070                         page_len = page_header->page_length;
6071                         break;
6072                 }
6073
6074                 /*
6075                  * If both pages have subpages, then the subpage numbers
6076                  * have to match.
6077                  */
6078                 if ((page_index->page_code & SMPH_SPF)
6079                   && (page_header->page_code & SMPH_SPF)) {
6080                         struct scsi_mode_page_header_sp *sph;
6081
6082                         sph = (struct scsi_mode_page_header_sp *)page_header;
6083                         if (page_index->subpage == sph->subpage) {
6084                                 page_len = scsi_2btoul(sph->page_length);
6085                                 break;
6086                         }
6087                 }
6088         }
6089
6090         /*
6091          * If we couldn't find the page, or if we don't have a mode select
6092          * handler for it, send back an error to the user.
6093          */
6094         if ((i >= CTL_NUM_MODE_PAGES)
6095          || (page_index->select_handler == NULL)) {
6096                 ctl_set_invalid_field(ctsio,
6097                                       /*sks_valid*/ 1,
6098                                       /*command*/ 0,
6099                                       /*field*/ *len_used,
6100                                       /*bit_valid*/ 0,
6101                                       /*bit*/ 0);
6102                 free(ctsio->kern_data_ptr, M_CTL);
6103                 ctl_done((union ctl_io *)ctsio);
6104                 return (CTL_RETVAL_COMPLETE);
6105         }
6106
6107         if (page_index->page_code & SMPH_SPF) {
6108                 page_len_offset = 2;
6109                 page_len_size = 2;
6110         } else {
6111                 page_len_size = 1;
6112                 page_len_offset = 1;
6113         }
6114
6115         /*
6116          * If the length the initiator gives us isn't the one we specify in
6117          * the mode page header, or if they didn't specify enough data in
6118          * the CDB to avoid truncating this page, kick out the request.
6119          */
6120         if ((page_len != (page_index->page_len - page_len_offset -
6121                           page_len_size))
6122          || (*len_left < page_index->page_len)) {
6123
6124
6125                 ctl_set_invalid_field(ctsio,
6126                                       /*sks_valid*/ 1,
6127                                       /*command*/ 0,
6128                                       /*field*/ *len_used + page_len_offset,
6129                                       /*bit_valid*/ 0,
6130                                       /*bit*/ 0);
6131                 free(ctsio->kern_data_ptr, M_CTL);
6132                 ctl_done((union ctl_io *)ctsio);
6133                 return (CTL_RETVAL_COMPLETE);
6134         }
6135
6136         /*
6137          * Run through the mode page, checking to make sure that the bits
6138          * the user changed are actually legal for him to change.
6139          */
6140         for (i = 0; i < page_index->page_len; i++) {
6141                 uint8_t *user_byte, *change_mask, *current_byte;
6142                 int bad_bit;
6143                 int j;
6144
6145                 user_byte = (uint8_t *)page_header + i;
6146                 change_mask = page_index->page_data +
6147                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6148                 current_byte = page_index->page_data +
6149                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6150
6151                 /*
6152                  * Check to see whether the user set any bits in this byte
6153                  * that he is not allowed to set.
6154                  */
6155                 if ((*user_byte & ~(*change_mask)) ==
6156                     (*current_byte & ~(*change_mask)))
6157                         continue;
6158
6159                 /*
6160                  * Go through bit by bit to determine which one is illegal.
6161                  */
6162                 bad_bit = 0;
6163                 for (j = 7; j >= 0; j--) {
6164                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6165                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6166                                 bad_bit = i;
6167                                 break;
6168                         }
6169                 }
6170                 ctl_set_invalid_field(ctsio,
6171                                       /*sks_valid*/ 1,
6172                                       /*command*/ 0,
6173                                       /*field*/ *len_used + i,
6174                                       /*bit_valid*/ 1,
6175                                       /*bit*/ bad_bit);
6176                 free(ctsio->kern_data_ptr, M_CTL);
6177                 ctl_done((union ctl_io *)ctsio);
6178                 return (CTL_RETVAL_COMPLETE);
6179         }
6180
6181         /*
6182          * Decrement these before we call the page handler, since we may
6183          * end up getting called back one way or another before the handler
6184          * returns to this context.
6185          */
6186         *len_left -= page_index->page_len;
6187         *len_used += page_index->page_len;
6188
6189         retval = page_index->select_handler(ctsio, page_index,
6190                                             (uint8_t *)page_header);
6191
6192         /*
6193          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6194          * wait until this queued command completes to finish processing
6195          * the mode page.  If it returns anything other than
6196          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6197          * already set the sense information, freed the data pointer, and
6198          * completed the io for us.
6199          */
6200         if (retval != CTL_RETVAL_COMPLETE)
6201                 goto bailout_no_done;
6202
6203         /*
6204          * If the initiator sent us more than one page, parse the next one.
6205          */
6206         if (*len_left > 0)
6207                 goto do_next_page;
6208
6209         ctl_set_success(ctsio);
6210         free(ctsio->kern_data_ptr, M_CTL);
6211         ctl_done((union ctl_io *)ctsio);
6212
6213 bailout_no_done:
6214
6215         return (CTL_RETVAL_COMPLETE);
6216
6217 }
6218
6219 int
6220 ctl_mode_select(struct ctl_scsiio *ctsio)
6221 {
6222         int param_len, pf, sp;
6223         int header_size, bd_len;
6224         union ctl_modepage_info *modepage_info;
6225
6226         switch (ctsio->cdb[0]) {
6227         case MODE_SELECT_6: {
6228                 struct scsi_mode_select_6 *cdb;
6229
6230                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6231
6232                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6233                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6234                 param_len = cdb->length;
6235                 header_size = sizeof(struct scsi_mode_header_6);
6236                 break;
6237         }
6238         case MODE_SELECT_10: {
6239                 struct scsi_mode_select_10 *cdb;
6240
6241                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6242
6243                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6244                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6245                 param_len = scsi_2btoul(cdb->length);
6246                 header_size = sizeof(struct scsi_mode_header_10);
6247                 break;
6248         }
6249         default:
6250                 ctl_set_invalid_opcode(ctsio);
6251                 ctl_done((union ctl_io *)ctsio);
6252                 return (CTL_RETVAL_COMPLETE);
6253         }
6254
6255         /*
6256          * From SPC-3:
6257          * "A parameter list length of zero indicates that the Data-Out Buffer
6258          * shall be empty. This condition shall not be considered as an error."
6259          */
6260         if (param_len == 0) {
6261                 ctl_set_success(ctsio);
6262                 ctl_done((union ctl_io *)ctsio);
6263                 return (CTL_RETVAL_COMPLETE);
6264         }
6265
6266         /*
6267          * Since we'll hit this the first time through, prior to
6268          * allocation, we don't need to free a data buffer here.
6269          */
6270         if (param_len < header_size) {
6271                 ctl_set_param_len_error(ctsio);
6272                 ctl_done((union ctl_io *)ctsio);
6273                 return (CTL_RETVAL_COMPLETE);
6274         }
6275
6276         /*
6277          * Allocate the data buffer and grab the user's data.  In theory,
6278          * we shouldn't have to sanity check the parameter list length here
6279          * because the maximum size is 64K.  We should be able to malloc
6280          * that much without too many problems.
6281          */
6282         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6283                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6284                 ctsio->kern_data_len = param_len;
6285                 ctsio->kern_total_len = param_len;
6286                 ctsio->kern_data_resid = 0;
6287                 ctsio->kern_rel_offset = 0;
6288                 ctsio->kern_sg_entries = 0;
6289                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6290                 ctsio->be_move_done = ctl_config_move_done;
6291                 ctl_datamove((union ctl_io *)ctsio);
6292
6293                 return (CTL_RETVAL_COMPLETE);
6294         }
6295
6296         switch (ctsio->cdb[0]) {
6297         case MODE_SELECT_6: {
6298                 struct scsi_mode_header_6 *mh6;
6299
6300                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6301                 bd_len = mh6->blk_desc_len;
6302                 break;
6303         }
6304         case MODE_SELECT_10: {
6305                 struct scsi_mode_header_10 *mh10;
6306
6307                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6308                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6309                 break;
6310         }
6311         default:
6312                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6313         }
6314
6315         if (param_len < (header_size + bd_len)) {
6316                 free(ctsio->kern_data_ptr, M_CTL);
6317                 ctl_set_param_len_error(ctsio);
6318                 ctl_done((union ctl_io *)ctsio);
6319                 return (CTL_RETVAL_COMPLETE);
6320         }
6321
6322         /*
6323          * Set the IO_CONT flag, so that if this I/O gets passed to
6324          * ctl_config_write_done(), it'll get passed back to
6325          * ctl_do_mode_select() for further processing, or completion if
6326          * we're all done.
6327          */
6328         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6329         ctsio->io_cont = ctl_do_mode_select;
6330
6331         modepage_info = (union ctl_modepage_info *)
6332                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6333         memset(modepage_info, 0, sizeof(*modepage_info));
6334         modepage_info->header.len_left = param_len - header_size - bd_len;
6335         modepage_info->header.len_used = header_size + bd_len;
6336
6337         return (ctl_do_mode_select((union ctl_io *)ctsio));
6338 }
6339
6340 int
6341 ctl_mode_sense(struct ctl_scsiio *ctsio)
6342 {
6343         struct ctl_lun *lun;
6344         int pc, page_code, dbd, llba, subpage;
6345         int alloc_len, page_len, header_len, total_len;
6346         struct scsi_mode_block_descr *block_desc;
6347         struct ctl_page_index *page_index;
6348
6349         dbd = 0;
6350         llba = 0;
6351         block_desc = NULL;
6352
6353         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6354
6355         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6356         switch (ctsio->cdb[0]) {
6357         case MODE_SENSE_6: {
6358                 struct scsi_mode_sense_6 *cdb;
6359
6360                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6361
6362                 header_len = sizeof(struct scsi_mode_hdr_6);
6363                 if (cdb->byte2 & SMS_DBD)
6364                         dbd = 1;
6365                 else
6366                         header_len += sizeof(struct scsi_mode_block_descr);
6367
6368                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6369                 page_code = cdb->page & SMS_PAGE_CODE;
6370                 subpage = cdb->subpage;
6371                 alloc_len = cdb->length;
6372                 break;
6373         }
6374         case MODE_SENSE_10: {
6375                 struct scsi_mode_sense_10 *cdb;
6376
6377                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6378
6379                 header_len = sizeof(struct scsi_mode_hdr_10);
6380
6381                 if (cdb->byte2 & SMS_DBD)
6382                         dbd = 1;
6383                 else
6384                         header_len += sizeof(struct scsi_mode_block_descr);
6385                 if (cdb->byte2 & SMS10_LLBAA)
6386                         llba = 1;
6387                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6388                 page_code = cdb->page & SMS_PAGE_CODE;
6389                 subpage = cdb->subpage;
6390                 alloc_len = scsi_2btoul(cdb->length);
6391                 break;
6392         }
6393         default:
6394                 ctl_set_invalid_opcode(ctsio);
6395                 ctl_done((union ctl_io *)ctsio);
6396                 return (CTL_RETVAL_COMPLETE);
6397                 break; /* NOTREACHED */
6398         }
6399
6400         /*
6401          * We have to make a first pass through to calculate the size of
6402          * the pages that match the user's query.  Then we allocate enough
6403          * memory to hold it, and actually copy the data into the buffer.
6404          */
6405         switch (page_code) {
6406         case SMS_ALL_PAGES_PAGE: {
6407                 int i;
6408
6409                 page_len = 0;
6410
6411                 /*
6412                  * At the moment, values other than 0 and 0xff here are
6413                  * reserved according to SPC-3.
6414                  */
6415                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6416                  && (subpage != SMS_SUBPAGE_ALL)) {
6417                         ctl_set_invalid_field(ctsio,
6418                                               /*sks_valid*/ 1,
6419                                               /*command*/ 1,
6420                                               /*field*/ 3,
6421                                               /*bit_valid*/ 0,
6422                                               /*bit*/ 0);
6423                         ctl_done((union ctl_io *)ctsio);
6424                         return (CTL_RETVAL_COMPLETE);
6425                 }
6426
6427                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6428                         page_index = &lun->mode_pages.index[i];
6429
6430                         /* Make sure the page is supported for this dev type */
6431                         if (lun->be_lun->lun_type == T_DIRECT &&
6432                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6433                                 continue;
6434                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6435                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6436                                 continue;
6437                         if (lun->be_lun->lun_type == T_CDROM &&
6438                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6439                                 continue;
6440
6441                         /*
6442                          * We don't use this subpage if the user didn't
6443                          * request all subpages.
6444                          */
6445                         if ((page_index->subpage != 0)
6446                          && (subpage == SMS_SUBPAGE_PAGE_0))
6447                                 continue;
6448
6449 #if 0
6450                         printf("found page %#x len %d\n",
6451                                page_index->page_code & SMPH_PC_MASK,
6452                                page_index->page_len);
6453 #endif
6454                         page_len += page_index->page_len;
6455                 }
6456                 break;
6457         }
6458         default: {
6459                 int i;
6460
6461                 page_len = 0;
6462
6463                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6464                         page_index = &lun->mode_pages.index[i];
6465
6466                         /* Make sure the page is supported for this dev type */
6467                         if (lun->be_lun->lun_type == T_DIRECT &&
6468                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6469                                 continue;
6470                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6471                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6472                                 continue;
6473                         if (lun->be_lun->lun_type == T_CDROM &&
6474                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6475                                 continue;
6476
6477                         /* Look for the right page code */
6478                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6479                                 continue;
6480
6481                         /* Look for the right subpage or the subpage wildcard*/
6482                         if ((page_index->subpage != subpage)
6483                          && (subpage != SMS_SUBPAGE_ALL))
6484                                 continue;
6485
6486 #if 0
6487                         printf("found page %#x len %d\n",
6488                                page_index->page_code & SMPH_PC_MASK,
6489                                page_index->page_len);
6490 #endif
6491
6492                         page_len += page_index->page_len;
6493                 }
6494
6495                 if (page_len == 0) {
6496                         ctl_set_invalid_field(ctsio,
6497                                               /*sks_valid*/ 1,
6498                                               /*command*/ 1,
6499                                               /*field*/ 2,
6500                                               /*bit_valid*/ 1,
6501                                               /*bit*/ 5);
6502                         ctl_done((union ctl_io *)ctsio);
6503                         return (CTL_RETVAL_COMPLETE);
6504                 }
6505                 break;
6506         }
6507         }
6508
6509         total_len = header_len + page_len;
6510 #if 0
6511         printf("header_len = %d, page_len = %d, total_len = %d\n",
6512                header_len, page_len, total_len);
6513 #endif
6514
6515         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6516         ctsio->kern_sg_entries = 0;
6517         ctsio->kern_data_resid = 0;
6518         ctsio->kern_rel_offset = 0;
6519         if (total_len < alloc_len) {
6520                 ctsio->residual = alloc_len - total_len;
6521                 ctsio->kern_data_len = total_len;
6522                 ctsio->kern_total_len = total_len;
6523         } else {
6524                 ctsio->residual = 0;
6525                 ctsio->kern_data_len = alloc_len;
6526                 ctsio->kern_total_len = alloc_len;
6527         }
6528
6529         switch (ctsio->cdb[0]) {
6530         case MODE_SENSE_6: {
6531                 struct scsi_mode_hdr_6 *header;
6532
6533                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6534
6535                 header->datalen = MIN(total_len - 1, 254);
6536                 if (lun->be_lun->lun_type == T_DIRECT) {
6537                         header->dev_specific = 0x10; /* DPOFUA */
6538                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6539                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6540                             .eca_and_aen & SCP_SWP) != 0)
6541                                     header->dev_specific |= 0x80; /* WP */
6542                 }
6543                 if (dbd)
6544                         header->block_descr_len = 0;
6545                 else
6546                         header->block_descr_len =
6547                                 sizeof(struct scsi_mode_block_descr);
6548                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6549                 break;
6550         }
6551         case MODE_SENSE_10: {
6552                 struct scsi_mode_hdr_10 *header;
6553                 int datalen;
6554
6555                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6556
6557                 datalen = MIN(total_len - 2, 65533);
6558                 scsi_ulto2b(datalen, header->datalen);
6559                 if (lun->be_lun->lun_type == T_DIRECT) {
6560                         header->dev_specific = 0x10; /* DPOFUA */
6561                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6562                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6563                             .eca_and_aen & SCP_SWP) != 0)
6564                                     header->dev_specific |= 0x80; /* WP */
6565                 }
6566                 if (dbd)
6567                         scsi_ulto2b(0, header->block_descr_len);
6568                 else
6569                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6570                                     header->block_descr_len);
6571                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6572                 break;
6573         }
6574         default:
6575                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6576         }
6577
6578         /*
6579          * If we've got a disk, use its blocksize in the block
6580          * descriptor.  Otherwise, just set it to 0.
6581          */
6582         if (dbd == 0) {
6583                 if (lun->be_lun->lun_type == T_DIRECT)
6584                         scsi_ulto3b(lun->be_lun->blocksize,
6585                                     block_desc->block_len);
6586                 else
6587                         scsi_ulto3b(0, block_desc->block_len);
6588         }
6589
6590         switch (page_code) {
6591         case SMS_ALL_PAGES_PAGE: {
6592                 int i, data_used;
6593
6594                 data_used = header_len;
6595                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6596                         struct ctl_page_index *page_index;
6597
6598                         page_index = &lun->mode_pages.index[i];
6599                         if (lun->be_lun->lun_type == T_DIRECT &&
6600                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6601                                 continue;
6602                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6603                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6604                                 continue;
6605                         if (lun->be_lun->lun_type == T_CDROM &&
6606                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6607                                 continue;
6608
6609                         /*
6610                          * We don't use this subpage if the user didn't
6611                          * request all subpages.  We already checked (above)
6612                          * to make sure the user only specified a subpage
6613                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6614                          */
6615                         if ((page_index->subpage != 0)
6616                          && (subpage == SMS_SUBPAGE_PAGE_0))
6617                                 continue;
6618
6619                         /*
6620                          * Call the handler, if it exists, to update the
6621                          * page to the latest values.
6622                          */
6623                         if (page_index->sense_handler != NULL)
6624                                 page_index->sense_handler(ctsio, page_index,pc);
6625
6626                         memcpy(ctsio->kern_data_ptr + data_used,
6627                                page_index->page_data +
6628                                (page_index->page_len * pc),
6629                                page_index->page_len);
6630                         data_used += page_index->page_len;
6631                 }
6632                 break;
6633         }
6634         default: {
6635                 int i, data_used;
6636
6637                 data_used = header_len;
6638
6639                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6640                         struct ctl_page_index *page_index;
6641
6642                         page_index = &lun->mode_pages.index[i];
6643
6644                         /* Look for the right page code */
6645                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6646                                 continue;
6647
6648                         /* Look for the right subpage or the subpage wildcard*/
6649                         if ((page_index->subpage != subpage)
6650                          && (subpage != SMS_SUBPAGE_ALL))
6651                                 continue;
6652
6653                         /* Make sure the page is supported for this dev type */
6654                         if (lun->be_lun->lun_type == T_DIRECT &&
6655                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6656                                 continue;
6657                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6658                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6659                                 continue;
6660                         if (lun->be_lun->lun_type == T_CDROM &&
6661                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6662                                 continue;
6663
6664                         /*
6665                          * Call the handler, if it exists, to update the
6666                          * page to the latest values.
6667                          */
6668                         if (page_index->sense_handler != NULL)
6669                                 page_index->sense_handler(ctsio, page_index,pc);
6670
6671                         memcpy(ctsio->kern_data_ptr + data_used,
6672                                page_index->page_data +
6673                                (page_index->page_len * pc),
6674                                page_index->page_len);
6675                         data_used += page_index->page_len;
6676                 }
6677                 break;
6678         }
6679         }
6680
6681         ctl_set_success(ctsio);
6682         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6683         ctsio->be_move_done = ctl_config_move_done;
6684         ctl_datamove((union ctl_io *)ctsio);
6685         return (CTL_RETVAL_COMPLETE);
6686 }
6687
6688 int
6689 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6690                                struct ctl_page_index *page_index,
6691                                int pc)
6692 {
6693         struct ctl_lun *lun;
6694         struct scsi_log_param_header *phdr;
6695         uint8_t *data;
6696         uint64_t val;
6697
6698         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6699         data = page_index->page_data;
6700
6701         if (lun->backend->lun_attr != NULL &&
6702             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6703              != UINT64_MAX) {
6704                 phdr = (struct scsi_log_param_header *)data;
6705                 scsi_ulto2b(0x0001, phdr->param_code);
6706                 phdr->param_control = SLP_LBIN | SLP_LP;
6707                 phdr->param_len = 8;
6708                 data = (uint8_t *)(phdr + 1);
6709                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6710                 data[4] = 0x02; /* per-pool */
6711                 data += phdr->param_len;
6712         }
6713
6714         if (lun->backend->lun_attr != NULL &&
6715             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6716              != UINT64_MAX) {
6717                 phdr = (struct scsi_log_param_header *)data;
6718                 scsi_ulto2b(0x0002, phdr->param_code);
6719                 phdr->param_control = SLP_LBIN | SLP_LP;
6720                 phdr->param_len = 8;
6721                 data = (uint8_t *)(phdr + 1);
6722                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6723                 data[4] = 0x01; /* per-LUN */
6724                 data += phdr->param_len;
6725         }
6726
6727         if (lun->backend->lun_attr != NULL &&
6728             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6729              != UINT64_MAX) {
6730                 phdr = (struct scsi_log_param_header *)data;
6731                 scsi_ulto2b(0x00f1, phdr->param_code);
6732                 phdr->param_control = SLP_LBIN | SLP_LP;
6733                 phdr->param_len = 8;
6734                 data = (uint8_t *)(phdr + 1);
6735                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6736                 data[4] = 0x02; /* per-pool */
6737                 data += phdr->param_len;
6738         }
6739
6740         if (lun->backend->lun_attr != NULL &&
6741             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6742              != UINT64_MAX) {
6743                 phdr = (struct scsi_log_param_header *)data;
6744                 scsi_ulto2b(0x00f2, phdr->param_code);
6745                 phdr->param_control = SLP_LBIN | SLP_LP;
6746                 phdr->param_len = 8;
6747                 data = (uint8_t *)(phdr + 1);
6748                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6749                 data[4] = 0x02; /* per-pool */
6750                 data += phdr->param_len;
6751         }
6752
6753         page_index->page_len = data - page_index->page_data;
6754         return (0);
6755 }
6756
6757 int
6758 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6759                                struct ctl_page_index *page_index,
6760                                int pc)
6761 {
6762         struct ctl_lun *lun;
6763         struct stat_page *data;
6764         uint64_t rn, wn, rb, wb;
6765         struct bintime rt, wt;
6766         int i;
6767
6768         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6769         data = (struct stat_page *)page_index->page_data;
6770
6771         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6772         data->sap.hdr.param_control = SLP_LBIN;
6773         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6774             sizeof(struct scsi_log_param_header);
6775         rn = wn = rb = wb = 0;
6776         bintime_clear(&rt);
6777         bintime_clear(&wt);
6778         for (i = 0; i < CTL_MAX_PORTS; i++) {
6779                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6780                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6781                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6782                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6783                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6784                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6785         }
6786         scsi_u64to8b(rn, data->sap.read_num);
6787         scsi_u64to8b(wn, data->sap.write_num);
6788         if (lun->stats.blocksize > 0) {
6789                 scsi_u64to8b(wb / lun->stats.blocksize,
6790                     data->sap.recvieved_lba);
6791                 scsi_u64to8b(rb / lun->stats.blocksize,
6792                     data->sap.transmitted_lba);
6793         }
6794         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6795             data->sap.read_int);
6796         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6797             data->sap.write_int);
6798         scsi_u64to8b(0, data->sap.weighted_num);
6799         scsi_u64to8b(0, data->sap.weighted_int);
6800         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6801         data->it.hdr.param_control = SLP_LBIN;
6802         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6803             sizeof(struct scsi_log_param_header);
6804 #ifdef CTL_TIME_IO
6805         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6806 #endif
6807         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6808         data->it.hdr.param_control = SLP_LBIN;
6809         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6810             sizeof(struct scsi_log_param_header);
6811         scsi_ulto4b(3, data->ti.exponent);
6812         scsi_ulto4b(1, data->ti.integer);
6813
6814         page_index->page_len = sizeof(*data);
6815         return (0);
6816 }
6817
6818 int
6819 ctl_log_sense(struct ctl_scsiio *ctsio)
6820 {
6821         struct ctl_lun *lun;
6822         int i, pc, page_code, subpage;
6823         int alloc_len, total_len;
6824         struct ctl_page_index *page_index;
6825         struct scsi_log_sense *cdb;
6826         struct scsi_log_header *header;
6827
6828         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6829
6830         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6831         cdb = (struct scsi_log_sense *)ctsio->cdb;
6832         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6833         page_code = cdb->page & SLS_PAGE_CODE;
6834         subpage = cdb->subpage;
6835         alloc_len = scsi_2btoul(cdb->length);
6836
6837         page_index = NULL;
6838         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6839                 page_index = &lun->log_pages.index[i];
6840
6841                 /* Look for the right page code */
6842                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6843                         continue;
6844
6845                 /* Look for the right subpage or the subpage wildcard*/
6846                 if (page_index->subpage != subpage)
6847                         continue;
6848
6849                 break;
6850         }
6851         if (i >= CTL_NUM_LOG_PAGES) {
6852                 ctl_set_invalid_field(ctsio,
6853                                       /*sks_valid*/ 1,
6854                                       /*command*/ 1,
6855                                       /*field*/ 2,
6856                                       /*bit_valid*/ 0,
6857                                       /*bit*/ 0);
6858                 ctl_done((union ctl_io *)ctsio);
6859                 return (CTL_RETVAL_COMPLETE);
6860         }
6861
6862         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6863
6864         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6865         ctsio->kern_sg_entries = 0;
6866         ctsio->kern_data_resid = 0;
6867         ctsio->kern_rel_offset = 0;
6868         if (total_len < alloc_len) {
6869                 ctsio->residual = alloc_len - total_len;
6870                 ctsio->kern_data_len = total_len;
6871                 ctsio->kern_total_len = total_len;
6872         } else {
6873                 ctsio->residual = 0;
6874                 ctsio->kern_data_len = alloc_len;
6875                 ctsio->kern_total_len = alloc_len;
6876         }
6877
6878         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6879         header->page = page_index->page_code;
6880         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6881                 header->page |= SL_DS;
6882         if (page_index->subpage) {
6883                 header->page |= SL_SPF;
6884                 header->subpage = page_index->subpage;
6885         }
6886         scsi_ulto2b(page_index->page_len, header->datalen);
6887
6888         /*
6889          * Call the handler, if it exists, to update the
6890          * page to the latest values.
6891          */
6892         if (page_index->sense_handler != NULL)
6893                 page_index->sense_handler(ctsio, page_index, pc);
6894
6895         memcpy(header + 1, page_index->page_data, page_index->page_len);
6896
6897         ctl_set_success(ctsio);
6898         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6899         ctsio->be_move_done = ctl_config_move_done;
6900         ctl_datamove((union ctl_io *)ctsio);
6901         return (CTL_RETVAL_COMPLETE);
6902 }
6903
6904 int
6905 ctl_read_capacity(struct ctl_scsiio *ctsio)
6906 {
6907         struct scsi_read_capacity *cdb;
6908         struct scsi_read_capacity_data *data;
6909         struct ctl_lun *lun;
6910         uint32_t lba;
6911
6912         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6913
6914         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6915
6916         lba = scsi_4btoul(cdb->addr);
6917         if (((cdb->pmi & SRC_PMI) == 0)
6918          && (lba != 0)) {
6919                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6920                                       /*sks_valid*/ 1,
6921                                       /*command*/ 1,
6922                                       /*field*/ 2,
6923                                       /*bit_valid*/ 0,
6924                                       /*bit*/ 0);
6925                 ctl_done((union ctl_io *)ctsio);
6926                 return (CTL_RETVAL_COMPLETE);
6927         }
6928
6929         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6930
6931         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6932         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6933         ctsio->residual = 0;
6934         ctsio->kern_data_len = sizeof(*data);
6935         ctsio->kern_total_len = sizeof(*data);
6936         ctsio->kern_data_resid = 0;
6937         ctsio->kern_rel_offset = 0;
6938         ctsio->kern_sg_entries = 0;
6939
6940         /*
6941          * If the maximum LBA is greater than 0xfffffffe, the user must
6942          * issue a SERVICE ACTION IN (16) command, with the read capacity
6943          * serivce action set.
6944          */
6945         if (lun->be_lun->maxlba > 0xfffffffe)
6946                 scsi_ulto4b(0xffffffff, data->addr);
6947         else
6948                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6949
6950         /*
6951          * XXX KDM this may not be 512 bytes...
6952          */
6953         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6954
6955         ctl_set_success(ctsio);
6956         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6957         ctsio->be_move_done = ctl_config_move_done;
6958         ctl_datamove((union ctl_io *)ctsio);
6959         return (CTL_RETVAL_COMPLETE);
6960 }
6961
6962 int
6963 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6964 {
6965         struct scsi_read_capacity_16 *cdb;
6966         struct scsi_read_capacity_data_long *data;
6967         struct ctl_lun *lun;
6968         uint64_t lba;
6969         uint32_t alloc_len;
6970
6971         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6972
6973         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6974
6975         alloc_len = scsi_4btoul(cdb->alloc_len);
6976         lba = scsi_8btou64(cdb->addr);
6977
6978         if ((cdb->reladr & SRC16_PMI)
6979          && (lba != 0)) {
6980                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6981                                       /*sks_valid*/ 1,
6982                                       /*command*/ 1,
6983                                       /*field*/ 2,
6984                                       /*bit_valid*/ 0,
6985                                       /*bit*/ 0);
6986                 ctl_done((union ctl_io *)ctsio);
6987                 return (CTL_RETVAL_COMPLETE);
6988         }
6989
6990         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6991
6992         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6993         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6994
6995         if (sizeof(*data) < alloc_len) {
6996                 ctsio->residual = alloc_len - sizeof(*data);
6997                 ctsio->kern_data_len = sizeof(*data);
6998                 ctsio->kern_total_len = sizeof(*data);
6999         } else {
7000                 ctsio->residual = 0;
7001                 ctsio->kern_data_len = alloc_len;
7002                 ctsio->kern_total_len = alloc_len;
7003         }
7004         ctsio->kern_data_resid = 0;
7005         ctsio->kern_rel_offset = 0;
7006         ctsio->kern_sg_entries = 0;
7007
7008         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7009         /* XXX KDM this may not be 512 bytes... */
7010         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7011         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7012         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7013         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7014                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7015
7016         ctl_set_success(ctsio);
7017         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7018         ctsio->be_move_done = ctl_config_move_done;
7019         ctl_datamove((union ctl_io *)ctsio);
7020         return (CTL_RETVAL_COMPLETE);
7021 }
7022
7023 int
7024 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7025 {
7026         struct scsi_get_lba_status *cdb;
7027         struct scsi_get_lba_status_data *data;
7028         struct ctl_lun *lun;
7029         struct ctl_lba_len_flags *lbalen;
7030         uint64_t lba;
7031         uint32_t alloc_len, total_len;
7032         int retval;
7033
7034         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7035
7036         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7037         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7038         lba = scsi_8btou64(cdb->addr);
7039         alloc_len = scsi_4btoul(cdb->alloc_len);
7040
7041         if (lba > lun->be_lun->maxlba) {
7042                 ctl_set_lba_out_of_range(ctsio);
7043                 ctl_done((union ctl_io *)ctsio);
7044                 return (CTL_RETVAL_COMPLETE);
7045         }
7046
7047         total_len = sizeof(*data) + sizeof(data->descr[0]);
7048         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7049         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7050
7051         if (total_len < alloc_len) {
7052                 ctsio->residual = alloc_len - total_len;
7053                 ctsio->kern_data_len = total_len;
7054                 ctsio->kern_total_len = total_len;
7055         } else {
7056                 ctsio->residual = 0;
7057                 ctsio->kern_data_len = alloc_len;
7058                 ctsio->kern_total_len = alloc_len;
7059         }
7060         ctsio->kern_data_resid = 0;
7061         ctsio->kern_rel_offset = 0;
7062         ctsio->kern_sg_entries = 0;
7063
7064         /* Fill dummy data in case backend can't tell anything. */
7065         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7066         scsi_u64to8b(lba, data->descr[0].addr);
7067         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7068             data->descr[0].length);
7069         data->descr[0].status = 0; /* Mapped or unknown. */
7070
7071         ctl_set_success(ctsio);
7072         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7073         ctsio->be_move_done = ctl_config_move_done;
7074
7075         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7076         lbalen->lba = lba;
7077         lbalen->len = total_len;
7078         lbalen->flags = 0;
7079         retval = lun->backend->config_read((union ctl_io *)ctsio);
7080         return (CTL_RETVAL_COMPLETE);
7081 }
7082
7083 int
7084 ctl_read_defect(struct ctl_scsiio *ctsio)
7085 {
7086         struct scsi_read_defect_data_10 *ccb10;
7087         struct scsi_read_defect_data_12 *ccb12;
7088         struct scsi_read_defect_data_hdr_10 *data10;
7089         struct scsi_read_defect_data_hdr_12 *data12;
7090         uint32_t alloc_len, data_len;
7091         uint8_t format;
7092
7093         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7094
7095         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7096                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7097                 format = ccb10->format;
7098                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7099                 data_len = sizeof(*data10);
7100         } else {
7101                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7102                 format = ccb12->format;
7103                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7104                 data_len = sizeof(*data12);
7105         }
7106         if (alloc_len == 0) {
7107                 ctl_set_success(ctsio);
7108                 ctl_done((union ctl_io *)ctsio);
7109                 return (CTL_RETVAL_COMPLETE);
7110         }
7111
7112         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7113         if (data_len < alloc_len) {
7114                 ctsio->residual = alloc_len - data_len;
7115                 ctsio->kern_data_len = data_len;
7116                 ctsio->kern_total_len = data_len;
7117         } else {
7118                 ctsio->residual = 0;
7119                 ctsio->kern_data_len = alloc_len;
7120                 ctsio->kern_total_len = alloc_len;
7121         }
7122         ctsio->kern_data_resid = 0;
7123         ctsio->kern_rel_offset = 0;
7124         ctsio->kern_sg_entries = 0;
7125
7126         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7127                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7128                     ctsio->kern_data_ptr;
7129                 data10->format = format;
7130                 scsi_ulto2b(0, data10->length);
7131         } else {
7132                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7133                     ctsio->kern_data_ptr;
7134                 data12->format = format;
7135                 scsi_ulto2b(0, data12->generation);
7136                 scsi_ulto4b(0, data12->length);
7137         }
7138
7139         ctl_set_success(ctsio);
7140         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7141         ctsio->be_move_done = ctl_config_move_done;
7142         ctl_datamove((union ctl_io *)ctsio);
7143         return (CTL_RETVAL_COMPLETE);
7144 }
7145
7146 int
7147 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7148 {
7149         struct scsi_maintenance_in *cdb;
7150         int retval;
7151         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7152         int num_ha_groups, num_target_ports, shared_group;
7153         struct ctl_lun *lun;
7154         struct ctl_softc *softc;
7155         struct ctl_port *port;
7156         struct scsi_target_group_data *rtg_ptr;
7157         struct scsi_target_group_data_extended *rtg_ext_ptr;
7158         struct scsi_target_port_group_descriptor *tpg_desc;
7159
7160         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7161
7162         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7163         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7164         softc = lun->ctl_softc;
7165
7166         retval = CTL_RETVAL_COMPLETE;
7167
7168         switch (cdb->byte2 & STG_PDF_MASK) {
7169         case STG_PDF_LENGTH:
7170                 ext = 0;
7171                 break;
7172         case STG_PDF_EXTENDED:
7173                 ext = 1;
7174                 break;
7175         default:
7176                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7177                                       /*sks_valid*/ 1,
7178                                       /*command*/ 1,
7179                                       /*field*/ 2,
7180                                       /*bit_valid*/ 1,
7181                                       /*bit*/ 5);
7182                 ctl_done((union ctl_io *)ctsio);
7183                 return(retval);
7184         }
7185
7186         num_target_ports = 0;
7187         shared_group = (softc->is_single != 0);
7188         mtx_lock(&softc->ctl_lock);
7189         STAILQ_FOREACH(port, &softc->port_list, links) {
7190                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7191                         continue;
7192                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7193                         continue;
7194                 num_target_ports++;
7195                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7196                         shared_group = 1;
7197         }
7198         mtx_unlock(&softc->ctl_lock);
7199         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7200
7201         if (ext)
7202                 total_len = sizeof(struct scsi_target_group_data_extended);
7203         else
7204                 total_len = sizeof(struct scsi_target_group_data);
7205         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7206                 (shared_group + num_ha_groups) +
7207             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7208
7209         alloc_len = scsi_4btoul(cdb->length);
7210
7211         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7212
7213         ctsio->kern_sg_entries = 0;
7214
7215         if (total_len < alloc_len) {
7216                 ctsio->residual = alloc_len - total_len;
7217                 ctsio->kern_data_len = total_len;
7218                 ctsio->kern_total_len = total_len;
7219         } else {
7220                 ctsio->residual = 0;
7221                 ctsio->kern_data_len = alloc_len;
7222                 ctsio->kern_total_len = alloc_len;
7223         }
7224         ctsio->kern_data_resid = 0;
7225         ctsio->kern_rel_offset = 0;
7226
7227         if (ext) {
7228                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7229                     ctsio->kern_data_ptr;
7230                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7231                 rtg_ext_ptr->format_type = 0x10;
7232                 rtg_ext_ptr->implicit_transition_time = 0;
7233                 tpg_desc = &rtg_ext_ptr->groups[0];
7234         } else {
7235                 rtg_ptr = (struct scsi_target_group_data *)
7236                     ctsio->kern_data_ptr;
7237                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7238                 tpg_desc = &rtg_ptr->groups[0];
7239         }
7240
7241         mtx_lock(&softc->ctl_lock);
7242         pg = softc->port_min / softc->port_cnt;
7243         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7244                 /* Some shelf is known to be primary. */
7245                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7246                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7247                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7248                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7249                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7250                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7251                 else
7252                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7253                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7254                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7255                 } else {
7256                         ts = os;
7257                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7258                 }
7259         } else {
7260                 /* No known primary shelf. */
7261                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7262                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7263                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7264                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7265                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7266                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7267                 } else {
7268                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7269                 }
7270         }
7271         if (shared_group) {
7272                 tpg_desc->pref_state = ts;
7273                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7274                     TPG_U_SUP | TPG_T_SUP;
7275                 scsi_ulto2b(1, tpg_desc->target_port_group);
7276                 tpg_desc->status = TPG_IMPLICIT;
7277                 pc = 0;
7278                 STAILQ_FOREACH(port, &softc->port_list, links) {
7279                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7280                                 continue;
7281                         if (!softc->is_single &&
7282                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7283                                 continue;
7284                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7285                                 continue;
7286                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7287                             relative_target_port_identifier);
7288                         pc++;
7289                 }
7290                 tpg_desc->target_port_count = pc;
7291                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7292                     &tpg_desc->descriptors[pc];
7293         }
7294         for (g = 0; g < num_ha_groups; g++) {
7295                 tpg_desc->pref_state = (g == pg) ? ts : os;
7296                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7297                     TPG_U_SUP | TPG_T_SUP;
7298                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7299                 tpg_desc->status = TPG_IMPLICIT;
7300                 pc = 0;
7301                 STAILQ_FOREACH(port, &softc->port_list, links) {
7302                         if (port->targ_port < g * softc->port_cnt ||
7303                             port->targ_port >= (g + 1) * softc->port_cnt)
7304                                 continue;
7305                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7306                                 continue;
7307                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7308                                 continue;
7309                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7310                                 continue;
7311                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7312                             relative_target_port_identifier);
7313                         pc++;
7314                 }
7315                 tpg_desc->target_port_count = pc;
7316                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7317                     &tpg_desc->descriptors[pc];
7318         }
7319         mtx_unlock(&softc->ctl_lock);
7320
7321         ctl_set_success(ctsio);
7322         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7323         ctsio->be_move_done = ctl_config_move_done;
7324         ctl_datamove((union ctl_io *)ctsio);
7325         return(retval);
7326 }
7327
7328 int
7329 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7330 {
7331         struct ctl_lun *lun;
7332         struct scsi_report_supported_opcodes *cdb;
7333         const struct ctl_cmd_entry *entry, *sentry;
7334         struct scsi_report_supported_opcodes_all *all;
7335         struct scsi_report_supported_opcodes_descr *descr;
7336         struct scsi_report_supported_opcodes_one *one;
7337         int retval;
7338         int alloc_len, total_len;
7339         int opcode, service_action, i, j, num;
7340
7341         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7342
7343         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7344         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7345
7346         retval = CTL_RETVAL_COMPLETE;
7347
7348         opcode = cdb->requested_opcode;
7349         service_action = scsi_2btoul(cdb->requested_service_action);
7350         switch (cdb->options & RSO_OPTIONS_MASK) {
7351         case RSO_OPTIONS_ALL:
7352                 num = 0;
7353                 for (i = 0; i < 256; i++) {
7354                         entry = &ctl_cmd_table[i];
7355                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7356                                 for (j = 0; j < 32; j++) {
7357                                         sentry = &((const struct ctl_cmd_entry *)
7358                                             entry->execute)[j];
7359                                         if (ctl_cmd_applicable(
7360                                             lun->be_lun->lun_type, sentry))
7361                                                 num++;
7362                                 }
7363                         } else {
7364                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7365                                     entry))
7366                                         num++;
7367                         }
7368                 }
7369                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7370                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7371                 break;
7372         case RSO_OPTIONS_OC:
7373                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7374                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7375                                               /*sks_valid*/ 1,
7376                                               /*command*/ 1,
7377                                               /*field*/ 2,
7378                                               /*bit_valid*/ 1,
7379                                               /*bit*/ 2);
7380                         ctl_done((union ctl_io *)ctsio);
7381                         return (CTL_RETVAL_COMPLETE);
7382                 }
7383                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7384                 break;
7385         case RSO_OPTIONS_OC_SA:
7386                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7387                     service_action >= 32) {
7388                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7389                                               /*sks_valid*/ 1,
7390                                               /*command*/ 1,
7391                                               /*field*/ 2,
7392                                               /*bit_valid*/ 1,
7393                                               /*bit*/ 2);
7394                         ctl_done((union ctl_io *)ctsio);
7395                         return (CTL_RETVAL_COMPLETE);
7396                 }
7397                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7398                 break;
7399         default:
7400                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7401                                       /*sks_valid*/ 1,
7402                                       /*command*/ 1,
7403                                       /*field*/ 2,
7404                                       /*bit_valid*/ 1,
7405                                       /*bit*/ 2);
7406                 ctl_done((union ctl_io *)ctsio);
7407                 return (CTL_RETVAL_COMPLETE);
7408         }
7409
7410         alloc_len = scsi_4btoul(cdb->length);
7411
7412         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7413
7414         ctsio->kern_sg_entries = 0;
7415
7416         if (total_len < alloc_len) {
7417                 ctsio->residual = alloc_len - total_len;
7418                 ctsio->kern_data_len = total_len;
7419                 ctsio->kern_total_len = total_len;
7420         } else {
7421                 ctsio->residual = 0;
7422                 ctsio->kern_data_len = alloc_len;
7423                 ctsio->kern_total_len = alloc_len;
7424         }
7425         ctsio->kern_data_resid = 0;
7426         ctsio->kern_rel_offset = 0;
7427
7428         switch (cdb->options & RSO_OPTIONS_MASK) {
7429         case RSO_OPTIONS_ALL:
7430                 all = (struct scsi_report_supported_opcodes_all *)
7431                     ctsio->kern_data_ptr;
7432                 num = 0;
7433                 for (i = 0; i < 256; i++) {
7434                         entry = &ctl_cmd_table[i];
7435                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7436                                 for (j = 0; j < 32; j++) {
7437                                         sentry = &((const struct ctl_cmd_entry *)
7438                                             entry->execute)[j];
7439                                         if (!ctl_cmd_applicable(
7440                                             lun->be_lun->lun_type, sentry))
7441                                                 continue;
7442                                         descr = &all->descr[num++];
7443                                         descr->opcode = i;
7444                                         scsi_ulto2b(j, descr->service_action);
7445                                         descr->flags = RSO_SERVACTV;
7446                                         scsi_ulto2b(sentry->length,
7447                                             descr->cdb_length);
7448                                 }
7449                         } else {
7450                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7451                                     entry))
7452                                         continue;
7453                                 descr = &all->descr[num++];
7454                                 descr->opcode = i;
7455                                 scsi_ulto2b(0, descr->service_action);
7456                                 descr->flags = 0;
7457                                 scsi_ulto2b(entry->length, descr->cdb_length);
7458                         }
7459                 }
7460                 scsi_ulto4b(
7461                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7462                     all->length);
7463                 break;
7464         case RSO_OPTIONS_OC:
7465                 one = (struct scsi_report_supported_opcodes_one *)
7466                     ctsio->kern_data_ptr;
7467                 entry = &ctl_cmd_table[opcode];
7468                 goto fill_one;
7469         case RSO_OPTIONS_OC_SA:
7470                 one = (struct scsi_report_supported_opcodes_one *)
7471                     ctsio->kern_data_ptr;
7472                 entry = &ctl_cmd_table[opcode];
7473                 entry = &((const struct ctl_cmd_entry *)
7474                     entry->execute)[service_action];
7475 fill_one:
7476                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7477                         one->support = 3;
7478                         scsi_ulto2b(entry->length, one->cdb_length);
7479                         one->cdb_usage[0] = opcode;
7480                         memcpy(&one->cdb_usage[1], entry->usage,
7481                             entry->length - 1);
7482                 } else
7483                         one->support = 1;
7484                 break;
7485         }
7486
7487         ctl_set_success(ctsio);
7488         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7489         ctsio->be_move_done = ctl_config_move_done;
7490         ctl_datamove((union ctl_io *)ctsio);
7491         return(retval);
7492 }
7493
7494 int
7495 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7496 {
7497         struct scsi_report_supported_tmf *cdb;
7498         struct scsi_report_supported_tmf_data *data;
7499         int retval;
7500         int alloc_len, total_len;
7501
7502         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7503
7504         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7505
7506         retval = CTL_RETVAL_COMPLETE;
7507
7508         total_len = sizeof(struct scsi_report_supported_tmf_data);
7509         alloc_len = scsi_4btoul(cdb->length);
7510
7511         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7512
7513         ctsio->kern_sg_entries = 0;
7514
7515         if (total_len < alloc_len) {
7516                 ctsio->residual = alloc_len - total_len;
7517                 ctsio->kern_data_len = total_len;
7518                 ctsio->kern_total_len = total_len;
7519         } else {
7520                 ctsio->residual = 0;
7521                 ctsio->kern_data_len = alloc_len;
7522                 ctsio->kern_total_len = alloc_len;
7523         }
7524         ctsio->kern_data_resid = 0;
7525         ctsio->kern_rel_offset = 0;
7526
7527         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7528         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7529             RST_TRS;
7530         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7531
7532         ctl_set_success(ctsio);
7533         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7534         ctsio->be_move_done = ctl_config_move_done;
7535         ctl_datamove((union ctl_io *)ctsio);
7536         return (retval);
7537 }
7538
7539 int
7540 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7541 {
7542         struct scsi_report_timestamp *cdb;
7543         struct scsi_report_timestamp_data *data;
7544         struct timeval tv;
7545         int64_t timestamp;
7546         int retval;
7547         int alloc_len, total_len;
7548
7549         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7550
7551         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7552
7553         retval = CTL_RETVAL_COMPLETE;
7554
7555         total_len = sizeof(struct scsi_report_timestamp_data);
7556         alloc_len = scsi_4btoul(cdb->length);
7557
7558         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7559
7560         ctsio->kern_sg_entries = 0;
7561
7562         if (total_len < alloc_len) {
7563                 ctsio->residual = alloc_len - total_len;
7564                 ctsio->kern_data_len = total_len;
7565                 ctsio->kern_total_len = total_len;
7566         } else {
7567                 ctsio->residual = 0;
7568                 ctsio->kern_data_len = alloc_len;
7569                 ctsio->kern_total_len = alloc_len;
7570         }
7571         ctsio->kern_data_resid = 0;
7572         ctsio->kern_rel_offset = 0;
7573
7574         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7575         scsi_ulto2b(sizeof(*data) - 2, data->length);
7576         data->origin = RTS_ORIG_OUTSIDE;
7577         getmicrotime(&tv);
7578         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7579         scsi_ulto4b(timestamp >> 16, data->timestamp);
7580         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7581
7582         ctl_set_success(ctsio);
7583         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7584         ctsio->be_move_done = ctl_config_move_done;
7585         ctl_datamove((union ctl_io *)ctsio);
7586         return (retval);
7587 }
7588
7589 int
7590 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7591 {
7592         struct scsi_per_res_in *cdb;
7593         int alloc_len, total_len = 0;
7594         /* struct scsi_per_res_in_rsrv in_data; */
7595         struct ctl_lun *lun;
7596         struct ctl_softc *softc;
7597         uint64_t key;
7598
7599         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7600
7601         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7602
7603         alloc_len = scsi_2btoul(cdb->length);
7604
7605         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7606         softc = lun->ctl_softc;
7607
7608 retry:
7609         mtx_lock(&lun->lun_lock);
7610         switch (cdb->action) {
7611         case SPRI_RK: /* read keys */
7612                 total_len = sizeof(struct scsi_per_res_in_keys) +
7613                         lun->pr_key_count *
7614                         sizeof(struct scsi_per_res_key);
7615                 break;
7616         case SPRI_RR: /* read reservation */
7617                 if (lun->flags & CTL_LUN_PR_RESERVED)
7618                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7619                 else
7620                         total_len = sizeof(struct scsi_per_res_in_header);
7621                 break;
7622         case SPRI_RC: /* report capabilities */
7623                 total_len = sizeof(struct scsi_per_res_cap);
7624                 break;
7625         case SPRI_RS: /* read full status */
7626                 total_len = sizeof(struct scsi_per_res_in_header) +
7627                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7628                     lun->pr_key_count;
7629                 break;
7630         default:
7631                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7632         }
7633         mtx_unlock(&lun->lun_lock);
7634
7635         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7636
7637         if (total_len < alloc_len) {
7638                 ctsio->residual = alloc_len - total_len;
7639                 ctsio->kern_data_len = total_len;
7640                 ctsio->kern_total_len = total_len;
7641         } else {
7642                 ctsio->residual = 0;
7643                 ctsio->kern_data_len = alloc_len;
7644                 ctsio->kern_total_len = alloc_len;
7645         }
7646
7647         ctsio->kern_data_resid = 0;
7648         ctsio->kern_rel_offset = 0;
7649         ctsio->kern_sg_entries = 0;
7650
7651         mtx_lock(&lun->lun_lock);
7652         switch (cdb->action) {
7653         case SPRI_RK: { // read keys
7654         struct scsi_per_res_in_keys *res_keys;
7655                 int i, key_count;
7656
7657                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7658
7659                 /*
7660                  * We had to drop the lock to allocate our buffer, which
7661                  * leaves time for someone to come in with another
7662                  * persistent reservation.  (That is unlikely, though,
7663                  * since this should be the only persistent reservation
7664                  * command active right now.)
7665                  */
7666                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7667                     (lun->pr_key_count *
7668                      sizeof(struct scsi_per_res_key)))){
7669                         mtx_unlock(&lun->lun_lock);
7670                         free(ctsio->kern_data_ptr, M_CTL);
7671                         printf("%s: reservation length changed, retrying\n",
7672                                __func__);
7673                         goto retry;
7674                 }
7675
7676                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7677
7678                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7679                              lun->pr_key_count, res_keys->header.length);
7680
7681                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7682                         if ((key = ctl_get_prkey(lun, i)) == 0)
7683                                 continue;
7684
7685                         /*
7686                          * We used lun->pr_key_count to calculate the
7687                          * size to allocate.  If it turns out the number of
7688                          * initiators with the registered flag set is
7689                          * larger than that (i.e. they haven't been kept in
7690                          * sync), we've got a problem.
7691                          */
7692                         if (key_count >= lun->pr_key_count) {
7693                                 key_count++;
7694                                 continue;
7695                         }
7696                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7697                         key_count++;
7698                 }
7699                 break;
7700         }
7701         case SPRI_RR: { // read reservation
7702                 struct scsi_per_res_in_rsrv *res;
7703                 int tmp_len, header_only;
7704
7705                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7706
7707                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7708
7709                 if (lun->flags & CTL_LUN_PR_RESERVED)
7710                 {
7711                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7712                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7713                                     res->header.length);
7714                         header_only = 0;
7715                 } else {
7716                         tmp_len = sizeof(struct scsi_per_res_in_header);
7717                         scsi_ulto4b(0, res->header.length);
7718                         header_only = 1;
7719                 }
7720
7721                 /*
7722                  * We had to drop the lock to allocate our buffer, which
7723                  * leaves time for someone to come in with another
7724                  * persistent reservation.  (That is unlikely, though,
7725                  * since this should be the only persistent reservation
7726                  * command active right now.)
7727                  */
7728                 if (tmp_len != total_len) {
7729                         mtx_unlock(&lun->lun_lock);
7730                         free(ctsio->kern_data_ptr, M_CTL);
7731                         printf("%s: reservation status changed, retrying\n",
7732                                __func__);
7733                         goto retry;
7734                 }
7735
7736                 /*
7737                  * No reservation held, so we're done.
7738                  */
7739                 if (header_only != 0)
7740                         break;
7741
7742                 /*
7743                  * If the registration is an All Registrants type, the key
7744                  * is 0, since it doesn't really matter.
7745                  */
7746                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7747                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7748                             res->data.reservation);
7749                 }
7750                 res->data.scopetype = lun->pr_res_type;
7751                 break;
7752         }
7753         case SPRI_RC:     //report capabilities
7754         {
7755                 struct scsi_per_res_cap *res_cap;
7756                 uint16_t type_mask;
7757
7758                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7759                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7760                 res_cap->flags1 = SPRI_CRH;
7761                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7762                 type_mask = SPRI_TM_WR_EX_AR |
7763                             SPRI_TM_EX_AC_RO |
7764                             SPRI_TM_WR_EX_RO |
7765                             SPRI_TM_EX_AC |
7766                             SPRI_TM_WR_EX |
7767                             SPRI_TM_EX_AC_AR;
7768                 scsi_ulto2b(type_mask, res_cap->type_mask);
7769                 break;
7770         }
7771         case SPRI_RS: { // read full status
7772                 struct scsi_per_res_in_full *res_status;
7773                 struct scsi_per_res_in_full_desc *res_desc;
7774                 struct ctl_port *port;
7775                 int i, len;
7776
7777                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7778
7779                 /*
7780                  * We had to drop the lock to allocate our buffer, which
7781                  * leaves time for someone to come in with another
7782                  * persistent reservation.  (That is unlikely, though,
7783                  * since this should be the only persistent reservation
7784                  * command active right now.)
7785                  */
7786                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7787                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7788                      lun->pr_key_count)){
7789                         mtx_unlock(&lun->lun_lock);
7790                         free(ctsio->kern_data_ptr, M_CTL);
7791                         printf("%s: reservation length changed, retrying\n",
7792                                __func__);
7793                         goto retry;
7794                 }
7795
7796                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7797
7798                 res_desc = &res_status->desc[0];
7799                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7800                         if ((key = ctl_get_prkey(lun, i)) == 0)
7801                                 continue;
7802
7803                         scsi_u64to8b(key, res_desc->res_key.key);
7804                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7805                             (lun->pr_res_idx == i ||
7806                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7807                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7808                                 res_desc->scopetype = lun->pr_res_type;
7809                         }
7810                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7811                             res_desc->rel_trgt_port_id);
7812                         len = 0;
7813                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7814                         if (port != NULL)
7815                                 len = ctl_create_iid(port,
7816                                     i % CTL_MAX_INIT_PER_PORT,
7817                                     res_desc->transport_id);
7818                         scsi_ulto4b(len, res_desc->additional_length);
7819                         res_desc = (struct scsi_per_res_in_full_desc *)
7820                             &res_desc->transport_id[len];
7821                 }
7822                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7823                     res_status->header.length);
7824                 break;
7825         }
7826         default:
7827                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7828         }
7829         mtx_unlock(&lun->lun_lock);
7830
7831         ctl_set_success(ctsio);
7832         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7833         ctsio->be_move_done = ctl_config_move_done;
7834         ctl_datamove((union ctl_io *)ctsio);
7835         return (CTL_RETVAL_COMPLETE);
7836 }
7837
7838 /*
7839  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7840  * it should return.
7841  */
7842 static int
7843 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7844                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7845                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7846                 struct scsi_per_res_out_parms* param)
7847 {
7848         union ctl_ha_msg persis_io;
7849         int i;
7850
7851         mtx_lock(&lun->lun_lock);
7852         if (sa_res_key == 0) {
7853                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7854                         /* validate scope and type */
7855                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7856                              SPR_LU_SCOPE) {
7857                                 mtx_unlock(&lun->lun_lock);
7858                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7859                                                       /*sks_valid*/ 1,
7860                                                       /*command*/ 1,
7861                                                       /*field*/ 2,
7862                                                       /*bit_valid*/ 1,
7863                                                       /*bit*/ 4);
7864                                 ctl_done((union ctl_io *)ctsio);
7865                                 return (1);
7866                         }
7867
7868                         if (type>8 || type==2 || type==4 || type==0) {
7869                                 mtx_unlock(&lun->lun_lock);
7870                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7871                                                       /*sks_valid*/ 1,
7872                                                       /*command*/ 1,
7873                                                       /*field*/ 2,
7874                                                       /*bit_valid*/ 1,
7875                                                       /*bit*/ 0);
7876                                 ctl_done((union ctl_io *)ctsio);
7877                                 return (1);
7878                         }
7879
7880                         /*
7881                          * Unregister everybody else and build UA for
7882                          * them
7883                          */
7884                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7885                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7886                                         continue;
7887
7888                                 ctl_clr_prkey(lun, i);
7889                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7890                         }
7891                         lun->pr_key_count = 1;
7892                         lun->pr_res_type = type;
7893                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7894                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7895                                 lun->pr_res_idx = residx;
7896                         lun->pr_generation++;
7897                         mtx_unlock(&lun->lun_lock);
7898
7899                         /* send msg to other side */
7900                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7901                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7902                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7903                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7904                         persis_io.pr.pr_info.res_type = type;
7905                         memcpy(persis_io.pr.pr_info.sa_res_key,
7906                                param->serv_act_res_key,
7907                                sizeof(param->serv_act_res_key));
7908                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7909                             sizeof(persis_io.pr), M_WAITOK);
7910                 } else {
7911                         /* not all registrants */
7912                         mtx_unlock(&lun->lun_lock);
7913                         free(ctsio->kern_data_ptr, M_CTL);
7914                         ctl_set_invalid_field(ctsio,
7915                                               /*sks_valid*/ 1,
7916                                               /*command*/ 0,
7917                                               /*field*/ 8,
7918                                               /*bit_valid*/ 0,
7919                                               /*bit*/ 0);
7920                         ctl_done((union ctl_io *)ctsio);
7921                         return (1);
7922                 }
7923         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7924                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7925                 int found = 0;
7926
7927                 if (res_key == sa_res_key) {
7928                         /* special case */
7929                         /*
7930                          * The spec implies this is not good but doesn't
7931                          * say what to do. There are two choices either
7932                          * generate a res conflict or check condition
7933                          * with illegal field in parameter data. Since
7934                          * that is what is done when the sa_res_key is
7935                          * zero I'll take that approach since this has
7936                          * to do with the sa_res_key.
7937                          */
7938                         mtx_unlock(&lun->lun_lock);
7939                         free(ctsio->kern_data_ptr, M_CTL);
7940                         ctl_set_invalid_field(ctsio,
7941                                               /*sks_valid*/ 1,
7942                                               /*command*/ 0,
7943                                               /*field*/ 8,
7944                                               /*bit_valid*/ 0,
7945                                               /*bit*/ 0);
7946                         ctl_done((union ctl_io *)ctsio);
7947                         return (1);
7948                 }
7949
7950                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7951                         if (ctl_get_prkey(lun, i) != sa_res_key)
7952                                 continue;
7953
7954                         found = 1;
7955                         ctl_clr_prkey(lun, i);
7956                         lun->pr_key_count--;
7957                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7958                 }
7959                 if (!found) {
7960                         mtx_unlock(&lun->lun_lock);
7961                         free(ctsio->kern_data_ptr, M_CTL);
7962                         ctl_set_reservation_conflict(ctsio);
7963                         ctl_done((union ctl_io *)ctsio);
7964                         return (CTL_RETVAL_COMPLETE);
7965                 }
7966                 lun->pr_generation++;
7967                 mtx_unlock(&lun->lun_lock);
7968
7969                 /* send msg to other side */
7970                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7971                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7972                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7973                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7974                 persis_io.pr.pr_info.res_type = type;
7975                 memcpy(persis_io.pr.pr_info.sa_res_key,
7976                        param->serv_act_res_key,
7977                        sizeof(param->serv_act_res_key));
7978                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7979                     sizeof(persis_io.pr), M_WAITOK);
7980         } else {
7981                 /* Reserved but not all registrants */
7982                 /* sa_res_key is res holder */
7983                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7984                         /* validate scope and type */
7985                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7986                              SPR_LU_SCOPE) {
7987                                 mtx_unlock(&lun->lun_lock);
7988                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7989                                                       /*sks_valid*/ 1,
7990                                                       /*command*/ 1,
7991                                                       /*field*/ 2,
7992                                                       /*bit_valid*/ 1,
7993                                                       /*bit*/ 4);
7994                                 ctl_done((union ctl_io *)ctsio);
7995                                 return (1);
7996                         }
7997
7998                         if (type>8 || type==2 || type==4 || type==0) {
7999                                 mtx_unlock(&lun->lun_lock);
8000                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8001                                                       /*sks_valid*/ 1,
8002                                                       /*command*/ 1,
8003                                                       /*field*/ 2,
8004                                                       /*bit_valid*/ 1,
8005                                                       /*bit*/ 0);
8006                                 ctl_done((union ctl_io *)ctsio);
8007                                 return (1);
8008                         }
8009
8010                         /*
8011                          * Do the following:
8012                          * if sa_res_key != res_key remove all
8013                          * registrants w/sa_res_key and generate UA
8014                          * for these registrants(Registrations
8015                          * Preempted) if it wasn't an exclusive
8016                          * reservation generate UA(Reservations
8017                          * Preempted) for all other registered nexuses
8018                          * if the type has changed. Establish the new
8019                          * reservation and holder. If res_key and
8020                          * sa_res_key are the same do the above
8021                          * except don't unregister the res holder.
8022                          */
8023
8024                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8025                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8026                                         continue;
8027
8028                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8029                                         ctl_clr_prkey(lun, i);
8030                                         lun->pr_key_count--;
8031                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8032                                 } else if (type != lun->pr_res_type &&
8033                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8034                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8035                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8036                                 }
8037                         }
8038                         lun->pr_res_type = type;
8039                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8040                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8041                                 lun->pr_res_idx = residx;
8042                         else
8043                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8044                         lun->pr_generation++;
8045                         mtx_unlock(&lun->lun_lock);
8046
8047                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8048                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8049                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8050                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8051                         persis_io.pr.pr_info.res_type = type;
8052                         memcpy(persis_io.pr.pr_info.sa_res_key,
8053                                param->serv_act_res_key,
8054                                sizeof(param->serv_act_res_key));
8055                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8056                             sizeof(persis_io.pr), M_WAITOK);
8057                 } else {
8058                         /*
8059                          * sa_res_key is not the res holder just
8060                          * remove registrants
8061                          */
8062                         int found=0;
8063
8064                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8065                                 if (sa_res_key != ctl_get_prkey(lun, i))
8066                                         continue;
8067
8068                                 found = 1;
8069                                 ctl_clr_prkey(lun, i);
8070                                 lun->pr_key_count--;
8071                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8072                         }
8073
8074                         if (!found) {
8075                                 mtx_unlock(&lun->lun_lock);
8076                                 free(ctsio->kern_data_ptr, M_CTL);
8077                                 ctl_set_reservation_conflict(ctsio);
8078                                 ctl_done((union ctl_io *)ctsio);
8079                                 return (1);
8080                         }
8081                         lun->pr_generation++;
8082                         mtx_unlock(&lun->lun_lock);
8083
8084                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8085                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8086                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8087                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8088                         persis_io.pr.pr_info.res_type = type;
8089                         memcpy(persis_io.pr.pr_info.sa_res_key,
8090                                param->serv_act_res_key,
8091                                sizeof(param->serv_act_res_key));
8092                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8093                             sizeof(persis_io.pr), M_WAITOK);
8094                 }
8095         }
8096         return (0);
8097 }
8098
8099 static void
8100 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8101 {
8102         uint64_t sa_res_key;
8103         int i;
8104
8105         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8106
8107         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8108          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8109          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8110                 if (sa_res_key == 0) {
8111                         /*
8112                          * Unregister everybody else and build UA for
8113                          * them
8114                          */
8115                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8116                                 if (i == msg->pr.pr_info.residx ||
8117                                     ctl_get_prkey(lun, i) == 0)
8118                                         continue;
8119
8120                                 ctl_clr_prkey(lun, i);
8121                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8122                         }
8123
8124                         lun->pr_key_count = 1;
8125                         lun->pr_res_type = msg->pr.pr_info.res_type;
8126                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8127                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8128                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8129                 } else {
8130                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8131                                 if (sa_res_key == ctl_get_prkey(lun, i))
8132                                         continue;
8133
8134                                 ctl_clr_prkey(lun, i);
8135                                 lun->pr_key_count--;
8136                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8137                         }
8138                 }
8139         } else {
8140                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8141                         if (i == msg->pr.pr_info.residx ||
8142                             ctl_get_prkey(lun, i) == 0)
8143                                 continue;
8144
8145                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8146                                 ctl_clr_prkey(lun, i);
8147                                 lun->pr_key_count--;
8148                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8149                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8150                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8151                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8152                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8153                         }
8154                 }
8155                 lun->pr_res_type = msg->pr.pr_info.res_type;
8156                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8157                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8158                         lun->pr_res_idx = msg->pr.pr_info.residx;
8159                 else
8160                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8161         }
8162         lun->pr_generation++;
8163
8164 }
8165
8166
8167 int
8168 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8169 {
8170         int retval;
8171         u_int32_t param_len;
8172         struct scsi_per_res_out *cdb;
8173         struct ctl_lun *lun;
8174         struct scsi_per_res_out_parms* param;
8175         struct ctl_softc *softc;
8176         uint32_t residx;
8177         uint64_t res_key, sa_res_key, key;
8178         uint8_t type;
8179         union ctl_ha_msg persis_io;
8180         int    i;
8181
8182         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8183
8184         retval = CTL_RETVAL_COMPLETE;
8185
8186         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8187         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8188         softc = lun->ctl_softc;
8189
8190         /*
8191          * We only support whole-LUN scope.  The scope & type are ignored for
8192          * register, register and ignore existing key and clear.
8193          * We sometimes ignore scope and type on preempts too!!
8194          * Verify reservation type here as well.
8195          */
8196         type = cdb->scope_type & SPR_TYPE_MASK;
8197         if ((cdb->action == SPRO_RESERVE)
8198          || (cdb->action == SPRO_RELEASE)) {
8199                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8200                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8201                                               /*sks_valid*/ 1,
8202                                               /*command*/ 1,
8203                                               /*field*/ 2,
8204                                               /*bit_valid*/ 1,
8205                                               /*bit*/ 4);
8206                         ctl_done((union ctl_io *)ctsio);
8207                         return (CTL_RETVAL_COMPLETE);
8208                 }
8209
8210                 if (type>8 || type==2 || type==4 || type==0) {
8211                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8212                                               /*sks_valid*/ 1,
8213                                               /*command*/ 1,
8214                                               /*field*/ 2,
8215                                               /*bit_valid*/ 1,
8216                                               /*bit*/ 0);
8217                         ctl_done((union ctl_io *)ctsio);
8218                         return (CTL_RETVAL_COMPLETE);
8219                 }
8220         }
8221
8222         param_len = scsi_4btoul(cdb->length);
8223
8224         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8225                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8226                 ctsio->kern_data_len = param_len;
8227                 ctsio->kern_total_len = param_len;
8228                 ctsio->kern_data_resid = 0;
8229                 ctsio->kern_rel_offset = 0;
8230                 ctsio->kern_sg_entries = 0;
8231                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8232                 ctsio->be_move_done = ctl_config_move_done;
8233                 ctl_datamove((union ctl_io *)ctsio);
8234
8235                 return (CTL_RETVAL_COMPLETE);
8236         }
8237
8238         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8239
8240         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8241         res_key = scsi_8btou64(param->res_key.key);
8242         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8243
8244         /*
8245          * Validate the reservation key here except for SPRO_REG_IGNO
8246          * This must be done for all other service actions
8247          */
8248         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8249                 mtx_lock(&lun->lun_lock);
8250                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8251                         if (res_key != key) {
8252                                 /*
8253                                  * The current key passed in doesn't match
8254                                  * the one the initiator previously
8255                                  * registered.
8256                                  */
8257                                 mtx_unlock(&lun->lun_lock);
8258                                 free(ctsio->kern_data_ptr, M_CTL);
8259                                 ctl_set_reservation_conflict(ctsio);
8260                                 ctl_done((union ctl_io *)ctsio);
8261                                 return (CTL_RETVAL_COMPLETE);
8262                         }
8263                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8264                         /*
8265                          * We are not registered
8266                          */
8267                         mtx_unlock(&lun->lun_lock);
8268                         free(ctsio->kern_data_ptr, M_CTL);
8269                         ctl_set_reservation_conflict(ctsio);
8270                         ctl_done((union ctl_io *)ctsio);
8271                         return (CTL_RETVAL_COMPLETE);
8272                 } else if (res_key != 0) {
8273                         /*
8274                          * We are not registered and trying to register but
8275                          * the register key isn't zero.
8276                          */
8277                         mtx_unlock(&lun->lun_lock);
8278                         free(ctsio->kern_data_ptr, M_CTL);
8279                         ctl_set_reservation_conflict(ctsio);
8280                         ctl_done((union ctl_io *)ctsio);
8281                         return (CTL_RETVAL_COMPLETE);
8282                 }
8283                 mtx_unlock(&lun->lun_lock);
8284         }
8285
8286         switch (cdb->action & SPRO_ACTION_MASK) {
8287         case SPRO_REGISTER:
8288         case SPRO_REG_IGNO: {
8289
8290 #if 0
8291                 printf("Registration received\n");
8292 #endif
8293
8294                 /*
8295                  * We don't support any of these options, as we report in
8296                  * the read capabilities request (see
8297                  * ctl_persistent_reserve_in(), above).
8298                  */
8299                 if ((param->flags & SPR_SPEC_I_PT)
8300                  || (param->flags & SPR_ALL_TG_PT)
8301                  || (param->flags & SPR_APTPL)) {
8302                         int bit_ptr;
8303
8304                         if (param->flags & SPR_APTPL)
8305                                 bit_ptr = 0;
8306                         else if (param->flags & SPR_ALL_TG_PT)
8307                                 bit_ptr = 2;
8308                         else /* SPR_SPEC_I_PT */
8309                                 bit_ptr = 3;
8310
8311                         free(ctsio->kern_data_ptr, M_CTL);
8312                         ctl_set_invalid_field(ctsio,
8313                                               /*sks_valid*/ 1,
8314                                               /*command*/ 0,
8315                                               /*field*/ 20,
8316                                               /*bit_valid*/ 1,
8317                                               /*bit*/ bit_ptr);
8318                         ctl_done((union ctl_io *)ctsio);
8319                         return (CTL_RETVAL_COMPLETE);
8320                 }
8321
8322                 mtx_lock(&lun->lun_lock);
8323
8324                 /*
8325                  * The initiator wants to clear the
8326                  * key/unregister.
8327                  */
8328                 if (sa_res_key == 0) {
8329                         if ((res_key == 0
8330                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8331                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8332                           && ctl_get_prkey(lun, residx) == 0)) {
8333                                 mtx_unlock(&lun->lun_lock);
8334                                 goto done;
8335                         }
8336
8337                         ctl_clr_prkey(lun, residx);
8338                         lun->pr_key_count--;
8339
8340                         if (residx == lun->pr_res_idx) {
8341                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8342                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8343
8344                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8345                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8346                                     lun->pr_key_count) {
8347                                         /*
8348                                          * If the reservation is a registrants
8349                                          * only type we need to generate a UA
8350                                          * for other registered inits.  The
8351                                          * sense code should be RESERVATIONS
8352                                          * RELEASED
8353                                          */
8354
8355                                         for (i = softc->init_min; i < softc->init_max; i++){
8356                                                 if (ctl_get_prkey(lun, i) == 0)
8357                                                         continue;
8358                                                 ctl_est_ua(lun, i,
8359                                                     CTL_UA_RES_RELEASE);
8360                                         }
8361                                 }
8362                                 lun->pr_res_type = 0;
8363                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8364                                 if (lun->pr_key_count==0) {
8365                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8366                                         lun->pr_res_type = 0;
8367                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8368                                 }
8369                         }
8370                         lun->pr_generation++;
8371                         mtx_unlock(&lun->lun_lock);
8372
8373                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8374                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8375                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8376                         persis_io.pr.pr_info.residx = residx;
8377                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8378                             sizeof(persis_io.pr), M_WAITOK);
8379                 } else /* sa_res_key != 0 */ {
8380
8381                         /*
8382                          * If we aren't registered currently then increment
8383                          * the key count and set the registered flag.
8384                          */
8385                         ctl_alloc_prkey(lun, residx);
8386                         if (ctl_get_prkey(lun, residx) == 0)
8387                                 lun->pr_key_count++;
8388                         ctl_set_prkey(lun, residx, sa_res_key);
8389                         lun->pr_generation++;
8390                         mtx_unlock(&lun->lun_lock);
8391
8392                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8393                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8394                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8395                         persis_io.pr.pr_info.residx = residx;
8396                         memcpy(persis_io.pr.pr_info.sa_res_key,
8397                                param->serv_act_res_key,
8398                                sizeof(param->serv_act_res_key));
8399                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8400                             sizeof(persis_io.pr), M_WAITOK);
8401                 }
8402
8403                 break;
8404         }
8405         case SPRO_RESERVE:
8406 #if 0
8407                 printf("Reserve executed type %d\n", type);
8408 #endif
8409                 mtx_lock(&lun->lun_lock);
8410                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8411                         /*
8412                          * if this isn't the reservation holder and it's
8413                          * not a "all registrants" type or if the type is
8414                          * different then we have a conflict
8415                          */
8416                         if ((lun->pr_res_idx != residx
8417                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8418                          || lun->pr_res_type != type) {
8419                                 mtx_unlock(&lun->lun_lock);
8420                                 free(ctsio->kern_data_ptr, M_CTL);
8421                                 ctl_set_reservation_conflict(ctsio);
8422                                 ctl_done((union ctl_io *)ctsio);
8423                                 return (CTL_RETVAL_COMPLETE);
8424                         }
8425                         mtx_unlock(&lun->lun_lock);
8426                 } else /* create a reservation */ {
8427                         /*
8428                          * If it's not an "all registrants" type record
8429                          * reservation holder
8430                          */
8431                         if (type != SPR_TYPE_WR_EX_AR
8432                          && type != SPR_TYPE_EX_AC_AR)
8433                                 lun->pr_res_idx = residx; /* Res holder */
8434                         else
8435                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8436
8437                         lun->flags |= CTL_LUN_PR_RESERVED;
8438                         lun->pr_res_type = type;
8439
8440                         mtx_unlock(&lun->lun_lock);
8441
8442                         /* send msg to other side */
8443                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8444                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8445                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8446                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8447                         persis_io.pr.pr_info.res_type = type;
8448                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8449                             sizeof(persis_io.pr), M_WAITOK);
8450                 }
8451                 break;
8452
8453         case SPRO_RELEASE:
8454                 mtx_lock(&lun->lun_lock);
8455                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8456                         /* No reservation exists return good status */
8457                         mtx_unlock(&lun->lun_lock);
8458                         goto done;
8459                 }
8460                 /*
8461                  * Is this nexus a reservation holder?
8462                  */
8463                 if (lun->pr_res_idx != residx
8464                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8465                         /*
8466                          * not a res holder return good status but
8467                          * do nothing
8468                          */
8469                         mtx_unlock(&lun->lun_lock);
8470                         goto done;
8471                 }
8472
8473                 if (lun->pr_res_type != type) {
8474                         mtx_unlock(&lun->lun_lock);
8475                         free(ctsio->kern_data_ptr, M_CTL);
8476                         ctl_set_illegal_pr_release(ctsio);
8477                         ctl_done((union ctl_io *)ctsio);
8478                         return (CTL_RETVAL_COMPLETE);
8479                 }
8480
8481                 /* okay to release */
8482                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8483                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8484                 lun->pr_res_type = 0;
8485
8486                 /*
8487                  * if this isn't an exclusive access
8488                  * res generate UA for all other
8489                  * registrants.
8490                  */
8491                 if (type != SPR_TYPE_EX_AC
8492                  && type != SPR_TYPE_WR_EX) {
8493                         for (i = softc->init_min; i < softc->init_max; i++) {
8494                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8495                                         continue;
8496                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8497                         }
8498                 }
8499                 mtx_unlock(&lun->lun_lock);
8500
8501                 /* Send msg to other side */
8502                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8503                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8504                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8505                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8506                      sizeof(persis_io.pr), M_WAITOK);
8507                 break;
8508
8509         case SPRO_CLEAR:
8510                 /* send msg to other side */
8511
8512                 mtx_lock(&lun->lun_lock);
8513                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8514                 lun->pr_res_type = 0;
8515                 lun->pr_key_count = 0;
8516                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8517
8518                 ctl_clr_prkey(lun, residx);
8519                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8520                         if (ctl_get_prkey(lun, i) != 0) {
8521                                 ctl_clr_prkey(lun, i);
8522                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8523                         }
8524                 lun->pr_generation++;
8525                 mtx_unlock(&lun->lun_lock);
8526
8527                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8528                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8529                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8530                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8531                      sizeof(persis_io.pr), M_WAITOK);
8532                 break;
8533
8534         case SPRO_PREEMPT:
8535         case SPRO_PRE_ABO: {
8536                 int nretval;
8537
8538                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8539                                           residx, ctsio, cdb, param);
8540                 if (nretval != 0)
8541                         return (CTL_RETVAL_COMPLETE);
8542                 break;
8543         }
8544         default:
8545                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8546         }
8547
8548 done:
8549         free(ctsio->kern_data_ptr, M_CTL);
8550         ctl_set_success(ctsio);
8551         ctl_done((union ctl_io *)ctsio);
8552
8553         return (retval);
8554 }
8555
8556 /*
8557  * This routine is for handling a message from the other SC pertaining to
8558  * persistent reserve out. All the error checking will have been done
8559  * so only perorming the action need be done here to keep the two
8560  * in sync.
8561  */
8562 static void
8563 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8564 {
8565         struct ctl_softc *softc = control_softc;
8566         struct ctl_lun *lun;
8567         int i;
8568         uint32_t residx, targ_lun;
8569
8570         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8571         mtx_lock(&softc->ctl_lock);
8572         if ((targ_lun >= CTL_MAX_LUNS) ||
8573             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8574                 mtx_unlock(&softc->ctl_lock);
8575                 return;
8576         }
8577         mtx_lock(&lun->lun_lock);
8578         mtx_unlock(&softc->ctl_lock);
8579         if (lun->flags & CTL_LUN_DISABLED) {
8580                 mtx_unlock(&lun->lun_lock);
8581                 return;
8582         }
8583         residx = ctl_get_initindex(&msg->hdr.nexus);
8584         switch(msg->pr.pr_info.action) {
8585         case CTL_PR_REG_KEY:
8586                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8587                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8588                         lun->pr_key_count++;
8589                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8590                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8591                 lun->pr_generation++;
8592                 break;
8593
8594         case CTL_PR_UNREG_KEY:
8595                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8596                 lun->pr_key_count--;
8597
8598                 /* XXX Need to see if the reservation has been released */
8599                 /* if so do we need to generate UA? */
8600                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8601                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8602                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8603
8604                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8605                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8606                             lun->pr_key_count) {
8607                                 /*
8608                                  * If the reservation is a registrants
8609                                  * only type we need to generate a UA
8610                                  * for other registered inits.  The
8611                                  * sense code should be RESERVATIONS
8612                                  * RELEASED
8613                                  */
8614
8615                                 for (i = softc->init_min; i < softc->init_max; i++) {
8616                                         if (ctl_get_prkey(lun, i) == 0)
8617                                                 continue;
8618
8619                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8620                                 }
8621                         }
8622                         lun->pr_res_type = 0;
8623                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8624                         if (lun->pr_key_count==0) {
8625                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8626                                 lun->pr_res_type = 0;
8627                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8628                         }
8629                 }
8630                 lun->pr_generation++;
8631                 break;
8632
8633         case CTL_PR_RESERVE:
8634                 lun->flags |= CTL_LUN_PR_RESERVED;
8635                 lun->pr_res_type = msg->pr.pr_info.res_type;
8636                 lun->pr_res_idx = msg->pr.pr_info.residx;
8637
8638                 break;
8639
8640         case CTL_PR_RELEASE:
8641                 /*
8642                  * if this isn't an exclusive access res generate UA for all
8643                  * other registrants.
8644                  */
8645                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8646                     lun->pr_res_type != SPR_TYPE_WR_EX) {
8647                         for (i = softc->init_min; i < softc->init_max; i++)
8648                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8649                                         continue;
8650                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8651                 }
8652
8653                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8654                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8655                 lun->pr_res_type = 0;
8656                 break;
8657
8658         case CTL_PR_PREEMPT:
8659                 ctl_pro_preempt_other(lun, msg);
8660                 break;
8661         case CTL_PR_CLEAR:
8662                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8663                 lun->pr_res_type = 0;
8664                 lun->pr_key_count = 0;
8665                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8666
8667                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8668                         if (ctl_get_prkey(lun, i) == 0)
8669                                 continue;
8670                         ctl_clr_prkey(lun, i);
8671                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8672                 }
8673                 lun->pr_generation++;
8674                 break;
8675         }
8676
8677         mtx_unlock(&lun->lun_lock);
8678 }
8679
8680 int
8681 ctl_read_write(struct ctl_scsiio *ctsio)
8682 {
8683         struct ctl_lun *lun;
8684         struct ctl_lba_len_flags *lbalen;
8685         uint64_t lba;
8686         uint32_t num_blocks;
8687         int flags, retval;
8688         int isread;
8689
8690         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8691
8692         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8693
8694         flags = 0;
8695         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8696               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8697         switch (ctsio->cdb[0]) {
8698         case READ_6:
8699         case WRITE_6: {
8700                 struct scsi_rw_6 *cdb;
8701
8702                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8703
8704                 lba = scsi_3btoul(cdb->addr);
8705                 /* only 5 bits are valid in the most significant address byte */
8706                 lba &= 0x1fffff;
8707                 num_blocks = cdb->length;
8708                 /*
8709                  * This is correct according to SBC-2.
8710                  */
8711                 if (num_blocks == 0)
8712                         num_blocks = 256;
8713                 break;
8714         }
8715         case READ_10:
8716         case WRITE_10: {
8717                 struct scsi_rw_10 *cdb;
8718
8719                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8720                 if (cdb->byte2 & SRW10_FUA)
8721                         flags |= CTL_LLF_FUA;
8722                 if (cdb->byte2 & SRW10_DPO)
8723                         flags |= CTL_LLF_DPO;
8724                 lba = scsi_4btoul(cdb->addr);
8725                 num_blocks = scsi_2btoul(cdb->length);
8726                 break;
8727         }
8728         case WRITE_VERIFY_10: {
8729                 struct scsi_write_verify_10 *cdb;
8730
8731                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8732                 flags |= CTL_LLF_FUA;
8733                 if (cdb->byte2 & SWV_DPO)
8734                         flags |= CTL_LLF_DPO;
8735                 lba = scsi_4btoul(cdb->addr);
8736                 num_blocks = scsi_2btoul(cdb->length);
8737                 break;
8738         }
8739         case READ_12:
8740         case WRITE_12: {
8741                 struct scsi_rw_12 *cdb;
8742
8743                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8744                 if (cdb->byte2 & SRW12_FUA)
8745                         flags |= CTL_LLF_FUA;
8746                 if (cdb->byte2 & SRW12_DPO)
8747                         flags |= CTL_LLF_DPO;
8748                 lba = scsi_4btoul(cdb->addr);
8749                 num_blocks = scsi_4btoul(cdb->length);
8750                 break;
8751         }
8752         case WRITE_VERIFY_12: {
8753                 struct scsi_write_verify_12 *cdb;
8754
8755                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8756                 flags |= CTL_LLF_FUA;
8757                 if (cdb->byte2 & SWV_DPO)
8758                         flags |= CTL_LLF_DPO;
8759                 lba = scsi_4btoul(cdb->addr);
8760                 num_blocks = scsi_4btoul(cdb->length);
8761                 break;
8762         }
8763         case READ_16:
8764         case WRITE_16: {
8765                 struct scsi_rw_16 *cdb;
8766
8767                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8768                 if (cdb->byte2 & SRW12_FUA)
8769                         flags |= CTL_LLF_FUA;
8770                 if (cdb->byte2 & SRW12_DPO)
8771                         flags |= CTL_LLF_DPO;
8772                 lba = scsi_8btou64(cdb->addr);
8773                 num_blocks = scsi_4btoul(cdb->length);
8774                 break;
8775         }
8776         case WRITE_ATOMIC_16: {
8777                 struct scsi_write_atomic_16 *cdb;
8778
8779                 if (lun->be_lun->atomicblock == 0) {
8780                         ctl_set_invalid_opcode(ctsio);
8781                         ctl_done((union ctl_io *)ctsio);
8782                         return (CTL_RETVAL_COMPLETE);
8783                 }
8784
8785                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8786                 if (cdb->byte2 & SRW12_FUA)
8787                         flags |= CTL_LLF_FUA;
8788                 if (cdb->byte2 & SRW12_DPO)
8789                         flags |= CTL_LLF_DPO;
8790                 lba = scsi_8btou64(cdb->addr);
8791                 num_blocks = scsi_2btoul(cdb->length);
8792                 if (num_blocks > lun->be_lun->atomicblock) {
8793                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8794                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8795                             /*bit*/ 0);
8796                         ctl_done((union ctl_io *)ctsio);
8797                         return (CTL_RETVAL_COMPLETE);
8798                 }
8799                 break;
8800         }
8801         case WRITE_VERIFY_16: {
8802                 struct scsi_write_verify_16 *cdb;
8803
8804                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8805                 flags |= CTL_LLF_FUA;
8806                 if (cdb->byte2 & SWV_DPO)
8807                         flags |= CTL_LLF_DPO;
8808                 lba = scsi_8btou64(cdb->addr);
8809                 num_blocks = scsi_4btoul(cdb->length);
8810                 break;
8811         }
8812         default:
8813                 /*
8814                  * We got a command we don't support.  This shouldn't
8815                  * happen, commands should be filtered out above us.
8816                  */
8817                 ctl_set_invalid_opcode(ctsio);
8818                 ctl_done((union ctl_io *)ctsio);
8819
8820                 return (CTL_RETVAL_COMPLETE);
8821                 break; /* NOTREACHED */
8822         }
8823
8824         /*
8825          * The first check is to make sure we're in bounds, the second
8826          * check is to catch wrap-around problems.  If the lba + num blocks
8827          * is less than the lba, then we've wrapped around and the block
8828          * range is invalid anyway.
8829          */
8830         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8831          || ((lba + num_blocks) < lba)) {
8832                 ctl_set_lba_out_of_range(ctsio);
8833                 ctl_done((union ctl_io *)ctsio);
8834                 return (CTL_RETVAL_COMPLETE);
8835         }
8836
8837         /*
8838          * According to SBC-3, a transfer length of 0 is not an error.
8839          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8840          * translates to 256 blocks for those commands.
8841          */
8842         if (num_blocks == 0) {
8843                 ctl_set_success(ctsio);
8844                 ctl_done((union ctl_io *)ctsio);
8845                 return (CTL_RETVAL_COMPLETE);
8846         }
8847
8848         /* Set FUA and/or DPO if caches are disabled. */
8849         if (isread) {
8850                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8851                     SCP_RCD) != 0)
8852                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8853         } else {
8854                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8855                     SCP_WCE) == 0)
8856                         flags |= CTL_LLF_FUA;
8857         }
8858
8859         lbalen = (struct ctl_lba_len_flags *)
8860             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8861         lbalen->lba = lba;
8862         lbalen->len = num_blocks;
8863         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8864
8865         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8866         ctsio->kern_rel_offset = 0;
8867
8868         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8869
8870         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8871         return (retval);
8872 }
8873
8874 static int
8875 ctl_cnw_cont(union ctl_io *io)
8876 {
8877         struct ctl_scsiio *ctsio;
8878         struct ctl_lun *lun;
8879         struct ctl_lba_len_flags *lbalen;
8880         int retval;
8881
8882         ctsio = &io->scsiio;
8883         ctsio->io_hdr.status = CTL_STATUS_NONE;
8884         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8885         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8886         lbalen = (struct ctl_lba_len_flags *)
8887             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8888         lbalen->flags &= ~CTL_LLF_COMPARE;
8889         lbalen->flags |= CTL_LLF_WRITE;
8890
8891         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8892         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8893         return (retval);
8894 }
8895
8896 int
8897 ctl_cnw(struct ctl_scsiio *ctsio)
8898 {
8899         struct ctl_lun *lun;
8900         struct ctl_lba_len_flags *lbalen;
8901         uint64_t lba;
8902         uint32_t num_blocks;
8903         int flags, retval;
8904
8905         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8906
8907         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8908
8909         flags = 0;
8910         switch (ctsio->cdb[0]) {
8911         case COMPARE_AND_WRITE: {
8912                 struct scsi_compare_and_write *cdb;
8913
8914                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8915                 if (cdb->byte2 & SRW10_FUA)
8916                         flags |= CTL_LLF_FUA;
8917                 if (cdb->byte2 & SRW10_DPO)
8918                         flags |= CTL_LLF_DPO;
8919                 lba = scsi_8btou64(cdb->addr);
8920                 num_blocks = cdb->length;
8921                 break;
8922         }
8923         default:
8924                 /*
8925                  * We got a command we don't support.  This shouldn't
8926                  * happen, commands should be filtered out above us.
8927                  */
8928                 ctl_set_invalid_opcode(ctsio);
8929                 ctl_done((union ctl_io *)ctsio);
8930
8931                 return (CTL_RETVAL_COMPLETE);
8932                 break; /* NOTREACHED */
8933         }
8934
8935         /*
8936          * The first check is to make sure we're in bounds, the second
8937          * check is to catch wrap-around problems.  If the lba + num blocks
8938          * is less than the lba, then we've wrapped around and the block
8939          * range is invalid anyway.
8940          */
8941         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8942          || ((lba + num_blocks) < lba)) {
8943                 ctl_set_lba_out_of_range(ctsio);
8944                 ctl_done((union ctl_io *)ctsio);
8945                 return (CTL_RETVAL_COMPLETE);
8946         }
8947
8948         /*
8949          * According to SBC-3, a transfer length of 0 is not an error.
8950          */
8951         if (num_blocks == 0) {
8952                 ctl_set_success(ctsio);
8953                 ctl_done((union ctl_io *)ctsio);
8954                 return (CTL_RETVAL_COMPLETE);
8955         }
8956
8957         /* Set FUA if write cache is disabled. */
8958         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8959             SCP_WCE) == 0)
8960                 flags |= CTL_LLF_FUA;
8961
8962         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8963         ctsio->kern_rel_offset = 0;
8964
8965         /*
8966          * Set the IO_CONT flag, so that if this I/O gets passed to
8967          * ctl_data_submit_done(), it'll get passed back to
8968          * ctl_ctl_cnw_cont() for further processing.
8969          */
8970         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8971         ctsio->io_cont = ctl_cnw_cont;
8972
8973         lbalen = (struct ctl_lba_len_flags *)
8974             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8975         lbalen->lba = lba;
8976         lbalen->len = num_blocks;
8977         lbalen->flags = CTL_LLF_COMPARE | flags;
8978
8979         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8980         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8981         return (retval);
8982 }
8983
8984 int
8985 ctl_verify(struct ctl_scsiio *ctsio)
8986 {
8987         struct ctl_lun *lun;
8988         struct ctl_lba_len_flags *lbalen;
8989         uint64_t lba;
8990         uint32_t num_blocks;
8991         int bytchk, flags;
8992         int retval;
8993
8994         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8995
8996         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8997
8998         bytchk = 0;
8999         flags = CTL_LLF_FUA;
9000         switch (ctsio->cdb[0]) {
9001         case VERIFY_10: {
9002                 struct scsi_verify_10 *cdb;
9003
9004                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9005                 if (cdb->byte2 & SVFY_BYTCHK)
9006                         bytchk = 1;
9007                 if (cdb->byte2 & SVFY_DPO)
9008                         flags |= CTL_LLF_DPO;
9009                 lba = scsi_4btoul(cdb->addr);
9010                 num_blocks = scsi_2btoul(cdb->length);
9011                 break;
9012         }
9013         case VERIFY_12: {
9014                 struct scsi_verify_12 *cdb;
9015
9016                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9017                 if (cdb->byte2 & SVFY_BYTCHK)
9018                         bytchk = 1;
9019                 if (cdb->byte2 & SVFY_DPO)
9020                         flags |= CTL_LLF_DPO;
9021                 lba = scsi_4btoul(cdb->addr);
9022                 num_blocks = scsi_4btoul(cdb->length);
9023                 break;
9024         }
9025         case VERIFY_16: {
9026                 struct scsi_rw_16 *cdb;
9027
9028                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9029                 if (cdb->byte2 & SVFY_BYTCHK)
9030                         bytchk = 1;
9031                 if (cdb->byte2 & SVFY_DPO)
9032                         flags |= CTL_LLF_DPO;
9033                 lba = scsi_8btou64(cdb->addr);
9034                 num_blocks = scsi_4btoul(cdb->length);
9035                 break;
9036         }
9037         default:
9038                 /*
9039                  * We got a command we don't support.  This shouldn't
9040                  * happen, commands should be filtered out above us.
9041                  */
9042                 ctl_set_invalid_opcode(ctsio);
9043                 ctl_done((union ctl_io *)ctsio);
9044                 return (CTL_RETVAL_COMPLETE);
9045         }
9046
9047         /*
9048          * The first check is to make sure we're in bounds, the second
9049          * check is to catch wrap-around problems.  If the lba + num blocks
9050          * is less than the lba, then we've wrapped around and the block
9051          * range is invalid anyway.
9052          */
9053         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9054          || ((lba + num_blocks) < lba)) {
9055                 ctl_set_lba_out_of_range(ctsio);
9056                 ctl_done((union ctl_io *)ctsio);
9057                 return (CTL_RETVAL_COMPLETE);
9058         }
9059
9060         /*
9061          * According to SBC-3, a transfer length of 0 is not an error.
9062          */
9063         if (num_blocks == 0) {
9064                 ctl_set_success(ctsio);
9065                 ctl_done((union ctl_io *)ctsio);
9066                 return (CTL_RETVAL_COMPLETE);
9067         }
9068
9069         lbalen = (struct ctl_lba_len_flags *)
9070             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9071         lbalen->lba = lba;
9072         lbalen->len = num_blocks;
9073         if (bytchk) {
9074                 lbalen->flags = CTL_LLF_COMPARE | flags;
9075                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9076         } else {
9077                 lbalen->flags = CTL_LLF_VERIFY | flags;
9078                 ctsio->kern_total_len = 0;
9079         }
9080         ctsio->kern_rel_offset = 0;
9081
9082         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9083         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9084         return (retval);
9085 }
9086
9087 int
9088 ctl_report_luns(struct ctl_scsiio *ctsio)
9089 {
9090         struct ctl_softc *softc;
9091         struct scsi_report_luns *cdb;
9092         struct scsi_report_luns_data *lun_data;
9093         struct ctl_lun *lun, *request_lun;
9094         struct ctl_port *port;
9095         int num_luns, retval;
9096         uint32_t alloc_len, lun_datalen;
9097         int num_filled;
9098         uint32_t initidx, targ_lun_id, lun_id;
9099
9100         retval = CTL_RETVAL_COMPLETE;
9101         cdb = (struct scsi_report_luns *)ctsio->cdb;
9102         port = ctl_io_port(&ctsio->io_hdr);
9103         softc = port->ctl_softc;
9104
9105         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9106
9107         mtx_lock(&softc->ctl_lock);
9108         num_luns = 0;
9109         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9110                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9111                         num_luns++;
9112         }
9113         mtx_unlock(&softc->ctl_lock);
9114
9115         switch (cdb->select_report) {
9116         case RPL_REPORT_DEFAULT:
9117         case RPL_REPORT_ALL:
9118         case RPL_REPORT_NONSUBSID:
9119                 break;
9120         case RPL_REPORT_WELLKNOWN:
9121         case RPL_REPORT_ADMIN:
9122         case RPL_REPORT_CONGLOM:
9123                 num_luns = 0;
9124                 break;
9125         default:
9126                 ctl_set_invalid_field(ctsio,
9127                                       /*sks_valid*/ 1,
9128                                       /*command*/ 1,
9129                                       /*field*/ 2,
9130                                       /*bit_valid*/ 0,
9131                                       /*bit*/ 0);
9132                 ctl_done((union ctl_io *)ctsio);
9133                 return (retval);
9134                 break; /* NOTREACHED */
9135         }
9136
9137         alloc_len = scsi_4btoul(cdb->length);
9138         /*
9139          * The initiator has to allocate at least 16 bytes for this request,
9140          * so he can at least get the header and the first LUN.  Otherwise
9141          * we reject the request (per SPC-3 rev 14, section 6.21).
9142          */
9143         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9144             sizeof(struct scsi_report_luns_lundata))) {
9145                 ctl_set_invalid_field(ctsio,
9146                                       /*sks_valid*/ 1,
9147                                       /*command*/ 1,
9148                                       /*field*/ 6,
9149                                       /*bit_valid*/ 0,
9150                                       /*bit*/ 0);
9151                 ctl_done((union ctl_io *)ctsio);
9152                 return (retval);
9153         }
9154
9155         request_lun = (struct ctl_lun *)
9156                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9157
9158         lun_datalen = sizeof(*lun_data) +
9159                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9160
9161         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9162         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9163         ctsio->kern_sg_entries = 0;
9164
9165         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9166
9167         mtx_lock(&softc->ctl_lock);
9168         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9169                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9170                 if (lun_id >= CTL_MAX_LUNS)
9171                         continue;
9172                 lun = softc->ctl_luns[lun_id];
9173                 if (lun == NULL)
9174                         continue;
9175
9176                 be64enc(lun_data->luns[num_filled++].lundata,
9177                     ctl_encode_lun(targ_lun_id));
9178
9179                 /*
9180                  * According to SPC-3, rev 14 section 6.21:
9181                  *
9182                  * "The execution of a REPORT LUNS command to any valid and
9183                  * installed logical unit shall clear the REPORTED LUNS DATA
9184                  * HAS CHANGED unit attention condition for all logical
9185                  * units of that target with respect to the requesting
9186                  * initiator. A valid and installed logical unit is one
9187                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9188                  * INQUIRY data (see 6.4.2)."
9189                  *
9190                  * If request_lun is NULL, the LUN this report luns command
9191                  * was issued to is either disabled or doesn't exist. In that
9192                  * case, we shouldn't clear any pending lun change unit
9193                  * attention.
9194                  */
9195                 if (request_lun != NULL) {
9196                         mtx_lock(&lun->lun_lock);
9197                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9198                         mtx_unlock(&lun->lun_lock);
9199                 }
9200         }
9201         mtx_unlock(&softc->ctl_lock);
9202
9203         /*
9204          * It's quite possible that we've returned fewer LUNs than we allocated
9205          * space for.  Trim it.
9206          */
9207         lun_datalen = sizeof(*lun_data) +
9208                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9209
9210         if (lun_datalen < alloc_len) {
9211                 ctsio->residual = alloc_len - lun_datalen;
9212                 ctsio->kern_data_len = lun_datalen;
9213                 ctsio->kern_total_len = lun_datalen;
9214         } else {
9215                 ctsio->residual = 0;
9216                 ctsio->kern_data_len = alloc_len;
9217                 ctsio->kern_total_len = alloc_len;
9218         }
9219         ctsio->kern_data_resid = 0;
9220         ctsio->kern_rel_offset = 0;
9221         ctsio->kern_sg_entries = 0;
9222
9223         /*
9224          * We set this to the actual data length, regardless of how much
9225          * space we actually have to return results.  If the user looks at
9226          * this value, he'll know whether or not he allocated enough space
9227          * and reissue the command if necessary.  We don't support well
9228          * known logical units, so if the user asks for that, return none.
9229          */
9230         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9231
9232         /*
9233          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9234          * this request.
9235          */
9236         ctl_set_success(ctsio);
9237         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9238         ctsio->be_move_done = ctl_config_move_done;
9239         ctl_datamove((union ctl_io *)ctsio);
9240         return (retval);
9241 }
9242
9243 int
9244 ctl_request_sense(struct ctl_scsiio *ctsio)
9245 {
9246         struct scsi_request_sense *cdb;
9247         struct scsi_sense_data *sense_ptr;
9248         struct ctl_softc *ctl_softc;
9249         struct ctl_lun *lun;
9250         uint32_t initidx;
9251         int have_error;
9252         scsi_sense_data_type sense_format;
9253         ctl_ua_type ua_type;
9254
9255         cdb = (struct scsi_request_sense *)ctsio->cdb;
9256
9257         ctl_softc = control_softc;
9258         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9259
9260         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9261
9262         /*
9263          * Determine which sense format the user wants.
9264          */
9265         if (cdb->byte2 & SRS_DESC)
9266                 sense_format = SSD_TYPE_DESC;
9267         else
9268                 sense_format = SSD_TYPE_FIXED;
9269
9270         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9271         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9272         ctsio->kern_sg_entries = 0;
9273
9274         /*
9275          * struct scsi_sense_data, which is currently set to 256 bytes, is
9276          * larger than the largest allowed value for the length field in the
9277          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9278          */
9279         ctsio->residual = 0;
9280         ctsio->kern_data_len = cdb->length;
9281         ctsio->kern_total_len = cdb->length;
9282
9283         ctsio->kern_data_resid = 0;
9284         ctsio->kern_rel_offset = 0;
9285         ctsio->kern_sg_entries = 0;
9286
9287         /*
9288          * If we don't have a LUN, we don't have any pending sense.
9289          */
9290         if (lun == NULL)
9291                 goto no_sense;
9292
9293         have_error = 0;
9294         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9295         /*
9296          * Check for pending sense, and then for pending unit attentions.
9297          * Pending sense gets returned first, then pending unit attentions.
9298          */
9299         mtx_lock(&lun->lun_lock);
9300 #ifdef CTL_WITH_CA
9301         if (ctl_is_set(lun->have_ca, initidx)) {
9302                 scsi_sense_data_type stored_format;
9303
9304                 /*
9305                  * Check to see which sense format was used for the stored
9306                  * sense data.
9307                  */
9308                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9309
9310                 /*
9311                  * If the user requested a different sense format than the
9312                  * one we stored, then we need to convert it to the other
9313                  * format.  If we're going from descriptor to fixed format
9314                  * sense data, we may lose things in translation, depending
9315                  * on what options were used.
9316                  *
9317                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9318                  * for some reason we'll just copy it out as-is.
9319                  */
9320                 if ((stored_format == SSD_TYPE_FIXED)
9321                  && (sense_format == SSD_TYPE_DESC))
9322                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9323                             &lun->pending_sense[initidx],
9324                             (struct scsi_sense_data_desc *)sense_ptr);
9325                 else if ((stored_format == SSD_TYPE_DESC)
9326                       && (sense_format == SSD_TYPE_FIXED))
9327                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9328                             &lun->pending_sense[initidx],
9329                             (struct scsi_sense_data_fixed *)sense_ptr);
9330                 else
9331                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9332                                MIN(sizeof(*sense_ptr),
9333                                sizeof(lun->pending_sense[initidx])));
9334
9335                 ctl_clear_mask(lun->have_ca, initidx);
9336                 have_error = 1;
9337         } else
9338 #endif
9339         {
9340                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9341                 if (ua_type != CTL_UA_NONE)
9342                         have_error = 1;
9343                 if (ua_type == CTL_UA_LUN_CHANGE) {
9344                         mtx_unlock(&lun->lun_lock);
9345                         mtx_lock(&ctl_softc->ctl_lock);
9346                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9347                         mtx_unlock(&ctl_softc->ctl_lock);
9348                         mtx_lock(&lun->lun_lock);
9349                 }
9350
9351         }
9352         mtx_unlock(&lun->lun_lock);
9353
9354         /*
9355          * We already have a pending error, return it.
9356          */
9357         if (have_error != 0) {
9358                 /*
9359                  * We report the SCSI status as OK, since the status of the
9360                  * request sense command itself is OK.
9361                  * We report 0 for the sense length, because we aren't doing
9362                  * autosense in this case.  We're reporting sense as
9363                  * parameter data.
9364                  */
9365                 ctl_set_success(ctsio);
9366                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9367                 ctsio->be_move_done = ctl_config_move_done;
9368                 ctl_datamove((union ctl_io *)ctsio);
9369                 return (CTL_RETVAL_COMPLETE);
9370         }
9371
9372 no_sense:
9373
9374         /*
9375          * No sense information to report, so we report that everything is
9376          * okay.
9377          */
9378         ctl_set_sense_data(sense_ptr,
9379                            lun,
9380                            sense_format,
9381                            /*current_error*/ 1,
9382                            /*sense_key*/ SSD_KEY_NO_SENSE,
9383                            /*asc*/ 0x00,
9384                            /*ascq*/ 0x00,
9385                            SSD_ELEM_NONE);
9386
9387         /*
9388          * We report 0 for the sense length, because we aren't doing
9389          * autosense in this case.  We're reporting sense as parameter data.
9390          */
9391         ctl_set_success(ctsio);
9392         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9393         ctsio->be_move_done = ctl_config_move_done;
9394         ctl_datamove((union ctl_io *)ctsio);
9395         return (CTL_RETVAL_COMPLETE);
9396 }
9397
9398 int
9399 ctl_tur(struct ctl_scsiio *ctsio)
9400 {
9401
9402         CTL_DEBUG_PRINT(("ctl_tur\n"));
9403
9404         ctl_set_success(ctsio);
9405         ctl_done((union ctl_io *)ctsio);
9406
9407         return (CTL_RETVAL_COMPLETE);
9408 }
9409
9410 /*
9411  * SCSI VPD page 0x00, the Supported VPD Pages page.
9412  */
9413 static int
9414 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9415 {
9416         struct scsi_vpd_supported_pages *pages;
9417         int sup_page_size;
9418         struct ctl_lun *lun;
9419         int p;
9420
9421         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9422
9423         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9424             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9425         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9426         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9427         ctsio->kern_sg_entries = 0;
9428
9429         if (sup_page_size < alloc_len) {
9430                 ctsio->residual = alloc_len - sup_page_size;
9431                 ctsio->kern_data_len = sup_page_size;
9432                 ctsio->kern_total_len = sup_page_size;
9433         } else {
9434                 ctsio->residual = 0;
9435                 ctsio->kern_data_len = alloc_len;
9436                 ctsio->kern_total_len = alloc_len;
9437         }
9438         ctsio->kern_data_resid = 0;
9439         ctsio->kern_rel_offset = 0;
9440         ctsio->kern_sg_entries = 0;
9441
9442         /*
9443          * The control device is always connected.  The disk device, on the
9444          * other hand, may not be online all the time.  Need to change this
9445          * to figure out whether the disk device is actually online or not.
9446          */
9447         if (lun != NULL)
9448                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9449                                 lun->be_lun->lun_type;
9450         else
9451                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9452
9453         p = 0;
9454         /* Supported VPD pages */
9455         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9456         /* Serial Number */
9457         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9458         /* Device Identification */
9459         pages->page_list[p++] = SVPD_DEVICE_ID;
9460         /* Extended INQUIRY Data */
9461         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9462         /* Mode Page Policy */
9463         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9464         /* SCSI Ports */
9465         pages->page_list[p++] = SVPD_SCSI_PORTS;
9466         /* Third-party Copy */
9467         pages->page_list[p++] = SVPD_SCSI_TPC;
9468         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9469                 /* Block limits */
9470                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9471                 /* Block Device Characteristics */
9472                 pages->page_list[p++] = SVPD_BDC;
9473                 /* Logical Block Provisioning */
9474                 pages->page_list[p++] = SVPD_LBP;
9475         }
9476         pages->length = p;
9477
9478         ctl_set_success(ctsio);
9479         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9480         ctsio->be_move_done = ctl_config_move_done;
9481         ctl_datamove((union ctl_io *)ctsio);
9482         return (CTL_RETVAL_COMPLETE);
9483 }
9484
9485 /*
9486  * SCSI VPD page 0x80, the Unit Serial Number page.
9487  */
9488 static int
9489 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9490 {
9491         struct scsi_vpd_unit_serial_number *sn_ptr;
9492         struct ctl_lun *lun;
9493         int data_len;
9494
9495         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9496
9497         data_len = 4 + CTL_SN_LEN;
9498         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9499         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9500         if (data_len < alloc_len) {
9501                 ctsio->residual = alloc_len - data_len;
9502                 ctsio->kern_data_len = data_len;
9503                 ctsio->kern_total_len = data_len;
9504         } else {
9505                 ctsio->residual = 0;
9506                 ctsio->kern_data_len = alloc_len;
9507                 ctsio->kern_total_len = alloc_len;
9508         }
9509         ctsio->kern_data_resid = 0;
9510         ctsio->kern_rel_offset = 0;
9511         ctsio->kern_sg_entries = 0;
9512
9513         /*
9514          * The control device is always connected.  The disk device, on the
9515          * other hand, may not be online all the time.  Need to change this
9516          * to figure out whether the disk device is actually online or not.
9517          */
9518         if (lun != NULL)
9519                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9520                                   lun->be_lun->lun_type;
9521         else
9522                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9523
9524         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9525         sn_ptr->length = CTL_SN_LEN;
9526         /*
9527          * If we don't have a LUN, we just leave the serial number as
9528          * all spaces.
9529          */
9530         if (lun != NULL) {
9531                 strncpy((char *)sn_ptr->serial_num,
9532                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9533         } else
9534                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9535
9536         ctl_set_success(ctsio);
9537         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9538         ctsio->be_move_done = ctl_config_move_done;
9539         ctl_datamove((union ctl_io *)ctsio);
9540         return (CTL_RETVAL_COMPLETE);
9541 }
9542
9543
9544 /*
9545  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9546  */
9547 static int
9548 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9549 {
9550         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9551         struct ctl_lun *lun;
9552         int data_len;
9553
9554         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9555
9556         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9557         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9558         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9559         ctsio->kern_sg_entries = 0;
9560
9561         if (data_len < alloc_len) {
9562                 ctsio->residual = alloc_len - data_len;
9563                 ctsio->kern_data_len = data_len;
9564                 ctsio->kern_total_len = data_len;
9565         } else {
9566                 ctsio->residual = 0;
9567                 ctsio->kern_data_len = alloc_len;
9568                 ctsio->kern_total_len = alloc_len;
9569         }
9570         ctsio->kern_data_resid = 0;
9571         ctsio->kern_rel_offset = 0;
9572         ctsio->kern_sg_entries = 0;
9573
9574         /*
9575          * The control device is always connected.  The disk device, on the
9576          * other hand, may not be online all the time.
9577          */
9578         if (lun != NULL)
9579                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9580                                      lun->be_lun->lun_type;
9581         else
9582                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9583         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9584         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9585         /*
9586          * We support head of queue, ordered and simple tags.
9587          */
9588         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9589         /*
9590          * Volatile cache supported.
9591          */
9592         eid_ptr->flags3 = SVPD_EID_V_SUP;
9593
9594         /*
9595          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9596          * attention for a particular IT nexus on all LUNs once we report
9597          * it to that nexus once.  This bit is required as of SPC-4.
9598          */
9599         eid_ptr->flags4 = SVPD_EID_LUICLT;
9600
9601         /*
9602          * XXX KDM in order to correctly answer this, we would need
9603          * information from the SIM to determine how much sense data it
9604          * can send.  So this would really be a path inquiry field, most
9605          * likely.  This can be set to a maximum of 252 according to SPC-4,
9606          * but the hardware may or may not be able to support that much.
9607          * 0 just means that the maximum sense data length is not reported.
9608          */
9609         eid_ptr->max_sense_length = 0;
9610
9611         ctl_set_success(ctsio);
9612         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9613         ctsio->be_move_done = ctl_config_move_done;
9614         ctl_datamove((union ctl_io *)ctsio);
9615         return (CTL_RETVAL_COMPLETE);
9616 }
9617
9618 static int
9619 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9620 {
9621         struct scsi_vpd_mode_page_policy *mpp_ptr;
9622         struct ctl_lun *lun;
9623         int data_len;
9624
9625         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9626
9627         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9628             sizeof(struct scsi_vpd_mode_page_policy_descr);
9629
9630         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9631         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9632         ctsio->kern_sg_entries = 0;
9633
9634         if (data_len < alloc_len) {
9635                 ctsio->residual = alloc_len - data_len;
9636                 ctsio->kern_data_len = data_len;
9637                 ctsio->kern_total_len = data_len;
9638         } else {
9639                 ctsio->residual = 0;
9640                 ctsio->kern_data_len = alloc_len;
9641                 ctsio->kern_total_len = alloc_len;
9642         }
9643         ctsio->kern_data_resid = 0;
9644         ctsio->kern_rel_offset = 0;
9645         ctsio->kern_sg_entries = 0;
9646
9647         /*
9648          * The control device is always connected.  The disk device, on the
9649          * other hand, may not be online all the time.
9650          */
9651         if (lun != NULL)
9652                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9653                                      lun->be_lun->lun_type;
9654         else
9655                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9656         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9657         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9658         mpp_ptr->descr[0].page_code = 0x3f;
9659         mpp_ptr->descr[0].subpage_code = 0xff;
9660         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9661
9662         ctl_set_success(ctsio);
9663         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9664         ctsio->be_move_done = ctl_config_move_done;
9665         ctl_datamove((union ctl_io *)ctsio);
9666         return (CTL_RETVAL_COMPLETE);
9667 }
9668
9669 /*
9670  * SCSI VPD page 0x83, the Device Identification page.
9671  */
9672 static int
9673 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9674 {
9675         struct scsi_vpd_device_id *devid_ptr;
9676         struct scsi_vpd_id_descriptor *desc;
9677         struct ctl_softc *softc;
9678         struct ctl_lun *lun;
9679         struct ctl_port *port;
9680         int data_len, g;
9681         uint8_t proto;
9682
9683         softc = control_softc;
9684
9685         port = ctl_io_port(&ctsio->io_hdr);
9686         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9687
9688         data_len = sizeof(struct scsi_vpd_device_id) +
9689             sizeof(struct scsi_vpd_id_descriptor) +
9690                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9691             sizeof(struct scsi_vpd_id_descriptor) +
9692                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9693         if (lun && lun->lun_devid)
9694                 data_len += lun->lun_devid->len;
9695         if (port && port->port_devid)
9696                 data_len += port->port_devid->len;
9697         if (port && port->target_devid)
9698                 data_len += port->target_devid->len;
9699
9700         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9701         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9702         ctsio->kern_sg_entries = 0;
9703
9704         if (data_len < alloc_len) {
9705                 ctsio->residual = alloc_len - data_len;
9706                 ctsio->kern_data_len = data_len;
9707                 ctsio->kern_total_len = data_len;
9708         } else {
9709                 ctsio->residual = 0;
9710                 ctsio->kern_data_len = alloc_len;
9711                 ctsio->kern_total_len = alloc_len;
9712         }
9713         ctsio->kern_data_resid = 0;
9714         ctsio->kern_rel_offset = 0;
9715         ctsio->kern_sg_entries = 0;
9716
9717         /*
9718          * The control device is always connected.  The disk device, on the
9719          * other hand, may not be online all the time.
9720          */
9721         if (lun != NULL)
9722                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9723                                      lun->be_lun->lun_type;
9724         else
9725                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9726         devid_ptr->page_code = SVPD_DEVICE_ID;
9727         scsi_ulto2b(data_len - 4, devid_ptr->length);
9728
9729         if (port && port->port_type == CTL_PORT_FC)
9730                 proto = SCSI_PROTO_FC << 4;
9731         else if (port && port->port_type == CTL_PORT_ISCSI)
9732                 proto = SCSI_PROTO_ISCSI << 4;
9733         else
9734                 proto = SCSI_PROTO_SPI << 4;
9735         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9736
9737         /*
9738          * We're using a LUN association here.  i.e., this device ID is a
9739          * per-LUN identifier.
9740          */
9741         if (lun && lun->lun_devid) {
9742                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9743                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9744                     lun->lun_devid->len);
9745         }
9746
9747         /*
9748          * This is for the WWPN which is a port association.
9749          */
9750         if (port && port->port_devid) {
9751                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9752                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9753                     port->port_devid->len);
9754         }
9755
9756         /*
9757          * This is for the Relative Target Port(type 4h) identifier
9758          */
9759         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9760         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9761             SVPD_ID_TYPE_RELTARG;
9762         desc->length = 4;
9763         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9764         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9765             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9766
9767         /*
9768          * This is for the Target Port Group(type 5h) identifier
9769          */
9770         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9771         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9772             SVPD_ID_TYPE_TPORTGRP;
9773         desc->length = 4;
9774         if (softc->is_single ||
9775             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9776                 g = 1;
9777         else
9778                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9779         scsi_ulto2b(g, &desc->identifier[2]);
9780         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9781             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9782
9783         /*
9784          * This is for the Target identifier
9785          */
9786         if (port && port->target_devid) {
9787                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9788         }
9789
9790         ctl_set_success(ctsio);
9791         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9792         ctsio->be_move_done = ctl_config_move_done;
9793         ctl_datamove((union ctl_io *)ctsio);
9794         return (CTL_RETVAL_COMPLETE);
9795 }
9796
9797 static int
9798 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9799 {
9800         struct ctl_softc *softc = control_softc;
9801         struct scsi_vpd_scsi_ports *sp;
9802         struct scsi_vpd_port_designation *pd;
9803         struct scsi_vpd_port_designation_cont *pdc;
9804         struct ctl_lun *lun;
9805         struct ctl_port *port;
9806         int data_len, num_target_ports, iid_len, id_len;
9807
9808         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9809
9810         num_target_ports = 0;
9811         iid_len = 0;
9812         id_len = 0;
9813         mtx_lock(&softc->ctl_lock);
9814         STAILQ_FOREACH(port, &softc->port_list, links) {
9815                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9816                         continue;
9817                 if (lun != NULL &&
9818                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9819                         continue;
9820                 num_target_ports++;
9821                 if (port->init_devid)
9822                         iid_len += port->init_devid->len;
9823                 if (port->port_devid)
9824                         id_len += port->port_devid->len;
9825         }
9826         mtx_unlock(&softc->ctl_lock);
9827
9828         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9829             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9830              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9831         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9832         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9833         ctsio->kern_sg_entries = 0;
9834
9835         if (data_len < alloc_len) {
9836                 ctsio->residual = alloc_len - data_len;
9837                 ctsio->kern_data_len = data_len;
9838                 ctsio->kern_total_len = data_len;
9839         } else {
9840                 ctsio->residual = 0;
9841                 ctsio->kern_data_len = alloc_len;
9842                 ctsio->kern_total_len = alloc_len;
9843         }
9844         ctsio->kern_data_resid = 0;
9845         ctsio->kern_rel_offset = 0;
9846         ctsio->kern_sg_entries = 0;
9847
9848         /*
9849          * The control device is always connected.  The disk device, on the
9850          * other hand, may not be online all the time.  Need to change this
9851          * to figure out whether the disk device is actually online or not.
9852          */
9853         if (lun != NULL)
9854                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9855                                   lun->be_lun->lun_type;
9856         else
9857                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9858
9859         sp->page_code = SVPD_SCSI_PORTS;
9860         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9861             sp->page_length);
9862         pd = &sp->design[0];
9863
9864         mtx_lock(&softc->ctl_lock);
9865         STAILQ_FOREACH(port, &softc->port_list, links) {
9866                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9867                         continue;
9868                 if (lun != NULL &&
9869                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9870                         continue;
9871                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9872                 if (port->init_devid) {
9873                         iid_len = port->init_devid->len;
9874                         memcpy(pd->initiator_transportid,
9875                             port->init_devid->data, port->init_devid->len);
9876                 } else
9877                         iid_len = 0;
9878                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9879                 pdc = (struct scsi_vpd_port_designation_cont *)
9880                     (&pd->initiator_transportid[iid_len]);
9881                 if (port->port_devid) {
9882                         id_len = port->port_devid->len;
9883                         memcpy(pdc->target_port_descriptors,
9884                             port->port_devid->data, port->port_devid->len);
9885                 } else
9886                         id_len = 0;
9887                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9888                 pd = (struct scsi_vpd_port_designation *)
9889                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9890         }
9891         mtx_unlock(&softc->ctl_lock);
9892
9893         ctl_set_success(ctsio);
9894         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9895         ctsio->be_move_done = ctl_config_move_done;
9896         ctl_datamove((union ctl_io *)ctsio);
9897         return (CTL_RETVAL_COMPLETE);
9898 }
9899
9900 static int
9901 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9902 {
9903         struct scsi_vpd_block_limits *bl_ptr;
9904         struct ctl_lun *lun;
9905
9906         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9907
9908         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9909         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9910         ctsio->kern_sg_entries = 0;
9911
9912         if (sizeof(*bl_ptr) < alloc_len) {
9913                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9914                 ctsio->kern_data_len = sizeof(*bl_ptr);
9915                 ctsio->kern_total_len = sizeof(*bl_ptr);
9916         } else {
9917                 ctsio->residual = 0;
9918                 ctsio->kern_data_len = alloc_len;
9919                 ctsio->kern_total_len = alloc_len;
9920         }
9921         ctsio->kern_data_resid = 0;
9922         ctsio->kern_rel_offset = 0;
9923         ctsio->kern_sg_entries = 0;
9924
9925         /*
9926          * The control device is always connected.  The disk device, on the
9927          * other hand, may not be online all the time.  Need to change this
9928          * to figure out whether the disk device is actually online or not.
9929          */
9930         if (lun != NULL)
9931                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9932                                   lun->be_lun->lun_type;
9933         else
9934                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9935
9936         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9937         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9938         bl_ptr->max_cmp_write_len = 0xff;
9939         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9940         if (lun != NULL) {
9941                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9942                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9943                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9944                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9945                         if (lun->be_lun->ublockexp != 0) {
9946                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9947                                     bl_ptr->opt_unmap_grain);
9948                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9949                                     bl_ptr->unmap_grain_align);
9950                         }
9951                 }
9952                 scsi_ulto4b(lun->be_lun->atomicblock,
9953                     bl_ptr->max_atomic_transfer_length);
9954                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9955                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9956                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9957                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9958         }
9959         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9960
9961         ctl_set_success(ctsio);
9962         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9963         ctsio->be_move_done = ctl_config_move_done;
9964         ctl_datamove((union ctl_io *)ctsio);
9965         return (CTL_RETVAL_COMPLETE);
9966 }
9967
9968 static int
9969 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9970 {
9971         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9972         struct ctl_lun *lun;
9973         const char *value;
9974         u_int i;
9975
9976         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9977
9978         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9979         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9980         ctsio->kern_sg_entries = 0;
9981
9982         if (sizeof(*bdc_ptr) < alloc_len) {
9983                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9984                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9985                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9986         } else {
9987                 ctsio->residual = 0;
9988                 ctsio->kern_data_len = alloc_len;
9989                 ctsio->kern_total_len = alloc_len;
9990         }
9991         ctsio->kern_data_resid = 0;
9992         ctsio->kern_rel_offset = 0;
9993         ctsio->kern_sg_entries = 0;
9994
9995         /*
9996          * The control device is always connected.  The disk device, on the
9997          * other hand, may not be online all the time.  Need to change this
9998          * to figure out whether the disk device is actually online or not.
9999          */
10000         if (lun != NULL)
10001                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10002                                   lun->be_lun->lun_type;
10003         else
10004                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10005         bdc_ptr->page_code = SVPD_BDC;
10006         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10007         if (lun != NULL &&
10008             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10009                 i = strtol(value, NULL, 0);
10010         else
10011                 i = CTL_DEFAULT_ROTATION_RATE;
10012         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10013         if (lun != NULL &&
10014             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10015                 i = strtol(value, NULL, 0);
10016         else
10017                 i = 0;
10018         bdc_ptr->wab_wac_ff = (i & 0x0f);
10019         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10020
10021         ctl_set_success(ctsio);
10022         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10023         ctsio->be_move_done = ctl_config_move_done;
10024         ctl_datamove((union ctl_io *)ctsio);
10025         return (CTL_RETVAL_COMPLETE);
10026 }
10027
10028 static int
10029 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10030 {
10031         struct scsi_vpd_logical_block_prov *lbp_ptr;
10032         struct ctl_lun *lun;
10033
10034         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10035
10036         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10037         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10038         ctsio->kern_sg_entries = 0;
10039
10040         if (sizeof(*lbp_ptr) < alloc_len) {
10041                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10042                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10043                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10044         } else {
10045                 ctsio->residual = 0;
10046                 ctsio->kern_data_len = alloc_len;
10047                 ctsio->kern_total_len = alloc_len;
10048         }
10049         ctsio->kern_data_resid = 0;
10050         ctsio->kern_rel_offset = 0;
10051         ctsio->kern_sg_entries = 0;
10052
10053         /*
10054          * The control device is always connected.  The disk device, on the
10055          * other hand, may not be online all the time.  Need to change this
10056          * to figure out whether the disk device is actually online or not.
10057          */
10058         if (lun != NULL)
10059                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10060                                   lun->be_lun->lun_type;
10061         else
10062                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10063
10064         lbp_ptr->page_code = SVPD_LBP;
10065         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10066         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10067         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10068                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10069                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10070                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10071         }
10072
10073         ctl_set_success(ctsio);
10074         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10075         ctsio->be_move_done = ctl_config_move_done;
10076         ctl_datamove((union ctl_io *)ctsio);
10077         return (CTL_RETVAL_COMPLETE);
10078 }
10079
10080 /*
10081  * INQUIRY with the EVPD bit set.
10082  */
10083 static int
10084 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10085 {
10086         struct ctl_lun *lun;
10087         struct scsi_inquiry *cdb;
10088         int alloc_len, retval;
10089
10090         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10091         cdb = (struct scsi_inquiry *)ctsio->cdb;
10092         alloc_len = scsi_2btoul(cdb->length);
10093
10094         switch (cdb->page_code) {
10095         case SVPD_SUPPORTED_PAGES:
10096                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10097                 break;
10098         case SVPD_UNIT_SERIAL_NUMBER:
10099                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10100                 break;
10101         case SVPD_DEVICE_ID:
10102                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10103                 break;
10104         case SVPD_EXTENDED_INQUIRY_DATA:
10105                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10106                 break;
10107         case SVPD_MODE_PAGE_POLICY:
10108                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10109                 break;
10110         case SVPD_SCSI_PORTS:
10111                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10112                 break;
10113         case SVPD_SCSI_TPC:
10114                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10115                 break;
10116         case SVPD_BLOCK_LIMITS:
10117                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10118                         goto err;
10119                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10120                 break;
10121         case SVPD_BDC:
10122                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10123                         goto err;
10124                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10125                 break;
10126         case SVPD_LBP:
10127                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10128                         goto err;
10129                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10130                 break;
10131         default:
10132 err:
10133                 ctl_set_invalid_field(ctsio,
10134                                       /*sks_valid*/ 1,
10135                                       /*command*/ 1,
10136                                       /*field*/ 2,
10137                                       /*bit_valid*/ 0,
10138                                       /*bit*/ 0);
10139                 ctl_done((union ctl_io *)ctsio);
10140                 retval = CTL_RETVAL_COMPLETE;
10141                 break;
10142         }
10143
10144         return (retval);
10145 }
10146
10147 /*
10148  * Standard INQUIRY data.
10149  */
10150 static int
10151 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10152 {
10153         struct scsi_inquiry_data *inq_ptr;
10154         struct scsi_inquiry *cdb;
10155         struct ctl_softc *softc = control_softc;
10156         struct ctl_port *port;
10157         struct ctl_lun *lun;
10158         char *val;
10159         uint32_t alloc_len, data_len;
10160         ctl_port_type port_type;
10161
10162         port = ctl_io_port(&ctsio->io_hdr);
10163         port_type = port->port_type;
10164         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10165                 port_type = CTL_PORT_SCSI;
10166
10167         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10168         cdb = (struct scsi_inquiry *)ctsio->cdb;
10169         alloc_len = scsi_2btoul(cdb->length);
10170
10171         /*
10172          * We malloc the full inquiry data size here and fill it
10173          * in.  If the user only asks for less, we'll give him
10174          * that much.
10175          */
10176         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10177         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10178         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10179         ctsio->kern_sg_entries = 0;
10180         ctsio->kern_data_resid = 0;
10181         ctsio->kern_rel_offset = 0;
10182
10183         if (data_len < alloc_len) {
10184                 ctsio->residual = alloc_len - data_len;
10185                 ctsio->kern_data_len = data_len;
10186                 ctsio->kern_total_len = data_len;
10187         } else {
10188                 ctsio->residual = 0;
10189                 ctsio->kern_data_len = alloc_len;
10190                 ctsio->kern_total_len = alloc_len;
10191         }
10192
10193         if (lun != NULL) {
10194                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10195                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10196                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10197                             lun->be_lun->lun_type;
10198                 } else {
10199                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10200                             lun->be_lun->lun_type;
10201                 }
10202                 if (lun->flags & CTL_LUN_REMOVABLE)
10203                         inq_ptr->dev_qual2 |= SID_RMB;
10204         } else
10205                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10206
10207         /* RMB in byte 2 is 0 */
10208         inq_ptr->version = SCSI_REV_SPC4;
10209
10210         /*
10211          * According to SAM-3, even if a device only supports a single
10212          * level of LUN addressing, it should still set the HISUP bit:
10213          *
10214          * 4.9.1 Logical unit numbers overview
10215          *
10216          * All logical unit number formats described in this standard are
10217          * hierarchical in structure even when only a single level in that
10218          * hierarchy is used. The HISUP bit shall be set to one in the
10219          * standard INQUIRY data (see SPC-2) when any logical unit number
10220          * format described in this standard is used.  Non-hierarchical
10221          * formats are outside the scope of this standard.
10222          *
10223          * Therefore we set the HiSup bit here.
10224          *
10225          * The reponse format is 2, per SPC-3.
10226          */
10227         inq_ptr->response_format = SID_HiSup | 2;
10228
10229         inq_ptr->additional_length = data_len -
10230             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10231         CTL_DEBUG_PRINT(("additional_length = %d\n",
10232                          inq_ptr->additional_length));
10233
10234         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10235         if (port_type == CTL_PORT_SCSI)
10236                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10237         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10238         inq_ptr->flags = SID_CmdQue;
10239         if (port_type == CTL_PORT_SCSI)
10240                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10241
10242         /*
10243          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10244          * We have 8 bytes for the vendor name, and 16 bytes for the device
10245          * name and 4 bytes for the revision.
10246          */
10247         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10248             "vendor")) == NULL) {
10249                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10250         } else {
10251                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10252                 strncpy(inq_ptr->vendor, val,
10253                     min(sizeof(inq_ptr->vendor), strlen(val)));
10254         }
10255         if (lun == NULL) {
10256                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10257                     sizeof(inq_ptr->product));
10258         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10259                 switch (lun->be_lun->lun_type) {
10260                 case T_DIRECT:
10261                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10262                             sizeof(inq_ptr->product));
10263                         break;
10264                 case T_PROCESSOR:
10265                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10266                             sizeof(inq_ptr->product));
10267                         break;
10268                 case T_CDROM:
10269                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10270                             sizeof(inq_ptr->product));
10271                         break;
10272                 default:
10273                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10274                             sizeof(inq_ptr->product));
10275                         break;
10276                 }
10277         } else {
10278                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10279                 strncpy(inq_ptr->product, val,
10280                     min(sizeof(inq_ptr->product), strlen(val)));
10281         }
10282
10283         /*
10284          * XXX make this a macro somewhere so it automatically gets
10285          * incremented when we make changes.
10286          */
10287         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10288             "revision")) == NULL) {
10289                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10290         } else {
10291                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10292                 strncpy(inq_ptr->revision, val,
10293                     min(sizeof(inq_ptr->revision), strlen(val)));
10294         }
10295
10296         /*
10297          * For parallel SCSI, we support double transition and single
10298          * transition clocking.  We also support QAS (Quick Arbitration
10299          * and Selection) and Information Unit transfers on both the
10300          * control and array devices.
10301          */
10302         if (port_type == CTL_PORT_SCSI)
10303                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10304                                     SID_SPI_IUS;
10305
10306         /* SAM-5 (no version claimed) */
10307         scsi_ulto2b(0x00A0, inq_ptr->version1);
10308         /* SPC-4 (no version claimed) */
10309         scsi_ulto2b(0x0460, inq_ptr->version2);
10310         if (port_type == CTL_PORT_FC) {
10311                 /* FCP-2 ANSI INCITS.350:2003 */
10312                 scsi_ulto2b(0x0917, inq_ptr->version3);
10313         } else if (port_type == CTL_PORT_SCSI) {
10314                 /* SPI-4 ANSI INCITS.362:200x */
10315                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10316         } else if (port_type == CTL_PORT_ISCSI) {
10317                 /* iSCSI (no version claimed) */
10318                 scsi_ulto2b(0x0960, inq_ptr->version3);
10319         } else if (port_type == CTL_PORT_SAS) {
10320                 /* SAS (no version claimed) */
10321                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10322         }
10323
10324         if (lun == NULL) {
10325                 /* SBC-4 (no version claimed) */
10326                 scsi_ulto2b(0x0600, inq_ptr->version4);
10327         } else {
10328                 switch (lun->be_lun->lun_type) {
10329                 case T_DIRECT:
10330                         /* SBC-4 (no version claimed) */
10331                         scsi_ulto2b(0x0600, inq_ptr->version4);
10332                         break;
10333                 case T_PROCESSOR:
10334                         break;
10335                 case T_CDROM:
10336                         /* MMC-6 (no version claimed) */
10337                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10338                         break;
10339                 default:
10340                         break;
10341                 }
10342         }
10343
10344         ctl_set_success(ctsio);
10345         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10346         ctsio->be_move_done = ctl_config_move_done;
10347         ctl_datamove((union ctl_io *)ctsio);
10348         return (CTL_RETVAL_COMPLETE);
10349 }
10350
10351 int
10352 ctl_inquiry(struct ctl_scsiio *ctsio)
10353 {
10354         struct scsi_inquiry *cdb;
10355         int retval;
10356
10357         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10358
10359         cdb = (struct scsi_inquiry *)ctsio->cdb;
10360         if (cdb->byte2 & SI_EVPD)
10361                 retval = ctl_inquiry_evpd(ctsio);
10362         else if (cdb->page_code == 0)
10363                 retval = ctl_inquiry_std(ctsio);
10364         else {
10365                 ctl_set_invalid_field(ctsio,
10366                                       /*sks_valid*/ 1,
10367                                       /*command*/ 1,
10368                                       /*field*/ 2,
10369                                       /*bit_valid*/ 0,
10370                                       /*bit*/ 0);
10371                 ctl_done((union ctl_io *)ctsio);
10372                 return (CTL_RETVAL_COMPLETE);
10373         }
10374
10375         return (retval);
10376 }
10377
10378 int
10379 ctl_get_config(struct ctl_scsiio *ctsio)
10380 {
10381         struct scsi_get_config_header *hdr;
10382         struct scsi_get_config_feature *feature;
10383         struct scsi_get_config *cdb;
10384         struct ctl_lun *lun;
10385         uint32_t alloc_len, data_len;
10386         int rt, starting;
10387
10388         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10389         cdb = (struct scsi_get_config *)ctsio->cdb;
10390         rt = (cdb->rt & SGC_RT_MASK);
10391         starting = scsi_2btoul(cdb->starting_feature);
10392         alloc_len = scsi_2btoul(cdb->length);
10393
10394         data_len = sizeof(struct scsi_get_config_header) +
10395             sizeof(struct scsi_get_config_feature) + 8 +
10396             sizeof(struct scsi_get_config_feature) + 8 +
10397             sizeof(struct scsi_get_config_feature) + 4 +
10398             sizeof(struct scsi_get_config_feature) + 4 +
10399             sizeof(struct scsi_get_config_feature) + 8 +
10400             sizeof(struct scsi_get_config_feature) +
10401             sizeof(struct scsi_get_config_feature) + 4 +
10402             sizeof(struct scsi_get_config_feature) + 4 +
10403             sizeof(struct scsi_get_config_feature) + 4 +
10404             sizeof(struct scsi_get_config_feature) + 4 +
10405             sizeof(struct scsi_get_config_feature) + 4 +
10406             sizeof(struct scsi_get_config_feature) + 4;
10407         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10408         ctsio->kern_sg_entries = 0;
10409         ctsio->kern_data_resid = 0;
10410         ctsio->kern_rel_offset = 0;
10411
10412         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10413         if (lun->flags & CTL_LUN_NO_MEDIA)
10414                 scsi_ulto2b(0x0000, hdr->current_profile);
10415         else
10416                 scsi_ulto2b(0x0010, hdr->current_profile);
10417         feature = (struct scsi_get_config_feature *)(hdr + 1);
10418
10419         if (starting > 0x003b)
10420                 goto done;
10421         if (starting > 0x003a)
10422                 goto f3b;
10423         if (starting > 0x002b)
10424                 goto f3a;
10425         if (starting > 0x002a)
10426                 goto f2b;
10427         if (starting > 0x001f)
10428                 goto f2a;
10429         if (starting > 0x001e)
10430                 goto f1f;
10431         if (starting > 0x001d)
10432                 goto f1e;
10433         if (starting > 0x0010)
10434                 goto f1d;
10435         if (starting > 0x0003)
10436                 goto f10;
10437         if (starting > 0x0002)
10438                 goto f3;
10439         if (starting > 0x0001)
10440                 goto f2;
10441         if (starting > 0x0000)
10442                 goto f1;
10443
10444         /* Profile List */
10445         scsi_ulto2b(0x0000, feature->feature_code);
10446         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10447         feature->add_length = 8;
10448         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10449         feature->feature_data[2] = 0x00;
10450         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10451         feature->feature_data[6] = 0x01;
10452         feature = (struct scsi_get_config_feature *)
10453             &feature->feature_data[feature->add_length];
10454
10455 f1:     /* Core */
10456         scsi_ulto2b(0x0001, feature->feature_code);
10457         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10458         feature->add_length = 8;
10459         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10460         feature->feature_data[4] = 0x03;
10461         feature = (struct scsi_get_config_feature *)
10462             &feature->feature_data[feature->add_length];
10463
10464 f2:     /* Morphing */
10465         scsi_ulto2b(0x0002, feature->feature_code);
10466         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10467         feature->add_length = 4;
10468         feature->feature_data[0] = 0x02;
10469         feature = (struct scsi_get_config_feature *)
10470             &feature->feature_data[feature->add_length];
10471
10472 f3:     /* Removable Medium */
10473         scsi_ulto2b(0x0003, feature->feature_code);
10474         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10475         feature->add_length = 4;
10476         feature->feature_data[0] = 0x39;
10477         feature = (struct scsi_get_config_feature *)
10478             &feature->feature_data[feature->add_length];
10479
10480         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10481                 goto done;
10482
10483 f10:    /* Random Read */
10484         scsi_ulto2b(0x0010, feature->feature_code);
10485         feature->flags = 0x00;
10486         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10487                 feature->flags |= SGC_F_CURRENT;
10488         feature->add_length = 8;
10489         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10490         scsi_ulto2b(1, &feature->feature_data[4]);
10491         feature->feature_data[6] = 0x00;
10492         feature = (struct scsi_get_config_feature *)
10493             &feature->feature_data[feature->add_length];
10494
10495 f1d:    /* Multi-Read */
10496         scsi_ulto2b(0x001D, feature->feature_code);
10497         feature->flags = 0x00;
10498         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10499                 feature->flags |= SGC_F_CURRENT;
10500         feature->add_length = 0;
10501         feature = (struct scsi_get_config_feature *)
10502             &feature->feature_data[feature->add_length];
10503
10504 f1e:    /* CD Read */
10505         scsi_ulto2b(0x001E, feature->feature_code);
10506         feature->flags = 0x00;
10507         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10508                 feature->flags |= SGC_F_CURRENT;
10509         feature->add_length = 4;
10510         feature->feature_data[0] = 0x00;
10511         feature = (struct scsi_get_config_feature *)
10512             &feature->feature_data[feature->add_length];
10513
10514 f1f:    /* DVD Read */
10515         scsi_ulto2b(0x001F, feature->feature_code);
10516         feature->flags = 0x08;
10517         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10518                 feature->flags |= SGC_F_CURRENT;
10519         feature->add_length = 4;
10520         feature->feature_data[0] = 0x01;
10521         feature->feature_data[2] = 0x03;
10522         feature = (struct scsi_get_config_feature *)
10523             &feature->feature_data[feature->add_length];
10524
10525 f2a:    /* DVD+RW */
10526         scsi_ulto2b(0x002A, feature->feature_code);
10527         feature->flags = 0x04;
10528         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10529                 feature->flags |= SGC_F_CURRENT;
10530         feature->add_length = 4;
10531         feature->feature_data[0] = 0x00;
10532         feature->feature_data[1] = 0x00;
10533         feature = (struct scsi_get_config_feature *)
10534             &feature->feature_data[feature->add_length];
10535
10536 f2b:    /* DVD+R */
10537         scsi_ulto2b(0x002B, feature->feature_code);
10538         feature->flags = 0x00;
10539         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10540                 feature->flags |= SGC_F_CURRENT;
10541         feature->add_length = 4;
10542         feature->feature_data[0] = 0x00;
10543         feature = (struct scsi_get_config_feature *)
10544             &feature->feature_data[feature->add_length];
10545
10546 f3a:    /* DVD+RW Dual Layer */
10547         scsi_ulto2b(0x003A, feature->feature_code);
10548         feature->flags = 0x00;
10549         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10550                 feature->flags |= SGC_F_CURRENT;
10551         feature->add_length = 4;
10552         feature->feature_data[0] = 0x00;
10553         feature->feature_data[1] = 0x00;
10554         feature = (struct scsi_get_config_feature *)
10555             &feature->feature_data[feature->add_length];
10556
10557 f3b:    /* DVD+R Dual Layer */
10558         scsi_ulto2b(0x003B, feature->feature_code);
10559         feature->flags = 0x00;
10560         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10561                 feature->flags |= SGC_F_CURRENT;
10562         feature->add_length = 4;
10563         feature->feature_data[0] = 0x00;
10564         feature = (struct scsi_get_config_feature *)
10565             &feature->feature_data[feature->add_length];
10566
10567 done:
10568         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10569         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10570                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10571                 if (scsi_2btoul(feature->feature_code) == starting)
10572                         feature = (struct scsi_get_config_feature *)
10573                             &feature->feature_data[feature->add_length];
10574                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10575         }
10576         scsi_ulto4b(data_len - 4, hdr->data_length);
10577         if (data_len < alloc_len) {
10578                 ctsio->residual = alloc_len - data_len;
10579                 ctsio->kern_data_len = data_len;
10580                 ctsio->kern_total_len = data_len;
10581         } else {
10582                 ctsio->residual = 0;
10583                 ctsio->kern_data_len = alloc_len;
10584                 ctsio->kern_total_len = alloc_len;
10585         }
10586
10587         ctl_set_success(ctsio);
10588         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10589         ctsio->be_move_done = ctl_config_move_done;
10590         ctl_datamove((union ctl_io *)ctsio);
10591         return (CTL_RETVAL_COMPLETE);
10592 }
10593
10594 int
10595 ctl_get_event_status(struct ctl_scsiio *ctsio)
10596 {
10597         struct scsi_get_event_status_header *hdr;
10598         struct scsi_get_event_status *cdb;
10599         struct ctl_lun *lun;
10600         uint32_t alloc_len, data_len;
10601         int notif_class;
10602
10603         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10604         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10605         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10606                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10607                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10608                 ctl_done((union ctl_io *)ctsio);
10609                 return (CTL_RETVAL_COMPLETE);
10610         }
10611         notif_class = cdb->notif_class;
10612         alloc_len = scsi_2btoul(cdb->length);
10613
10614         data_len = sizeof(struct scsi_get_event_status_header);
10615         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10616         ctsio->kern_sg_entries = 0;
10617         ctsio->kern_data_resid = 0;
10618         ctsio->kern_rel_offset = 0;
10619
10620         if (data_len < alloc_len) {
10621                 ctsio->residual = alloc_len - data_len;
10622                 ctsio->kern_data_len = data_len;
10623                 ctsio->kern_total_len = data_len;
10624         } else {
10625                 ctsio->residual = 0;
10626                 ctsio->kern_data_len = alloc_len;
10627                 ctsio->kern_total_len = alloc_len;
10628         }
10629
10630         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10631         scsi_ulto2b(0, hdr->descr_length);
10632         hdr->nea_class = SGESN_NEA;
10633         hdr->supported_class = 0;
10634
10635         ctl_set_success(ctsio);
10636         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10637         ctsio->be_move_done = ctl_config_move_done;
10638         ctl_datamove((union ctl_io *)ctsio);
10639         return (CTL_RETVAL_COMPLETE);
10640 }
10641
10642 int
10643 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10644 {
10645         struct scsi_mechanism_status_header *hdr;
10646         struct scsi_mechanism_status *cdb;
10647         struct ctl_lun *lun;
10648         uint32_t alloc_len, data_len;
10649
10650         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10651         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10652         alloc_len = scsi_2btoul(cdb->length);
10653
10654         data_len = sizeof(struct scsi_mechanism_status_header);
10655         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10656         ctsio->kern_sg_entries = 0;
10657         ctsio->kern_data_resid = 0;
10658         ctsio->kern_rel_offset = 0;
10659
10660         if (data_len < alloc_len) {
10661                 ctsio->residual = alloc_len - data_len;
10662                 ctsio->kern_data_len = data_len;
10663                 ctsio->kern_total_len = data_len;
10664         } else {
10665                 ctsio->residual = 0;
10666                 ctsio->kern_data_len = alloc_len;
10667                 ctsio->kern_total_len = alloc_len;
10668         }
10669
10670         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10671         hdr->state1 = 0x00;
10672         hdr->state2 = 0xe0;
10673         scsi_ulto3b(0, hdr->lba);
10674         hdr->slots_num = 0;
10675         scsi_ulto2b(0, hdr->slots_length);
10676
10677         ctl_set_success(ctsio);
10678         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10679         ctsio->be_move_done = ctl_config_move_done;
10680         ctl_datamove((union ctl_io *)ctsio);
10681         return (CTL_RETVAL_COMPLETE);
10682 }
10683
10684 static void
10685 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10686 {
10687
10688         lba += 150;
10689         buf[0] = 0;
10690         buf[1] = bin2bcd((lba / 75) / 60);
10691         buf[2] = bin2bcd((lba / 75) % 60);
10692         buf[3] = bin2bcd(lba % 75);
10693 }
10694
10695 int
10696 ctl_read_toc(struct ctl_scsiio *ctsio)
10697 {
10698         struct scsi_read_toc_hdr *hdr;
10699         struct scsi_read_toc_type01_descr *descr;
10700         struct scsi_read_toc *cdb;
10701         struct ctl_lun *lun;
10702         uint32_t alloc_len, data_len;
10703         int format, msf;
10704
10705         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10706         cdb = (struct scsi_read_toc *)ctsio->cdb;
10707         msf = (cdb->byte2 & CD_MSF) != 0;
10708         format = cdb->format;
10709         alloc_len = scsi_2btoul(cdb->data_len);
10710
10711         data_len = sizeof(struct scsi_read_toc_hdr);
10712         if (format == 0)
10713                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10714         else
10715                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10716         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10717         ctsio->kern_sg_entries = 0;
10718         ctsio->kern_data_resid = 0;
10719         ctsio->kern_rel_offset = 0;
10720
10721         if (data_len < alloc_len) {
10722                 ctsio->residual = alloc_len - data_len;
10723                 ctsio->kern_data_len = data_len;
10724                 ctsio->kern_total_len = data_len;
10725         } else {
10726                 ctsio->residual = 0;
10727                 ctsio->kern_data_len = alloc_len;
10728                 ctsio->kern_total_len = alloc_len;
10729         }
10730
10731         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10732         if (format == 0) {
10733                 scsi_ulto2b(0x12, hdr->data_length);
10734                 hdr->first = 1;
10735                 hdr->last = 1;
10736                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10737                 descr->addr_ctl = 0x14;
10738                 descr->track_number = 1;
10739                 if (msf)
10740                         ctl_ultomsf(0, descr->track_start);
10741                 else
10742                         scsi_ulto4b(0, descr->track_start);
10743                 descr++;
10744                 descr->addr_ctl = 0x14;
10745                 descr->track_number = 0xaa;
10746                 if (msf)
10747                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10748                 else
10749                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10750         } else {
10751                 scsi_ulto2b(0x0a, hdr->data_length);
10752                 hdr->first = 1;
10753                 hdr->last = 1;
10754                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10755                 descr->addr_ctl = 0x14;
10756                 descr->track_number = 1;
10757                 if (msf)
10758                         ctl_ultomsf(0, descr->track_start);
10759                 else
10760                         scsi_ulto4b(0, descr->track_start);
10761         }
10762
10763         ctl_set_success(ctsio);
10764         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10765         ctsio->be_move_done = ctl_config_move_done;
10766         ctl_datamove((union ctl_io *)ctsio);
10767         return (CTL_RETVAL_COMPLETE);
10768 }
10769
10770 /*
10771  * For known CDB types, parse the LBA and length.
10772  */
10773 static int
10774 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10775 {
10776         if (io->io_hdr.io_type != CTL_IO_SCSI)
10777                 return (1);
10778
10779         switch (io->scsiio.cdb[0]) {
10780         case COMPARE_AND_WRITE: {
10781                 struct scsi_compare_and_write *cdb;
10782
10783                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10784
10785                 *lba = scsi_8btou64(cdb->addr);
10786                 *len = cdb->length;
10787                 break;
10788         }
10789         case READ_6:
10790         case WRITE_6: {
10791                 struct scsi_rw_6 *cdb;
10792
10793                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10794
10795                 *lba = scsi_3btoul(cdb->addr);
10796                 /* only 5 bits are valid in the most significant address byte */
10797                 *lba &= 0x1fffff;
10798                 *len = cdb->length;
10799                 break;
10800         }
10801         case READ_10:
10802         case WRITE_10: {
10803                 struct scsi_rw_10 *cdb;
10804
10805                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10806
10807                 *lba = scsi_4btoul(cdb->addr);
10808                 *len = scsi_2btoul(cdb->length);
10809                 break;
10810         }
10811         case WRITE_VERIFY_10: {
10812                 struct scsi_write_verify_10 *cdb;
10813
10814                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10815
10816                 *lba = scsi_4btoul(cdb->addr);
10817                 *len = scsi_2btoul(cdb->length);
10818                 break;
10819         }
10820         case READ_12:
10821         case WRITE_12: {
10822                 struct scsi_rw_12 *cdb;
10823
10824                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10825
10826                 *lba = scsi_4btoul(cdb->addr);
10827                 *len = scsi_4btoul(cdb->length);
10828                 break;
10829         }
10830         case WRITE_VERIFY_12: {
10831                 struct scsi_write_verify_12 *cdb;
10832
10833                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10834
10835                 *lba = scsi_4btoul(cdb->addr);
10836                 *len = scsi_4btoul(cdb->length);
10837                 break;
10838         }
10839         case READ_16:
10840         case WRITE_16: {
10841                 struct scsi_rw_16 *cdb;
10842
10843                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10844
10845                 *lba = scsi_8btou64(cdb->addr);
10846                 *len = scsi_4btoul(cdb->length);
10847                 break;
10848         }
10849         case WRITE_ATOMIC_16: {
10850                 struct scsi_write_atomic_16 *cdb;
10851
10852                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10853
10854                 *lba = scsi_8btou64(cdb->addr);
10855                 *len = scsi_2btoul(cdb->length);
10856                 break;
10857         }
10858         case WRITE_VERIFY_16: {
10859                 struct scsi_write_verify_16 *cdb;
10860
10861                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10862
10863                 *lba = scsi_8btou64(cdb->addr);
10864                 *len = scsi_4btoul(cdb->length);
10865                 break;
10866         }
10867         case WRITE_SAME_10: {
10868                 struct scsi_write_same_10 *cdb;
10869
10870                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10871
10872                 *lba = scsi_4btoul(cdb->addr);
10873                 *len = scsi_2btoul(cdb->length);
10874                 break;
10875         }
10876         case WRITE_SAME_16: {
10877                 struct scsi_write_same_16 *cdb;
10878
10879                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10880
10881                 *lba = scsi_8btou64(cdb->addr);
10882                 *len = scsi_4btoul(cdb->length);
10883                 break;
10884         }
10885         case VERIFY_10: {
10886                 struct scsi_verify_10 *cdb;
10887
10888                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10889
10890                 *lba = scsi_4btoul(cdb->addr);
10891                 *len = scsi_2btoul(cdb->length);
10892                 break;
10893         }
10894         case VERIFY_12: {
10895                 struct scsi_verify_12 *cdb;
10896
10897                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10898
10899                 *lba = scsi_4btoul(cdb->addr);
10900                 *len = scsi_4btoul(cdb->length);
10901                 break;
10902         }
10903         case VERIFY_16: {
10904                 struct scsi_verify_16 *cdb;
10905
10906                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10907
10908                 *lba = scsi_8btou64(cdb->addr);
10909                 *len = scsi_4btoul(cdb->length);
10910                 break;
10911         }
10912         case UNMAP: {
10913                 *lba = 0;
10914                 *len = UINT64_MAX;
10915                 break;
10916         }
10917         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10918                 struct scsi_get_lba_status *cdb;
10919
10920                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10921                 *lba = scsi_8btou64(cdb->addr);
10922                 *len = UINT32_MAX;
10923                 break;
10924         }
10925         default:
10926                 return (1);
10927                 break; /* NOTREACHED */
10928         }
10929
10930         return (0);
10931 }
10932
10933 static ctl_action
10934 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10935     bool seq)
10936 {
10937         uint64_t endlba1, endlba2;
10938
10939         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10940         endlba2 = lba2 + len2 - 1;
10941
10942         if ((endlba1 < lba2) || (endlba2 < lba1))
10943                 return (CTL_ACTION_PASS);
10944         else
10945                 return (CTL_ACTION_BLOCK);
10946 }
10947
10948 static int
10949 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10950 {
10951         struct ctl_ptr_len_flags *ptrlen;
10952         struct scsi_unmap_desc *buf, *end, *range;
10953         uint64_t lba;
10954         uint32_t len;
10955
10956         /* If not UNMAP -- go other way. */
10957         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10958             io->scsiio.cdb[0] != UNMAP)
10959                 return (CTL_ACTION_ERROR);
10960
10961         /* If UNMAP without data -- block and wait for data. */
10962         ptrlen = (struct ctl_ptr_len_flags *)
10963             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10964         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10965             ptrlen->ptr == NULL)
10966                 return (CTL_ACTION_BLOCK);
10967
10968         /* UNMAP with data -- check for collision. */
10969         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10970         end = buf + ptrlen->len / sizeof(*buf);
10971         for (range = buf; range < end; range++) {
10972                 lba = scsi_8btou64(range->lba);
10973                 len = scsi_4btoul(range->length);
10974                 if ((lba < lba2 + len2) && (lba + len > lba2))
10975                         return (CTL_ACTION_BLOCK);
10976         }
10977         return (CTL_ACTION_PASS);
10978 }
10979
10980 static ctl_action
10981 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10982 {
10983         uint64_t lba1, lba2;
10984         uint64_t len1, len2;
10985         int retval;
10986
10987         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10988                 return (CTL_ACTION_ERROR);
10989
10990         retval = ctl_extent_check_unmap(io1, lba2, len2);
10991         if (retval != CTL_ACTION_ERROR)
10992                 return (retval);
10993
10994         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10995                 return (CTL_ACTION_ERROR);
10996
10997         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10998                 seq = FALSE;
10999         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11000 }
11001
11002 static ctl_action
11003 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
11004 {
11005         uint64_t lba1, lba2;
11006         uint64_t len1, len2;
11007
11008         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11009                 return (CTL_ACTION_PASS);
11010         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11011                 return (CTL_ACTION_ERROR);
11012         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11013                 return (CTL_ACTION_ERROR);
11014
11015         if (lba1 + len1 == lba2)
11016                 return (CTL_ACTION_BLOCK);
11017         return (CTL_ACTION_PASS);
11018 }
11019
11020 static ctl_action
11021 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11022     union ctl_io *ooa_io)
11023 {
11024         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11025         const ctl_serialize_action *serialize_row;
11026
11027         /*
11028          * The initiator attempted multiple untagged commands at the same
11029          * time.  Can't do that.
11030          */
11031         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11032          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11033          && ((pending_io->io_hdr.nexus.targ_port ==
11034               ooa_io->io_hdr.nexus.targ_port)
11035           && (pending_io->io_hdr.nexus.initid ==
11036               ooa_io->io_hdr.nexus.initid))
11037          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11038               CTL_FLAG_STATUS_SENT)) == 0))
11039                 return (CTL_ACTION_OVERLAP);
11040
11041         /*
11042          * The initiator attempted to send multiple tagged commands with
11043          * the same ID.  (It's fine if different initiators have the same
11044          * tag ID.)
11045          *
11046          * Even if all of those conditions are true, we don't kill the I/O
11047          * if the command ahead of us has been aborted.  We won't end up
11048          * sending it to the FETD, and it's perfectly legal to resend a
11049          * command with the same tag number as long as the previous
11050          * instance of this tag number has been aborted somehow.
11051          */
11052         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11053          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11054          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11055          && ((pending_io->io_hdr.nexus.targ_port ==
11056               ooa_io->io_hdr.nexus.targ_port)
11057           && (pending_io->io_hdr.nexus.initid ==
11058               ooa_io->io_hdr.nexus.initid))
11059          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11060               CTL_FLAG_STATUS_SENT)) == 0))
11061                 return (CTL_ACTION_OVERLAP_TAG);
11062
11063         /*
11064          * If we get a head of queue tag, SAM-3 says that we should
11065          * immediately execute it.
11066          *
11067          * What happens if this command would normally block for some other
11068          * reason?  e.g. a request sense with a head of queue tag
11069          * immediately after a write.  Normally that would block, but this
11070          * will result in its getting executed immediately...
11071          *
11072          * We currently return "pass" instead of "skip", so we'll end up
11073          * going through the rest of the queue to check for overlapped tags.
11074          *
11075          * XXX KDM check for other types of blockage first??
11076          */
11077         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11078                 return (CTL_ACTION_PASS);
11079
11080         /*
11081          * Ordered tags have to block until all items ahead of them
11082          * have completed.  If we get called with an ordered tag, we always
11083          * block, if something else is ahead of us in the queue.
11084          */
11085         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11086                 return (CTL_ACTION_BLOCK);
11087
11088         /*
11089          * Simple tags get blocked until all head of queue and ordered tags
11090          * ahead of them have completed.  I'm lumping untagged commands in
11091          * with simple tags here.  XXX KDM is that the right thing to do?
11092          */
11093         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11094           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11095          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11096           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11097                 return (CTL_ACTION_BLOCK);
11098
11099         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11100         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11101             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11102              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11103              pending_io->scsiio.cdb[1], pending_io));
11104         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11105         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11106                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11107         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11108             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11109              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11110              ooa_io->scsiio.cdb[1], ooa_io));
11111
11112         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11113
11114         switch (serialize_row[pending_entry->seridx]) {
11115         case CTL_SER_BLOCK:
11116                 return (CTL_ACTION_BLOCK);
11117         case CTL_SER_EXTENT:
11118                 return (ctl_extent_check(ooa_io, pending_io,
11119                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11120         case CTL_SER_EXTENTOPT:
11121                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11122                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11123                         return (ctl_extent_check(ooa_io, pending_io,
11124                             (lun->be_lun &&
11125                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11126                 return (CTL_ACTION_PASS);
11127         case CTL_SER_EXTENTSEQ:
11128                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11129                         return (ctl_extent_check_seq(ooa_io, pending_io));
11130                 return (CTL_ACTION_PASS);
11131         case CTL_SER_PASS:
11132                 return (CTL_ACTION_PASS);
11133         case CTL_SER_BLOCKOPT:
11134                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11135                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11136                         return (CTL_ACTION_BLOCK);
11137                 return (CTL_ACTION_PASS);
11138         case CTL_SER_SKIP:
11139                 return (CTL_ACTION_SKIP);
11140         default:
11141                 panic("%s: Invalid serialization value %d for %d => %d",
11142                     __func__, serialize_row[pending_entry->seridx],
11143                     pending_entry->seridx, ooa_entry->seridx);
11144         }
11145
11146         return (CTL_ACTION_ERROR);
11147 }
11148
11149 /*
11150  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11151  * Assumptions:
11152  * - pending_io is generally either incoming, or on the blocked queue
11153  * - starting I/O is the I/O we want to start the check with.
11154  */
11155 static ctl_action
11156 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11157               union ctl_io *starting_io)
11158 {
11159         union ctl_io *ooa_io;
11160         ctl_action action;
11161
11162         mtx_assert(&lun->lun_lock, MA_OWNED);
11163
11164         /*
11165          * Run back along the OOA queue, starting with the current
11166          * blocked I/O and going through every I/O before it on the
11167          * queue.  If starting_io is NULL, we'll just end up returning
11168          * CTL_ACTION_PASS.
11169          */
11170         for (ooa_io = starting_io; ooa_io != NULL;
11171              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11172              ooa_links)){
11173
11174                 /*
11175                  * This routine just checks to see whether
11176                  * cur_blocked is blocked by ooa_io, which is ahead
11177                  * of it in the queue.  It doesn't queue/dequeue
11178                  * cur_blocked.
11179                  */
11180                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11181                 switch (action) {
11182                 case CTL_ACTION_BLOCK:
11183                 case CTL_ACTION_OVERLAP:
11184                 case CTL_ACTION_OVERLAP_TAG:
11185                 case CTL_ACTION_SKIP:
11186                 case CTL_ACTION_ERROR:
11187                         return (action);
11188                         break; /* NOTREACHED */
11189                 case CTL_ACTION_PASS:
11190                         break;
11191                 default:
11192                         panic("%s: Invalid action %d\n", __func__, action);
11193                 }
11194         }
11195
11196         return (CTL_ACTION_PASS);
11197 }
11198
11199 /*
11200  * Assumptions:
11201  * - An I/O has just completed, and has been removed from the per-LUN OOA
11202  *   queue, so some items on the blocked queue may now be unblocked.
11203  */
11204 static int
11205 ctl_check_blocked(struct ctl_lun *lun)
11206 {
11207         struct ctl_softc *softc = lun->ctl_softc;
11208         union ctl_io *cur_blocked, *next_blocked;
11209
11210         mtx_assert(&lun->lun_lock, MA_OWNED);
11211
11212         /*
11213          * Run forward from the head of the blocked queue, checking each
11214          * entry against the I/Os prior to it on the OOA queue to see if
11215          * there is still any blockage.
11216          *
11217          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11218          * with our removing a variable on it while it is traversing the
11219          * list.
11220          */
11221         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11222              cur_blocked != NULL; cur_blocked = next_blocked) {
11223                 union ctl_io *prev_ooa;
11224                 ctl_action action;
11225
11226                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11227                                                           blocked_links);
11228
11229                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11230                                                       ctl_ooaq, ooa_links);
11231
11232                 /*
11233                  * If cur_blocked happens to be the first item in the OOA
11234                  * queue now, prev_ooa will be NULL, and the action
11235                  * returned will just be CTL_ACTION_PASS.
11236                  */
11237                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11238
11239                 switch (action) {
11240                 case CTL_ACTION_BLOCK:
11241                         /* Nothing to do here, still blocked */
11242                         break;
11243                 case CTL_ACTION_OVERLAP:
11244                 case CTL_ACTION_OVERLAP_TAG:
11245                         /*
11246                          * This shouldn't happen!  In theory we've already
11247                          * checked this command for overlap...
11248                          */
11249                         break;
11250                 case CTL_ACTION_PASS:
11251                 case CTL_ACTION_SKIP: {
11252                         const struct ctl_cmd_entry *entry;
11253
11254                         /*
11255                          * The skip case shouldn't happen, this transaction
11256                          * should have never made it onto the blocked queue.
11257                          */
11258                         /*
11259                          * This I/O is no longer blocked, we can remove it
11260                          * from the blocked queue.  Since this is a TAILQ
11261                          * (doubly linked list), we can do O(1) removals
11262                          * from any place on the list.
11263                          */
11264                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11265                                      blocked_links);
11266                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11267
11268                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11269                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11270                                 /*
11271                                  * Need to send IO back to original side to
11272                                  * run
11273                                  */
11274                                 union ctl_ha_msg msg_info;
11275
11276                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11277                                 msg_info.hdr.original_sc =
11278                                         cur_blocked->io_hdr.original_sc;
11279                                 msg_info.hdr.serializing_sc = cur_blocked;
11280                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11281                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11282                                     sizeof(msg_info.hdr), M_NOWAIT);
11283                                 break;
11284                         }
11285                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11286
11287                         /*
11288                          * Check this I/O for LUN state changes that may
11289                          * have happened while this command was blocked.
11290                          * The LUN state may have been changed by a command
11291                          * ahead of us in the queue, so we need to re-check
11292                          * for any states that can be caused by SCSI
11293                          * commands.
11294                          */
11295                         if (ctl_scsiio_lun_check(lun, entry,
11296                                                  &cur_blocked->scsiio) == 0) {
11297                                 cur_blocked->io_hdr.flags |=
11298                                                       CTL_FLAG_IS_WAS_ON_RTR;
11299                                 ctl_enqueue_rtr(cur_blocked);
11300                         } else
11301                                 ctl_done(cur_blocked);
11302                         break;
11303                 }
11304                 default:
11305                         /*
11306                          * This probably shouldn't happen -- we shouldn't
11307                          * get CTL_ACTION_ERROR, or anything else.
11308                          */
11309                         break;
11310                 }
11311         }
11312
11313         return (CTL_RETVAL_COMPLETE);
11314 }
11315
11316 /*
11317  * This routine (with one exception) checks LUN flags that can be set by
11318  * commands ahead of us in the OOA queue.  These flags have to be checked
11319  * when a command initially comes in, and when we pull a command off the
11320  * blocked queue and are preparing to execute it.  The reason we have to
11321  * check these flags for commands on the blocked queue is that the LUN
11322  * state may have been changed by a command ahead of us while we're on the
11323  * blocked queue.
11324  *
11325  * Ordering is somewhat important with these checks, so please pay
11326  * careful attention to the placement of any new checks.
11327  */
11328 static int
11329 ctl_scsiio_lun_check(struct ctl_lun *lun,
11330     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11331 {
11332         struct ctl_softc *softc = lun->ctl_softc;
11333         int retval;
11334         uint32_t residx;
11335
11336         retval = 0;
11337
11338         mtx_assert(&lun->lun_lock, MA_OWNED);
11339
11340         /*
11341          * If this shelf is a secondary shelf controller, we may have to
11342          * reject some commands disallowed by HA mode and link state.
11343          */
11344         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11345                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11346                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11347                         ctl_set_lun_unavail(ctsio);
11348                         retval = 1;
11349                         goto bailout;
11350                 }
11351                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11352                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11353                         ctl_set_lun_transit(ctsio);
11354                         retval = 1;
11355                         goto bailout;
11356                 }
11357                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11358                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11359                         ctl_set_lun_standby(ctsio);
11360                         retval = 1;
11361                         goto bailout;
11362                 }
11363
11364                 /* The rest of checks are only done on executing side */
11365                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11366                         goto bailout;
11367         }
11368
11369         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11370                 if (lun->be_lun &&
11371                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11372                         ctl_set_hw_write_protected(ctsio);
11373                         retval = 1;
11374                         goto bailout;
11375                 }
11376                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11377                     .eca_and_aen & SCP_SWP) != 0) {
11378                         ctl_set_sense(ctsio, /*current_error*/ 1,
11379                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11380                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11381                         retval = 1;
11382                         goto bailout;
11383                 }
11384         }
11385
11386         /*
11387          * Check for a reservation conflict.  If this command isn't allowed
11388          * even on reserved LUNs, and if this initiator isn't the one who
11389          * reserved us, reject the command with a reservation conflict.
11390          */
11391         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11392         if ((lun->flags & CTL_LUN_RESERVED)
11393          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11394                 if (lun->res_idx != residx) {
11395                         ctl_set_reservation_conflict(ctsio);
11396                         retval = 1;
11397                         goto bailout;
11398                 }
11399         }
11400
11401         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11402             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11403                 /* No reservation or command is allowed. */;
11404         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11405             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11406              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11407              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11408                 /* The command is allowed for Write Exclusive resv. */;
11409         } else {
11410                 /*
11411                  * if we aren't registered or it's a res holder type
11412                  * reservation and this isn't the res holder then set a
11413                  * conflict.
11414                  */
11415                 if (ctl_get_prkey(lun, residx) == 0 ||
11416                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11417                         ctl_set_reservation_conflict(ctsio);
11418                         retval = 1;
11419                         goto bailout;
11420                 }
11421         }
11422
11423         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11424                 if (lun->flags & CTL_LUN_EJECTED)
11425                         ctl_set_lun_ejected(ctsio);
11426                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11427                         if (lun->flags & CTL_LUN_REMOVABLE)
11428                                 ctl_set_lun_no_media(ctsio);
11429                         else
11430                                 ctl_set_lun_int_reqd(ctsio);
11431                 } else if (lun->flags & CTL_LUN_STOPPED)
11432                         ctl_set_lun_stopped(ctsio);
11433                 else
11434                         goto bailout;
11435                 retval = 1;
11436                 goto bailout;
11437         }
11438
11439 bailout:
11440         return (retval);
11441 }
11442
11443 static void
11444 ctl_failover_io(union ctl_io *io, int have_lock)
11445 {
11446         ctl_set_busy(&io->scsiio);
11447         ctl_done(io);
11448 }
11449
11450 static void
11451 ctl_failover_lun(union ctl_io *rio)
11452 {
11453         struct ctl_softc *softc = control_softc;
11454         struct ctl_lun *lun;
11455         struct ctl_io_hdr *io, *next_io;
11456         uint32_t targ_lun;
11457
11458         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11459         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11460
11461         /* Find and lock the LUN. */
11462         mtx_lock(&softc->ctl_lock);
11463         if ((targ_lun < CTL_MAX_LUNS) &&
11464             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11465                 mtx_lock(&lun->lun_lock);
11466                 mtx_unlock(&softc->ctl_lock);
11467                 if (lun->flags & CTL_LUN_DISABLED) {
11468                         mtx_unlock(&lun->lun_lock);
11469                         return;
11470                 }
11471         } else {
11472                 mtx_unlock(&softc->ctl_lock);
11473                 return;
11474         }
11475
11476         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11477                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11478                         /* We are master */
11479                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11480                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11481                                         io->flags |= CTL_FLAG_ABORT;
11482                                         io->flags |= CTL_FLAG_FAILOVER;
11483                                 } else { /* This can be only due to DATAMOVE */
11484                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11485                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11486                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11487                                         io->port_status = 31340;
11488                                         ctl_enqueue_isc((union ctl_io *)io);
11489                                 }
11490                         }
11491                         /* We are slave */
11492                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11493                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11494                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11495                                         io->flags |= CTL_FLAG_FAILOVER;
11496                                 } else {
11497                                         ctl_set_busy(&((union ctl_io *)io)->
11498                                             scsiio);
11499                                         ctl_done((union ctl_io *)io);
11500                                 }
11501                         }
11502                 }
11503         } else { /* SERIALIZE modes */
11504                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11505                     next_io) {
11506                         /* We are master */
11507                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11508                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11509                                     blocked_links);
11510                                 io->flags &= ~CTL_FLAG_BLOCKED;
11511                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11512                                 ctl_free_io((union ctl_io *)io);
11513                         }
11514                 }
11515                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11516                         /* We are master */
11517                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11518                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11519                                 ctl_free_io((union ctl_io *)io);
11520                         }
11521                         /* We are slave */
11522                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11523                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11524                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11525                                         ctl_set_busy(&((union ctl_io *)io)->
11526                                             scsiio);
11527                                         ctl_done((union ctl_io *)io);
11528                                 }
11529                         }
11530                 }
11531                 ctl_check_blocked(lun);
11532         }
11533         mtx_unlock(&lun->lun_lock);
11534 }
11535
11536 static int
11537 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11538 {
11539         struct ctl_lun *lun;
11540         const struct ctl_cmd_entry *entry;
11541         uint32_t initidx, targ_lun;
11542         int retval;
11543
11544         retval = 0;
11545
11546         lun = NULL;
11547
11548         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11549         if ((targ_lun < CTL_MAX_LUNS)
11550          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11551                 /*
11552                  * If the LUN is invalid, pretend that it doesn't exist.
11553                  * It will go away as soon as all pending I/O has been
11554                  * completed.
11555                  */
11556                 mtx_lock(&lun->lun_lock);
11557                 if (lun->flags & CTL_LUN_DISABLED) {
11558                         mtx_unlock(&lun->lun_lock);
11559                         lun = NULL;
11560                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11561                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11562                 } else {
11563                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11564                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11565                                 lun->be_lun;
11566
11567                         /*
11568                          * Every I/O goes into the OOA queue for a
11569                          * particular LUN, and stays there until completion.
11570                          */
11571 #ifdef CTL_TIME_IO
11572                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11573                                 lun->idle_time += getsbinuptime() -
11574                                     lun->last_busy;
11575                         }
11576 #endif
11577                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11578                             ooa_links);
11579                 }
11580         } else {
11581                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11582                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11583         }
11584
11585         /* Get command entry and return error if it is unsuppotyed. */
11586         entry = ctl_validate_command(ctsio);
11587         if (entry == NULL) {
11588                 if (lun)
11589                         mtx_unlock(&lun->lun_lock);
11590                 return (retval);
11591         }
11592
11593         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11594         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11595
11596         /*
11597          * Check to see whether we can send this command to LUNs that don't
11598          * exist.  This should pretty much only be the case for inquiry
11599          * and request sense.  Further checks, below, really require having
11600          * a LUN, so we can't really check the command anymore.  Just put
11601          * it on the rtr queue.
11602          */
11603         if (lun == NULL) {
11604                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11605                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11606                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11607                         return (retval);
11608                 }
11609
11610                 ctl_set_unsupported_lun(ctsio);
11611                 ctl_done((union ctl_io *)ctsio);
11612                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11613                 return (retval);
11614         } else {
11615                 /*
11616                  * Make sure we support this particular command on this LUN.
11617                  * e.g., we don't support writes to the control LUN.
11618                  */
11619                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11620                         mtx_unlock(&lun->lun_lock);
11621                         ctl_set_invalid_opcode(ctsio);
11622                         ctl_done((union ctl_io *)ctsio);
11623                         return (retval);
11624                 }
11625         }
11626
11627         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11628
11629 #ifdef CTL_WITH_CA
11630         /*
11631          * If we've got a request sense, it'll clear the contingent
11632          * allegiance condition.  Otherwise, if we have a CA condition for
11633          * this initiator, clear it, because it sent down a command other
11634          * than request sense.
11635          */
11636         if ((ctsio->cdb[0] != REQUEST_SENSE)
11637          && (ctl_is_set(lun->have_ca, initidx)))
11638                 ctl_clear_mask(lun->have_ca, initidx);
11639 #endif
11640
11641         /*
11642          * If the command has this flag set, it handles its own unit
11643          * attention reporting, we shouldn't do anything.  Otherwise we
11644          * check for any pending unit attentions, and send them back to the
11645          * initiator.  We only do this when a command initially comes in,
11646          * not when we pull it off the blocked queue.
11647          *
11648          * According to SAM-3, section 5.3.2, the order that things get
11649          * presented back to the host is basically unit attentions caused
11650          * by some sort of reset event, busy status, reservation conflicts
11651          * or task set full, and finally any other status.
11652          *
11653          * One issue here is that some of the unit attentions we report
11654          * don't fall into the "reset" category (e.g. "reported luns data
11655          * has changed").  So reporting it here, before the reservation
11656          * check, may be technically wrong.  I guess the only thing to do
11657          * would be to check for and report the reset events here, and then
11658          * check for the other unit attention types after we check for a
11659          * reservation conflict.
11660          *
11661          * XXX KDM need to fix this
11662          */
11663         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11664                 ctl_ua_type ua_type;
11665
11666                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11667                     SSD_TYPE_NONE);
11668                 if (ua_type != CTL_UA_NONE) {
11669                         mtx_unlock(&lun->lun_lock);
11670                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11671                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11672                         ctsio->sense_len = SSD_FULL_SIZE;
11673                         ctl_done((union ctl_io *)ctsio);
11674                         return (retval);
11675                 }
11676         }
11677
11678
11679         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11680                 mtx_unlock(&lun->lun_lock);
11681                 ctl_done((union ctl_io *)ctsio);
11682                 return (retval);
11683         }
11684
11685         /*
11686          * XXX CHD this is where we want to send IO to other side if
11687          * this LUN is secondary on this SC. We will need to make a copy
11688          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11689          * the copy we send as FROM_OTHER.
11690          * We also need to stuff the address of the original IO so we can
11691          * find it easily. Something similar will need be done on the other
11692          * side so when we are done we can find the copy.
11693          */
11694         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11695             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11696             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11697                 union ctl_ha_msg msg_info;
11698                 int isc_retval;
11699
11700                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11701                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11702                 mtx_unlock(&lun->lun_lock);
11703
11704                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11705                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11706                 msg_info.hdr.serializing_sc = NULL;
11707                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11708                 msg_info.scsi.tag_num = ctsio->tag_num;
11709                 msg_info.scsi.tag_type = ctsio->tag_type;
11710                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11711                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11712
11713                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11714                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11715                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11716                         ctl_set_busy(ctsio);
11717                         ctl_done((union ctl_io *)ctsio);
11718                         return (retval);
11719                 }
11720                 return (retval);
11721         }
11722
11723         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11724                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11725                               ctl_ooaq, ooa_links))) {
11726         case CTL_ACTION_BLOCK:
11727                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11728                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11729                                   blocked_links);
11730                 mtx_unlock(&lun->lun_lock);
11731                 return (retval);
11732         case CTL_ACTION_PASS:
11733         case CTL_ACTION_SKIP:
11734                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11735                 mtx_unlock(&lun->lun_lock);
11736                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11737                 break;
11738         case CTL_ACTION_OVERLAP:
11739                 mtx_unlock(&lun->lun_lock);
11740                 ctl_set_overlapped_cmd(ctsio);
11741                 ctl_done((union ctl_io *)ctsio);
11742                 break;
11743         case CTL_ACTION_OVERLAP_TAG:
11744                 mtx_unlock(&lun->lun_lock);
11745                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11746                 ctl_done((union ctl_io *)ctsio);
11747                 break;
11748         case CTL_ACTION_ERROR:
11749         default:
11750                 mtx_unlock(&lun->lun_lock);
11751                 ctl_set_internal_failure(ctsio,
11752                                          /*sks_valid*/ 0,
11753                                          /*retry_count*/ 0);
11754                 ctl_done((union ctl_io *)ctsio);
11755                 break;
11756         }
11757         return (retval);
11758 }
11759
11760 const struct ctl_cmd_entry *
11761 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11762 {
11763         const struct ctl_cmd_entry *entry;
11764         int service_action;
11765
11766         entry = &ctl_cmd_table[ctsio->cdb[0]];
11767         if (sa)
11768                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11769         if (entry->flags & CTL_CMD_FLAG_SA5) {
11770                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11771                 entry = &((const struct ctl_cmd_entry *)
11772                     entry->execute)[service_action];
11773         }
11774         return (entry);
11775 }
11776
11777 const struct ctl_cmd_entry *
11778 ctl_validate_command(struct ctl_scsiio *ctsio)
11779 {
11780         const struct ctl_cmd_entry *entry;
11781         int i, sa;
11782         uint8_t diff;
11783
11784         entry = ctl_get_cmd_entry(ctsio, &sa);
11785         if (entry->execute == NULL) {
11786                 if (sa)
11787                         ctl_set_invalid_field(ctsio,
11788                                               /*sks_valid*/ 1,
11789                                               /*command*/ 1,
11790                                               /*field*/ 1,
11791                                               /*bit_valid*/ 1,
11792                                               /*bit*/ 4);
11793                 else
11794                         ctl_set_invalid_opcode(ctsio);
11795                 ctl_done((union ctl_io *)ctsio);
11796                 return (NULL);
11797         }
11798         KASSERT(entry->length > 0,
11799             ("Not defined length for command 0x%02x/0x%02x",
11800              ctsio->cdb[0], ctsio->cdb[1]));
11801         for (i = 1; i < entry->length; i++) {
11802                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11803                 if (diff == 0)
11804                         continue;
11805                 ctl_set_invalid_field(ctsio,
11806                                       /*sks_valid*/ 1,
11807                                       /*command*/ 1,
11808                                       /*field*/ i,
11809                                       /*bit_valid*/ 1,
11810                                       /*bit*/ fls(diff) - 1);
11811                 ctl_done((union ctl_io *)ctsio);
11812                 return (NULL);
11813         }
11814         return (entry);
11815 }
11816
11817 static int
11818 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11819 {
11820
11821         switch (lun_type) {
11822         case T_DIRECT:
11823                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11824                         return (0);
11825                 break;
11826         case T_PROCESSOR:
11827                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11828                         return (0);
11829                 break;
11830         case T_CDROM:
11831                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11832                         return (0);
11833                 break;
11834         default:
11835                 return (0);
11836         }
11837         return (1);
11838 }
11839
11840 static int
11841 ctl_scsiio(struct ctl_scsiio *ctsio)
11842 {
11843         int retval;
11844         const struct ctl_cmd_entry *entry;
11845
11846         retval = CTL_RETVAL_COMPLETE;
11847
11848         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11849
11850         entry = ctl_get_cmd_entry(ctsio, NULL);
11851
11852         /*
11853          * If this I/O has been aborted, just send it straight to
11854          * ctl_done() without executing it.
11855          */
11856         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11857                 ctl_done((union ctl_io *)ctsio);
11858                 goto bailout;
11859         }
11860
11861         /*
11862          * All the checks should have been handled by ctl_scsiio_precheck().
11863          * We should be clear now to just execute the I/O.
11864          */
11865         retval = entry->execute(ctsio);
11866
11867 bailout:
11868         return (retval);
11869 }
11870
11871 /*
11872  * Since we only implement one target right now, a bus reset simply resets
11873  * our single target.
11874  */
11875 static int
11876 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11877 {
11878         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11879 }
11880
11881 static int
11882 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11883                  ctl_ua_type ua_type)
11884 {
11885         struct ctl_port *port;
11886         struct ctl_lun *lun;
11887         int retval;
11888
11889         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11890                 union ctl_ha_msg msg_info;
11891
11892                 msg_info.hdr.nexus = io->io_hdr.nexus;
11893                 if (ua_type==CTL_UA_TARG_RESET)
11894                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11895                 else
11896                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11897                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11898                 msg_info.hdr.original_sc = NULL;
11899                 msg_info.hdr.serializing_sc = NULL;
11900                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11901                     sizeof(msg_info.task), M_WAITOK);
11902         }
11903         retval = 0;
11904
11905         mtx_lock(&softc->ctl_lock);
11906         port = ctl_io_port(&io->io_hdr);
11907         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11908                 if (port != NULL &&
11909                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11910                         continue;
11911                 retval += ctl_do_lun_reset(lun, io, ua_type);
11912         }
11913         mtx_unlock(&softc->ctl_lock);
11914         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11915         return (retval);
11916 }
11917
11918 /*
11919  * The LUN should always be set.  The I/O is optional, and is used to
11920  * distinguish between I/Os sent by this initiator, and by other
11921  * initiators.  We set unit attention for initiators other than this one.
11922  * SAM-3 is vague on this point.  It does say that a unit attention should
11923  * be established for other initiators when a LUN is reset (see section
11924  * 5.7.3), but it doesn't specifically say that the unit attention should
11925  * be established for this particular initiator when a LUN is reset.  Here
11926  * is the relevant text, from SAM-3 rev 8:
11927  *
11928  * 5.7.2 When a SCSI initiator port aborts its own tasks
11929  *
11930  * When a SCSI initiator port causes its own task(s) to be aborted, no
11931  * notification that the task(s) have been aborted shall be returned to
11932  * the SCSI initiator port other than the completion response for the
11933  * command or task management function action that caused the task(s) to
11934  * be aborted and notification(s) associated with related effects of the
11935  * action (e.g., a reset unit attention condition).
11936  *
11937  * XXX KDM for now, we're setting unit attention for all initiators.
11938  */
11939 static int
11940 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11941 {
11942         union ctl_io *xio;
11943 #if 0
11944         uint32_t initidx;
11945 #endif
11946         int i;
11947
11948         mtx_lock(&lun->lun_lock);
11949         /*
11950          * Run through the OOA queue and abort each I/O.
11951          */
11952         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11953              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11954                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11955         }
11956
11957         /*
11958          * This version sets unit attention for every
11959          */
11960 #if 0
11961         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11962         ctl_est_ua_all(lun, initidx, ua_type);
11963 #else
11964         ctl_est_ua_all(lun, -1, ua_type);
11965 #endif
11966
11967         /*
11968          * A reset (any kind, really) clears reservations established with
11969          * RESERVE/RELEASE.  It does not clear reservations established
11970          * with PERSISTENT RESERVE OUT, but we don't support that at the
11971          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11972          * reservations made with the RESERVE/RELEASE commands, because
11973          * those commands are obsolete in SPC-3.
11974          */
11975         lun->flags &= ~CTL_LUN_RESERVED;
11976
11977 #ifdef CTL_WITH_CA
11978         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11979                 ctl_clear_mask(lun->have_ca, i);
11980 #endif
11981         lun->prevent_count = 0;
11982         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11983                 ctl_clear_mask(lun->prevent, i);
11984         mtx_unlock(&lun->lun_lock);
11985
11986         return (0);
11987 }
11988
11989 static int
11990 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11991 {
11992         struct ctl_lun *lun;
11993         uint32_t targ_lun;
11994         int retval;
11995
11996         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11997         mtx_lock(&softc->ctl_lock);
11998         if ((targ_lun >= CTL_MAX_LUNS) ||
11999             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12000                 mtx_unlock(&softc->ctl_lock);
12001                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12002                 return (1);
12003         }
12004         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
12005         mtx_unlock(&softc->ctl_lock);
12006         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12007
12008         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
12009                 union ctl_ha_msg msg_info;
12010
12011                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12012                 msg_info.hdr.nexus = io->io_hdr.nexus;
12013                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
12014                 msg_info.hdr.original_sc = NULL;
12015                 msg_info.hdr.serializing_sc = NULL;
12016                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12017                     sizeof(msg_info.task), M_WAITOK);
12018         }
12019         return (retval);
12020 }
12021
12022 static void
12023 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12024     int other_sc)
12025 {
12026         union ctl_io *xio;
12027
12028         mtx_assert(&lun->lun_lock, MA_OWNED);
12029
12030         /*
12031          * Run through the OOA queue and attempt to find the given I/O.
12032          * The target port, initiator ID, tag type and tag number have to
12033          * match the values that we got from the initiator.  If we have an
12034          * untagged command to abort, simply abort the first untagged command
12035          * we come to.  We only allow one untagged command at a time of course.
12036          */
12037         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12038              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12039
12040                 if ((targ_port == UINT32_MAX ||
12041                      targ_port == xio->io_hdr.nexus.targ_port) &&
12042                     (init_id == UINT32_MAX ||
12043                      init_id == xio->io_hdr.nexus.initid)) {
12044                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12045                             init_id != xio->io_hdr.nexus.initid)
12046                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12047                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12048                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12049                                 union ctl_ha_msg msg_info;
12050
12051                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12052                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12053                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12054                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12055                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12056                                 msg_info.hdr.original_sc = NULL;
12057                                 msg_info.hdr.serializing_sc = NULL;
12058                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12059                                     sizeof(msg_info.task), M_NOWAIT);
12060                         }
12061                 }
12062         }
12063 }
12064
12065 static int
12066 ctl_abort_task_set(union ctl_io *io)
12067 {
12068         struct ctl_softc *softc = control_softc;
12069         struct ctl_lun *lun;
12070         uint32_t targ_lun;
12071
12072         /*
12073          * Look up the LUN.
12074          */
12075         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12076         mtx_lock(&softc->ctl_lock);
12077         if ((targ_lun >= CTL_MAX_LUNS) ||
12078             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12079                 mtx_unlock(&softc->ctl_lock);
12080                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12081                 return (1);
12082         }
12083
12084         mtx_lock(&lun->lun_lock);
12085         mtx_unlock(&softc->ctl_lock);
12086         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12087                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12088                     io->io_hdr.nexus.initid,
12089                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12090         } else { /* CTL_TASK_CLEAR_TASK_SET */
12091                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12092                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12093         }
12094         mtx_unlock(&lun->lun_lock);
12095         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12096         return (0);
12097 }
12098
12099 static int
12100 ctl_i_t_nexus_reset(union ctl_io *io)
12101 {
12102         struct ctl_softc *softc = control_softc;
12103         struct ctl_lun *lun;
12104         uint32_t initidx;
12105
12106         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12107                 union ctl_ha_msg msg_info;
12108
12109                 msg_info.hdr.nexus = io->io_hdr.nexus;
12110                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12111                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12112                 msg_info.hdr.original_sc = NULL;
12113                 msg_info.hdr.serializing_sc = NULL;
12114                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12115                     sizeof(msg_info.task), M_WAITOK);
12116         }
12117
12118         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12119         mtx_lock(&softc->ctl_lock);
12120         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12121                 mtx_lock(&lun->lun_lock);
12122                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12123                     io->io_hdr.nexus.initid, 1);
12124 #ifdef CTL_WITH_CA
12125                 ctl_clear_mask(lun->have_ca, initidx);
12126 #endif
12127                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12128                         lun->flags &= ~CTL_LUN_RESERVED;
12129                 if (ctl_is_set(lun->prevent, initidx)) {
12130                         ctl_clear_mask(lun->prevent, initidx);
12131                         lun->prevent_count--;
12132                 }
12133                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12134                 mtx_unlock(&lun->lun_lock);
12135         }
12136         mtx_unlock(&softc->ctl_lock);
12137         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12138         return (0);
12139 }
12140
12141 static int
12142 ctl_abort_task(union ctl_io *io)
12143 {
12144         union ctl_io *xio;
12145         struct ctl_lun *lun;
12146         struct ctl_softc *softc;
12147 #if 0
12148         struct sbuf sb;
12149         char printbuf[128];
12150 #endif
12151         int found;
12152         uint32_t targ_lun;
12153
12154         softc = control_softc;
12155         found = 0;
12156
12157         /*
12158          * Look up the LUN.
12159          */
12160         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12161         mtx_lock(&softc->ctl_lock);
12162         if ((targ_lun >= CTL_MAX_LUNS) ||
12163             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12164                 mtx_unlock(&softc->ctl_lock);
12165                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12166                 return (1);
12167         }
12168
12169 #if 0
12170         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12171                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12172 #endif
12173
12174         mtx_lock(&lun->lun_lock);
12175         mtx_unlock(&softc->ctl_lock);
12176         /*
12177          * Run through the OOA queue and attempt to find the given I/O.
12178          * The target port, initiator ID, tag type and tag number have to
12179          * match the values that we got from the initiator.  If we have an
12180          * untagged command to abort, simply abort the first untagged command
12181          * we come to.  We only allow one untagged command at a time of course.
12182          */
12183         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12184              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12185 #if 0
12186                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12187
12188                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12189                             lun->lun, xio->scsiio.tag_num,
12190                             xio->scsiio.tag_type,
12191                             (xio->io_hdr.blocked_links.tqe_prev
12192                             == NULL) ? "" : " BLOCKED",
12193                             (xio->io_hdr.flags &
12194                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12195                             (xio->io_hdr.flags &
12196                             CTL_FLAG_ABORT) ? " ABORT" : "",
12197                             (xio->io_hdr.flags &
12198                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12199                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12200                 sbuf_finish(&sb);
12201                 printf("%s\n", sbuf_data(&sb));
12202 #endif
12203
12204                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12205                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12206                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12207                         continue;
12208
12209                 /*
12210                  * If the abort says that the task is untagged, the
12211                  * task in the queue must be untagged.  Otherwise,
12212                  * we just check to see whether the tag numbers
12213                  * match.  This is because the QLogic firmware
12214                  * doesn't pass back the tag type in an abort
12215                  * request.
12216                  */
12217 #if 0
12218                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12219                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12220                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12221 #endif
12222                 /*
12223                  * XXX KDM we've got problems with FC, because it
12224                  * doesn't send down a tag type with aborts.  So we
12225                  * can only really go by the tag number...
12226                  * This may cause problems with parallel SCSI.
12227                  * Need to figure that out!!
12228                  */
12229                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12230                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12231                         found = 1;
12232                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12233                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12234                                 union ctl_ha_msg msg_info;
12235
12236                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12237                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12238                                 msg_info.task.tag_num = io->taskio.tag_num;
12239                                 msg_info.task.tag_type = io->taskio.tag_type;
12240                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12241                                 msg_info.hdr.original_sc = NULL;
12242                                 msg_info.hdr.serializing_sc = NULL;
12243 #if 0
12244                                 printf("Sent Abort to other side\n");
12245 #endif
12246                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12247                                     sizeof(msg_info.task), M_NOWAIT);
12248                         }
12249 #if 0
12250                         printf("ctl_abort_task: found I/O to abort\n");
12251 #endif
12252                 }
12253         }
12254         mtx_unlock(&lun->lun_lock);
12255
12256         if (found == 0) {
12257                 /*
12258                  * This isn't really an error.  It's entirely possible for
12259                  * the abort and command completion to cross on the wire.
12260                  * This is more of an informative/diagnostic error.
12261                  */
12262 #if 0
12263                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12264                        "%u:%u:%u tag %d type %d\n",
12265                        io->io_hdr.nexus.initid,
12266                        io->io_hdr.nexus.targ_port,
12267                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12268                        io->taskio.tag_type);
12269 #endif
12270         }
12271         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12272         return (0);
12273 }
12274
12275 static int
12276 ctl_query_task(union ctl_io *io, int task_set)
12277 {
12278         union ctl_io *xio;
12279         struct ctl_lun *lun;
12280         struct ctl_softc *softc;
12281         int found = 0;
12282         uint32_t targ_lun;
12283
12284         softc = control_softc;
12285         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12286         mtx_lock(&softc->ctl_lock);
12287         if ((targ_lun >= CTL_MAX_LUNS) ||
12288             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12289                 mtx_unlock(&softc->ctl_lock);
12290                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12291                 return (1);
12292         }
12293         mtx_lock(&lun->lun_lock);
12294         mtx_unlock(&softc->ctl_lock);
12295         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12296              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12297
12298                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12299                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12300                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12301                         continue;
12302
12303                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12304                         found = 1;
12305                         break;
12306                 }
12307         }
12308         mtx_unlock(&lun->lun_lock);
12309         if (found)
12310                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12311         else
12312                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12313         return (0);
12314 }
12315
12316 static int
12317 ctl_query_async_event(union ctl_io *io)
12318 {
12319         struct ctl_lun *lun;
12320         struct ctl_softc *softc;
12321         ctl_ua_type ua;
12322         uint32_t targ_lun, initidx;
12323
12324         softc = control_softc;
12325         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12326         mtx_lock(&softc->ctl_lock);
12327         if ((targ_lun >= CTL_MAX_LUNS) ||
12328             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12329                 mtx_unlock(&softc->ctl_lock);
12330                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12331                 return (1);
12332         }
12333         mtx_lock(&lun->lun_lock);
12334         mtx_unlock(&softc->ctl_lock);
12335         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12336         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12337         mtx_unlock(&lun->lun_lock);
12338         if (ua != CTL_UA_NONE)
12339                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12340         else
12341                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12342         return (0);
12343 }
12344
12345 static void
12346 ctl_run_task(union ctl_io *io)
12347 {
12348         struct ctl_softc *softc = control_softc;
12349         int retval = 1;
12350
12351         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12352         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12353             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12354         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12355         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12356         switch (io->taskio.task_action) {
12357         case CTL_TASK_ABORT_TASK:
12358                 retval = ctl_abort_task(io);
12359                 break;
12360         case CTL_TASK_ABORT_TASK_SET:
12361         case CTL_TASK_CLEAR_TASK_SET:
12362                 retval = ctl_abort_task_set(io);
12363                 break;
12364         case CTL_TASK_CLEAR_ACA:
12365                 break;
12366         case CTL_TASK_I_T_NEXUS_RESET:
12367                 retval = ctl_i_t_nexus_reset(io);
12368                 break;
12369         case CTL_TASK_LUN_RESET:
12370                 retval = ctl_lun_reset(softc, io);
12371                 break;
12372         case CTL_TASK_TARGET_RESET:
12373                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12374                 break;
12375         case CTL_TASK_BUS_RESET:
12376                 retval = ctl_bus_reset(softc, io);
12377                 break;
12378         case CTL_TASK_PORT_LOGIN:
12379                 break;
12380         case CTL_TASK_PORT_LOGOUT:
12381                 break;
12382         case CTL_TASK_QUERY_TASK:
12383                 retval = ctl_query_task(io, 0);
12384                 break;
12385         case CTL_TASK_QUERY_TASK_SET:
12386                 retval = ctl_query_task(io, 1);
12387                 break;
12388         case CTL_TASK_QUERY_ASYNC_EVENT:
12389                 retval = ctl_query_async_event(io);
12390                 break;
12391         default:
12392                 printf("%s: got unknown task management event %d\n",
12393                        __func__, io->taskio.task_action);
12394                 break;
12395         }
12396         if (retval == 0)
12397                 io->io_hdr.status = CTL_SUCCESS;
12398         else
12399                 io->io_hdr.status = CTL_ERROR;
12400         ctl_done(io);
12401 }
12402
12403 /*
12404  * For HA operation.  Handle commands that come in from the other
12405  * controller.
12406  */
12407 static void
12408 ctl_handle_isc(union ctl_io *io)
12409 {
12410         int free_io;
12411         struct ctl_lun *lun;
12412         struct ctl_softc *softc = control_softc;
12413         uint32_t targ_lun;
12414
12415         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12416         lun = softc->ctl_luns[targ_lun];
12417
12418         switch (io->io_hdr.msg_type) {
12419         case CTL_MSG_SERIALIZE:
12420                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12421                 break;
12422         case CTL_MSG_R2R: {
12423                 const struct ctl_cmd_entry *entry;
12424
12425                 /*
12426                  * This is only used in SER_ONLY mode.
12427                  */
12428                 free_io = 0;
12429                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12430                 mtx_lock(&lun->lun_lock);
12431                 if (ctl_scsiio_lun_check(lun,
12432                     entry, (struct ctl_scsiio *)io) != 0) {
12433                         mtx_unlock(&lun->lun_lock);
12434                         ctl_done(io);
12435                         break;
12436                 }
12437                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12438                 mtx_unlock(&lun->lun_lock);
12439                 ctl_enqueue_rtr(io);
12440                 break;
12441         }
12442         case CTL_MSG_FINISH_IO:
12443                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12444                         free_io = 0;
12445                         ctl_done(io);
12446                 } else {
12447                         free_io = 1;
12448                         mtx_lock(&lun->lun_lock);
12449                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12450                                      ooa_links);
12451                         ctl_check_blocked(lun);
12452                         mtx_unlock(&lun->lun_lock);
12453                 }
12454                 break;
12455         case CTL_MSG_PERS_ACTION:
12456                 ctl_hndl_per_res_out_on_other_sc(
12457                         (union ctl_ha_msg *)&io->presio.pr_msg);
12458                 free_io = 1;
12459                 break;
12460         case CTL_MSG_BAD_JUJU:
12461                 free_io = 0;
12462                 ctl_done(io);
12463                 break;
12464         case CTL_MSG_DATAMOVE:
12465                 /* Only used in XFER mode */
12466                 free_io = 0;
12467                 ctl_datamove_remote(io);
12468                 break;
12469         case CTL_MSG_DATAMOVE_DONE:
12470                 /* Only used in XFER mode */
12471                 free_io = 0;
12472                 io->scsiio.be_move_done(io);
12473                 break;
12474         case CTL_MSG_FAILOVER:
12475                 ctl_failover_lun(io);
12476                 free_io = 1;
12477                 break;
12478         default:
12479                 free_io = 1;
12480                 printf("%s: Invalid message type %d\n",
12481                        __func__, io->io_hdr.msg_type);
12482                 break;
12483         }
12484         if (free_io)
12485                 ctl_free_io(io);
12486
12487 }
12488
12489
12490 /*
12491  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12492  * there is no match.
12493  */
12494 static ctl_lun_error_pattern
12495 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12496 {
12497         const struct ctl_cmd_entry *entry;
12498         ctl_lun_error_pattern filtered_pattern, pattern;
12499
12500         pattern = desc->error_pattern;
12501
12502         /*
12503          * XXX KDM we need more data passed into this function to match a
12504          * custom pattern, and we actually need to implement custom pattern
12505          * matching.
12506          */
12507         if (pattern & CTL_LUN_PAT_CMD)
12508                 return (CTL_LUN_PAT_CMD);
12509
12510         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12511                 return (CTL_LUN_PAT_ANY);
12512
12513         entry = ctl_get_cmd_entry(ctsio, NULL);
12514
12515         filtered_pattern = entry->pattern & pattern;
12516
12517         /*
12518          * If the user requested specific flags in the pattern (e.g.
12519          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12520          * flags.
12521          *
12522          * If the user did not specify any flags, it doesn't matter whether
12523          * or not the command supports the flags.
12524          */
12525         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12526              (pattern & ~CTL_LUN_PAT_MASK))
12527                 return (CTL_LUN_PAT_NONE);
12528
12529         /*
12530          * If the user asked for a range check, see if the requested LBA
12531          * range overlaps with this command's LBA range.
12532          */
12533         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12534                 uint64_t lba1;
12535                 uint64_t len1;
12536                 ctl_action action;
12537                 int retval;
12538
12539                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12540                 if (retval != 0)
12541                         return (CTL_LUN_PAT_NONE);
12542
12543                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12544                                               desc->lba_range.len, FALSE);
12545                 /*
12546                  * A "pass" means that the LBA ranges don't overlap, so
12547                  * this doesn't match the user's range criteria.
12548                  */
12549                 if (action == CTL_ACTION_PASS)
12550                         return (CTL_LUN_PAT_NONE);
12551         }
12552
12553         return (filtered_pattern);
12554 }
12555
12556 static void
12557 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12558 {
12559         struct ctl_error_desc *desc, *desc2;
12560
12561         mtx_assert(&lun->lun_lock, MA_OWNED);
12562
12563         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12564                 ctl_lun_error_pattern pattern;
12565                 /*
12566                  * Check to see whether this particular command matches
12567                  * the pattern in the descriptor.
12568                  */
12569                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12570                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12571                         continue;
12572
12573                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12574                 case CTL_LUN_INJ_ABORTED:
12575                         ctl_set_aborted(&io->scsiio);
12576                         break;
12577                 case CTL_LUN_INJ_MEDIUM_ERR:
12578                         ctl_set_medium_error(&io->scsiio,
12579                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12580                              CTL_FLAG_DATA_OUT);
12581                         break;
12582                 case CTL_LUN_INJ_UA:
12583                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12584                          * OCCURRED */
12585                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12586                         break;
12587                 case CTL_LUN_INJ_CUSTOM:
12588                         /*
12589                          * We're assuming the user knows what he is doing.
12590                          * Just copy the sense information without doing
12591                          * checks.
12592                          */
12593                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12594                               MIN(sizeof(desc->custom_sense),
12595                                   sizeof(io->scsiio.sense_data)));
12596                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12597                         io->scsiio.sense_len = SSD_FULL_SIZE;
12598                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12599                         break;
12600                 case CTL_LUN_INJ_NONE:
12601                 default:
12602                         /*
12603                          * If this is an error injection type we don't know
12604                          * about, clear the continuous flag (if it is set)
12605                          * so it will get deleted below.
12606                          */
12607                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12608                         break;
12609                 }
12610                 /*
12611                  * By default, each error injection action is a one-shot
12612                  */
12613                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12614                         continue;
12615
12616                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12617
12618                 free(desc, M_CTL);
12619         }
12620 }
12621
12622 #ifdef CTL_IO_DELAY
12623 static void
12624 ctl_datamove_timer_wakeup(void *arg)
12625 {
12626         union ctl_io *io;
12627
12628         io = (union ctl_io *)arg;
12629
12630         ctl_datamove(io);
12631 }
12632 #endif /* CTL_IO_DELAY */
12633
12634 void
12635 ctl_datamove(union ctl_io *io)
12636 {
12637         struct ctl_lun *lun;
12638         void (*fe_datamove)(union ctl_io *io);
12639
12640         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12641
12642         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12643
12644         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12645 #ifdef CTL_TIME_IO
12646         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12647                 char str[256];
12648                 char path_str[64];
12649                 struct sbuf sb;
12650
12651                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12652                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12653
12654                 sbuf_cat(&sb, path_str);
12655                 switch (io->io_hdr.io_type) {
12656                 case CTL_IO_SCSI:
12657                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12658                         sbuf_printf(&sb, "\n");
12659                         sbuf_cat(&sb, path_str);
12660                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12661                                     io->scsiio.tag_num, io->scsiio.tag_type);
12662                         break;
12663                 case CTL_IO_TASK:
12664                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12665                                     "Tag Type: %d\n", io->taskio.task_action,
12666                                     io->taskio.tag_num, io->taskio.tag_type);
12667                         break;
12668                 default:
12669                         panic("%s: Invalid CTL I/O type %d\n",
12670                             __func__, io->io_hdr.io_type);
12671                 }
12672                 sbuf_cat(&sb, path_str);
12673                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12674                             (intmax_t)time_uptime - io->io_hdr.start_time);
12675                 sbuf_finish(&sb);
12676                 printf("%s", sbuf_data(&sb));
12677         }
12678 #endif /* CTL_TIME_IO */
12679
12680 #ifdef CTL_IO_DELAY
12681         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12682                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12683         } else {
12684                 if ((lun != NULL)
12685                  && (lun->delay_info.datamove_delay > 0)) {
12686
12687                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12688                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12689                         callout_reset(&io->io_hdr.delay_callout,
12690                                       lun->delay_info.datamove_delay * hz,
12691                                       ctl_datamove_timer_wakeup, io);
12692                         if (lun->delay_info.datamove_type ==
12693                             CTL_DELAY_TYPE_ONESHOT)
12694                                 lun->delay_info.datamove_delay = 0;
12695                         return;
12696                 }
12697         }
12698 #endif
12699
12700         /*
12701          * This command has been aborted.  Set the port status, so we fail
12702          * the data move.
12703          */
12704         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12705                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12706                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12707                        io->io_hdr.nexus.targ_port,
12708                        io->io_hdr.nexus.targ_lun);
12709                 io->io_hdr.port_status = 31337;
12710                 /*
12711                  * Note that the backend, in this case, will get the
12712                  * callback in its context.  In other cases it may get
12713                  * called in the frontend's interrupt thread context.
12714                  */
12715                 io->scsiio.be_move_done(io);
12716                 return;
12717         }
12718
12719         /* Don't confuse frontend with zero length data move. */
12720         if (io->scsiio.kern_data_len == 0) {
12721                 io->scsiio.be_move_done(io);
12722                 return;
12723         }
12724
12725         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12726         fe_datamove(io);
12727 }
12728
12729 static void
12730 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12731 {
12732         union ctl_ha_msg msg;
12733 #ifdef CTL_TIME_IO
12734         struct bintime cur_bt;
12735 #endif
12736
12737         memset(&msg, 0, sizeof(msg));
12738         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12739         msg.hdr.original_sc = io;
12740         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12741         msg.hdr.nexus = io->io_hdr.nexus;
12742         msg.hdr.status = io->io_hdr.status;
12743         msg.scsi.tag_num = io->scsiio.tag_num;
12744         msg.scsi.tag_type = io->scsiio.tag_type;
12745         msg.scsi.scsi_status = io->scsiio.scsi_status;
12746         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12747                io->scsiio.sense_len);
12748         msg.scsi.sense_len = io->scsiio.sense_len;
12749         msg.scsi.sense_residual = io->scsiio.sense_residual;
12750         msg.scsi.fetd_status = io->io_hdr.port_status;
12751         msg.scsi.residual = io->scsiio.residual;
12752         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12753         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12754                 ctl_failover_io(io, /*have_lock*/ have_lock);
12755                 return;
12756         }
12757         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12758             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12759             msg.scsi.sense_len, M_WAITOK);
12760
12761 #ifdef CTL_TIME_IO
12762         getbinuptime(&cur_bt);
12763         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12764         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12765 #endif
12766         io->io_hdr.num_dmas++;
12767 }
12768
12769 /*
12770  * The DMA to the remote side is done, now we need to tell the other side
12771  * we're done so it can continue with its data movement.
12772  */
12773 static void
12774 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12775 {
12776         union ctl_io *io;
12777         int i;
12778
12779         io = rq->context;
12780
12781         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12782                 printf("%s: ISC DMA write failed with error %d", __func__,
12783                        rq->ret);
12784                 ctl_set_internal_failure(&io->scsiio,
12785                                          /*sks_valid*/ 1,
12786                                          /*retry_count*/ rq->ret);
12787         }
12788
12789         ctl_dt_req_free(rq);
12790
12791         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12792                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12793         free(io->io_hdr.remote_sglist, M_CTL);
12794         io->io_hdr.remote_sglist = NULL;
12795         io->io_hdr.local_sglist = NULL;
12796
12797         /*
12798          * The data is in local and remote memory, so now we need to send
12799          * status (good or back) back to the other side.
12800          */
12801         ctl_send_datamove_done(io, /*have_lock*/ 0);
12802 }
12803
12804 /*
12805  * We've moved the data from the host/controller into local memory.  Now we
12806  * need to push it over to the remote controller's memory.
12807  */
12808 static int
12809 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12810 {
12811         int retval;
12812
12813         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12814                                           ctl_datamove_remote_write_cb);
12815         return (retval);
12816 }
12817
12818 static void
12819 ctl_datamove_remote_write(union ctl_io *io)
12820 {
12821         int retval;
12822         void (*fe_datamove)(union ctl_io *io);
12823
12824         /*
12825          * - Get the data from the host/HBA into local memory.
12826          * - DMA memory from the local controller to the remote controller.
12827          * - Send status back to the remote controller.
12828          */
12829
12830         retval = ctl_datamove_remote_sgl_setup(io);
12831         if (retval != 0)
12832                 return;
12833
12834         /* Switch the pointer over so the FETD knows what to do */
12835         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12836
12837         /*
12838          * Use a custom move done callback, since we need to send completion
12839          * back to the other controller, not to the backend on this side.
12840          */
12841         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12842
12843         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12844         fe_datamove(io);
12845 }
12846
12847 static int
12848 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12849 {
12850 #if 0
12851         char str[256];
12852         char path_str[64];
12853         struct sbuf sb;
12854 #endif
12855         int i;
12856
12857         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12858                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12859         free(io->io_hdr.remote_sglist, M_CTL);
12860         io->io_hdr.remote_sglist = NULL;
12861         io->io_hdr.local_sglist = NULL;
12862
12863 #if 0
12864         scsi_path_string(io, path_str, sizeof(path_str));
12865         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12866         sbuf_cat(&sb, path_str);
12867         scsi_command_string(&io->scsiio, NULL, &sb);
12868         sbuf_printf(&sb, "\n");
12869         sbuf_cat(&sb, path_str);
12870         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12871                     io->scsiio.tag_num, io->scsiio.tag_type);
12872         sbuf_cat(&sb, path_str);
12873         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12874                     io->io_hdr.flags, io->io_hdr.status);
12875         sbuf_finish(&sb);
12876         printk("%s", sbuf_data(&sb));
12877 #endif
12878
12879
12880         /*
12881          * The read is done, now we need to send status (good or bad) back
12882          * to the other side.
12883          */
12884         ctl_send_datamove_done(io, /*have_lock*/ 0);
12885
12886         return (0);
12887 }
12888
12889 static void
12890 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12891 {
12892         union ctl_io *io;
12893         void (*fe_datamove)(union ctl_io *io);
12894
12895         io = rq->context;
12896
12897         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12898                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12899                        rq->ret);
12900                 ctl_set_internal_failure(&io->scsiio,
12901                                          /*sks_valid*/ 1,
12902                                          /*retry_count*/ rq->ret);
12903         }
12904
12905         ctl_dt_req_free(rq);
12906
12907         /* Switch the pointer over so the FETD knows what to do */
12908         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12909
12910         /*
12911          * Use a custom move done callback, since we need to send completion
12912          * back to the other controller, not to the backend on this side.
12913          */
12914         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12915
12916         /* XXX KDM add checks like the ones in ctl_datamove? */
12917
12918         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12919         fe_datamove(io);
12920 }
12921
12922 static int
12923 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12924 {
12925         struct ctl_sg_entry *local_sglist;
12926         uint32_t len_to_go;
12927         int retval;
12928         int i;
12929
12930         retval = 0;
12931         local_sglist = io->io_hdr.local_sglist;
12932         len_to_go = io->scsiio.kern_data_len;
12933
12934         /*
12935          * The difficult thing here is that the size of the various
12936          * S/G segments may be different than the size from the
12937          * remote controller.  That'll make it harder when DMAing
12938          * the data back to the other side.
12939          */
12940         for (i = 0; len_to_go > 0; i++) {
12941                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12942                 local_sglist[i].addr =
12943                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12944
12945                 len_to_go -= local_sglist[i].len;
12946         }
12947         /*
12948          * Reset the number of S/G entries accordingly.  The original
12949          * number of S/G entries is available in rem_sg_entries.
12950          */
12951         io->scsiio.kern_sg_entries = i;
12952
12953 #if 0
12954         printf("%s: kern_sg_entries = %d\n", __func__,
12955                io->scsiio.kern_sg_entries);
12956         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12957                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12958                        local_sglist[i].addr, local_sglist[i].len);
12959 #endif
12960
12961         return (retval);
12962 }
12963
12964 static int
12965 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12966                          ctl_ha_dt_cb callback)
12967 {
12968         struct ctl_ha_dt_req *rq;
12969         struct ctl_sg_entry *remote_sglist, *local_sglist;
12970         uint32_t local_used, remote_used, total_used;
12971         int i, j, isc_ret;
12972
12973         rq = ctl_dt_req_alloc();
12974
12975         /*
12976          * If we failed to allocate the request, and if the DMA didn't fail
12977          * anyway, set busy status.  This is just a resource allocation
12978          * failure.
12979          */
12980         if ((rq == NULL)
12981          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12982              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12983                 ctl_set_busy(&io->scsiio);
12984
12985         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12986             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12987
12988                 if (rq != NULL)
12989                         ctl_dt_req_free(rq);
12990
12991                 /*
12992                  * The data move failed.  We need to return status back
12993                  * to the other controller.  No point in trying to DMA
12994                  * data to the remote controller.
12995                  */
12996
12997                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12998
12999                 return (1);
13000         }
13001
13002         local_sglist = io->io_hdr.local_sglist;
13003         remote_sglist = io->io_hdr.remote_sglist;
13004         local_used = 0;
13005         remote_used = 0;
13006         total_used = 0;
13007
13008         /*
13009          * Pull/push the data over the wire from/to the other controller.
13010          * This takes into account the possibility that the local and
13011          * remote sglists may not be identical in terms of the size of
13012          * the elements and the number of elements.
13013          *
13014          * One fundamental assumption here is that the length allocated for
13015          * both the local and remote sglists is identical.  Otherwise, we've
13016          * essentially got a coding error of some sort.
13017          */
13018         isc_ret = CTL_HA_STATUS_SUCCESS;
13019         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13020                 uint32_t cur_len;
13021                 uint8_t *tmp_ptr;
13022
13023                 rq->command = command;
13024                 rq->context = io;
13025
13026                 /*
13027                  * Both pointers should be aligned.  But it is possible
13028                  * that the allocation length is not.  They should both
13029                  * also have enough slack left over at the end, though,
13030                  * to round up to the next 8 byte boundary.
13031                  */
13032                 cur_len = MIN(local_sglist[i].len - local_used,
13033                               remote_sglist[j].len - remote_used);
13034                 rq->size = cur_len;
13035
13036                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13037                 tmp_ptr += local_used;
13038
13039 #if 0
13040                 /* Use physical addresses when talking to ISC hardware */
13041                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13042                         /* XXX KDM use busdma */
13043                         rq->local = vtophys(tmp_ptr);
13044                 } else
13045                         rq->local = tmp_ptr;
13046 #else
13047                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13048                     ("HA does not support BUS_ADDR"));
13049                 rq->local = tmp_ptr;
13050 #endif
13051
13052                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13053                 tmp_ptr += remote_used;
13054                 rq->remote = tmp_ptr;
13055
13056                 rq->callback = NULL;
13057
13058                 local_used += cur_len;
13059                 if (local_used >= local_sglist[i].len) {
13060                         i++;
13061                         local_used = 0;
13062                 }
13063
13064                 remote_used += cur_len;
13065                 if (remote_used >= remote_sglist[j].len) {
13066                         j++;
13067                         remote_used = 0;
13068                 }
13069                 total_used += cur_len;
13070
13071                 if (total_used >= io->scsiio.kern_data_len)
13072                         rq->callback = callback;
13073
13074 #if 0
13075                 printf("%s: %s: local %p remote %p size %d\n", __func__,
13076                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13077                        rq->local, rq->remote, rq->size);
13078 #endif
13079
13080                 isc_ret = ctl_dt_single(rq);
13081                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
13082                         break;
13083         }
13084         if (isc_ret != CTL_HA_STATUS_WAIT) {
13085                 rq->ret = isc_ret;
13086                 callback(rq);
13087         }
13088
13089         return (0);
13090 }
13091
13092 static void
13093 ctl_datamove_remote_read(union ctl_io *io)
13094 {
13095         int retval;
13096         int i;
13097
13098         /*
13099          * This will send an error to the other controller in the case of a
13100          * failure.
13101          */
13102         retval = ctl_datamove_remote_sgl_setup(io);
13103         if (retval != 0)
13104                 return;
13105
13106         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13107                                           ctl_datamove_remote_read_cb);
13108         if (retval != 0) {
13109                 /*
13110                  * Make sure we free memory if there was an error..  The
13111                  * ctl_datamove_remote_xfer() function will send the
13112                  * datamove done message, or call the callback with an
13113                  * error if there is a problem.
13114                  */
13115                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13116                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13117                 free(io->io_hdr.remote_sglist, M_CTL);
13118                 io->io_hdr.remote_sglist = NULL;
13119                 io->io_hdr.local_sglist = NULL;
13120         }
13121 }
13122
13123 /*
13124  * Process a datamove request from the other controller.  This is used for
13125  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13126  * first.  Once that is complete, the data gets DMAed into the remote
13127  * controller's memory.  For reads, we DMA from the remote controller's
13128  * memory into our memory first, and then move it out to the FETD.
13129  */
13130 static void
13131 ctl_datamove_remote(union ctl_io *io)
13132 {
13133
13134         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13135
13136         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13137                 ctl_failover_io(io, /*have_lock*/ 0);
13138                 return;
13139         }
13140
13141         /*
13142          * Note that we look for an aborted I/O here, but don't do some of
13143          * the other checks that ctl_datamove() normally does.
13144          * We don't need to run the datamove delay code, since that should
13145          * have been done if need be on the other controller.
13146          */
13147         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13148                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13149                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13150                        io->io_hdr.nexus.targ_port,
13151                        io->io_hdr.nexus.targ_lun);
13152                 io->io_hdr.port_status = 31338;
13153                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13154                 return;
13155         }
13156
13157         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13158                 ctl_datamove_remote_write(io);
13159         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13160                 ctl_datamove_remote_read(io);
13161         else {
13162                 io->io_hdr.port_status = 31339;
13163                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13164         }
13165 }
13166
13167 static void
13168 ctl_process_done(union ctl_io *io)
13169 {
13170         struct ctl_lun *lun;
13171         struct ctl_softc *softc = control_softc;
13172         void (*fe_done)(union ctl_io *io);
13173         union ctl_ha_msg msg;
13174         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13175
13176         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13177         fe_done = softc->ctl_ports[targ_port]->fe_done;
13178
13179 #ifdef CTL_TIME_IO
13180         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13181                 char str[256];
13182                 char path_str[64];
13183                 struct sbuf sb;
13184
13185                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13186                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13187
13188                 sbuf_cat(&sb, path_str);
13189                 switch (io->io_hdr.io_type) {
13190                 case CTL_IO_SCSI:
13191                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13192                         sbuf_printf(&sb, "\n");
13193                         sbuf_cat(&sb, path_str);
13194                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13195                                     io->scsiio.tag_num, io->scsiio.tag_type);
13196                         break;
13197                 case CTL_IO_TASK:
13198                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13199                                     "Tag Type: %d\n", io->taskio.task_action,
13200                                     io->taskio.tag_num, io->taskio.tag_type);
13201                         break;
13202                 default:
13203                         panic("%s: Invalid CTL I/O type %d\n",
13204                             __func__, io->io_hdr.io_type);
13205                 }
13206                 sbuf_cat(&sb, path_str);
13207                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13208                             (intmax_t)time_uptime - io->io_hdr.start_time);
13209                 sbuf_finish(&sb);
13210                 printf("%s", sbuf_data(&sb));
13211         }
13212 #endif /* CTL_TIME_IO */
13213
13214         switch (io->io_hdr.io_type) {
13215         case CTL_IO_SCSI:
13216                 break;
13217         case CTL_IO_TASK:
13218                 if (ctl_debug & CTL_DEBUG_INFO)
13219                         ctl_io_error_print(io, NULL);
13220                 fe_done(io);
13221                 return;
13222         default:
13223                 panic("%s: Invalid CTL I/O type %d\n",
13224                     __func__, io->io_hdr.io_type);
13225         }
13226
13227         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13228         if (lun == NULL) {
13229                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13230                                  io->io_hdr.nexus.targ_mapped_lun));
13231                 goto bailout;
13232         }
13233
13234         mtx_lock(&lun->lun_lock);
13235
13236         /*
13237          * Check to see if we have any errors to inject here.  We only
13238          * inject errors for commands that don't already have errors set.
13239          */
13240         if (!STAILQ_EMPTY(&lun->error_list) &&
13241             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13242             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13243                 ctl_inject_error(lun, io);
13244
13245         /*
13246          * XXX KDM how do we treat commands that aren't completed
13247          * successfully?
13248          *
13249          * XXX KDM should we also track I/O latency?
13250          */
13251         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13252             io->io_hdr.io_type == CTL_IO_SCSI) {
13253 #ifdef CTL_TIME_IO
13254                 struct bintime cur_bt;
13255 #endif
13256                 int type;
13257
13258                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13259                     CTL_FLAG_DATA_IN)
13260                         type = CTL_STATS_READ;
13261                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13262                     CTL_FLAG_DATA_OUT)
13263                         type = CTL_STATS_WRITE;
13264                 else
13265                         type = CTL_STATS_NO_IO;
13266
13267                 lun->stats.ports[targ_port].bytes[type] +=
13268                     io->scsiio.kern_total_len;
13269                 lun->stats.ports[targ_port].operations[type]++;
13270 #ifdef CTL_TIME_IO
13271                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13272                    &io->io_hdr.dma_bt);
13273                 getbinuptime(&cur_bt);
13274                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13275                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13276 #endif
13277                 lun->stats.ports[targ_port].num_dmas[type] +=
13278                     io->io_hdr.num_dmas;
13279         }
13280
13281         /*
13282          * Remove this from the OOA queue.
13283          */
13284         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13285 #ifdef CTL_TIME_IO
13286         if (TAILQ_EMPTY(&lun->ooa_queue))
13287                 lun->last_busy = getsbinuptime();
13288 #endif
13289
13290         /*
13291          * Run through the blocked queue on this LUN and see if anything
13292          * has become unblocked, now that this transaction is done.
13293          */
13294         ctl_check_blocked(lun);
13295
13296         /*
13297          * If the LUN has been invalidated, free it if there is nothing
13298          * left on its OOA queue.
13299          */
13300         if ((lun->flags & CTL_LUN_INVALID)
13301          && TAILQ_EMPTY(&lun->ooa_queue)) {
13302                 mtx_unlock(&lun->lun_lock);
13303                 mtx_lock(&softc->ctl_lock);
13304                 ctl_free_lun(lun);
13305                 mtx_unlock(&softc->ctl_lock);
13306         } else
13307                 mtx_unlock(&lun->lun_lock);
13308
13309 bailout:
13310
13311         /*
13312          * If this command has been aborted, make sure we set the status
13313          * properly.  The FETD is responsible for freeing the I/O and doing
13314          * whatever it needs to do to clean up its state.
13315          */
13316         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13317                 ctl_set_task_aborted(&io->scsiio);
13318
13319         /*
13320          * If enabled, print command error status.
13321          */
13322         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13323             (ctl_debug & CTL_DEBUG_INFO) != 0)
13324                 ctl_io_error_print(io, NULL);
13325
13326         /*
13327          * Tell the FETD or the other shelf controller we're done with this
13328          * command.  Note that only SCSI commands get to this point.  Task
13329          * management commands are completed above.
13330          */
13331         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13332             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13333                 memset(&msg, 0, sizeof(msg));
13334                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13335                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13336                 msg.hdr.nexus = io->io_hdr.nexus;
13337                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13338                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13339                     M_WAITOK);
13340         }
13341
13342         fe_done(io);
13343 }
13344
13345 #ifdef CTL_WITH_CA
13346 /*
13347  * Front end should call this if it doesn't do autosense.  When the request
13348  * sense comes back in from the initiator, we'll dequeue this and send it.
13349  */
13350 int
13351 ctl_queue_sense(union ctl_io *io)
13352 {
13353         struct ctl_lun *lun;
13354         struct ctl_port *port;
13355         struct ctl_softc *softc;
13356         uint32_t initidx, targ_lun;
13357
13358         softc = control_softc;
13359
13360         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13361
13362         /*
13363          * LUN lookup will likely move to the ctl_work_thread() once we
13364          * have our new queueing infrastructure (that doesn't put things on
13365          * a per-LUN queue initially).  That is so that we can handle
13366          * things like an INQUIRY to a LUN that we don't have enabled.  We
13367          * can't deal with that right now.
13368          */
13369         mtx_lock(&softc->ctl_lock);
13370
13371         /*
13372          * If we don't have a LUN for this, just toss the sense
13373          * information.
13374          */
13375         port = ctl_io_port(&ctsio->io_hdr);
13376         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13377         if ((targ_lun < CTL_MAX_LUNS)
13378          && (softc->ctl_luns[targ_lun] != NULL))
13379                 lun = softc->ctl_luns[targ_lun];
13380         else
13381                 goto bailout;
13382
13383         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13384
13385         mtx_lock(&lun->lun_lock);
13386         /*
13387          * Already have CA set for this LUN...toss the sense information.
13388          */
13389         if (ctl_is_set(lun->have_ca, initidx)) {
13390                 mtx_unlock(&lun->lun_lock);
13391                 goto bailout;
13392         }
13393
13394         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13395                MIN(sizeof(lun->pending_sense[initidx]),
13396                sizeof(io->scsiio.sense_data)));
13397         ctl_set_mask(lun->have_ca, initidx);
13398         mtx_unlock(&lun->lun_lock);
13399
13400 bailout:
13401         mtx_unlock(&softc->ctl_lock);
13402
13403         ctl_free_io(io);
13404
13405         return (CTL_RETVAL_COMPLETE);
13406 }
13407 #endif
13408
13409 /*
13410  * Primary command inlet from frontend ports.  All SCSI and task I/O
13411  * requests must go through this function.
13412  */
13413 int
13414 ctl_queue(union ctl_io *io)
13415 {
13416         struct ctl_port *port;
13417
13418         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13419
13420 #ifdef CTL_TIME_IO
13421         io->io_hdr.start_time = time_uptime;
13422         getbinuptime(&io->io_hdr.start_bt);
13423 #endif /* CTL_TIME_IO */
13424
13425         /* Map FE-specific LUN ID into global one. */
13426         port = ctl_io_port(&io->io_hdr);
13427         io->io_hdr.nexus.targ_mapped_lun =
13428             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13429
13430         switch (io->io_hdr.io_type) {
13431         case CTL_IO_SCSI:
13432         case CTL_IO_TASK:
13433                 if (ctl_debug & CTL_DEBUG_CDB)
13434                         ctl_io_print(io);
13435                 ctl_enqueue_incoming(io);
13436                 break;
13437         default:
13438                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13439                 return (EINVAL);
13440         }
13441
13442         return (CTL_RETVAL_COMPLETE);
13443 }
13444
13445 #ifdef CTL_IO_DELAY
13446 static void
13447 ctl_done_timer_wakeup(void *arg)
13448 {
13449         union ctl_io *io;
13450
13451         io = (union ctl_io *)arg;
13452         ctl_done(io);
13453 }
13454 #endif /* CTL_IO_DELAY */
13455
13456 void
13457 ctl_serseq_done(union ctl_io *io)
13458 {
13459         struct ctl_lun *lun;
13460
13461         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13462         if (lun->be_lun == NULL ||
13463             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13464                 return;
13465         mtx_lock(&lun->lun_lock);
13466         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13467         ctl_check_blocked(lun);
13468         mtx_unlock(&lun->lun_lock);
13469 }
13470
13471 void
13472 ctl_done(union ctl_io *io)
13473 {
13474
13475         /*
13476          * Enable this to catch duplicate completion issues.
13477          */
13478 #if 0
13479         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13480                 printf("%s: type %d msg %d cdb %x iptl: "
13481                        "%u:%u:%u tag 0x%04x "
13482                        "flag %#x status %x\n",
13483                         __func__,
13484                         io->io_hdr.io_type,
13485                         io->io_hdr.msg_type,
13486                         io->scsiio.cdb[0],
13487                         io->io_hdr.nexus.initid,
13488                         io->io_hdr.nexus.targ_port,
13489                         io->io_hdr.nexus.targ_lun,
13490                         (io->io_hdr.io_type ==
13491                         CTL_IO_TASK) ?
13492                         io->taskio.tag_num :
13493                         io->scsiio.tag_num,
13494                         io->io_hdr.flags,
13495                         io->io_hdr.status);
13496         } else
13497                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13498 #endif
13499
13500         /*
13501          * This is an internal copy of an I/O, and should not go through
13502          * the normal done processing logic.
13503          */
13504         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13505                 return;
13506
13507 #ifdef CTL_IO_DELAY
13508         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13509                 struct ctl_lun *lun;
13510
13511                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13512
13513                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13514         } else {
13515                 struct ctl_lun *lun;
13516
13517                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13518
13519                 if ((lun != NULL)
13520                  && (lun->delay_info.done_delay > 0)) {
13521
13522                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13523                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13524                         callout_reset(&io->io_hdr.delay_callout,
13525                                       lun->delay_info.done_delay * hz,
13526                                       ctl_done_timer_wakeup, io);
13527                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13528                                 lun->delay_info.done_delay = 0;
13529                         return;
13530                 }
13531         }
13532 #endif /* CTL_IO_DELAY */
13533
13534         ctl_enqueue_done(io);
13535 }
13536
13537 static void
13538 ctl_work_thread(void *arg)
13539 {
13540         struct ctl_thread *thr = (struct ctl_thread *)arg;
13541         struct ctl_softc *softc = thr->ctl_softc;
13542         union ctl_io *io;
13543         int retval;
13544
13545         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13546
13547         for (;;) {
13548                 /*
13549                  * We handle the queues in this order:
13550                  * - ISC
13551                  * - done queue (to free up resources, unblock other commands)
13552                  * - RtR queue
13553                  * - incoming queue
13554                  *
13555                  * If those queues are empty, we break out of the loop and
13556                  * go to sleep.
13557                  */
13558                 mtx_lock(&thr->queue_lock);
13559                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13560                 if (io != NULL) {
13561                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13562                         mtx_unlock(&thr->queue_lock);
13563                         ctl_handle_isc(io);
13564                         continue;
13565                 }
13566                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13567                 if (io != NULL) {
13568                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13569                         /* clear any blocked commands, call fe_done */
13570                         mtx_unlock(&thr->queue_lock);
13571                         ctl_process_done(io);
13572                         continue;
13573                 }
13574                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13575                 if (io != NULL) {
13576                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13577                         mtx_unlock(&thr->queue_lock);
13578                         if (io->io_hdr.io_type == CTL_IO_TASK)
13579                                 ctl_run_task(io);
13580                         else
13581                                 ctl_scsiio_precheck(softc, &io->scsiio);
13582                         continue;
13583                 }
13584                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13585                 if (io != NULL) {
13586                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13587                         mtx_unlock(&thr->queue_lock);
13588                         retval = ctl_scsiio(&io->scsiio);
13589                         if (retval != CTL_RETVAL_COMPLETE)
13590                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13591                         continue;
13592                 }
13593
13594                 /* Sleep until we have something to do. */
13595                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13596         }
13597 }
13598
13599 static void
13600 ctl_lun_thread(void *arg)
13601 {
13602         struct ctl_softc *softc = (struct ctl_softc *)arg;
13603         struct ctl_be_lun *be_lun;
13604
13605         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13606
13607         for (;;) {
13608                 mtx_lock(&softc->ctl_lock);
13609                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13610                 if (be_lun != NULL) {
13611                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13612                         mtx_unlock(&softc->ctl_lock);
13613                         ctl_create_lun(be_lun);
13614                         continue;
13615                 }
13616
13617                 /* Sleep until we have something to do. */
13618                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13619                     PDROP | PRIBIO, "-", 0);
13620         }
13621 }
13622
13623 static void
13624 ctl_thresh_thread(void *arg)
13625 {
13626         struct ctl_softc *softc = (struct ctl_softc *)arg;
13627         struct ctl_lun *lun;
13628         struct scsi_da_rw_recovery_page *rwpage;
13629         struct ctl_logical_block_provisioning_page *page;
13630         const char *attr;
13631         union ctl_ha_msg msg;
13632         uint64_t thres, val;
13633         int i, e, set;
13634
13635         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13636
13637         for (;;) {
13638                 mtx_lock(&softc->ctl_lock);
13639                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13640                         if ((lun->flags & CTL_LUN_DISABLED) ||
13641                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13642                             lun->backend->lun_attr == NULL)
13643                                 continue;
13644                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13645                             softc->ha_mode == CTL_HA_MODE_XFER)
13646                                 continue;
13647                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13648                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13649                                 continue;
13650                         e = 0;
13651                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13652                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13653                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13654                                         continue;
13655                                 thres = scsi_4btoul(page->descr[i].count);
13656                                 thres <<= CTL_LBP_EXPONENT;
13657                                 switch (page->descr[i].resource) {
13658                                 case 0x01:
13659                                         attr = "blocksavail";
13660                                         break;
13661                                 case 0x02:
13662                                         attr = "blocksused";
13663                                         break;
13664                                 case 0xf1:
13665                                         attr = "poolblocksavail";
13666                                         break;
13667                                 case 0xf2:
13668                                         attr = "poolblocksused";
13669                                         break;
13670                                 default:
13671                                         continue;
13672                                 }
13673                                 mtx_unlock(&softc->ctl_lock); // XXX
13674                                 val = lun->backend->lun_attr(
13675                                     lun->be_lun->be_lun, attr);
13676                                 mtx_lock(&softc->ctl_lock);
13677                                 if (val == UINT64_MAX)
13678                                         continue;
13679                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13680                                     == SLBPPD_ARMING_INC)
13681                                         e = (val >= thres);
13682                                 else
13683                                         e = (val <= thres);
13684                                 if (e)
13685                                         break;
13686                         }
13687                         mtx_lock(&lun->lun_lock);
13688                         if (e) {
13689                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13690                                     (uint8_t *)page, lun->ua_tpt_info);
13691                                 if (lun->lasttpt == 0 ||
13692                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13693                                         lun->lasttpt = time_uptime;
13694                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13695                                         set = 1;
13696                                 } else
13697                                         set = 0;
13698                         } else {
13699                                 lun->lasttpt = 0;
13700                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13701                                 set = -1;
13702                         }
13703                         mtx_unlock(&lun->lun_lock);
13704                         if (set != 0 &&
13705                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13706                                 /* Send msg to other side. */
13707                                 bzero(&msg.ua, sizeof(msg.ua));
13708                                 msg.hdr.msg_type = CTL_MSG_UA;
13709                                 msg.hdr.nexus.initid = -1;
13710                                 msg.hdr.nexus.targ_port = -1;
13711                                 msg.hdr.nexus.targ_lun = lun->lun;
13712                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13713                                 msg.ua.ua_all = 1;
13714                                 msg.ua.ua_set = (set > 0);
13715                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13716                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13717                                 mtx_unlock(&softc->ctl_lock); // XXX
13718                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13719                                     sizeof(msg.ua), M_WAITOK);
13720                                 mtx_lock(&softc->ctl_lock);
13721                         }
13722                 }
13723                 mtx_unlock(&softc->ctl_lock);
13724                 pause("-", CTL_LBP_PERIOD * hz);
13725         }
13726 }
13727
13728 static void
13729 ctl_enqueue_incoming(union ctl_io *io)
13730 {
13731         struct ctl_softc *softc = control_softc;
13732         struct ctl_thread *thr;
13733         u_int idx;
13734
13735         idx = (io->io_hdr.nexus.targ_port * 127 +
13736                io->io_hdr.nexus.initid) % worker_threads;
13737         thr = &softc->threads[idx];
13738         mtx_lock(&thr->queue_lock);
13739         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13740         mtx_unlock(&thr->queue_lock);
13741         wakeup(thr);
13742 }
13743
13744 static void
13745 ctl_enqueue_rtr(union ctl_io *io)
13746 {
13747         struct ctl_softc *softc = control_softc;
13748         struct ctl_thread *thr;
13749
13750         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13751         mtx_lock(&thr->queue_lock);
13752         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13753         mtx_unlock(&thr->queue_lock);
13754         wakeup(thr);
13755 }
13756
13757 static void
13758 ctl_enqueue_done(union ctl_io *io)
13759 {
13760         struct ctl_softc *softc = control_softc;
13761         struct ctl_thread *thr;
13762
13763         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13764         mtx_lock(&thr->queue_lock);
13765         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13766         mtx_unlock(&thr->queue_lock);
13767         wakeup(thr);
13768 }
13769
13770 static void
13771 ctl_enqueue_isc(union ctl_io *io)
13772 {
13773         struct ctl_softc *softc = control_softc;
13774         struct ctl_thread *thr;
13775
13776         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13777         mtx_lock(&thr->queue_lock);
13778         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13779         mtx_unlock(&thr->queue_lock);
13780         wakeup(thr);
13781 }
13782
13783 /*
13784  *  vim: ts=8
13785  */