]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl.c
Remove some duplicate, legacy, dead and questionable code.
[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_da.h>
73 #include <cam/ctl/ctl_io.h>
74 #include <cam/ctl/ctl.h>
75 #include <cam/ctl/ctl_frontend.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Template mode pages.
89  */
90
91 /*
92  * Note that these are default values only.  The actual values will be
93  * filled in when the user does a mode sense.
94  */
95 const static struct copan_debugconf_subpage debugconf_page_default = {
96         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
97         DBGCNF_SUBPAGE_CODE,            /* subpage */
98         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
99          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
100         DBGCNF_VERSION,                 /* page_version */
101         {CTL_TIME_IO_DEFAULT_SECS>>8,
102          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
103 };
104
105 const static struct copan_debugconf_subpage debugconf_page_changeable = {
106         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
107         DBGCNF_SUBPAGE_CODE,            /* subpage */
108         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
109          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
110         0,                              /* page_version */
111         {0xff,0xff},                    /* ctl_time_io_secs */
112 };
113
114 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
115         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
118         /*read_retry_count*/0,
119         /*correction_span*/0,
120         /*head_offset_count*/0,
121         /*data_strobe_offset_cnt*/0,
122         /*byte8*/SMS_RWER_LBPERE,
123         /*write_retry_count*/0,
124         /*reserved2*/0,
125         /*recovery_time_limit*/{0, 0},
126 };
127
128 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
129         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
130         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
131         /*byte3*/0,
132         /*read_retry_count*/0,
133         /*correction_span*/0,
134         /*head_offset_count*/0,
135         /*data_strobe_offset_cnt*/0,
136         /*byte8*/0,
137         /*write_retry_count*/0,
138         /*reserved2*/0,
139         /*recovery_time_limit*/{0, 0},
140 };
141
142 const static struct scsi_format_page format_page_default = {
143         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
144         /*page_length*/sizeof(struct scsi_format_page) - 2,
145         /*tracks_per_zone*/ {0, 0},
146         /*alt_sectors_per_zone*/ {0, 0},
147         /*alt_tracks_per_zone*/ {0, 0},
148         /*alt_tracks_per_lun*/ {0, 0},
149         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
150                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
151         /*bytes_per_sector*/ {0, 0},
152         /*interleave*/ {0, 0},
153         /*track_skew*/ {0, 0},
154         /*cylinder_skew*/ {0, 0},
155         /*flags*/ SFP_HSEC,
156         /*reserved*/ {0, 0, 0}
157 };
158
159 const static struct scsi_format_page format_page_changeable = {
160         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
161         /*page_length*/sizeof(struct scsi_format_page) - 2,
162         /*tracks_per_zone*/ {0, 0},
163         /*alt_sectors_per_zone*/ {0, 0},
164         /*alt_tracks_per_zone*/ {0, 0},
165         /*alt_tracks_per_lun*/ {0, 0},
166         /*sectors_per_track*/ {0, 0},
167         /*bytes_per_sector*/ {0, 0},
168         /*interleave*/ {0, 0},
169         /*track_skew*/ {0, 0},
170         /*cylinder_skew*/ {0, 0},
171         /*flags*/ 0,
172         /*reserved*/ {0, 0, 0}
173 };
174
175 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
176         /*page_code*/SMS_RIGID_DISK_PAGE,
177         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
178         /*cylinders*/ {0, 0, 0},
179         /*heads*/ CTL_DEFAULT_HEADS,
180         /*start_write_precomp*/ {0, 0, 0},
181         /*start_reduced_current*/ {0, 0, 0},
182         /*step_rate*/ {0, 0},
183         /*landing_zone_cylinder*/ {0, 0, 0},
184         /*rpl*/ SRDP_RPL_DISABLED,
185         /*rotational_offset*/ 0,
186         /*reserved1*/ 0,
187         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
188                            CTL_DEFAULT_ROTATION_RATE & 0xff},
189         /*reserved2*/ {0, 0}
190 };
191
192 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
193         /*page_code*/SMS_RIGID_DISK_PAGE,
194         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
195         /*cylinders*/ {0, 0, 0},
196         /*heads*/ 0,
197         /*start_write_precomp*/ {0, 0, 0},
198         /*start_reduced_current*/ {0, 0, 0},
199         /*step_rate*/ {0, 0},
200         /*landing_zone_cylinder*/ {0, 0, 0},
201         /*rpl*/ 0,
202         /*rotational_offset*/ 0,
203         /*reserved1*/ 0,
204         /*rotation_rate*/ {0, 0},
205         /*reserved2*/ {0, 0}
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
265
266 const static struct scsi_control_ext_page control_ext_page_default = {
267         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268         /*subpage_code*/0x01,
269         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270         /*flags*/0,
271         /*prio*/0,
272         /*max_sense*/0
273 };
274
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277         /*subpage_code*/0x01,
278         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279         /*flags*/0,
280         /*prio*/0,
281         /*max_sense*/0
282 };
283
284 const static struct scsi_info_exceptions_page ie_page_default = {
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287         /*info_flags*/SIEP_FLAGS_DEXCPT,
288         /*mrie*/0,
289         /*interval_timer*/{0, 0, 0, 0},
290         /*report_count*/{0, 0, 0, 0}
291 };
292
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296         /*info_flags*/0,
297         /*mrie*/0,
298         /*interval_timer*/{0, 0, 0, 0},
299         /*report_count*/{0, 0, 0, 0}
300 };
301
302 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
303
304 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
305         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
306         /*subpage_code*/0x02,
307         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
308         /*flags*/0,
309         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
310         /*descr*/{}},
311         {{/*flags*/0,
312           /*resource*/0x01,
313           /*reserved*/{0, 0},
314           /*count*/{0, 0, 0, 0}},
315          {/*flags*/0,
316           /*resource*/0x02,
317           /*reserved*/{0, 0},
318           /*count*/{0, 0, 0, 0}},
319          {/*flags*/0,
320           /*resource*/0xf1,
321           /*reserved*/{0, 0},
322           /*count*/{0, 0, 0, 0}},
323          {/*flags*/0,
324           /*resource*/0xf2,
325           /*reserved*/{0, 0},
326           /*count*/{0, 0, 0, 0}}
327         }
328 };
329
330 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
331         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
332         /*subpage_code*/0x02,
333         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
334         /*flags*/0,
335         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
336         /*descr*/{}},
337         {{/*flags*/0,
338           /*resource*/0,
339           /*reserved*/{0, 0},
340           /*count*/{0, 0, 0, 0}},
341          {/*flags*/0,
342           /*resource*/0,
343           /*reserved*/{0, 0},
344           /*count*/{0, 0, 0, 0}},
345          {/*flags*/0,
346           /*resource*/0,
347           /*reserved*/{0, 0},
348           /*count*/{0, 0, 0, 0}},
349          {/*flags*/0,
350           /*resource*/0,
351           /*reserved*/{0, 0},
352           /*count*/{0, 0, 0, 0}}
353         }
354 };
355
356 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
357 static int worker_threads = -1;
358 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
359     &worker_threads, 1, "Number of worker threads");
360 static int ctl_debug = CTL_DEBUG_NONE;
361 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
362     &ctl_debug, 0, "Enabled debug flags");
363
364 /*
365  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
366  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
367  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
368  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
369  */
370 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
371
372 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
373                                   int param);
374 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
375 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
376 static int ctl_init(void);
377 void ctl_shutdown(void);
378 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
379 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
380 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
381 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
382                               struct ctl_ooa *ooa_hdr,
383                               struct ctl_ooa_entry *kern_entries);
384 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
385                      struct thread *td);
386 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
387                          struct ctl_be_lun *be_lun);
388 static int ctl_free_lun(struct ctl_lun *lun);
389 static void ctl_create_lun(struct ctl_be_lun *be_lun);
390 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
391
392 static int ctl_do_mode_select(union ctl_io *io);
393 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
394                            uint64_t res_key, uint64_t sa_res_key,
395                            uint8_t type, uint32_t residx,
396                            struct ctl_scsiio *ctsio,
397                            struct scsi_per_res_out *cdb,
398                            struct scsi_per_res_out_parms* param);
399 static void ctl_pro_preempt_other(struct ctl_lun *lun,
400                                   union ctl_ha_msg *msg);
401 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
402 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
403 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
404 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
405 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
406 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
407 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
408                                          int alloc_len);
409 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
410                                          int alloc_len);
411 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
412 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
413 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
414 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
415 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
416 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
417     bool seq);
418 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
419 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
420     union ctl_io *pending_io, union ctl_io *ooa_io);
421 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
422                                 union ctl_io *starting_io);
423 static int ctl_check_blocked(struct ctl_lun *lun);
424 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
425                                 const struct ctl_cmd_entry *entry,
426                                 struct ctl_scsiio *ctsio);
427 static void ctl_failover_lun(union ctl_io *io);
428 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
429                                struct ctl_scsiio *ctsio);
430 static int ctl_scsiio(struct ctl_scsiio *ctsio);
431
432 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
433 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
434                             ctl_ua_type ua_type);
435 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
436                          ctl_ua_type ua_type);
437 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
438 static int ctl_abort_task(union ctl_io *io);
439 static int ctl_abort_task_set(union ctl_io *io);
440 static int ctl_query_task(union ctl_io *io, int task_set);
441 static int ctl_i_t_nexus_reset(union ctl_io *io);
442 static int ctl_query_async_event(union ctl_io *io);
443 static void ctl_run_task(union ctl_io *io);
444 #ifdef CTL_IO_DELAY
445 static void ctl_datamove_timer_wakeup(void *arg);
446 static void ctl_done_timer_wakeup(void *arg);
447 #endif /* CTL_IO_DELAY */
448
449 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
450 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
451 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
452 static void ctl_datamove_remote_write(union ctl_io *io);
453 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
454 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
455 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
456 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
457                                     ctl_ha_dt_cb callback);
458 static void ctl_datamove_remote_read(union ctl_io *io);
459 static void ctl_datamove_remote(union ctl_io *io);
460 static void ctl_process_done(union ctl_io *io);
461 static void ctl_lun_thread(void *arg);
462 static void ctl_thresh_thread(void *arg);
463 static void ctl_work_thread(void *arg);
464 static void ctl_enqueue_incoming(union ctl_io *io);
465 static void ctl_enqueue_rtr(union ctl_io *io);
466 static void ctl_enqueue_done(union ctl_io *io);
467 static void ctl_enqueue_isc(union ctl_io *io);
468 static const struct ctl_cmd_entry *
469     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
470 static const struct ctl_cmd_entry *
471     ctl_validate_command(struct ctl_scsiio *ctsio);
472 static int ctl_cmd_applicable(uint8_t lun_type,
473     const struct ctl_cmd_entry *entry);
474
475 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
476 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
477 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
478 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
479
480 /*
481  * Load the serialization table.  This isn't very pretty, but is probably
482  * the easiest way to do it.
483  */
484 #include "ctl_ser_table.c"
485
486 /*
487  * We only need to define open, close and ioctl routines for this driver.
488  */
489 static struct cdevsw ctl_cdevsw = {
490         .d_version =    D_VERSION,
491         .d_flags =      0,
492         .d_open =       ctl_open,
493         .d_close =      ctl_close,
494         .d_ioctl =      ctl_ioctl,
495         .d_name =       "ctl",
496 };
497
498
499 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
500
501 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
502
503 static moduledata_t ctl_moduledata = {
504         "ctl",
505         ctl_module_event_handler,
506         NULL
507 };
508
509 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
510 MODULE_VERSION(ctl, 1);
511
512 static struct ctl_frontend ha_frontend =
513 {
514         .name = "ha",
515 };
516
517 static void
518 ctl_ha_datamove(union ctl_io *io)
519 {
520         struct ctl_lun *lun;
521         struct ctl_sg_entry *sgl;
522         union ctl_ha_msg msg;
523         uint32_t sg_entries_sent;
524         int do_sg_copy, i, j;
525
526         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
527         memset(&msg.dt, 0, sizeof(msg.dt));
528         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
529         msg.hdr.original_sc = io->io_hdr.original_sc;
530         msg.hdr.serializing_sc = io;
531         msg.hdr.nexus = io->io_hdr.nexus;
532         msg.hdr.status = io->io_hdr.status;
533         msg.dt.flags = io->io_hdr.flags;
534
535         /*
536          * We convert everything into a S/G list here.  We can't
537          * pass by reference, only by value between controllers.
538          * So we can't pass a pointer to the S/G list, only as many
539          * S/G entries as we can fit in here.  If it's possible for
540          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
541          * then we need to break this up into multiple transfers.
542          */
543         if (io->scsiio.kern_sg_entries == 0) {
544                 msg.dt.kern_sg_entries = 1;
545 #if 0
546                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
547                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
548                 } else {
549                         /* XXX KDM use busdma here! */
550                         msg.dt.sg_list[0].addr =
551                             (void *)vtophys(io->scsiio.kern_data_ptr);
552                 }
553 #else
554                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
555                     ("HA does not support BUS_ADDR"));
556                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
557 #endif
558                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
559                 do_sg_copy = 0;
560         } else {
561                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
562                 do_sg_copy = 1;
563         }
564
565         msg.dt.kern_data_len = io->scsiio.kern_data_len;
566         msg.dt.kern_total_len = io->scsiio.kern_total_len;
567         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
568         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
569         msg.dt.sg_sequence = 0;
570
571         /*
572          * Loop until we've sent all of the S/G entries.  On the
573          * other end, we'll recompose these S/G entries into one
574          * contiguous list before processing.
575          */
576         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
577             msg.dt.sg_sequence++) {
578                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
579                     sizeof(msg.dt.sg_list[0])),
580                     msg.dt.kern_sg_entries - sg_entries_sent);
581                 if (do_sg_copy != 0) {
582                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
583                         for (i = sg_entries_sent, j = 0;
584                              i < msg.dt.cur_sg_entries; i++, j++) {
585 #if 0
586                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
587                                         msg.dt.sg_list[j].addr = sgl[i].addr;
588                                 } else {
589                                         /* XXX KDM use busdma here! */
590                                         msg.dt.sg_list[j].addr =
591                                             (void *)vtophys(sgl[i].addr);
592                                 }
593 #else
594                                 KASSERT((io->io_hdr.flags &
595                                     CTL_FLAG_BUS_ADDR) == 0,
596                                     ("HA does not support BUS_ADDR"));
597                                 msg.dt.sg_list[j].addr = sgl[i].addr;
598 #endif
599                                 msg.dt.sg_list[j].len = sgl[i].len;
600                         }
601                 }
602
603                 sg_entries_sent += msg.dt.cur_sg_entries;
604                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
605                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
606                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
607                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
608                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
609                         io->io_hdr.port_status = 31341;
610                         io->scsiio.be_move_done(io);
611                         return;
612                 }
613                 msg.dt.sent_sg_entries = sg_entries_sent;
614         }
615
616         /*
617          * Officially handover the request from us to peer.
618          * If failover has just happened, then we must return error.
619          * If failover happen just after, then it is not our problem.
620          */
621         if (lun)
622                 mtx_lock(&lun->lun_lock);
623         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
624                 if (lun)
625                         mtx_unlock(&lun->lun_lock);
626                 io->io_hdr.port_status = 31342;
627                 io->scsiio.be_move_done(io);
628                 return;
629         }
630         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
631         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
632         if (lun)
633                 mtx_unlock(&lun->lun_lock);
634 }
635
636 static void
637 ctl_ha_done(union ctl_io *io)
638 {
639         union ctl_ha_msg msg;
640
641         if (io->io_hdr.io_type == CTL_IO_SCSI) {
642                 memset(&msg, 0, sizeof(msg));
643                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
644                 msg.hdr.original_sc = io->io_hdr.original_sc;
645                 msg.hdr.nexus = io->io_hdr.nexus;
646                 msg.hdr.status = io->io_hdr.status;
647                 msg.scsi.scsi_status = io->scsiio.scsi_status;
648                 msg.scsi.tag_num = io->scsiio.tag_num;
649                 msg.scsi.tag_type = io->scsiio.tag_type;
650                 msg.scsi.sense_len = io->scsiio.sense_len;
651                 msg.scsi.sense_residual = io->scsiio.sense_residual;
652                 msg.scsi.residual = io->scsiio.residual;
653                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
654                     io->scsiio.sense_len);
655                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
656                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
657                     msg.scsi.sense_len, M_WAITOK);
658         }
659         ctl_free_io(io);
660 }
661
662 static void
663 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
664                             union ctl_ha_msg *msg_info)
665 {
666         struct ctl_scsiio *ctsio;
667
668         if (msg_info->hdr.original_sc == NULL) {
669                 printf("%s: original_sc == NULL!\n", __func__);
670                 /* XXX KDM now what? */
671                 return;
672         }
673
674         ctsio = &msg_info->hdr.original_sc->scsiio;
675         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
676         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
677         ctsio->io_hdr.status = msg_info->hdr.status;
678         ctsio->scsi_status = msg_info->scsi.scsi_status;
679         ctsio->sense_len = msg_info->scsi.sense_len;
680         ctsio->sense_residual = msg_info->scsi.sense_residual;
681         ctsio->residual = msg_info->scsi.residual;
682         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
683                msg_info->scsi.sense_len);
684         ctl_enqueue_isc((union ctl_io *)ctsio);
685 }
686
687 static void
688 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
689                                 union ctl_ha_msg *msg_info)
690 {
691         struct ctl_scsiio *ctsio;
692
693         if (msg_info->hdr.serializing_sc == NULL) {
694                 printf("%s: serializing_sc == NULL!\n", __func__);
695                 /* XXX KDM now what? */
696                 return;
697         }
698
699         ctsio = &msg_info->hdr.serializing_sc->scsiio;
700         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
701         ctl_enqueue_isc((union ctl_io *)ctsio);
702 }
703
704 void
705 ctl_isc_announce_lun(struct ctl_lun *lun)
706 {
707         struct ctl_softc *softc = lun->ctl_softc;
708         union ctl_ha_msg *msg;
709         struct ctl_ha_msg_lun_pr_key pr_key;
710         int i, k;
711
712         if (softc->ha_link != CTL_HA_LINK_ONLINE)
713                 return;
714         mtx_lock(&lun->lun_lock);
715         i = sizeof(msg->lun);
716         if (lun->lun_devid)
717                 i += lun->lun_devid->len;
718         i += sizeof(pr_key) * lun->pr_key_count;
719 alloc:
720         mtx_unlock(&lun->lun_lock);
721         msg = malloc(i, M_CTL, M_WAITOK);
722         mtx_lock(&lun->lun_lock);
723         k = sizeof(msg->lun);
724         if (lun->lun_devid)
725                 k += lun->lun_devid->len;
726         k += sizeof(pr_key) * lun->pr_key_count;
727         if (i < k) {
728                 free(msg, M_CTL);
729                 i = k;
730                 goto alloc;
731         }
732         bzero(&msg->lun, sizeof(msg->lun));
733         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
734         msg->hdr.nexus.targ_lun = lun->lun;
735         msg->hdr.nexus.targ_mapped_lun = lun->lun;
736         msg->lun.flags = lun->flags;
737         msg->lun.pr_generation = lun->PRGeneration;
738         msg->lun.pr_res_idx = lun->pr_res_idx;
739         msg->lun.pr_res_type = lun->res_type;
740         msg->lun.pr_key_count = lun->pr_key_count;
741         i = 0;
742         if (lun->lun_devid) {
743                 msg->lun.lun_devid_len = lun->lun_devid->len;
744                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
745                     msg->lun.lun_devid_len);
746                 i += msg->lun.lun_devid_len;
747         }
748         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
749                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
750                         continue;
751                 pr_key.pr_iid = k;
752                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
753                 i += sizeof(pr_key);
754         }
755         mtx_unlock(&lun->lun_lock);
756         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
757             M_WAITOK);
758         free(msg, M_CTL);
759
760         if (lun->flags & CTL_LUN_PRIMARY_SC) {
761                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
762                         ctl_isc_announce_mode(lun, -1,
763                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
764                             lun->mode_pages.index[i].subpage);
765                 }
766         }
767 }
768
769 void
770 ctl_isc_announce_port(struct ctl_port *port)
771 {
772         struct ctl_softc *softc = port->ctl_softc;
773         union ctl_ha_msg *msg;
774         int i;
775
776         if (port->targ_port < softc->port_min ||
777             port->targ_port >= softc->port_max ||
778             softc->ha_link != CTL_HA_LINK_ONLINE)
779                 return;
780         i = sizeof(msg->port) + strlen(port->port_name) + 1;
781         if (port->lun_map)
782                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
783         if (port->port_devid)
784                 i += port->port_devid->len;
785         if (port->target_devid)
786                 i += port->target_devid->len;
787         if (port->init_devid)
788                 i += port->init_devid->len;
789         msg = malloc(i, M_CTL, M_WAITOK);
790         bzero(&msg->port, sizeof(msg->port));
791         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
792         msg->hdr.nexus.targ_port = port->targ_port;
793         msg->port.port_type = port->port_type;
794         msg->port.physical_port = port->physical_port;
795         msg->port.virtual_port = port->virtual_port;
796         msg->port.status = port->status;
797         i = 0;
798         msg->port.name_len = sprintf(&msg->port.data[i],
799             "%d:%s", softc->ha_id, port->port_name) + 1;
800         i += msg->port.name_len;
801         if (port->lun_map) {
802                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
803                 memcpy(&msg->port.data[i], port->lun_map,
804                     msg->port.lun_map_len);
805                 i += msg->port.lun_map_len;
806         }
807         if (port->port_devid) {
808                 msg->port.port_devid_len = port->port_devid->len;
809                 memcpy(&msg->port.data[i], port->port_devid->data,
810                     msg->port.port_devid_len);
811                 i += msg->port.port_devid_len;
812         }
813         if (port->target_devid) {
814                 msg->port.target_devid_len = port->target_devid->len;
815                 memcpy(&msg->port.data[i], port->target_devid->data,
816                     msg->port.target_devid_len);
817                 i += msg->port.target_devid_len;
818         }
819         if (port->init_devid) {
820                 msg->port.init_devid_len = port->init_devid->len;
821                 memcpy(&msg->port.data[i], port->init_devid->data,
822                     msg->port.init_devid_len);
823                 i += msg->port.init_devid_len;
824         }
825         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
826             M_WAITOK);
827         free(msg, M_CTL);
828 }
829
830 void
831 ctl_isc_announce_iid(struct ctl_port *port, int iid)
832 {
833         struct ctl_softc *softc = port->ctl_softc;
834         union ctl_ha_msg *msg;
835         int i, l;
836
837         if (port->targ_port < softc->port_min ||
838             port->targ_port >= softc->port_max ||
839             softc->ha_link != CTL_HA_LINK_ONLINE)
840                 return;
841         mtx_lock(&softc->ctl_lock);
842         i = sizeof(msg->iid);
843         l = 0;
844         if (port->wwpn_iid[iid].name)
845                 l = strlen(port->wwpn_iid[iid].name) + 1;
846         i += l;
847         msg = malloc(i, M_CTL, M_NOWAIT);
848         if (msg == NULL) {
849                 mtx_unlock(&softc->ctl_lock);
850                 return;
851         }
852         bzero(&msg->iid, sizeof(msg->iid));
853         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
854         msg->hdr.nexus.targ_port = port->targ_port;
855         msg->hdr.nexus.initid = iid;
856         msg->iid.in_use = port->wwpn_iid[iid].in_use;
857         msg->iid.name_len = l;
858         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
859         if (port->wwpn_iid[iid].name)
860                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
861         mtx_unlock(&softc->ctl_lock);
862         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
863         free(msg, M_CTL);
864 }
865
866 void
867 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
868     uint8_t page, uint8_t subpage)
869 {
870         struct ctl_softc *softc = lun->ctl_softc;
871         union ctl_ha_msg msg;
872         int i;
873
874         if (softc->ha_link != CTL_HA_LINK_ONLINE)
875                 return;
876         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
877                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
878                     page && lun->mode_pages.index[i].subpage == subpage)
879                         break;
880         }
881         if (i == CTL_NUM_MODE_PAGES)
882                 return;
883         bzero(&msg.mode, sizeof(msg.mode));
884         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
885         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
886         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
887         msg.hdr.nexus.targ_lun = lun->lun;
888         msg.hdr.nexus.targ_mapped_lun = lun->lun;
889         msg.mode.page_code = page;
890         msg.mode.subpage = subpage;
891         msg.mode.page_len = lun->mode_pages.index[i].page_len;
892         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
893             msg.mode.page_len);
894         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
895             M_WAITOK);
896 }
897
898 static void
899 ctl_isc_ha_link_up(struct ctl_softc *softc)
900 {
901         struct ctl_port *port;
902         struct ctl_lun *lun;
903         union ctl_ha_msg msg;
904         int i;
905
906         /* Announce this node parameters to peer for validation. */
907         msg.login.msg_type = CTL_MSG_LOGIN;
908         msg.login.version = CTL_HA_VERSION;
909         msg.login.ha_mode = softc->ha_mode;
910         msg.login.ha_id = softc->ha_id;
911         msg.login.max_luns = CTL_MAX_LUNS;
912         msg.login.max_ports = CTL_MAX_PORTS;
913         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
914         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
915             M_WAITOK);
916
917         STAILQ_FOREACH(port, &softc->port_list, links) {
918                 ctl_isc_announce_port(port);
919                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
920                         if (port->wwpn_iid[i].in_use)
921                                 ctl_isc_announce_iid(port, i);
922                 }
923         }
924         STAILQ_FOREACH(lun, &softc->lun_list, links)
925                 ctl_isc_announce_lun(lun);
926 }
927
928 static void
929 ctl_isc_ha_link_down(struct ctl_softc *softc)
930 {
931         struct ctl_port *port;
932         struct ctl_lun *lun;
933         union ctl_io *io;
934         int i;
935
936         mtx_lock(&softc->ctl_lock);
937         STAILQ_FOREACH(lun, &softc->lun_list, links) {
938                 mtx_lock(&lun->lun_lock);
939                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
940                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
941                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
942                 }
943                 mtx_unlock(&lun->lun_lock);
944
945                 mtx_unlock(&softc->ctl_lock);
946                 io = ctl_alloc_io(softc->othersc_pool);
947                 mtx_lock(&softc->ctl_lock);
948                 ctl_zero_io(io);
949                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
950                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
951                 ctl_enqueue_isc(io);
952         }
953
954         STAILQ_FOREACH(port, &softc->port_list, links) {
955                 if (port->targ_port >= softc->port_min &&
956                     port->targ_port < softc->port_max)
957                         continue;
958                 port->status &= ~CTL_PORT_STATUS_ONLINE;
959                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
960                         port->wwpn_iid[i].in_use = 0;
961                         free(port->wwpn_iid[i].name, M_CTL);
962                         port->wwpn_iid[i].name = NULL;
963                 }
964         }
965         mtx_unlock(&softc->ctl_lock);
966 }
967
968 static void
969 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
970 {
971         struct ctl_lun *lun;
972         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
973
974         mtx_lock(&softc->ctl_lock);
975         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
976             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
977                 mtx_lock(&lun->lun_lock);
978                 mtx_unlock(&softc->ctl_lock);
979                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
980                     msg->ua.ua_set)
981                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
982                 if (msg->ua.ua_all) {
983                         if (msg->ua.ua_set)
984                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
985                         else
986                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
987                 } else {
988                         if (msg->ua.ua_set)
989                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
990                         else
991                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
992                 }
993                 mtx_unlock(&lun->lun_lock);
994         } else
995                 mtx_unlock(&softc->ctl_lock);
996 }
997
998 static void
999 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1000 {
1001         struct ctl_lun *lun;
1002         struct ctl_ha_msg_lun_pr_key pr_key;
1003         int i, k;
1004         ctl_lun_flags oflags;
1005         uint32_t targ_lun;
1006
1007         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1008         mtx_lock(&softc->ctl_lock);
1009         if ((targ_lun >= CTL_MAX_LUNS) ||
1010             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1011                 mtx_unlock(&softc->ctl_lock);
1012                 return;
1013         }
1014         mtx_lock(&lun->lun_lock);
1015         mtx_unlock(&softc->ctl_lock);
1016         if (lun->flags & CTL_LUN_DISABLED) {
1017                 mtx_unlock(&lun->lun_lock);
1018                 return;
1019         }
1020         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1021         if (msg->lun.lun_devid_len != i || (i > 0 &&
1022             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1023                 mtx_unlock(&lun->lun_lock);
1024                 printf("%s: Received conflicting HA LUN %d\n",
1025                     __func__, msg->hdr.nexus.targ_lun);
1026                 return;
1027         } else {
1028                 /* Record whether peer is primary. */
1029                 oflags = lun->flags;
1030                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1031                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1032                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1033                 else
1034                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1035                 if (oflags != lun->flags)
1036                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1037
1038                 /* If peer is primary and we are not -- use data */
1039                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1040                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1041                         lun->PRGeneration = msg->lun.pr_generation;
1042                         lun->pr_res_idx = msg->lun.pr_res_idx;
1043                         lun->res_type = msg->lun.pr_res_type;
1044                         lun->pr_key_count = msg->lun.pr_key_count;
1045                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1046                                 ctl_clr_prkey(lun, k);
1047                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1048                                 memcpy(&pr_key, &msg->lun.data[i],
1049                                     sizeof(pr_key));
1050                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1051                                 ctl_set_prkey(lun, pr_key.pr_iid,
1052                                     pr_key.pr_key);
1053                                 i += sizeof(pr_key);
1054                         }
1055                 }
1056
1057                 mtx_unlock(&lun->lun_lock);
1058                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1059                     __func__, msg->hdr.nexus.targ_lun,
1060                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1061                     "primary" : "secondary"));
1062
1063                 /* If we are primary but peer doesn't know -- notify */
1064                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1065                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1066                         ctl_isc_announce_lun(lun);
1067         }
1068 }
1069
1070 static void
1071 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1072 {
1073         struct ctl_port *port;
1074         struct ctl_lun *lun;
1075         int i, new;
1076
1077         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1078         if (port == NULL) {
1079                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1080                     msg->hdr.nexus.targ_port));
1081                 new = 1;
1082                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1083                 port->frontend = &ha_frontend;
1084                 port->targ_port = msg->hdr.nexus.targ_port;
1085                 port->fe_datamove = ctl_ha_datamove;
1086                 port->fe_done = ctl_ha_done;
1087         } else if (port->frontend == &ha_frontend) {
1088                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1089                     msg->hdr.nexus.targ_port));
1090                 new = 0;
1091         } else {
1092                 printf("%s: Received conflicting HA port %d\n",
1093                     __func__, msg->hdr.nexus.targ_port);
1094                 return;
1095         }
1096         port->port_type = msg->port.port_type;
1097         port->physical_port = msg->port.physical_port;
1098         port->virtual_port = msg->port.virtual_port;
1099         port->status = msg->port.status;
1100         i = 0;
1101         free(port->port_name, M_CTL);
1102         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1103             M_CTL);
1104         i += msg->port.name_len;
1105         if (msg->port.lun_map_len != 0) {
1106                 if (port->lun_map == NULL)
1107                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1108                             M_CTL, M_WAITOK);
1109                 memcpy(port->lun_map, &msg->port.data[i],
1110                     sizeof(uint32_t) * CTL_MAX_LUNS);
1111                 i += msg->port.lun_map_len;
1112         } else {
1113                 free(port->lun_map, M_CTL);
1114                 port->lun_map = NULL;
1115         }
1116         if (msg->port.port_devid_len != 0) {
1117                 if (port->port_devid == NULL ||
1118                     port->port_devid->len != msg->port.port_devid_len) {
1119                         free(port->port_devid, M_CTL);
1120                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1121                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1122                 }
1123                 memcpy(port->port_devid->data, &msg->port.data[i],
1124                     msg->port.port_devid_len);
1125                 port->port_devid->len = msg->port.port_devid_len;
1126                 i += msg->port.port_devid_len;
1127         } else {
1128                 free(port->port_devid, M_CTL);
1129                 port->port_devid = NULL;
1130         }
1131         if (msg->port.target_devid_len != 0) {
1132                 if (port->target_devid == NULL ||
1133                     port->target_devid->len != msg->port.target_devid_len) {
1134                         free(port->target_devid, M_CTL);
1135                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1136                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1137                 }
1138                 memcpy(port->target_devid->data, &msg->port.data[i],
1139                     msg->port.target_devid_len);
1140                 port->target_devid->len = msg->port.target_devid_len;
1141                 i += msg->port.target_devid_len;
1142         } else {
1143                 free(port->target_devid, M_CTL);
1144                 port->target_devid = NULL;
1145         }
1146         if (msg->port.init_devid_len != 0) {
1147                 if (port->init_devid == NULL ||
1148                     port->init_devid->len != msg->port.init_devid_len) {
1149                         free(port->init_devid, M_CTL);
1150                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1151                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1152                 }
1153                 memcpy(port->init_devid->data, &msg->port.data[i],
1154                     msg->port.init_devid_len);
1155                 port->init_devid->len = msg->port.init_devid_len;
1156                 i += msg->port.init_devid_len;
1157         } else {
1158                 free(port->init_devid, M_CTL);
1159                 port->init_devid = NULL;
1160         }
1161         if (new) {
1162                 if (ctl_port_register(port) != 0) {
1163                         printf("%s: ctl_port_register() failed with error\n",
1164                             __func__);
1165                 }
1166         }
1167         mtx_lock(&softc->ctl_lock);
1168         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1169                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1170                         continue;
1171                 mtx_lock(&lun->lun_lock);
1172                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1173                 mtx_unlock(&lun->lun_lock);
1174         }
1175         mtx_unlock(&softc->ctl_lock);
1176 }
1177
1178 static void
1179 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1180 {
1181         struct ctl_port *port;
1182         int iid;
1183
1184         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1185         if (port == NULL) {
1186                 printf("%s: Received IID for unknown port %d\n",
1187                     __func__, msg->hdr.nexus.targ_port);
1188                 return;
1189         }
1190         iid = msg->hdr.nexus.initid;
1191         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1192         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1193         free(port->wwpn_iid[iid].name, M_CTL);
1194         if (msg->iid.name_len) {
1195                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1196                     msg->iid.name_len, M_CTL);
1197         } else
1198                 port->wwpn_iid[iid].name = NULL;
1199 }
1200
1201 static void
1202 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1203 {
1204
1205         if (msg->login.version != CTL_HA_VERSION) {
1206                 printf("CTL HA peers have different versions %d != %d\n",
1207                     msg->login.version, CTL_HA_VERSION);
1208                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1209                 return;
1210         }
1211         if (msg->login.ha_mode != softc->ha_mode) {
1212                 printf("CTL HA peers have different ha_mode %d != %d\n",
1213                     msg->login.ha_mode, softc->ha_mode);
1214                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1215                 return;
1216         }
1217         if (msg->login.ha_id == softc->ha_id) {
1218                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1219                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1220                 return;
1221         }
1222         if (msg->login.max_luns != CTL_MAX_LUNS ||
1223             msg->login.max_ports != CTL_MAX_PORTS ||
1224             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1225                 printf("CTL HA peers have different limits\n");
1226                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1227                 return;
1228         }
1229 }
1230
1231 static void
1232 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1233 {
1234         struct ctl_lun *lun;
1235         int i;
1236         uint32_t initidx, targ_lun;
1237
1238         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1239         mtx_lock(&softc->ctl_lock);
1240         if ((targ_lun >= CTL_MAX_LUNS) ||
1241             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1242                 mtx_unlock(&softc->ctl_lock);
1243                 return;
1244         }
1245         mtx_lock(&lun->lun_lock);
1246         mtx_unlock(&softc->ctl_lock);
1247         if (lun->flags & CTL_LUN_DISABLED) {
1248                 mtx_unlock(&lun->lun_lock);
1249                 return;
1250         }
1251         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1252                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1253                     msg->mode.page_code &&
1254                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1255                         break;
1256         }
1257         if (i == CTL_NUM_MODE_PAGES) {
1258                 mtx_unlock(&lun->lun_lock);
1259                 return;
1260         }
1261         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1262             lun->mode_pages.index[i].page_len);
1263         initidx = ctl_get_initindex(&msg->hdr.nexus);
1264         if (initidx != -1)
1265                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1266         mtx_unlock(&lun->lun_lock);
1267 }
1268
1269 /*
1270  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1271  * subsystem come in here.
1272  */
1273 static void
1274 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1275 {
1276         struct ctl_softc *softc = control_softc;
1277         union ctl_io *io;
1278         struct ctl_prio *presio;
1279         ctl_ha_status isc_status;
1280
1281         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1282         if (event == CTL_HA_EVT_MSG_RECV) {
1283                 union ctl_ha_msg *msg, msgbuf;
1284
1285                 if (param > sizeof(msgbuf))
1286                         msg = malloc(param, M_CTL, M_WAITOK);
1287                 else
1288                         msg = &msgbuf;
1289                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1290                     M_WAITOK);
1291                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1292                         printf("%s: Error receiving message: %d\n",
1293                             __func__, isc_status);
1294                         if (msg != &msgbuf)
1295                                 free(msg, M_CTL);
1296                         return;
1297                 }
1298
1299                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1300                 switch (msg->hdr.msg_type) {
1301                 case CTL_MSG_SERIALIZE:
1302                         io = ctl_alloc_io(softc->othersc_pool);
1303                         ctl_zero_io(io);
1304                         // populate ctsio from msg
1305                         io->io_hdr.io_type = CTL_IO_SCSI;
1306                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1307                         io->io_hdr.original_sc = msg->hdr.original_sc;
1308                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1309                                             CTL_FLAG_IO_ACTIVE;
1310                         /*
1311                          * If we're in serialization-only mode, we don't
1312                          * want to go through full done processing.  Thus
1313                          * the COPY flag.
1314                          *
1315                          * XXX KDM add another flag that is more specific.
1316                          */
1317                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1318                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1319                         io->io_hdr.nexus = msg->hdr.nexus;
1320 #if 0
1321                         printf("port %u, iid %u, lun %u\n",
1322                                io->io_hdr.nexus.targ_port,
1323                                io->io_hdr.nexus.initid,
1324                                io->io_hdr.nexus.targ_lun);
1325 #endif
1326                         io->scsiio.tag_num = msg->scsi.tag_num;
1327                         io->scsiio.tag_type = msg->scsi.tag_type;
1328 #ifdef CTL_TIME_IO
1329                         io->io_hdr.start_time = time_uptime;
1330                         getbinuptime(&io->io_hdr.start_bt);
1331 #endif /* CTL_TIME_IO */
1332                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1333                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1334                                CTL_MAX_CDBLEN);
1335                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1336                                 const struct ctl_cmd_entry *entry;
1337
1338                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1339                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1340                                 io->io_hdr.flags |=
1341                                         entry->flags & CTL_FLAG_DATA_MASK;
1342                         }
1343                         ctl_enqueue_isc(io);
1344                         break;
1345
1346                 /* Performed on the Originating SC, XFER mode only */
1347                 case CTL_MSG_DATAMOVE: {
1348                         struct ctl_sg_entry *sgl;
1349                         int i, j;
1350
1351                         io = msg->hdr.original_sc;
1352                         if (io == NULL) {
1353                                 printf("%s: original_sc == NULL!\n", __func__);
1354                                 /* XXX KDM do something here */
1355                                 break;
1356                         }
1357                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1358                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1359                         /*
1360                          * Keep track of this, we need to send it back over
1361                          * when the datamove is complete.
1362                          */
1363                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1364                         if (msg->hdr.status == CTL_SUCCESS)
1365                                 io->io_hdr.status = msg->hdr.status;
1366
1367                         if (msg->dt.sg_sequence == 0) {
1368 #ifdef CTL_TIME_IO
1369                                 getbinuptime(&io->io_hdr.dma_start_bt);
1370 #endif
1371                                 i = msg->dt.kern_sg_entries +
1372                                     msg->dt.kern_data_len /
1373                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1374                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1375                                     M_WAITOK | M_ZERO);
1376                                 io->io_hdr.remote_sglist = sgl;
1377                                 io->io_hdr.local_sglist =
1378                                     &sgl[msg->dt.kern_sg_entries];
1379
1380                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1381
1382                                 io->scsiio.kern_sg_entries =
1383                                         msg->dt.kern_sg_entries;
1384                                 io->scsiio.rem_sg_entries =
1385                                         msg->dt.kern_sg_entries;
1386                                 io->scsiio.kern_data_len =
1387                                         msg->dt.kern_data_len;
1388                                 io->scsiio.kern_total_len =
1389                                         msg->dt.kern_total_len;
1390                                 io->scsiio.kern_data_resid =
1391                                         msg->dt.kern_data_resid;
1392                                 io->scsiio.kern_rel_offset =
1393                                         msg->dt.kern_rel_offset;
1394                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1395                                 io->io_hdr.flags |= msg->dt.flags &
1396                                     CTL_FLAG_BUS_ADDR;
1397                         } else
1398                                 sgl = (struct ctl_sg_entry *)
1399                                         io->scsiio.kern_data_ptr;
1400
1401                         for (i = msg->dt.sent_sg_entries, j = 0;
1402                              i < (msg->dt.sent_sg_entries +
1403                              msg->dt.cur_sg_entries); i++, j++) {
1404                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1405                                 sgl[i].len = msg->dt.sg_list[j].len;
1406
1407 #if 0
1408                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1409                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1410 #endif
1411                         }
1412
1413                         /*
1414                          * If this is the last piece of the I/O, we've got
1415                          * the full S/G list.  Queue processing in the thread.
1416                          * Otherwise wait for the next piece.
1417                          */
1418                         if (msg->dt.sg_last != 0)
1419                                 ctl_enqueue_isc(io);
1420                         break;
1421                 }
1422                 /* Performed on the Serializing (primary) SC, XFER mode only */
1423                 case CTL_MSG_DATAMOVE_DONE: {
1424                         if (msg->hdr.serializing_sc == NULL) {
1425                                 printf("%s: serializing_sc == NULL!\n",
1426                                        __func__);
1427                                 /* XXX KDM now what? */
1428                                 break;
1429                         }
1430                         /*
1431                          * We grab the sense information here in case
1432                          * there was a failure, so we can return status
1433                          * back to the initiator.
1434                          */
1435                         io = msg->hdr.serializing_sc;
1436                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1437                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1438                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1439                         io->io_hdr.port_status = msg->scsi.fetd_status;
1440                         io->scsiio.residual = msg->scsi.residual;
1441                         if (msg->hdr.status != CTL_STATUS_NONE) {
1442                                 io->io_hdr.status = msg->hdr.status;
1443                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1444                                 io->scsiio.sense_len = msg->scsi.sense_len;
1445                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1446                                 memcpy(&io->scsiio.sense_data,
1447                                     &msg->scsi.sense_data,
1448                                     msg->scsi.sense_len);
1449                                 if (msg->hdr.status == CTL_SUCCESS)
1450                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1451                         }
1452                         ctl_enqueue_isc(io);
1453                         break;
1454                 }
1455
1456                 /* Preformed on Originating SC, SER_ONLY mode */
1457                 case CTL_MSG_R2R:
1458                         io = msg->hdr.original_sc;
1459                         if (io == NULL) {
1460                                 printf("%s: original_sc == NULL!\n",
1461                                     __func__);
1462                                 break;
1463                         }
1464                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1465                         io->io_hdr.msg_type = CTL_MSG_R2R;
1466                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1467                         ctl_enqueue_isc(io);
1468                         break;
1469
1470                 /*
1471                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1472                  * mode.
1473                  * Performed on the Originating (i.e. secondary) SC in XFER
1474                  * mode
1475                  */
1476                 case CTL_MSG_FINISH_IO:
1477                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1478                                 ctl_isc_handler_finish_xfer(softc, msg);
1479                         else
1480                                 ctl_isc_handler_finish_ser_only(softc, msg);
1481                         break;
1482
1483                 /* Preformed on Originating SC */
1484                 case CTL_MSG_BAD_JUJU:
1485                         io = msg->hdr.original_sc;
1486                         if (io == NULL) {
1487                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1488                                        __func__);
1489                                 break;
1490                         }
1491                         ctl_copy_sense_data(msg, io);
1492                         /*
1493                          * IO should have already been cleaned up on other
1494                          * SC so clear this flag so we won't send a message
1495                          * back to finish the IO there.
1496                          */
1497                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1498                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1499
1500                         /* io = msg->hdr.serializing_sc; */
1501                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1502                         ctl_enqueue_isc(io);
1503                         break;
1504
1505                 /* Handle resets sent from the other side */
1506                 case CTL_MSG_MANAGE_TASKS: {
1507                         struct ctl_taskio *taskio;
1508                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1509                             softc->othersc_pool);
1510                         ctl_zero_io((union ctl_io *)taskio);
1511                         taskio->io_hdr.io_type = CTL_IO_TASK;
1512                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1513                         taskio->io_hdr.nexus = msg->hdr.nexus;
1514                         taskio->task_action = msg->task.task_action;
1515                         taskio->tag_num = msg->task.tag_num;
1516                         taskio->tag_type = msg->task.tag_type;
1517 #ifdef CTL_TIME_IO
1518                         taskio->io_hdr.start_time = time_uptime;
1519                         getbinuptime(&taskio->io_hdr.start_bt);
1520 #endif /* CTL_TIME_IO */
1521                         ctl_run_task((union ctl_io *)taskio);
1522                         break;
1523                 }
1524                 /* Persistent Reserve action which needs attention */
1525                 case CTL_MSG_PERS_ACTION:
1526                         presio = (struct ctl_prio *)ctl_alloc_io(
1527                             softc->othersc_pool);
1528                         ctl_zero_io((union ctl_io *)presio);
1529                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1530                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1531                         presio->io_hdr.nexus = msg->hdr.nexus;
1532                         presio->pr_msg = msg->pr;
1533                         ctl_enqueue_isc((union ctl_io *)presio);
1534                         break;
1535                 case CTL_MSG_UA:
1536                         ctl_isc_ua(softc, msg, param);
1537                         break;
1538                 case CTL_MSG_PORT_SYNC:
1539                         ctl_isc_port_sync(softc, msg, param);
1540                         break;
1541                 case CTL_MSG_LUN_SYNC:
1542                         ctl_isc_lun_sync(softc, msg, param);
1543                         break;
1544                 case CTL_MSG_IID_SYNC:
1545                         ctl_isc_iid_sync(softc, msg, param);
1546                         break;
1547                 case CTL_MSG_LOGIN:
1548                         ctl_isc_login(softc, msg, param);
1549                         break;
1550                 case CTL_MSG_MODE_SYNC:
1551                         ctl_isc_mode_sync(softc, msg, param);
1552                         break;
1553                 default:
1554                         printf("Received HA message of unknown type %d\n",
1555                             msg->hdr.msg_type);
1556                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1557                         break;
1558                 }
1559                 if (msg != &msgbuf)
1560                         free(msg, M_CTL);
1561         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1562                 printf("CTL: HA link status changed from %d to %d\n",
1563                     softc->ha_link, param);
1564                 if (param == softc->ha_link)
1565                         return;
1566                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1567                         softc->ha_link = param;
1568                         ctl_isc_ha_link_down(softc);
1569                 } else {
1570                         softc->ha_link = param;
1571                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1572                                 ctl_isc_ha_link_up(softc);
1573                 }
1574                 return;
1575         } else {
1576                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1577                 return;
1578         }
1579 }
1580
1581 static void
1582 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1583 {
1584
1585         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1586             src->scsi.sense_len);
1587         dest->scsiio.scsi_status = src->scsi.scsi_status;
1588         dest->scsiio.sense_len = src->scsi.sense_len;
1589         dest->io_hdr.status = src->hdr.status;
1590 }
1591
1592 static void
1593 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1594 {
1595
1596         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1597             src->scsiio.sense_len);
1598         dest->scsi.scsi_status = src->scsiio.scsi_status;
1599         dest->scsi.sense_len = src->scsiio.sense_len;
1600         dest->hdr.status = src->io_hdr.status;
1601 }
1602
1603 void
1604 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1605 {
1606         struct ctl_softc *softc = lun->ctl_softc;
1607         ctl_ua_type *pu;
1608
1609         if (initidx < softc->init_min || initidx >= softc->init_max)
1610                 return;
1611         mtx_assert(&lun->lun_lock, MA_OWNED);
1612         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1613         if (pu == NULL)
1614                 return;
1615         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1616 }
1617
1618 void
1619 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1620 {
1621         int i;
1622
1623         mtx_assert(&lun->lun_lock, MA_OWNED);
1624         if (lun->pending_ua[port] == NULL)
1625                 return;
1626         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1627                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1628                         continue;
1629                 lun->pending_ua[port][i] |= ua;
1630         }
1631 }
1632
1633 void
1634 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1635 {
1636         struct ctl_softc *softc = lun->ctl_softc;
1637         int i;
1638
1639         mtx_assert(&lun->lun_lock, MA_OWNED);
1640         for (i = softc->port_min; i < softc->port_max; i++)
1641                 ctl_est_ua_port(lun, i, except, ua);
1642 }
1643
1644 void
1645 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1646 {
1647         struct ctl_softc *softc = lun->ctl_softc;
1648         ctl_ua_type *pu;
1649
1650         if (initidx < softc->init_min || initidx >= softc->init_max)
1651                 return;
1652         mtx_assert(&lun->lun_lock, MA_OWNED);
1653         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1654         if (pu == NULL)
1655                 return;
1656         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1657 }
1658
1659 void
1660 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1661 {
1662         struct ctl_softc *softc = lun->ctl_softc;
1663         int i, j;
1664
1665         mtx_assert(&lun->lun_lock, MA_OWNED);
1666         for (i = softc->port_min; i < softc->port_max; i++) {
1667                 if (lun->pending_ua[i] == NULL)
1668                         continue;
1669                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1670                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1671                                 continue;
1672                         lun->pending_ua[i][j] &= ~ua;
1673                 }
1674         }
1675 }
1676
1677 void
1678 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1679     ctl_ua_type ua_type)
1680 {
1681         struct ctl_lun *lun;
1682
1683         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1684         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1685                 mtx_lock(&lun->lun_lock);
1686                 ctl_clr_ua(lun, initidx, ua_type);
1687                 mtx_unlock(&lun->lun_lock);
1688         }
1689 }
1690
1691 static int
1692 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1693 {
1694         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1695         struct ctl_lun *lun;
1696         struct ctl_lun_req ireq;
1697         int error, value;
1698
1699         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1700         error = sysctl_handle_int(oidp, &value, 0, req);
1701         if ((error != 0) || (req->newptr == NULL))
1702                 return (error);
1703
1704         mtx_lock(&softc->ctl_lock);
1705         if (value == 0)
1706                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1707         else
1708                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1709         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1710                 mtx_unlock(&softc->ctl_lock);
1711                 bzero(&ireq, sizeof(ireq));
1712                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1713                 ireq.reqdata.modify.lun_id = lun->lun;
1714                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1715                     curthread);
1716                 if (ireq.status != CTL_LUN_OK) {
1717                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1718                             __func__, ireq.status, ireq.error_str);
1719                 }
1720                 mtx_lock(&softc->ctl_lock);
1721         }
1722         mtx_unlock(&softc->ctl_lock);
1723         return (0);
1724 }
1725
1726 static int
1727 ctl_init(void)
1728 {
1729         struct ctl_softc *softc;
1730         void *other_pool;
1731         int i, error;
1732
1733         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1734                                M_WAITOK | M_ZERO);
1735
1736         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1737                               "cam/ctl");
1738         softc->dev->si_drv1 = softc;
1739
1740         sysctl_ctx_init(&softc->sysctl_ctx);
1741         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1742                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1743                 CTLFLAG_RD, 0, "CAM Target Layer");
1744
1745         if (softc->sysctl_tree == NULL) {
1746                 printf("%s: unable to allocate sysctl tree\n", __func__);
1747                 destroy_dev(softc->dev);
1748                 free(control_softc, M_DEVBUF);
1749                 control_softc = NULL;
1750                 return (ENOMEM);
1751         }
1752
1753         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1754         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1755             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1756         softc->open_count = 0;
1757         softc->flags = 0;
1758
1759         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1760             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1761             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1762
1763         /*
1764          * In Copan's HA scheme, the "master" and "slave" roles are
1765          * figured out through the slot the controller is in.  Although it
1766          * is an active/active system, someone has to be in charge.
1767          */
1768         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1769             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1770             "HA head ID (0 - no HA)");
1771         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1772                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1773                 softc->is_single = 1;
1774                 softc->port_cnt = CTL_MAX_PORTS;
1775                 softc->port_min = 0;
1776         } else {
1777                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1778                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1779         }
1780         softc->port_max = softc->port_min + softc->port_cnt;
1781         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1782         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1783
1784         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1785             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1786             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1787
1788         STAILQ_INIT(&softc->lun_list);
1789         STAILQ_INIT(&softc->pending_lun_queue);
1790         STAILQ_INIT(&softc->fe_list);
1791         STAILQ_INIT(&softc->port_list);
1792         STAILQ_INIT(&softc->be_list);
1793         ctl_tpc_init(softc);
1794
1795         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1796                             &other_pool) != 0)
1797         {
1798                 printf("ctl: can't allocate %d entry other SC pool, "
1799                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1800                 return (ENOMEM);
1801         }
1802         softc->othersc_pool = other_pool;
1803
1804         if (worker_threads <= 0)
1805                 worker_threads = max(1, mp_ncpus / 4);
1806         if (worker_threads > CTL_MAX_THREADS)
1807                 worker_threads = CTL_MAX_THREADS;
1808
1809         for (i = 0; i < worker_threads; i++) {
1810                 struct ctl_thread *thr = &softc->threads[i];
1811
1812                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1813                 thr->ctl_softc = softc;
1814                 STAILQ_INIT(&thr->incoming_queue);
1815                 STAILQ_INIT(&thr->rtr_queue);
1816                 STAILQ_INIT(&thr->done_queue);
1817                 STAILQ_INIT(&thr->isc_queue);
1818
1819                 error = kproc_kthread_add(ctl_work_thread, thr,
1820                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1821                 if (error != 0) {
1822                         printf("error creating CTL work thread!\n");
1823                         ctl_pool_free(other_pool);
1824                         return (error);
1825                 }
1826         }
1827         error = kproc_kthread_add(ctl_lun_thread, softc,
1828             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1829         if (error != 0) {
1830                 printf("error creating CTL lun thread!\n");
1831                 ctl_pool_free(other_pool);
1832                 return (error);
1833         }
1834         error = kproc_kthread_add(ctl_thresh_thread, softc,
1835             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1836         if (error != 0) {
1837                 printf("error creating CTL threshold thread!\n");
1838                 ctl_pool_free(other_pool);
1839                 return (error);
1840         }
1841
1842         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1843             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1844             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1845
1846         if (softc->is_single == 0) {
1847                 ctl_frontend_register(&ha_frontend);
1848                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1849                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1850                         softc->is_single = 1;
1851                 } else
1852                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1853                     != CTL_HA_STATUS_SUCCESS) {
1854                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1855                         softc->is_single = 1;
1856                 }
1857         }
1858         return (0);
1859 }
1860
1861 void
1862 ctl_shutdown(void)
1863 {
1864         struct ctl_softc *softc = control_softc;
1865         struct ctl_lun *lun, *next_lun;
1866
1867         if (softc->is_single == 0) {
1868                 ctl_ha_msg_shutdown(softc);
1869                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1870                     != CTL_HA_STATUS_SUCCESS)
1871                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1872                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1873                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1874                 ctl_frontend_deregister(&ha_frontend);
1875         }
1876
1877         mtx_lock(&softc->ctl_lock);
1878
1879         /*
1880          * Free up each LUN.
1881          */
1882         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1883                 next_lun = STAILQ_NEXT(lun, links);
1884                 ctl_free_lun(lun);
1885         }
1886
1887         mtx_unlock(&softc->ctl_lock);
1888
1889 #if 0
1890         ctl_shutdown_thread(softc->work_thread);
1891         mtx_destroy(&softc->queue_lock);
1892 #endif
1893
1894         ctl_tpc_shutdown(softc);
1895         uma_zdestroy(softc->io_zone);
1896         mtx_destroy(&softc->ctl_lock);
1897
1898         destroy_dev(softc->dev);
1899
1900         sysctl_ctx_free(&softc->sysctl_ctx);
1901
1902         free(control_softc, M_DEVBUF);
1903         control_softc = NULL;
1904 }
1905
1906 static int
1907 ctl_module_event_handler(module_t mod, int what, void *arg)
1908 {
1909
1910         switch (what) {
1911         case MOD_LOAD:
1912                 return (ctl_init());
1913         case MOD_UNLOAD:
1914                 return (EBUSY);
1915         default:
1916                 return (EOPNOTSUPP);
1917         }
1918 }
1919
1920 /*
1921  * XXX KDM should we do some access checks here?  Bump a reference count to
1922  * prevent a CTL module from being unloaded while someone has it open?
1923  */
1924 static int
1925 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1926 {
1927         return (0);
1928 }
1929
1930 static int
1931 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1932 {
1933         return (0);
1934 }
1935
1936 /*
1937  * Remove an initiator by port number and initiator ID.
1938  * Returns 0 for success, -1 for failure.
1939  */
1940 int
1941 ctl_remove_initiator(struct ctl_port *port, int iid)
1942 {
1943         struct ctl_softc *softc = port->ctl_softc;
1944
1945         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1946
1947         if (iid > CTL_MAX_INIT_PER_PORT) {
1948                 printf("%s: initiator ID %u > maximun %u!\n",
1949                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1950                 return (-1);
1951         }
1952
1953         mtx_lock(&softc->ctl_lock);
1954         port->wwpn_iid[iid].in_use--;
1955         port->wwpn_iid[iid].last_use = time_uptime;
1956         mtx_unlock(&softc->ctl_lock);
1957         ctl_isc_announce_iid(port, iid);
1958
1959         return (0);
1960 }
1961
1962 /*
1963  * Add an initiator to the initiator map.
1964  * Returns iid for success, < 0 for failure.
1965  */
1966 int
1967 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1968 {
1969         struct ctl_softc *softc = port->ctl_softc;
1970         time_t best_time;
1971         int i, best;
1972
1973         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1974
1975         if (iid >= CTL_MAX_INIT_PER_PORT) {
1976                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1977                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1978                 free(name, M_CTL);
1979                 return (-1);
1980         }
1981
1982         mtx_lock(&softc->ctl_lock);
1983
1984         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1985                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1986                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1987                                 iid = i;
1988                                 break;
1989                         }
1990                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1991                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1992                                 iid = i;
1993                                 break;
1994                         }
1995                 }
1996         }
1997
1998         if (iid < 0) {
1999                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2000                         if (port->wwpn_iid[i].in_use == 0 &&
2001                             port->wwpn_iid[i].wwpn == 0 &&
2002                             port->wwpn_iid[i].name == NULL) {
2003                                 iid = i;
2004                                 break;
2005                         }
2006                 }
2007         }
2008
2009         if (iid < 0) {
2010                 best = -1;
2011                 best_time = INT32_MAX;
2012                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2013                         if (port->wwpn_iid[i].in_use == 0) {
2014                                 if (port->wwpn_iid[i].last_use < best_time) {
2015                                         best = i;
2016                                         best_time = port->wwpn_iid[i].last_use;
2017                                 }
2018                         }
2019                 }
2020                 iid = best;
2021         }
2022
2023         if (iid < 0) {
2024                 mtx_unlock(&softc->ctl_lock);
2025                 free(name, M_CTL);
2026                 return (-2);
2027         }
2028
2029         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2030                 /*
2031                  * This is not an error yet.
2032                  */
2033                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2034 #if 0
2035                         printf("%s: port %d iid %u WWPN %#jx arrived"
2036                             " again\n", __func__, port->targ_port,
2037                             iid, (uintmax_t)wwpn);
2038 #endif
2039                         goto take;
2040                 }
2041                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2042                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2043 #if 0
2044                         printf("%s: port %d iid %u name '%s' arrived"
2045                             " again\n", __func__, port->targ_port,
2046                             iid, name);
2047 #endif
2048                         goto take;
2049                 }
2050
2051                 /*
2052                  * This is an error, but what do we do about it?  The
2053                  * driver is telling us we have a new WWPN for this
2054                  * initiator ID, so we pretty much need to use it.
2055                  */
2056                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2057                     " but WWPN %#jx '%s' is still at that address\n",
2058                     __func__, port->targ_port, iid, wwpn, name,
2059                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2060                     port->wwpn_iid[iid].name);
2061
2062                 /*
2063                  * XXX KDM clear have_ca and ua_pending on each LUN for
2064                  * this initiator.
2065                  */
2066         }
2067 take:
2068         free(port->wwpn_iid[iid].name, M_CTL);
2069         port->wwpn_iid[iid].name = name;
2070         port->wwpn_iid[iid].wwpn = wwpn;
2071         port->wwpn_iid[iid].in_use++;
2072         mtx_unlock(&softc->ctl_lock);
2073         ctl_isc_announce_iid(port, iid);
2074
2075         return (iid);
2076 }
2077
2078 static int
2079 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2080 {
2081         int len;
2082
2083         switch (port->port_type) {
2084         case CTL_PORT_FC:
2085         {
2086                 struct scsi_transportid_fcp *id =
2087                     (struct scsi_transportid_fcp *)buf;
2088                 if (port->wwpn_iid[iid].wwpn == 0)
2089                         return (0);
2090                 memset(id, 0, sizeof(*id));
2091                 id->format_protocol = SCSI_PROTO_FC;
2092                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2093                 return (sizeof(*id));
2094         }
2095         case CTL_PORT_ISCSI:
2096         {
2097                 struct scsi_transportid_iscsi_port *id =
2098                     (struct scsi_transportid_iscsi_port *)buf;
2099                 if (port->wwpn_iid[iid].name == NULL)
2100                         return (0);
2101                 memset(id, 0, 256);
2102                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2103                     SCSI_PROTO_ISCSI;
2104                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2105                 len = roundup2(min(len, 252), 4);
2106                 scsi_ulto2b(len, id->additional_length);
2107                 return (sizeof(*id) + len);
2108         }
2109         case CTL_PORT_SAS:
2110         {
2111                 struct scsi_transportid_sas *id =
2112                     (struct scsi_transportid_sas *)buf;
2113                 if (port->wwpn_iid[iid].wwpn == 0)
2114                         return (0);
2115                 memset(id, 0, sizeof(*id));
2116                 id->format_protocol = SCSI_PROTO_SAS;
2117                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2118                 return (sizeof(*id));
2119         }
2120         default:
2121         {
2122                 struct scsi_transportid_spi *id =
2123                     (struct scsi_transportid_spi *)buf;
2124                 memset(id, 0, sizeof(*id));
2125                 id->format_protocol = SCSI_PROTO_SPI;
2126                 scsi_ulto2b(iid, id->scsi_addr);
2127                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2128                 return (sizeof(*id));
2129         }
2130         }
2131 }
2132
2133 /*
2134  * Serialize a command that went down the "wrong" side, and so was sent to
2135  * this controller for execution.  The logic is a little different than the
2136  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2137  * sent back to the other side, but in the success case, we execute the
2138  * command on this side (XFER mode) or tell the other side to execute it
2139  * (SER_ONLY mode).
2140  */
2141 static int
2142 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2143 {
2144         struct ctl_softc *softc = control_softc;
2145         union ctl_ha_msg msg_info;
2146         struct ctl_port *port;
2147         struct ctl_lun *lun;
2148         const struct ctl_cmd_entry *entry;
2149         int retval = 0;
2150         uint32_t targ_lun;
2151
2152         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2153         mtx_lock(&softc->ctl_lock);
2154
2155         /* Make sure that we know about this port. */
2156         port = ctl_io_port(&ctsio->io_hdr);
2157         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2158                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2159                                          /*retry_count*/ 1);
2160                 goto badjuju;
2161         }
2162
2163         /* Make sure that we know about this LUN. */
2164         if ((targ_lun < CTL_MAX_LUNS) &&
2165             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2166                 mtx_lock(&lun->lun_lock);
2167                 mtx_unlock(&softc->ctl_lock);
2168                 /*
2169                  * If the LUN is invalid, pretend that it doesn't exist.
2170                  * It will go away as soon as all pending I/O has been
2171                  * completed.
2172                  */
2173                 if (lun->flags & CTL_LUN_DISABLED) {
2174                         mtx_unlock(&lun->lun_lock);
2175                         lun = NULL;
2176                 }
2177         } else {
2178                 mtx_unlock(&softc->ctl_lock);
2179                 lun = NULL;
2180         }
2181         if (lun == NULL) {
2182                 /*
2183                  * The other node would not send this request to us unless
2184                  * received announce that we are primary node for this LUN.
2185                  * If this LUN does not exist now, it is probably result of
2186                  * a race, so respond to initiator in the most opaque way.
2187                  */
2188                 ctl_set_busy(ctsio);
2189                 goto badjuju;
2190         }
2191
2192         entry = ctl_get_cmd_entry(ctsio, NULL);
2193         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2194                 mtx_unlock(&lun->lun_lock);
2195                 goto badjuju;
2196         }
2197
2198         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2199         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2200
2201         /*
2202          * Every I/O goes into the OOA queue for a
2203          * particular LUN, and stays there until completion.
2204          */
2205 #ifdef CTL_TIME_IO
2206         if (TAILQ_EMPTY(&lun->ooa_queue))
2207                 lun->idle_time += getsbinuptime() - lun->last_busy;
2208 #endif
2209         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2210
2211         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2212                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2213                  ooa_links))) {
2214         case CTL_ACTION_BLOCK:
2215                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2216                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2217                                   blocked_links);
2218                 mtx_unlock(&lun->lun_lock);
2219                 break;
2220         case CTL_ACTION_PASS:
2221         case CTL_ACTION_SKIP:
2222                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2223                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2224                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2225                         mtx_unlock(&lun->lun_lock);
2226                 } else {
2227                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2228                         mtx_unlock(&lun->lun_lock);
2229
2230                         /* send msg back to other side */
2231                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2232                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2233                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2234                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2235                             sizeof(msg_info.hdr), M_WAITOK);
2236                 }
2237                 break;
2238         case CTL_ACTION_OVERLAP:
2239                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2240                 mtx_unlock(&lun->lun_lock);
2241                 ctl_set_overlapped_cmd(ctsio);
2242                 goto badjuju;
2243         case CTL_ACTION_OVERLAP_TAG:
2244                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2245                 mtx_unlock(&lun->lun_lock);
2246                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2247                 goto badjuju;
2248         case CTL_ACTION_ERROR:
2249         default:
2250                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2251                 mtx_unlock(&lun->lun_lock);
2252
2253                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2254                                          /*retry_count*/ 0);
2255 badjuju:
2256                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2257                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2258                 msg_info.hdr.serializing_sc = NULL;
2259                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2260                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2261                     sizeof(msg_info.scsi), M_WAITOK);
2262                 retval = 1;
2263                 break;
2264         }
2265         return (retval);
2266 }
2267
2268 /*
2269  * Returns 0 for success, errno for failure.
2270  */
2271 static void
2272 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2273                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2274 {
2275         union ctl_io *io;
2276
2277         mtx_lock(&lun->lun_lock);
2278         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2279              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2280              ooa_links)) {
2281                 struct ctl_ooa_entry *entry;
2282
2283                 /*
2284                  * If we've got more than we can fit, just count the
2285                  * remaining entries.
2286                  */
2287                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2288                         continue;
2289
2290                 entry = &kern_entries[*cur_fill_num];
2291
2292                 entry->tag_num = io->scsiio.tag_num;
2293                 entry->lun_num = lun->lun;
2294 #ifdef CTL_TIME_IO
2295                 entry->start_bt = io->io_hdr.start_bt;
2296 #endif
2297                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2298                 entry->cdb_len = io->scsiio.cdb_len;
2299                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2300                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2301
2302                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2303                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2304
2305                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2306                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2307
2308                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2309                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2310
2311                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2312                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2313         }
2314         mtx_unlock(&lun->lun_lock);
2315 }
2316
2317 static void *
2318 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2319                  size_t error_str_len)
2320 {
2321         void *kptr;
2322
2323         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2324
2325         if (copyin(user_addr, kptr, len) != 0) {
2326                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2327                          "from user address %p to kernel address %p", len,
2328                          user_addr, kptr);
2329                 free(kptr, M_CTL);
2330                 return (NULL);
2331         }
2332
2333         return (kptr);
2334 }
2335
2336 static void
2337 ctl_free_args(int num_args, struct ctl_be_arg *args)
2338 {
2339         int i;
2340
2341         if (args == NULL)
2342                 return;
2343
2344         for (i = 0; i < num_args; i++) {
2345                 free(args[i].kname, M_CTL);
2346                 free(args[i].kvalue, M_CTL);
2347         }
2348
2349         free(args, M_CTL);
2350 }
2351
2352 static struct ctl_be_arg *
2353 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2354                 char *error_str, size_t error_str_len)
2355 {
2356         struct ctl_be_arg *args;
2357         int i;
2358
2359         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2360                                 error_str, error_str_len);
2361
2362         if (args == NULL)
2363                 goto bailout;
2364
2365         for (i = 0; i < num_args; i++) {
2366                 args[i].kname = NULL;
2367                 args[i].kvalue = NULL;
2368         }
2369
2370         for (i = 0; i < num_args; i++) {
2371                 uint8_t *tmpptr;
2372
2373                 args[i].kname = ctl_copyin_alloc(args[i].name,
2374                         args[i].namelen, error_str, error_str_len);
2375                 if (args[i].kname == NULL)
2376                         goto bailout;
2377
2378                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2379                         snprintf(error_str, error_str_len, "Argument %d "
2380                                  "name is not NUL-terminated", i);
2381                         goto bailout;
2382                 }
2383
2384                 if (args[i].flags & CTL_BEARG_RD) {
2385                         tmpptr = ctl_copyin_alloc(args[i].value,
2386                                 args[i].vallen, error_str, error_str_len);
2387                         if (tmpptr == NULL)
2388                                 goto bailout;
2389                         if ((args[i].flags & CTL_BEARG_ASCII)
2390                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2391                                 snprintf(error_str, error_str_len, "Argument "
2392                                     "%d value is not NUL-terminated", i);
2393                                 goto bailout;
2394                         }
2395                         args[i].kvalue = tmpptr;
2396                 } else {
2397                         args[i].kvalue = malloc(args[i].vallen,
2398                             M_CTL, M_WAITOK | M_ZERO);
2399                 }
2400         }
2401
2402         return (args);
2403 bailout:
2404
2405         ctl_free_args(num_args, args);
2406
2407         return (NULL);
2408 }
2409
2410 static void
2411 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2412 {
2413         int i;
2414
2415         for (i = 0; i < num_args; i++) {
2416                 if (args[i].flags & CTL_BEARG_WR)
2417                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2418         }
2419 }
2420
2421 /*
2422  * Escape characters that are illegal or not recommended in XML.
2423  */
2424 int
2425 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2426 {
2427         char *end = str + size;
2428         int retval;
2429
2430         retval = 0;
2431
2432         for (; *str && str < end; str++) {
2433                 switch (*str) {
2434                 case '&':
2435                         retval = sbuf_printf(sb, "&amp;");
2436                         break;
2437                 case '>':
2438                         retval = sbuf_printf(sb, "&gt;");
2439                         break;
2440                 case '<':
2441                         retval = sbuf_printf(sb, "&lt;");
2442                         break;
2443                 default:
2444                         retval = sbuf_putc(sb, *str);
2445                         break;
2446                 }
2447
2448                 if (retval != 0)
2449                         break;
2450
2451         }
2452
2453         return (retval);
2454 }
2455
2456 static void
2457 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2458 {
2459         struct scsi_vpd_id_descriptor *desc;
2460         int i;
2461
2462         if (id == NULL || id->len < 4)
2463                 return;
2464         desc = (struct scsi_vpd_id_descriptor *)id->data;
2465         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2466         case SVPD_ID_TYPE_T10:
2467                 sbuf_printf(sb, "t10.");
2468                 break;
2469         case SVPD_ID_TYPE_EUI64:
2470                 sbuf_printf(sb, "eui.");
2471                 break;
2472         case SVPD_ID_TYPE_NAA:
2473                 sbuf_printf(sb, "naa.");
2474                 break;
2475         case SVPD_ID_TYPE_SCSI_NAME:
2476                 break;
2477         }
2478         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2479         case SVPD_ID_CODESET_BINARY:
2480                 for (i = 0; i < desc->length; i++)
2481                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2482                 break;
2483         case SVPD_ID_CODESET_ASCII:
2484                 sbuf_printf(sb, "%.*s", (int)desc->length,
2485                     (char *)desc->identifier);
2486                 break;
2487         case SVPD_ID_CODESET_UTF8:
2488                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2489                 break;
2490         }
2491 }
2492
2493 static int
2494 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2495           struct thread *td)
2496 {
2497         struct ctl_softc *softc = dev->si_drv1;
2498         struct ctl_lun *lun;
2499         int retval;
2500
2501         retval = 0;
2502
2503         switch (cmd) {
2504         case CTL_IO:
2505                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2506                 break;
2507         case CTL_ENABLE_PORT:
2508         case CTL_DISABLE_PORT:
2509         case CTL_SET_PORT_WWNS: {
2510                 struct ctl_port *port;
2511                 struct ctl_port_entry *entry;
2512
2513                 entry = (struct ctl_port_entry *)addr;
2514                 
2515                 mtx_lock(&softc->ctl_lock);
2516                 STAILQ_FOREACH(port, &softc->port_list, links) {
2517                         int action, done;
2518
2519                         if (port->targ_port < softc->port_min ||
2520                             port->targ_port >= softc->port_max)
2521                                 continue;
2522
2523                         action = 0;
2524                         done = 0;
2525                         if ((entry->port_type == CTL_PORT_NONE)
2526                          && (entry->targ_port == port->targ_port)) {
2527                                 /*
2528                                  * If the user only wants to enable or
2529                                  * disable or set WWNs on a specific port,
2530                                  * do the operation and we're done.
2531                                  */
2532                                 action = 1;
2533                                 done = 1;
2534                         } else if (entry->port_type & port->port_type) {
2535                                 /*
2536                                  * Compare the user's type mask with the
2537                                  * particular frontend type to see if we
2538                                  * have a match.
2539                                  */
2540                                 action = 1;
2541                                 done = 0;
2542
2543                                 /*
2544                                  * Make sure the user isn't trying to set
2545                                  * WWNs on multiple ports at the same time.
2546                                  */
2547                                 if (cmd == CTL_SET_PORT_WWNS) {
2548                                         printf("%s: Can't set WWNs on "
2549                                                "multiple ports\n", __func__);
2550                                         retval = EINVAL;
2551                                         break;
2552                                 }
2553                         }
2554                         if (action == 0)
2555                                 continue;
2556
2557                         /*
2558                          * XXX KDM we have to drop the lock here, because
2559                          * the online/offline operations can potentially
2560                          * block.  We need to reference count the frontends
2561                          * so they can't go away,
2562                          */
2563                         if (cmd == CTL_ENABLE_PORT) {
2564                                 mtx_unlock(&softc->ctl_lock);
2565                                 ctl_port_online(port);
2566                                 mtx_lock(&softc->ctl_lock);
2567                         } else if (cmd == CTL_DISABLE_PORT) {
2568                                 mtx_unlock(&softc->ctl_lock);
2569                                 ctl_port_offline(port);
2570                                 mtx_lock(&softc->ctl_lock);
2571                         } else if (cmd == CTL_SET_PORT_WWNS) {
2572                                 ctl_port_set_wwns(port,
2573                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2574                                     1 : 0, entry->wwnn,
2575                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2576                                     1 : 0, entry->wwpn);
2577                         }
2578                         if (done != 0)
2579                                 break;
2580                 }
2581                 mtx_unlock(&softc->ctl_lock);
2582                 break;
2583         }
2584         case CTL_GET_OOA: {
2585                 struct ctl_ooa *ooa_hdr;
2586                 struct ctl_ooa_entry *entries;
2587                 uint32_t cur_fill_num;
2588
2589                 ooa_hdr = (struct ctl_ooa *)addr;
2590
2591                 if ((ooa_hdr->alloc_len == 0)
2592                  || (ooa_hdr->alloc_num == 0)) {
2593                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2594                                "must be non-zero\n", __func__,
2595                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2596                         retval = EINVAL;
2597                         break;
2598                 }
2599
2600                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2601                     sizeof(struct ctl_ooa_entry))) {
2602                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2603                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2604                                __func__, ooa_hdr->alloc_len,
2605                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2606                         retval = EINVAL;
2607                         break;
2608                 }
2609
2610                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2611                 if (entries == NULL) {
2612                         printf("%s: could not allocate %d bytes for OOA "
2613                                "dump\n", __func__, ooa_hdr->alloc_len);
2614                         retval = ENOMEM;
2615                         break;
2616                 }
2617
2618                 mtx_lock(&softc->ctl_lock);
2619                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2620                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2621                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2622                         mtx_unlock(&softc->ctl_lock);
2623                         free(entries, M_CTL);
2624                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2625                                __func__, (uintmax_t)ooa_hdr->lun_num);
2626                         retval = EINVAL;
2627                         break;
2628                 }
2629
2630                 cur_fill_num = 0;
2631
2632                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2633                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2634                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2635                                     ooa_hdr, entries);
2636                         }
2637                 } else {
2638                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2639                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2640                             entries);
2641                 }
2642                 mtx_unlock(&softc->ctl_lock);
2643
2644                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2645                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2646                         sizeof(struct ctl_ooa_entry);
2647                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2648                 if (retval != 0) {
2649                         printf("%s: error copying out %d bytes for OOA dump\n", 
2650                                __func__, ooa_hdr->fill_len);
2651                 }
2652
2653                 getbinuptime(&ooa_hdr->cur_bt);
2654
2655                 if (cur_fill_num > ooa_hdr->alloc_num) {
2656                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2657                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2658                 } else {
2659                         ooa_hdr->dropped_num = 0;
2660                         ooa_hdr->status = CTL_OOA_OK;
2661                 }
2662
2663                 free(entries, M_CTL);
2664                 break;
2665         }
2666         case CTL_DELAY_IO: {
2667                 struct ctl_io_delay_info *delay_info;
2668
2669                 delay_info = (struct ctl_io_delay_info *)addr;
2670
2671 #ifdef CTL_IO_DELAY
2672                 mtx_lock(&softc->ctl_lock);
2673
2674                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2675                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2676                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2677                 } else {
2678                         lun = softc->ctl_luns[delay_info->lun_id];
2679                         mtx_lock(&lun->lun_lock);
2680
2681                         delay_info->status = CTL_DELAY_STATUS_OK;
2682
2683                         switch (delay_info->delay_type) {
2684                         case CTL_DELAY_TYPE_CONT:
2685                                 break;
2686                         case CTL_DELAY_TYPE_ONESHOT:
2687                                 break;
2688                         default:
2689                                 delay_info->status =
2690                                         CTL_DELAY_STATUS_INVALID_TYPE;
2691                                 break;
2692                         }
2693
2694                         switch (delay_info->delay_loc) {
2695                         case CTL_DELAY_LOC_DATAMOVE:
2696                                 lun->delay_info.datamove_type =
2697                                         delay_info->delay_type;
2698                                 lun->delay_info.datamove_delay =
2699                                         delay_info->delay_secs;
2700                                 break;
2701                         case CTL_DELAY_LOC_DONE:
2702                                 lun->delay_info.done_type =
2703                                         delay_info->delay_type;
2704                                 lun->delay_info.done_delay =
2705                                         delay_info->delay_secs;
2706                                 break;
2707                         default:
2708                                 delay_info->status =
2709                                         CTL_DELAY_STATUS_INVALID_LOC;
2710                                 break;
2711                         }
2712                         mtx_unlock(&lun->lun_lock);
2713                 }
2714
2715                 mtx_unlock(&softc->ctl_lock);
2716 #else
2717                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2718 #endif /* CTL_IO_DELAY */
2719                 break;
2720         }
2721         case CTL_GETSTATS: {
2722                 struct ctl_stats *stats;
2723                 int i;
2724
2725                 stats = (struct ctl_stats *)addr;
2726
2727                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2728                      stats->alloc_len) {
2729                         stats->status = CTL_SS_NEED_MORE_SPACE;
2730                         stats->num_luns = softc->num_luns;
2731                         break;
2732                 }
2733                 /*
2734                  * XXX KDM no locking here.  If the LUN list changes,
2735                  * things can blow up.
2736                  */
2737                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2738                      i++, lun = STAILQ_NEXT(lun, links)) {
2739                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2740                                          sizeof(lun->stats));
2741                         if (retval != 0)
2742                                 break;
2743                 }
2744                 stats->num_luns = softc->num_luns;
2745                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2746                                  softc->num_luns;
2747                 stats->status = CTL_SS_OK;
2748 #ifdef CTL_TIME_IO
2749                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2750 #else
2751                 stats->flags = CTL_STATS_FLAG_NONE;
2752 #endif
2753                 getnanouptime(&stats->timestamp);
2754                 break;
2755         }
2756         case CTL_ERROR_INJECT: {
2757                 struct ctl_error_desc *err_desc, *new_err_desc;
2758
2759                 err_desc = (struct ctl_error_desc *)addr;
2760
2761                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2762                                       M_WAITOK | M_ZERO);
2763                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2764
2765                 mtx_lock(&softc->ctl_lock);
2766                 lun = softc->ctl_luns[err_desc->lun_id];
2767                 if (lun == NULL) {
2768                         mtx_unlock(&softc->ctl_lock);
2769                         free(new_err_desc, M_CTL);
2770                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2771                                __func__, (uintmax_t)err_desc->lun_id);
2772                         retval = EINVAL;
2773                         break;
2774                 }
2775                 mtx_lock(&lun->lun_lock);
2776                 mtx_unlock(&softc->ctl_lock);
2777
2778                 /*
2779                  * We could do some checking here to verify the validity
2780                  * of the request, but given the complexity of error
2781                  * injection requests, the checking logic would be fairly
2782                  * complex.
2783                  *
2784                  * For now, if the request is invalid, it just won't get
2785                  * executed and might get deleted.
2786                  */
2787                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2788
2789                 /*
2790                  * XXX KDM check to make sure the serial number is unique,
2791                  * in case we somehow manage to wrap.  That shouldn't
2792                  * happen for a very long time, but it's the right thing to
2793                  * do.
2794                  */
2795                 new_err_desc->serial = lun->error_serial;
2796                 err_desc->serial = lun->error_serial;
2797                 lun->error_serial++;
2798
2799                 mtx_unlock(&lun->lun_lock);
2800                 break;
2801         }
2802         case CTL_ERROR_INJECT_DELETE: {
2803                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2804                 int delete_done;
2805
2806                 delete_desc = (struct ctl_error_desc *)addr;
2807                 delete_done = 0;
2808
2809                 mtx_lock(&softc->ctl_lock);
2810                 lun = softc->ctl_luns[delete_desc->lun_id];
2811                 if (lun == NULL) {
2812                         mtx_unlock(&softc->ctl_lock);
2813                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2814                                __func__, (uintmax_t)delete_desc->lun_id);
2815                         retval = EINVAL;
2816                         break;
2817                 }
2818                 mtx_lock(&lun->lun_lock);
2819                 mtx_unlock(&softc->ctl_lock);
2820                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2821                         if (desc->serial != delete_desc->serial)
2822                                 continue;
2823
2824                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2825                                       links);
2826                         free(desc, M_CTL);
2827                         delete_done = 1;
2828                 }
2829                 mtx_unlock(&lun->lun_lock);
2830                 if (delete_done == 0) {
2831                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2832                                "error serial %ju on LUN %u\n", __func__, 
2833                                delete_desc->serial, delete_desc->lun_id);
2834                         retval = EINVAL;
2835                         break;
2836                 }
2837                 break;
2838         }
2839         case CTL_DUMP_STRUCTS: {
2840                 int i, j, k;
2841                 struct ctl_port *port;
2842                 struct ctl_frontend *fe;
2843
2844                 mtx_lock(&softc->ctl_lock);
2845                 printf("CTL Persistent Reservation information start:\n");
2846                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2847                         lun = softc->ctl_luns[i];
2848
2849                         if ((lun == NULL)
2850                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2851                                 continue;
2852
2853                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2854                                 if (lun->pr_keys[j] == NULL)
2855                                         continue;
2856                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2857                                         if (lun->pr_keys[j][k] == 0)
2858                                                 continue;
2859                                         printf("  LUN %d port %d iid %d key "
2860                                                "%#jx\n", i, j, k,
2861                                                (uintmax_t)lun->pr_keys[j][k]);
2862                                 }
2863                         }
2864                 }
2865                 printf("CTL Persistent Reservation information end\n");
2866                 printf("CTL Ports:\n");
2867                 STAILQ_FOREACH(port, &softc->port_list, links) {
2868                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2869                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2870                                port->frontend->name, port->port_type,
2871                                port->physical_port, port->virtual_port,
2872                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2873                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2874                                 if (port->wwpn_iid[j].in_use == 0 &&
2875                                     port->wwpn_iid[j].wwpn == 0 &&
2876                                     port->wwpn_iid[j].name == NULL)
2877                                         continue;
2878
2879                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2880                                     j, port->wwpn_iid[j].in_use,
2881                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2882                                     port->wwpn_iid[j].name);
2883                         }
2884                 }
2885                 printf("CTL Port information end\n");
2886                 mtx_unlock(&softc->ctl_lock);
2887                 /*
2888                  * XXX KDM calling this without a lock.  We'd likely want
2889                  * to drop the lock before calling the frontend's dump
2890                  * routine anyway.
2891                  */
2892                 printf("CTL Frontends:\n");
2893                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2894                         printf("  Frontend '%s'\n", fe->name);
2895                         if (fe->fe_dump != NULL)
2896                                 fe->fe_dump();
2897                 }
2898                 printf("CTL Frontend information end\n");
2899                 break;
2900         }
2901         case CTL_LUN_REQ: {
2902                 struct ctl_lun_req *lun_req;
2903                 struct ctl_backend_driver *backend;
2904
2905                 lun_req = (struct ctl_lun_req *)addr;
2906
2907                 backend = ctl_backend_find(lun_req->backend);
2908                 if (backend == NULL) {
2909                         lun_req->status = CTL_LUN_ERROR;
2910                         snprintf(lun_req->error_str,
2911                                  sizeof(lun_req->error_str),
2912                                  "Backend \"%s\" not found.",
2913                                  lun_req->backend);
2914                         break;
2915                 }
2916                 if (lun_req->num_be_args > 0) {
2917                         lun_req->kern_be_args = ctl_copyin_args(
2918                                 lun_req->num_be_args,
2919                                 lun_req->be_args,
2920                                 lun_req->error_str,
2921                                 sizeof(lun_req->error_str));
2922                         if (lun_req->kern_be_args == NULL) {
2923                                 lun_req->status = CTL_LUN_ERROR;
2924                                 break;
2925                         }
2926                 }
2927
2928                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2929
2930                 if (lun_req->num_be_args > 0) {
2931                         ctl_copyout_args(lun_req->num_be_args,
2932                                       lun_req->kern_be_args);
2933                         ctl_free_args(lun_req->num_be_args,
2934                                       lun_req->kern_be_args);
2935                 }
2936                 break;
2937         }
2938         case CTL_LUN_LIST: {
2939                 struct sbuf *sb;
2940                 struct ctl_lun_list *list;
2941                 struct ctl_option *opt;
2942
2943                 list = (struct ctl_lun_list *)addr;
2944
2945                 /*
2946                  * Allocate a fixed length sbuf here, based on the length
2947                  * of the user's buffer.  We could allocate an auto-extending
2948                  * buffer, and then tell the user how much larger our
2949                  * amount of data is than his buffer, but that presents
2950                  * some problems:
2951                  *
2952                  * 1.  The sbuf(9) routines use a blocking malloc, and so
2953                  *     we can't hold a lock while calling them with an
2954                  *     auto-extending buffer.
2955                  *
2956                  * 2.  There is not currently a LUN reference counting
2957                  *     mechanism, outside of outstanding transactions on
2958                  *     the LUN's OOA queue.  So a LUN could go away on us
2959                  *     while we're getting the LUN number, backend-specific
2960                  *     information, etc.  Thus, given the way things
2961                  *     currently work, we need to hold the CTL lock while
2962                  *     grabbing LUN information.
2963                  *
2964                  * So, from the user's standpoint, the best thing to do is
2965                  * allocate what he thinks is a reasonable buffer length,
2966                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2967                  * double the buffer length and try again.  (And repeat
2968                  * that until he succeeds.)
2969                  */
2970                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2971                 if (sb == NULL) {
2972                         list->status = CTL_LUN_LIST_ERROR;
2973                         snprintf(list->error_str, sizeof(list->error_str),
2974                                  "Unable to allocate %d bytes for LUN list",
2975                                  list->alloc_len);
2976                         break;
2977                 }
2978
2979                 sbuf_printf(sb, "<ctllunlist>\n");
2980
2981                 mtx_lock(&softc->ctl_lock);
2982                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2983                         mtx_lock(&lun->lun_lock);
2984                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2985                                              (uintmax_t)lun->lun);
2986
2987                         /*
2988                          * Bail out as soon as we see that we've overfilled
2989                          * the buffer.
2990                          */
2991                         if (retval != 0)
2992                                 break;
2993
2994                         retval = sbuf_printf(sb, "\t<backend_type>%s"
2995                                              "</backend_type>\n",
2996                                              (lun->backend == NULL) ?  "none" :
2997                                              lun->backend->name);
2998
2999                         if (retval != 0)
3000                                 break;
3001
3002                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3003                                              lun->be_lun->lun_type);
3004
3005                         if (retval != 0)
3006                                 break;
3007
3008                         if (lun->backend == NULL) {
3009                                 retval = sbuf_printf(sb, "</lun>\n");
3010                                 if (retval != 0)
3011                                         break;
3012                                 continue;
3013                         }
3014
3015                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3016                                              (lun->be_lun->maxlba > 0) ?
3017                                              lun->be_lun->maxlba + 1 : 0);
3018
3019                         if (retval != 0)
3020                                 break;
3021
3022                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3023                                              lun->be_lun->blocksize);
3024
3025                         if (retval != 0)
3026                                 break;
3027
3028                         retval = sbuf_printf(sb, "\t<serial_number>");
3029
3030                         if (retval != 0)
3031                                 break;
3032
3033                         retval = ctl_sbuf_printf_esc(sb,
3034                             lun->be_lun->serial_num,
3035                             sizeof(lun->be_lun->serial_num));
3036
3037                         if (retval != 0)
3038                                 break;
3039
3040                         retval = sbuf_printf(sb, "</serial_number>\n");
3041                 
3042                         if (retval != 0)
3043                                 break;
3044
3045                         retval = sbuf_printf(sb, "\t<device_id>");
3046
3047                         if (retval != 0)
3048                                 break;
3049
3050                         retval = ctl_sbuf_printf_esc(sb,
3051                             lun->be_lun->device_id,
3052                             sizeof(lun->be_lun->device_id));
3053
3054                         if (retval != 0)
3055                                 break;
3056
3057                         retval = sbuf_printf(sb, "</device_id>\n");
3058
3059                         if (retval != 0)
3060                                 break;
3061
3062                         if (lun->backend->lun_info != NULL) {
3063                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3064                                 if (retval != 0)
3065                                         break;
3066                         }
3067                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3068                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3069                                     opt->name, opt->value, opt->name);
3070                                 if (retval != 0)
3071                                         break;
3072                         }
3073
3074                         retval = sbuf_printf(sb, "</lun>\n");
3075
3076                         if (retval != 0)
3077                                 break;
3078                         mtx_unlock(&lun->lun_lock);
3079                 }
3080                 if (lun != NULL)
3081                         mtx_unlock(&lun->lun_lock);
3082                 mtx_unlock(&softc->ctl_lock);
3083
3084                 if ((retval != 0)
3085                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3086                         retval = 0;
3087                         sbuf_delete(sb);
3088                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3089                         snprintf(list->error_str, sizeof(list->error_str),
3090                                  "Out of space, %d bytes is too small",
3091                                  list->alloc_len);
3092                         break;
3093                 }
3094
3095                 sbuf_finish(sb);
3096
3097                 retval = copyout(sbuf_data(sb), list->lun_xml,
3098                                  sbuf_len(sb) + 1);
3099
3100                 list->fill_len = sbuf_len(sb) + 1;
3101                 list->status = CTL_LUN_LIST_OK;
3102                 sbuf_delete(sb);
3103                 break;
3104         }
3105         case CTL_ISCSI: {
3106                 struct ctl_iscsi *ci;
3107                 struct ctl_frontend *fe;
3108
3109                 ci = (struct ctl_iscsi *)addr;
3110
3111                 fe = ctl_frontend_find("iscsi");
3112                 if (fe == NULL) {
3113                         ci->status = CTL_ISCSI_ERROR;
3114                         snprintf(ci->error_str, sizeof(ci->error_str),
3115                             "Frontend \"iscsi\" not found.");
3116                         break;
3117                 }
3118
3119                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3120                 break;
3121         }
3122         case CTL_PORT_REQ: {
3123                 struct ctl_req *req;
3124                 struct ctl_frontend *fe;
3125
3126                 req = (struct ctl_req *)addr;
3127
3128                 fe = ctl_frontend_find(req->driver);
3129                 if (fe == NULL) {
3130                         req->status = CTL_LUN_ERROR;
3131                         snprintf(req->error_str, sizeof(req->error_str),
3132                             "Frontend \"%s\" not found.", req->driver);
3133                         break;
3134                 }
3135                 if (req->num_args > 0) {
3136                         req->kern_args = ctl_copyin_args(req->num_args,
3137                             req->args, req->error_str, sizeof(req->error_str));
3138                         if (req->kern_args == NULL) {
3139                                 req->status = CTL_LUN_ERROR;
3140                                 break;
3141                         }
3142                 }
3143
3144                 if (fe->ioctl)
3145                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3146                 else
3147                         retval = ENODEV;
3148
3149                 if (req->num_args > 0) {
3150                         ctl_copyout_args(req->num_args, req->kern_args);
3151                         ctl_free_args(req->num_args, req->kern_args);
3152                 }
3153                 break;
3154         }
3155         case CTL_PORT_LIST: {
3156                 struct sbuf *sb;
3157                 struct ctl_port *port;
3158                 struct ctl_lun_list *list;
3159                 struct ctl_option *opt;
3160                 int j;
3161                 uint32_t plun;
3162
3163                 list = (struct ctl_lun_list *)addr;
3164
3165                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3166                 if (sb == NULL) {
3167                         list->status = CTL_LUN_LIST_ERROR;
3168                         snprintf(list->error_str, sizeof(list->error_str),
3169                                  "Unable to allocate %d bytes for LUN list",
3170                                  list->alloc_len);
3171                         break;
3172                 }
3173
3174                 sbuf_printf(sb, "<ctlportlist>\n");
3175
3176                 mtx_lock(&softc->ctl_lock);
3177                 STAILQ_FOREACH(port, &softc->port_list, links) {
3178                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3179                                              (uintmax_t)port->targ_port);
3180
3181                         /*
3182                          * Bail out as soon as we see that we've overfilled
3183                          * the buffer.
3184                          */
3185                         if (retval != 0)
3186                                 break;
3187
3188                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3189                             "</frontend_type>\n", port->frontend->name);
3190                         if (retval != 0)
3191                                 break;
3192
3193                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3194                                              port->port_type);
3195                         if (retval != 0)
3196                                 break;
3197
3198                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3199                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3200                         if (retval != 0)
3201                                 break;
3202
3203                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3204                             port->port_name);
3205                         if (retval != 0)
3206                                 break;
3207
3208                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3209                             port->physical_port);
3210                         if (retval != 0)
3211                                 break;
3212
3213                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3214                             port->virtual_port);
3215                         if (retval != 0)
3216                                 break;
3217
3218                         if (port->target_devid != NULL) {
3219                                 sbuf_printf(sb, "\t<target>");
3220                                 ctl_id_sbuf(port->target_devid, sb);
3221                                 sbuf_printf(sb, "</target>\n");
3222                         }
3223
3224                         if (port->port_devid != NULL) {
3225                                 sbuf_printf(sb, "\t<port>");
3226                                 ctl_id_sbuf(port->port_devid, sb);
3227                                 sbuf_printf(sb, "</port>\n");
3228                         }
3229
3230                         if (port->port_info != NULL) {
3231                                 retval = port->port_info(port->onoff_arg, sb);
3232                                 if (retval != 0)
3233                                         break;
3234                         }
3235                         STAILQ_FOREACH(opt, &port->options, links) {
3236                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3237                                     opt->name, opt->value, opt->name);
3238                                 if (retval != 0)
3239                                         break;
3240                         }
3241
3242                         if (port->lun_map != NULL) {
3243                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3244                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3245                                         plun = ctl_lun_map_from_port(port, j);
3246                                         if (plun >= CTL_MAX_LUNS)
3247                                                 continue;
3248                                         sbuf_printf(sb,
3249                                             "\t<lun id=\"%u\">%u</lun>\n",
3250                                             j, plun);
3251                                 }
3252                         }
3253
3254                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3255                                 if (port->wwpn_iid[j].in_use == 0 ||
3256                                     (port->wwpn_iid[j].wwpn == 0 &&
3257                                      port->wwpn_iid[j].name == NULL))
3258                                         continue;
3259
3260                                 if (port->wwpn_iid[j].name != NULL)
3261                                         retval = sbuf_printf(sb,
3262                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3263                                             j, port->wwpn_iid[j].name);
3264                                 else
3265                                         retval = sbuf_printf(sb,
3266                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3267                                             j, port->wwpn_iid[j].wwpn);
3268                                 if (retval != 0)
3269                                         break;
3270                         }
3271                         if (retval != 0)
3272                                 break;
3273
3274                         retval = sbuf_printf(sb, "</targ_port>\n");
3275                         if (retval != 0)
3276                                 break;
3277                 }
3278                 mtx_unlock(&softc->ctl_lock);
3279
3280                 if ((retval != 0)
3281                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3282                         retval = 0;
3283                         sbuf_delete(sb);
3284                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3285                         snprintf(list->error_str, sizeof(list->error_str),
3286                                  "Out of space, %d bytes is too small",
3287                                  list->alloc_len);
3288                         break;
3289                 }
3290
3291                 sbuf_finish(sb);
3292
3293                 retval = copyout(sbuf_data(sb), list->lun_xml,
3294                                  sbuf_len(sb) + 1);
3295
3296                 list->fill_len = sbuf_len(sb) + 1;
3297                 list->status = CTL_LUN_LIST_OK;
3298                 sbuf_delete(sb);
3299                 break;
3300         }
3301         case CTL_LUN_MAP: {
3302                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3303                 struct ctl_port *port;
3304
3305                 mtx_lock(&softc->ctl_lock);
3306                 if (lm->port < softc->port_min ||
3307                     lm->port >= softc->port_max ||
3308                     (port = softc->ctl_ports[lm->port]) == NULL) {
3309                         mtx_unlock(&softc->ctl_lock);
3310                         return (ENXIO);
3311                 }
3312                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3313                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3314                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3315                                     CTL_MAX_LUNS)
3316                                         continue;
3317                                 mtx_lock(&lun->lun_lock);
3318                                 ctl_est_ua_port(lun, lm->port, -1,
3319                                     CTL_UA_LUN_CHANGE);
3320                                 mtx_unlock(&lun->lun_lock);
3321                         }
3322                 }
3323                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3324                 if (lm->plun < CTL_MAX_LUNS) {
3325                         if (lm->lun == UINT32_MAX)
3326                                 retval = ctl_lun_map_unset(port, lm->plun);
3327                         else if (lm->lun < CTL_MAX_LUNS &&
3328                             softc->ctl_luns[lm->lun] != NULL)
3329                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3330                         else
3331                                 return (ENXIO);
3332                 } else if (lm->plun == UINT32_MAX) {
3333                         if (lm->lun == UINT32_MAX)
3334                                 retval = ctl_lun_map_deinit(port);
3335                         else
3336                                 retval = ctl_lun_map_init(port);
3337                 } else
3338                         return (ENXIO);
3339                 if (port->status & CTL_PORT_STATUS_ONLINE)
3340                         ctl_isc_announce_port(port);
3341                 break;
3342         }
3343         default: {
3344                 /* XXX KDM should we fix this? */
3345 #if 0
3346                 struct ctl_backend_driver *backend;
3347                 unsigned int type;
3348                 int found;
3349
3350                 found = 0;
3351
3352                 /*
3353                  * We encode the backend type as the ioctl type for backend
3354                  * ioctls.  So parse it out here, and then search for a
3355                  * backend of this type.
3356                  */
3357                 type = _IOC_TYPE(cmd);
3358
3359                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3360                         if (backend->type == type) {
3361                                 found = 1;
3362                                 break;
3363                         }
3364                 }
3365                 if (found == 0) {
3366                         printf("ctl: unknown ioctl command %#lx or backend "
3367                                "%d\n", cmd, type);
3368                         retval = EINVAL;
3369                         break;
3370                 }
3371                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3372 #endif
3373                 retval = ENOTTY;
3374                 break;
3375         }
3376         }
3377         return (retval);
3378 }
3379
3380 uint32_t
3381 ctl_get_initindex(struct ctl_nexus *nexus)
3382 {
3383         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3384 }
3385
3386 int
3387 ctl_lun_map_init(struct ctl_port *port)
3388 {
3389         struct ctl_softc *softc = port->ctl_softc;
3390         struct ctl_lun *lun;
3391         uint32_t i;
3392
3393         if (port->lun_map == NULL)
3394                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3395                     M_CTL, M_NOWAIT);
3396         if (port->lun_map == NULL)
3397                 return (ENOMEM);
3398         for (i = 0; i < CTL_MAX_LUNS; i++)
3399                 port->lun_map[i] = UINT32_MAX;
3400         if (port->status & CTL_PORT_STATUS_ONLINE) {
3401                 if (port->lun_disable != NULL) {
3402                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3403                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3404                 }
3405                 ctl_isc_announce_port(port);
3406         }
3407         return (0);
3408 }
3409
3410 int
3411 ctl_lun_map_deinit(struct ctl_port *port)
3412 {
3413         struct ctl_softc *softc = port->ctl_softc;
3414         struct ctl_lun *lun;
3415
3416         if (port->lun_map == NULL)
3417                 return (0);
3418         free(port->lun_map, M_CTL);
3419         port->lun_map = NULL;
3420         if (port->status & CTL_PORT_STATUS_ONLINE) {
3421                 if (port->lun_enable != NULL) {
3422                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3423                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3424                 }
3425                 ctl_isc_announce_port(port);
3426         }
3427         return (0);
3428 }
3429
3430 int
3431 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3432 {
3433         int status;
3434         uint32_t old;
3435
3436         if (port->lun_map == NULL) {
3437                 status = ctl_lun_map_init(port);
3438                 if (status != 0)
3439                         return (status);
3440         }
3441         old = port->lun_map[plun];
3442         port->lun_map[plun] = glun;
3443         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3444                 if (port->lun_enable != NULL)
3445                         port->lun_enable(port->targ_lun_arg, plun);
3446                 ctl_isc_announce_port(port);
3447         }
3448         return (0);
3449 }
3450
3451 int
3452 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3453 {
3454         uint32_t old;
3455
3456         if (port->lun_map == NULL)
3457                 return (0);
3458         old = port->lun_map[plun];
3459         port->lun_map[plun] = UINT32_MAX;
3460         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3461                 if (port->lun_disable != NULL)
3462                         port->lun_disable(port->targ_lun_arg, plun);
3463                 ctl_isc_announce_port(port);
3464         }
3465         return (0);
3466 }
3467
3468 uint32_t
3469 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3470 {
3471
3472         if (port == NULL)
3473                 return (UINT32_MAX);
3474         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3475                 return (lun_id);
3476         return (port->lun_map[lun_id]);
3477 }
3478
3479 uint32_t
3480 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3481 {
3482         uint32_t i;
3483
3484         if (port == NULL)
3485                 return (UINT32_MAX);
3486         if (port->lun_map == NULL)
3487                 return (lun_id);
3488         for (i = 0; i < CTL_MAX_LUNS; i++) {
3489                 if (port->lun_map[i] == lun_id)
3490                         return (i);
3491         }
3492         return (UINT32_MAX);
3493 }
3494
3495 static struct ctl_port *
3496 ctl_io_port(struct ctl_io_hdr *io_hdr)
3497 {
3498
3499         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3500 }
3501
3502 int
3503 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3504 {
3505         int i;
3506
3507         for (i = first; i < last; i++) {
3508                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3509                         return (i);
3510         }
3511         return (-1);
3512 }
3513
3514 int
3515 ctl_set_mask(uint32_t *mask, uint32_t bit)
3516 {
3517         uint32_t chunk, piece;
3518
3519         chunk = bit >> 5;
3520         piece = bit % (sizeof(uint32_t) * 8);
3521
3522         if ((mask[chunk] & (1 << piece)) != 0)
3523                 return (-1);
3524         else
3525                 mask[chunk] |= (1 << piece);
3526
3527         return (0);
3528 }
3529
3530 int
3531 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3532 {
3533         uint32_t chunk, piece;
3534
3535         chunk = bit >> 5;
3536         piece = bit % (sizeof(uint32_t) * 8);
3537
3538         if ((mask[chunk] & (1 << piece)) == 0)
3539                 return (-1);
3540         else
3541                 mask[chunk] &= ~(1 << piece);
3542
3543         return (0);
3544 }
3545
3546 int
3547 ctl_is_set(uint32_t *mask, uint32_t bit)
3548 {
3549         uint32_t chunk, piece;
3550
3551         chunk = bit >> 5;
3552         piece = bit % (sizeof(uint32_t) * 8);
3553
3554         if ((mask[chunk] & (1 << piece)) == 0)
3555                 return (0);
3556         else
3557                 return (1);
3558 }
3559
3560 static uint64_t
3561 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3562 {
3563         uint64_t *t;
3564
3565         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3566         if (t == NULL)
3567                 return (0);
3568         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3569 }
3570
3571 static void
3572 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3573 {
3574         uint64_t *t;
3575
3576         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3577         if (t == NULL)
3578                 return;
3579         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3580 }
3581
3582 static void
3583 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3584 {
3585         uint64_t *p;
3586         u_int i;
3587
3588         i = residx/CTL_MAX_INIT_PER_PORT;
3589         if (lun->pr_keys[i] != NULL)
3590                 return;
3591         mtx_unlock(&lun->lun_lock);
3592         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3593             M_WAITOK | M_ZERO);
3594         mtx_lock(&lun->lun_lock);
3595         if (lun->pr_keys[i] == NULL)
3596                 lun->pr_keys[i] = p;
3597         else
3598                 free(p, M_CTL);
3599 }
3600
3601 static void
3602 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3603 {
3604         uint64_t *t;
3605
3606         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3607         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3608         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3609 }
3610
3611 /*
3612  * ctl_softc, pool_name, total_ctl_io are passed in.
3613  * npool is passed out.
3614  */
3615 int
3616 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3617                 uint32_t total_ctl_io, void **npool)
3618 {
3619 #ifdef IO_POOLS
3620         struct ctl_io_pool *pool;
3621
3622         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3623                                             M_NOWAIT | M_ZERO);
3624         if (pool == NULL)
3625                 return (ENOMEM);
3626
3627         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3628         pool->ctl_softc = ctl_softc;
3629         pool->zone = uma_zsecond_create(pool->name, NULL,
3630             NULL, NULL, NULL, ctl_softc->io_zone);
3631         /* uma_prealloc(pool->zone, total_ctl_io); */
3632
3633         *npool = pool;
3634 #else
3635         *npool = ctl_softc->io_zone;
3636 #endif
3637         return (0);
3638 }
3639
3640 void
3641 ctl_pool_free(struct ctl_io_pool *pool)
3642 {
3643
3644         if (pool == NULL)
3645                 return;
3646
3647 #ifdef IO_POOLS
3648         uma_zdestroy(pool->zone);
3649         free(pool, M_CTL);
3650 #endif
3651 }
3652
3653 union ctl_io *
3654 ctl_alloc_io(void *pool_ref)
3655 {
3656         union ctl_io *io;
3657 #ifdef IO_POOLS
3658         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3659
3660         io = uma_zalloc(pool->zone, M_WAITOK);
3661 #else
3662         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3663 #endif
3664         if (io != NULL)
3665                 io->io_hdr.pool = pool_ref;
3666         return (io);
3667 }
3668
3669 union ctl_io *
3670 ctl_alloc_io_nowait(void *pool_ref)
3671 {
3672         union ctl_io *io;
3673 #ifdef IO_POOLS
3674         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3675
3676         io = uma_zalloc(pool->zone, M_NOWAIT);
3677 #else
3678         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3679 #endif
3680         if (io != NULL)
3681                 io->io_hdr.pool = pool_ref;
3682         return (io);
3683 }
3684
3685 void
3686 ctl_free_io(union ctl_io *io)
3687 {
3688 #ifdef IO_POOLS
3689         struct ctl_io_pool *pool;
3690 #endif
3691
3692         if (io == NULL)
3693                 return;
3694
3695 #ifdef IO_POOLS
3696         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3697         uma_zfree(pool->zone, io);
3698 #else
3699         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3700 #endif
3701 }
3702
3703 void
3704 ctl_zero_io(union ctl_io *io)
3705 {
3706         void *pool_ref;
3707
3708         if (io == NULL)
3709                 return;
3710
3711         /*
3712          * May need to preserve linked list pointers at some point too.
3713          */
3714         pool_ref = io->io_hdr.pool;
3715         memset(io, 0, sizeof(*io));
3716         io->io_hdr.pool = pool_ref;
3717 }
3718
3719 /*
3720  * This routine is currently used for internal copies of ctl_ios that need
3721  * to persist for some reason after we've already returned status to the
3722  * FETD.  (Thus the flag set.)
3723  *
3724  * XXX XXX
3725  * Note that this makes a blind copy of all fields in the ctl_io, except
3726  * for the pool reference.  This includes any memory that has been
3727  * allocated!  That memory will no longer be valid after done has been
3728  * called, so this would be VERY DANGEROUS for command that actually does
3729  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3730  * start and stop commands, which don't transfer any data, so this is not a
3731  * problem.  If it is used for anything else, the caller would also need to
3732  * allocate data buffer space and this routine would need to be modified to
3733  * copy the data buffer(s) as well.
3734  */
3735 void
3736 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3737 {
3738         void *pool_ref;
3739
3740         if ((src == NULL)
3741          || (dest == NULL))
3742                 return;
3743
3744         /*
3745          * May need to preserve linked list pointers at some point too.
3746          */
3747         pool_ref = dest->io_hdr.pool;
3748
3749         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3750
3751         dest->io_hdr.pool = pool_ref;
3752         /*
3753          * We need to know that this is an internal copy, and doesn't need
3754          * to get passed back to the FETD that allocated it.
3755          */
3756         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3757 }
3758
3759 int
3760 ctl_expand_number(const char *buf, uint64_t *num)
3761 {
3762         char *endptr;
3763         uint64_t number;
3764         unsigned shift;
3765
3766         number = strtoq(buf, &endptr, 0);
3767
3768         switch (tolower((unsigned char)*endptr)) {
3769         case 'e':
3770                 shift = 60;
3771                 break;
3772         case 'p':
3773                 shift = 50;
3774                 break;
3775         case 't':
3776                 shift = 40;
3777                 break;
3778         case 'g':
3779                 shift = 30;
3780                 break;
3781         case 'm':
3782                 shift = 20;
3783                 break;
3784         case 'k':
3785                 shift = 10;
3786                 break;
3787         case 'b':
3788         case '\0': /* No unit. */
3789                 *num = number;
3790                 return (0);
3791         default:
3792                 /* Unrecognized unit. */
3793                 return (-1);
3794         }
3795
3796         if ((number << shift) >> shift != number) {
3797                 /* Overflow */
3798                 return (-1);
3799         }
3800         *num = number << shift;
3801         return (0);
3802 }
3803
3804
3805 /*
3806  * This routine could be used in the future to load default and/or saved
3807  * mode page parameters for a particuar lun.
3808  */
3809 static int
3810 ctl_init_page_index(struct ctl_lun *lun)
3811 {
3812         int i;
3813         struct ctl_page_index *page_index;
3814         const char *value;
3815         uint64_t ival;
3816
3817         memcpy(&lun->mode_pages.index, page_index_template,
3818                sizeof(page_index_template));
3819
3820         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3821
3822                 page_index = &lun->mode_pages.index[i];
3823                 /*
3824                  * If this is a disk-only mode page, there's no point in
3825                  * setting it up.  For some pages, we have to have some
3826                  * basic information about the disk in order to calculate the
3827                  * mode page data.
3828                  */
3829                 if ((lun->be_lun->lun_type != T_DIRECT)
3830                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3831                         continue;
3832
3833                 switch (page_index->page_code & SMPH_PC_MASK) {
3834                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3835                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3836                                 panic("subpage is incorrect!");
3837                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3838                                &rw_er_page_default,
3839                                sizeof(rw_er_page_default));
3840                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3841                                &rw_er_page_changeable,
3842                                sizeof(rw_er_page_changeable));
3843                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3844                                &rw_er_page_default,
3845                                sizeof(rw_er_page_default));
3846                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3847                                &rw_er_page_default,
3848                                sizeof(rw_er_page_default));
3849                         page_index->page_data =
3850                                 (uint8_t *)lun->mode_pages.rw_er_page;
3851                         break;
3852                 }
3853                 case SMS_FORMAT_DEVICE_PAGE: {
3854                         struct scsi_format_page *format_page;
3855
3856                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3857                                 panic("subpage is incorrect!");
3858
3859                         /*
3860                          * Sectors per track are set above.  Bytes per
3861                          * sector need to be set here on a per-LUN basis.
3862                          */
3863                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3864                                &format_page_default,
3865                                sizeof(format_page_default));
3866                         memcpy(&lun->mode_pages.format_page[
3867                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3868                                sizeof(format_page_changeable));
3869                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3870                                &format_page_default,
3871                                sizeof(format_page_default));
3872                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3873                                &format_page_default,
3874                                sizeof(format_page_default));
3875
3876                         format_page = &lun->mode_pages.format_page[
3877                                 CTL_PAGE_CURRENT];
3878                         scsi_ulto2b(lun->be_lun->blocksize,
3879                                     format_page->bytes_per_sector);
3880
3881                         format_page = &lun->mode_pages.format_page[
3882                                 CTL_PAGE_DEFAULT];
3883                         scsi_ulto2b(lun->be_lun->blocksize,
3884                                     format_page->bytes_per_sector);
3885
3886                         format_page = &lun->mode_pages.format_page[
3887                                 CTL_PAGE_SAVED];
3888                         scsi_ulto2b(lun->be_lun->blocksize,
3889                                     format_page->bytes_per_sector);
3890
3891                         page_index->page_data =
3892                                 (uint8_t *)lun->mode_pages.format_page;
3893                         break;
3894                 }
3895                 case SMS_RIGID_DISK_PAGE: {
3896                         struct scsi_rigid_disk_page *rigid_disk_page;
3897                         uint32_t sectors_per_cylinder;
3898                         uint64_t cylinders;
3899 #ifndef __XSCALE__
3900                         int shift;
3901 #endif /* !__XSCALE__ */
3902
3903                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3904                                 panic("invalid subpage value %d",
3905                                       page_index->subpage);
3906
3907                         /*
3908                          * Rotation rate and sectors per track are set
3909                          * above.  We calculate the cylinders here based on
3910                          * capacity.  Due to the number of heads and
3911                          * sectors per track we're using, smaller arrays
3912                          * may turn out to have 0 cylinders.  Linux and
3913                          * FreeBSD don't pay attention to these mode pages
3914                          * to figure out capacity, but Solaris does.  It
3915                          * seems to deal with 0 cylinders just fine, and
3916                          * works out a fake geometry based on the capacity.
3917                          */
3918                         memcpy(&lun->mode_pages.rigid_disk_page[
3919                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3920                                sizeof(rigid_disk_page_default));
3921                         memcpy(&lun->mode_pages.rigid_disk_page[
3922                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3923                                sizeof(rigid_disk_page_changeable));
3924
3925                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3926                                 CTL_DEFAULT_HEADS;
3927
3928                         /*
3929                          * The divide method here will be more accurate,
3930                          * probably, but results in floating point being
3931                          * used in the kernel on i386 (__udivdi3()).  On the
3932                          * XScale, though, __udivdi3() is implemented in
3933                          * software.
3934                          *
3935                          * The shift method for cylinder calculation is
3936                          * accurate if sectors_per_cylinder is a power of
3937                          * 2.  Otherwise it might be slightly off -- you
3938                          * might have a bit of a truncation problem.
3939                          */
3940 #ifdef  __XSCALE__
3941                         cylinders = (lun->be_lun->maxlba + 1) /
3942                                 sectors_per_cylinder;
3943 #else
3944                         for (shift = 31; shift > 0; shift--) {
3945                                 if (sectors_per_cylinder & (1 << shift))
3946                                         break;
3947                         }
3948                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
3949 #endif
3950
3951                         /*
3952                          * We've basically got 3 bytes, or 24 bits for the
3953                          * cylinder size in the mode page.  If we're over,
3954                          * just round down to 2^24.
3955                          */
3956                         if (cylinders > 0xffffff)
3957                                 cylinders = 0xffffff;
3958
3959                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3960                                 CTL_PAGE_DEFAULT];
3961                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3962
3963                         if ((value = ctl_get_opt(&lun->be_lun->options,
3964                             "rpm")) != NULL) {
3965                                 scsi_ulto2b(strtol(value, NULL, 0),
3966                                      rigid_disk_page->rotation_rate);
3967                         }
3968
3969                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3970                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3971                                sizeof(rigid_disk_page_default));
3972                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3973                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3974                                sizeof(rigid_disk_page_default));
3975
3976                         page_index->page_data =
3977                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
3978                         break;
3979                 }
3980                 case SMS_CACHING_PAGE: {
3981                         struct scsi_caching_page *caching_page;
3982
3983                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3984                                 panic("invalid subpage value %d",
3985                                       page_index->subpage);
3986                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3987                                &caching_page_default,
3988                                sizeof(caching_page_default));
3989                         memcpy(&lun->mode_pages.caching_page[
3990                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3991                                sizeof(caching_page_changeable));
3992                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3993                                &caching_page_default,
3994                                sizeof(caching_page_default));
3995                         caching_page = &lun->mode_pages.caching_page[
3996                             CTL_PAGE_SAVED];
3997                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
3998                         if (value != NULL && strcmp(value, "off") == 0)
3999                                 caching_page->flags1 &= ~SCP_WCE;
4000                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4001                         if (value != NULL && strcmp(value, "off") == 0)
4002                                 caching_page->flags1 |= SCP_RCD;
4003                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4004                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4005                                sizeof(caching_page_default));
4006                         page_index->page_data =
4007                                 (uint8_t *)lun->mode_pages.caching_page;
4008                         break;
4009                 }
4010                 case SMS_CONTROL_MODE_PAGE: {
4011                         switch (page_index->subpage) {
4012                         case SMS_SUBPAGE_PAGE_0: {
4013                                 struct scsi_control_page *control_page;
4014
4015                                 memcpy(&lun->mode_pages.control_page[
4016                                     CTL_PAGE_DEFAULT],
4017                                        &control_page_default,
4018                                        sizeof(control_page_default));
4019                                 memcpy(&lun->mode_pages.control_page[
4020                                     CTL_PAGE_CHANGEABLE],
4021                                        &control_page_changeable,
4022                                        sizeof(control_page_changeable));
4023                                 memcpy(&lun->mode_pages.control_page[
4024                                     CTL_PAGE_SAVED],
4025                                        &control_page_default,
4026                                        sizeof(control_page_default));
4027                                 control_page = &lun->mode_pages.control_page[
4028                                     CTL_PAGE_SAVED];
4029                                 value = ctl_get_opt(&lun->be_lun->options,
4030                                     "reordering");
4031                                 if (value != NULL &&
4032                                     strcmp(value, "unrestricted") == 0) {
4033                                         control_page->queue_flags &=
4034                                             ~SCP_QUEUE_ALG_MASK;
4035                                         control_page->queue_flags |=
4036                                             SCP_QUEUE_ALG_UNRESTRICTED;
4037                                 }
4038                                 memcpy(&lun->mode_pages.control_page[
4039                                     CTL_PAGE_CURRENT],
4040                                        &lun->mode_pages.control_page[
4041                                     CTL_PAGE_SAVED],
4042                                        sizeof(control_page_default));
4043                                 page_index->page_data =
4044                                     (uint8_t *)lun->mode_pages.control_page;
4045                                 break;
4046                         }
4047                         case 0x01:
4048                                 memcpy(&lun->mode_pages.control_ext_page[
4049                                     CTL_PAGE_DEFAULT],
4050                                        &control_ext_page_default,
4051                                        sizeof(control_ext_page_default));
4052                                 memcpy(&lun->mode_pages.control_ext_page[
4053                                     CTL_PAGE_CHANGEABLE],
4054                                        &control_ext_page_changeable,
4055                                        sizeof(control_ext_page_changeable));
4056                                 memcpy(&lun->mode_pages.control_ext_page[
4057                                     CTL_PAGE_SAVED],
4058                                        &control_ext_page_default,
4059                                        sizeof(control_ext_page_default));
4060                                 memcpy(&lun->mode_pages.control_ext_page[
4061                                     CTL_PAGE_CURRENT],
4062                                        &lun->mode_pages.control_ext_page[
4063                                     CTL_PAGE_SAVED],
4064                                        sizeof(control_ext_page_default));
4065                                 page_index->page_data =
4066                                     (uint8_t *)lun->mode_pages.control_ext_page;
4067                                 break;
4068                         }
4069                         break;
4070                 }
4071                 case SMS_INFO_EXCEPTIONS_PAGE: {
4072                         switch (page_index->subpage) {
4073                         case SMS_SUBPAGE_PAGE_0:
4074                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4075                                        &ie_page_default,
4076                                        sizeof(ie_page_default));
4077                                 memcpy(&lun->mode_pages.ie_page[
4078                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4079                                        sizeof(ie_page_changeable));
4080                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4081                                        &ie_page_default,
4082                                        sizeof(ie_page_default));
4083                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4084                                        &ie_page_default,
4085                                        sizeof(ie_page_default));
4086                                 page_index->page_data =
4087                                         (uint8_t *)lun->mode_pages.ie_page;
4088                                 break;
4089                         case 0x02: {
4090                                 struct ctl_logical_block_provisioning_page *page;
4091
4092                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4093                                        &lbp_page_default,
4094                                        sizeof(lbp_page_default));
4095                                 memcpy(&lun->mode_pages.lbp_page[
4096                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4097                                        sizeof(lbp_page_changeable));
4098                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4099                                        &lbp_page_default,
4100                                        sizeof(lbp_page_default));
4101                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4102                                 value = ctl_get_opt(&lun->be_lun->options,
4103                                     "avail-threshold");
4104                                 if (value != NULL &&
4105                                     ctl_expand_number(value, &ival) == 0) {
4106                                         page->descr[0].flags |= SLBPPD_ENABLED |
4107                                             SLBPPD_ARMING_DEC;
4108                                         if (lun->be_lun->blocksize)
4109                                                 ival /= lun->be_lun->blocksize;
4110                                         else
4111                                                 ival /= 512;
4112                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4113                                             page->descr[0].count);
4114                                 }
4115                                 value = ctl_get_opt(&lun->be_lun->options,
4116                                     "used-threshold");
4117                                 if (value != NULL &&
4118                                     ctl_expand_number(value, &ival) == 0) {
4119                                         page->descr[1].flags |= SLBPPD_ENABLED |
4120                                             SLBPPD_ARMING_INC;
4121                                         if (lun->be_lun->blocksize)
4122                                                 ival /= lun->be_lun->blocksize;
4123                                         else
4124                                                 ival /= 512;
4125                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4126                                             page->descr[1].count);
4127                                 }
4128                                 value = ctl_get_opt(&lun->be_lun->options,
4129                                     "pool-avail-threshold");
4130                                 if (value != NULL &&
4131                                     ctl_expand_number(value, &ival) == 0) {
4132                                         page->descr[2].flags |= SLBPPD_ENABLED |
4133                                             SLBPPD_ARMING_DEC;
4134                                         if (lun->be_lun->blocksize)
4135                                                 ival /= lun->be_lun->blocksize;
4136                                         else
4137                                                 ival /= 512;
4138                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4139                                             page->descr[2].count);
4140                                 }
4141                                 value = ctl_get_opt(&lun->be_lun->options,
4142                                     "pool-used-threshold");
4143                                 if (value != NULL &&
4144                                     ctl_expand_number(value, &ival) == 0) {
4145                                         page->descr[3].flags |= SLBPPD_ENABLED |
4146                                             SLBPPD_ARMING_INC;
4147                                         if (lun->be_lun->blocksize)
4148                                                 ival /= lun->be_lun->blocksize;
4149                                         else
4150                                                 ival /= 512;
4151                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4152                                             page->descr[3].count);
4153                                 }
4154                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4155                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4156                                        sizeof(lbp_page_default));
4157                                 page_index->page_data =
4158                                         (uint8_t *)lun->mode_pages.lbp_page;
4159                         }}
4160                         break;
4161                 }
4162                 case SMS_VENDOR_SPECIFIC_PAGE:{
4163                         switch (page_index->subpage) {
4164                         case DBGCNF_SUBPAGE_CODE: {
4165                                 memcpy(&lun->mode_pages.debugconf_subpage[
4166                                        CTL_PAGE_CURRENT],
4167                                        &debugconf_page_default,
4168                                        sizeof(debugconf_page_default));
4169                                 memcpy(&lun->mode_pages.debugconf_subpage[
4170                                        CTL_PAGE_CHANGEABLE],
4171                                        &debugconf_page_changeable,
4172                                        sizeof(debugconf_page_changeable));
4173                                 memcpy(&lun->mode_pages.debugconf_subpage[
4174                                        CTL_PAGE_DEFAULT],
4175                                        &debugconf_page_default,
4176                                        sizeof(debugconf_page_default));
4177                                 memcpy(&lun->mode_pages.debugconf_subpage[
4178                                        CTL_PAGE_SAVED],
4179                                        &debugconf_page_default,
4180                                        sizeof(debugconf_page_default));
4181                                 page_index->page_data =
4182                                     (uint8_t *)lun->mode_pages.debugconf_subpage;
4183                                 break;
4184                         }
4185                         default:
4186                                 panic("invalid subpage value %d",
4187                                       page_index->subpage);
4188                                 break;
4189                         }
4190                         break;
4191                 }
4192                 default:
4193                         panic("invalid page value %d",
4194                               page_index->page_code & SMPH_PC_MASK);
4195                         break;
4196         }
4197         }
4198
4199         return (CTL_RETVAL_COMPLETE);
4200 }
4201
4202 static int
4203 ctl_init_log_page_index(struct ctl_lun *lun)
4204 {
4205         struct ctl_page_index *page_index;
4206         int i, j, k, prev;
4207
4208         memcpy(&lun->log_pages.index, log_page_index_template,
4209                sizeof(log_page_index_template));
4210
4211         prev = -1;
4212         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4213
4214                 page_index = &lun->log_pages.index[i];
4215                 /*
4216                  * If this is a disk-only mode page, there's no point in
4217                  * setting it up.  For some pages, we have to have some
4218                  * basic information about the disk in order to calculate the
4219                  * mode page data.
4220                  */
4221                 if ((lun->be_lun->lun_type != T_DIRECT)
4222                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4223                         continue;
4224
4225                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4226                      lun->backend->lun_attr == NULL)
4227                         continue;
4228
4229                 if (page_index->page_code != prev) {
4230                         lun->log_pages.pages_page[j] = page_index->page_code;
4231                         prev = page_index->page_code;
4232                         j++;
4233                 }
4234                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4235                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4236                 k++;
4237         }
4238         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4239         lun->log_pages.index[0].page_len = j;
4240         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4241         lun->log_pages.index[1].page_len = k * 2;
4242         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4243         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4244         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4245         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4246
4247         return (CTL_RETVAL_COMPLETE);
4248 }
4249
4250 static int
4251 hex2bin(const char *str, uint8_t *buf, int buf_size)
4252 {
4253         int i;
4254         u_char c;
4255
4256         memset(buf, 0, buf_size);
4257         while (isspace(str[0]))
4258                 str++;
4259         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4260                 str += 2;
4261         buf_size *= 2;
4262         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4263                 c = str[i];
4264                 if (isdigit(c))
4265                         c -= '0';
4266                 else if (isalpha(c))
4267                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4268                 else
4269                         break;
4270                 if (c >= 16)
4271                         break;
4272                 if ((i & 1) == 0)
4273                         buf[i / 2] |= (c << 4);
4274                 else
4275                         buf[i / 2] |= c;
4276         }
4277         return ((i + 1) / 2);
4278 }
4279
4280 /*
4281  * LUN allocation.
4282  *
4283  * Requirements:
4284  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4285  *   wants us to allocate the LUN and he can block.
4286  * - ctl_softc is always set
4287  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4288  *
4289  * Returns 0 for success, non-zero (errno) for failure.
4290  */
4291 static int
4292 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4293               struct ctl_be_lun *const be_lun)
4294 {
4295         struct ctl_lun *nlun, *lun;
4296         struct scsi_vpd_id_descriptor *desc;
4297         struct scsi_vpd_id_t10 *t10id;
4298         const char *eui, *naa, *scsiname, *vendor;
4299         int lun_number, i, lun_malloced;
4300         int devidlen, idlen1, idlen2 = 0, len;
4301
4302         if (be_lun == NULL)
4303                 return (EINVAL);
4304
4305         /*
4306          * We currently only support Direct Access or Processor LUN types.
4307          */
4308         switch (be_lun->lun_type) {
4309         case T_DIRECT:
4310                 break;
4311         case T_PROCESSOR:
4312                 break;
4313         case T_SEQUENTIAL:
4314         case T_CHANGER:
4315         default:
4316                 be_lun->lun_config_status(be_lun->be_lun,
4317                                           CTL_LUN_CONFIG_FAILURE);
4318                 break;
4319         }
4320         if (ctl_lun == NULL) {
4321                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4322                 lun_malloced = 1;
4323         } else {
4324                 lun_malloced = 0;
4325                 lun = ctl_lun;
4326         }
4327
4328         memset(lun, 0, sizeof(*lun));
4329         if (lun_malloced)
4330                 lun->flags = CTL_LUN_MALLOCED;
4331
4332         /* Generate LUN ID. */
4333         devidlen = max(CTL_DEVID_MIN_LEN,
4334             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4335         idlen1 = sizeof(*t10id) + devidlen;
4336         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4337         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4338         if (scsiname != NULL) {
4339                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4340                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4341         }
4342         eui = ctl_get_opt(&be_lun->options, "eui");
4343         if (eui != NULL) {
4344                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4345         }
4346         naa = ctl_get_opt(&be_lun->options, "naa");
4347         if (naa != NULL) {
4348                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4349         }
4350         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4351             M_CTL, M_WAITOK | M_ZERO);
4352         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4353         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4354         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4355         desc->length = idlen1;
4356         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4357         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4358         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4359                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4360         } else {
4361                 strncpy(t10id->vendor, vendor,
4362                     min(sizeof(t10id->vendor), strlen(vendor)));
4363         }
4364         strncpy((char *)t10id->vendor_spec_id,
4365             (char *)be_lun->device_id, devidlen);
4366         if (scsiname != NULL) {
4367                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4368                     desc->length);
4369                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4370                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4371                     SVPD_ID_TYPE_SCSI_NAME;
4372                 desc->length = idlen2;
4373                 strlcpy(desc->identifier, scsiname, idlen2);
4374         }
4375         if (eui != NULL) {
4376                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4377                     desc->length);
4378                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4379                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4380                     SVPD_ID_TYPE_EUI64;
4381                 desc->length = hex2bin(eui, desc->identifier, 16);
4382                 desc->length = desc->length > 12 ? 16 :
4383                     (desc->length > 8 ? 12 : 8);
4384                 len -= 16 - desc->length;
4385         }
4386         if (naa != NULL) {
4387                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4388                     desc->length);
4389                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4390                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4391                     SVPD_ID_TYPE_NAA;
4392                 desc->length = hex2bin(naa, desc->identifier, 16);
4393                 desc->length = desc->length > 8 ? 16 : 8;
4394                 len -= 16 - desc->length;
4395         }
4396         lun->lun_devid->len = len;
4397
4398         mtx_lock(&ctl_softc->ctl_lock);
4399         /*
4400          * See if the caller requested a particular LUN number.  If so, see
4401          * if it is available.  Otherwise, allocate the first available LUN.
4402          */
4403         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4404                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4405                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4406                         mtx_unlock(&ctl_softc->ctl_lock);
4407                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4408                                 printf("ctl: requested LUN ID %d is higher "
4409                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4410                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4411                         } else {
4412                                 /*
4413                                  * XXX KDM return an error, or just assign
4414                                  * another LUN ID in this case??
4415                                  */
4416                                 printf("ctl: requested LUN ID %d is already "
4417                                        "in use\n", be_lun->req_lun_id);
4418                         }
4419                         if (lun->flags & CTL_LUN_MALLOCED)
4420                                 free(lun, M_CTL);
4421                         be_lun->lun_config_status(be_lun->be_lun,
4422                                                   CTL_LUN_CONFIG_FAILURE);
4423                         return (ENOSPC);
4424                 }
4425                 lun_number = be_lun->req_lun_id;
4426         } else {
4427                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4428                 if (lun_number == -1) {
4429                         mtx_unlock(&ctl_softc->ctl_lock);
4430                         printf("ctl: can't allocate LUN, out of LUNs\n");
4431                         if (lun->flags & CTL_LUN_MALLOCED)
4432                                 free(lun, M_CTL);
4433                         be_lun->lun_config_status(be_lun->be_lun,
4434                                                   CTL_LUN_CONFIG_FAILURE);
4435                         return (ENOSPC);
4436                 }
4437         }
4438         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4439
4440         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4441         lun->lun = lun_number;
4442         lun->be_lun = be_lun;
4443         /*
4444          * The processor LUN is always enabled.  Disk LUNs come on line
4445          * disabled, and must be enabled by the backend.
4446          */
4447         lun->flags |= CTL_LUN_DISABLED;
4448         lun->backend = be_lun->be;
4449         be_lun->ctl_lun = lun;
4450         be_lun->lun_id = lun_number;
4451         atomic_add_int(&be_lun->be->num_luns, 1);
4452         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4453                 lun->flags |= CTL_LUN_OFFLINE;
4454
4455         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4456                 lun->flags |= CTL_LUN_STOPPED;
4457
4458         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4459                 lun->flags |= CTL_LUN_INOPERABLE;
4460
4461         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4462                 lun->flags |= CTL_LUN_PRIMARY_SC;
4463
4464         lun->ctl_softc = ctl_softc;
4465 #ifdef CTL_TIME_IO
4466         lun->last_busy = getsbinuptime();
4467 #endif
4468         TAILQ_INIT(&lun->ooa_queue);
4469         TAILQ_INIT(&lun->blocked_queue);
4470         STAILQ_INIT(&lun->error_list);
4471         ctl_tpc_lun_init(lun);
4472
4473         /*
4474          * Initialize the mode and log page index.
4475          */
4476         ctl_init_page_index(lun);
4477         ctl_init_log_page_index(lun);
4478
4479         /*
4480          * Now, before we insert this lun on the lun list, set the lun
4481          * inventory changed UA for all other luns.
4482          */
4483         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4484                 mtx_lock(&nlun->lun_lock);
4485                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4486                 mtx_unlock(&nlun->lun_lock);
4487         }
4488
4489         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4490
4491         ctl_softc->ctl_luns[lun_number] = lun;
4492
4493         ctl_softc->num_luns++;
4494
4495         /* Setup statistics gathering */
4496         lun->stats.device_type = be_lun->lun_type;
4497         lun->stats.lun_number = lun_number;
4498         if (lun->stats.device_type == T_DIRECT)
4499                 lun->stats.blocksize = be_lun->blocksize;
4500         else
4501                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4502         for (i = 0;i < CTL_MAX_PORTS;i++)
4503                 lun->stats.ports[i].targ_port = i;
4504
4505         mtx_unlock(&ctl_softc->ctl_lock);
4506
4507         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4508         return (0);
4509 }
4510
4511 /*
4512  * Delete a LUN.
4513  * Assumptions:
4514  * - LUN has already been marked invalid and any pending I/O has been taken
4515  *   care of.
4516  */
4517 static int
4518 ctl_free_lun(struct ctl_lun *lun)
4519 {
4520         struct ctl_softc *softc;
4521         struct ctl_lun *nlun;
4522         int i;
4523
4524         softc = lun->ctl_softc;
4525
4526         mtx_assert(&softc->ctl_lock, MA_OWNED);
4527
4528         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4529
4530         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4531
4532         softc->ctl_luns[lun->lun] = NULL;
4533
4534         if (!TAILQ_EMPTY(&lun->ooa_queue))
4535                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4536
4537         softc->num_luns--;
4538
4539         /*
4540          * Tell the backend to free resources, if this LUN has a backend.
4541          */
4542         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4543         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4544
4545         ctl_tpc_lun_shutdown(lun);
4546         mtx_destroy(&lun->lun_lock);
4547         free(lun->lun_devid, M_CTL);
4548         for (i = 0; i < CTL_MAX_PORTS; i++)
4549                 free(lun->pending_ua[i], M_CTL);
4550         for (i = 0; i < CTL_MAX_PORTS; i++)
4551                 free(lun->pr_keys[i], M_CTL);
4552         free(lun->write_buffer, M_CTL);
4553         if (lun->flags & CTL_LUN_MALLOCED)
4554                 free(lun, M_CTL);
4555
4556         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4557                 mtx_lock(&nlun->lun_lock);
4558                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4559                 mtx_unlock(&nlun->lun_lock);
4560         }
4561
4562         return (0);
4563 }
4564
4565 static void
4566 ctl_create_lun(struct ctl_be_lun *be_lun)
4567 {
4568
4569         /*
4570          * ctl_alloc_lun() should handle all potential failure cases.
4571          */
4572         ctl_alloc_lun(control_softc, NULL, be_lun);
4573 }
4574
4575 int
4576 ctl_add_lun(struct ctl_be_lun *be_lun)
4577 {
4578         struct ctl_softc *softc = control_softc;
4579
4580         mtx_lock(&softc->ctl_lock);
4581         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4582         mtx_unlock(&softc->ctl_lock);
4583         wakeup(&softc->pending_lun_queue);
4584
4585         return (0);
4586 }
4587
4588 int
4589 ctl_enable_lun(struct ctl_be_lun *be_lun)
4590 {
4591         struct ctl_softc *softc;
4592         struct ctl_port *port, *nport;
4593         struct ctl_lun *lun;
4594         int retval;
4595
4596         lun = (struct ctl_lun *)be_lun->ctl_lun;
4597         softc = lun->ctl_softc;
4598
4599         mtx_lock(&softc->ctl_lock);
4600         mtx_lock(&lun->lun_lock);
4601         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4602                 /*
4603                  * eh?  Why did we get called if the LUN is already
4604                  * enabled?
4605                  */
4606                 mtx_unlock(&lun->lun_lock);
4607                 mtx_unlock(&softc->ctl_lock);
4608                 return (0);
4609         }
4610         lun->flags &= ~CTL_LUN_DISABLED;
4611         mtx_unlock(&lun->lun_lock);
4612
4613         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4614                 nport = STAILQ_NEXT(port, links);
4615                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4616                     port->lun_map != NULL || port->lun_enable == NULL)
4617                         continue;
4618
4619                 /*
4620                  * Drop the lock while we call the FETD's enable routine.
4621                  * This can lead to a callback into CTL (at least in the
4622                  * case of the internal initiator frontend.
4623                  */
4624                 mtx_unlock(&softc->ctl_lock);
4625                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4626                 mtx_lock(&softc->ctl_lock);
4627                 if (retval != 0) {
4628                         printf("%s: FETD %s port %d returned error "
4629                                "%d for lun_enable on lun %jd\n",
4630                                __func__, port->port_name, port->targ_port,
4631                                retval, (intmax_t)lun->lun);
4632                 }
4633         }
4634
4635         mtx_unlock(&softc->ctl_lock);
4636         ctl_isc_announce_lun(lun);
4637
4638         return (0);
4639 }
4640
4641 int
4642 ctl_disable_lun(struct ctl_be_lun *be_lun)
4643 {
4644         struct ctl_softc *softc;
4645         struct ctl_port *port;
4646         struct ctl_lun *lun;
4647         int retval;
4648
4649         lun = (struct ctl_lun *)be_lun->ctl_lun;
4650         softc = lun->ctl_softc;
4651
4652         mtx_lock(&softc->ctl_lock);
4653         mtx_lock(&lun->lun_lock);
4654         if (lun->flags & CTL_LUN_DISABLED) {
4655                 mtx_unlock(&lun->lun_lock);
4656                 mtx_unlock(&softc->ctl_lock);
4657                 return (0);
4658         }
4659         lun->flags |= CTL_LUN_DISABLED;
4660         mtx_unlock(&lun->lun_lock);
4661
4662         STAILQ_FOREACH(port, &softc->port_list, links) {
4663                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4664                     port->lun_map != NULL || port->lun_disable == NULL)
4665                         continue;
4666
4667                 /*
4668                  * Drop the lock before we call the frontend's disable
4669                  * routine, to avoid lock order reversals.
4670                  *
4671                  * XXX KDM what happens if the frontend list changes while
4672                  * we're traversing it?  It's unlikely, but should be handled.
4673                  */
4674                 mtx_unlock(&softc->ctl_lock);
4675                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4676                 mtx_lock(&softc->ctl_lock);
4677                 if (retval != 0) {
4678                         printf("%s: FETD %s port %d returned error "
4679                                "%d for lun_disable on lun %jd\n",
4680                                __func__, port->port_name, port->targ_port,
4681                                retval, (intmax_t)lun->lun);
4682                 }
4683         }
4684
4685         mtx_unlock(&softc->ctl_lock);
4686         ctl_isc_announce_lun(lun);
4687
4688         return (0);
4689 }
4690
4691 int
4692 ctl_start_lun(struct ctl_be_lun *be_lun)
4693 {
4694         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4695
4696         mtx_lock(&lun->lun_lock);
4697         lun->flags &= ~CTL_LUN_STOPPED;
4698         mtx_unlock(&lun->lun_lock);
4699         return (0);
4700 }
4701
4702 int
4703 ctl_stop_lun(struct ctl_be_lun *be_lun)
4704 {
4705         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4706
4707         mtx_lock(&lun->lun_lock);
4708         lun->flags |= CTL_LUN_STOPPED;
4709         mtx_unlock(&lun->lun_lock);
4710         return (0);
4711 }
4712
4713 int
4714 ctl_lun_offline(struct ctl_be_lun *be_lun)
4715 {
4716         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4717
4718         mtx_lock(&lun->lun_lock);
4719         lun->flags |= CTL_LUN_OFFLINE;
4720         mtx_unlock(&lun->lun_lock);
4721         return (0);
4722 }
4723
4724 int
4725 ctl_lun_online(struct ctl_be_lun *be_lun)
4726 {
4727         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4728
4729         mtx_lock(&lun->lun_lock);
4730         lun->flags &= ~CTL_LUN_OFFLINE;
4731         mtx_unlock(&lun->lun_lock);
4732         return (0);
4733 }
4734
4735 int
4736 ctl_lun_primary(struct ctl_be_lun *be_lun)
4737 {
4738         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4739
4740         mtx_lock(&lun->lun_lock);
4741         lun->flags |= CTL_LUN_PRIMARY_SC;
4742         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4743         mtx_unlock(&lun->lun_lock);
4744         ctl_isc_announce_lun(lun);
4745         return (0);
4746 }
4747
4748 int
4749 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4750 {
4751         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4752
4753         mtx_lock(&lun->lun_lock);
4754         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4755         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4756         mtx_unlock(&lun->lun_lock);
4757         ctl_isc_announce_lun(lun);
4758         return (0);
4759 }
4760
4761 int
4762 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4763 {
4764         struct ctl_softc *softc;
4765         struct ctl_lun *lun;
4766
4767         lun = (struct ctl_lun *)be_lun->ctl_lun;
4768         softc = lun->ctl_softc;
4769
4770         mtx_lock(&lun->lun_lock);
4771
4772         /*
4773          * The LUN needs to be disabled before it can be marked invalid.
4774          */
4775         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4776                 mtx_unlock(&lun->lun_lock);
4777                 return (-1);
4778         }
4779         /*
4780          * Mark the LUN invalid.
4781          */
4782         lun->flags |= CTL_LUN_INVALID;
4783
4784         /*
4785          * If there is nothing in the OOA queue, go ahead and free the LUN.
4786          * If we have something in the OOA queue, we'll free it when the
4787          * last I/O completes.
4788          */
4789         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4790                 mtx_unlock(&lun->lun_lock);
4791                 mtx_lock(&softc->ctl_lock);
4792                 ctl_free_lun(lun);
4793                 mtx_unlock(&softc->ctl_lock);
4794         } else
4795                 mtx_unlock(&lun->lun_lock);
4796
4797         return (0);
4798 }
4799
4800 int
4801 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4802 {
4803         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4804
4805         mtx_lock(&lun->lun_lock);
4806         lun->flags |= CTL_LUN_INOPERABLE;
4807         mtx_unlock(&lun->lun_lock);
4808         return (0);
4809 }
4810
4811 int
4812 ctl_lun_operable(struct ctl_be_lun *be_lun)
4813 {
4814         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4815
4816         mtx_lock(&lun->lun_lock);
4817         lun->flags &= ~CTL_LUN_INOPERABLE;
4818         mtx_unlock(&lun->lun_lock);
4819         return (0);
4820 }
4821
4822 void
4823 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4824 {
4825         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4826         union ctl_ha_msg msg;
4827
4828         mtx_lock(&lun->lun_lock);
4829         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4830         mtx_unlock(&lun->lun_lock);
4831         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4832                 /* Send msg to other side. */
4833                 bzero(&msg.ua, sizeof(msg.ua));
4834                 msg.hdr.msg_type = CTL_MSG_UA;
4835                 msg.hdr.nexus.initid = -1;
4836                 msg.hdr.nexus.targ_port = -1;
4837                 msg.hdr.nexus.targ_lun = lun->lun;
4838                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4839                 msg.ua.ua_all = 1;
4840                 msg.ua.ua_set = 1;
4841                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4842                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4843                     M_WAITOK);
4844         }
4845 }
4846
4847 /*
4848  * Backend "memory move is complete" callback for requests that never
4849  * make it down to say RAIDCore's configuration code.
4850  */
4851 int
4852 ctl_config_move_done(union ctl_io *io)
4853 {
4854         int retval;
4855
4856         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4857         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4858             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4859
4860         if ((io->io_hdr.port_status != 0) &&
4861             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4862              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4863                 /*
4864                  * For hardware error sense keys, the sense key
4865                  * specific value is defined to be a retry count,
4866                  * but we use it to pass back an internal FETD
4867                  * error code.  XXX KDM  Hopefully the FETD is only
4868                  * using 16 bits for an error code, since that's
4869                  * all the space we have in the sks field.
4870                  */
4871                 ctl_set_internal_failure(&io->scsiio,
4872                                          /*sks_valid*/ 1,
4873                                          /*retry_count*/
4874                                          io->io_hdr.port_status);
4875         }
4876
4877         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4878                 ctl_data_print(io);
4879         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4880             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4881              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4882             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4883                 /*
4884                  * XXX KDM just assuming a single pointer here, and not a
4885                  * S/G list.  If we start using S/G lists for config data,
4886                  * we'll need to know how to clean them up here as well.
4887                  */
4888                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4889                         free(io->scsiio.kern_data_ptr, M_CTL);
4890                 ctl_done(io);
4891                 retval = CTL_RETVAL_COMPLETE;
4892         } else {
4893                 /*
4894                  * XXX KDM now we need to continue data movement.  Some
4895                  * options:
4896                  * - call ctl_scsiio() again?  We don't do this for data
4897                  *   writes, because for those at least we know ahead of
4898                  *   time where the write will go and how long it is.  For
4899                  *   config writes, though, that information is largely
4900                  *   contained within the write itself, thus we need to
4901                  *   parse out the data again.
4902                  *
4903                  * - Call some other function once the data is in?
4904                  */
4905
4906                 /*
4907                  * XXX KDM call ctl_scsiio() again for now, and check flag
4908                  * bits to see whether we're allocated or not.
4909                  */
4910                 retval = ctl_scsiio(&io->scsiio);
4911         }
4912         return (retval);
4913 }
4914
4915 /*
4916  * This gets called by a backend driver when it is done with a
4917  * data_submit method.
4918  */
4919 void
4920 ctl_data_submit_done(union ctl_io *io)
4921 {
4922         /*
4923          * If the IO_CONT flag is set, we need to call the supplied
4924          * function to continue processing the I/O, instead of completing
4925          * the I/O just yet.
4926          *
4927          * If there is an error, though, we don't want to keep processing.
4928          * Instead, just send status back to the initiator.
4929          */
4930         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4931             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4932             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4933              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4934                 io->scsiio.io_cont(io);
4935                 return;
4936         }
4937         ctl_done(io);
4938 }
4939
4940 /*
4941  * This gets called by a backend driver when it is done with a
4942  * configuration write.
4943  */
4944 void
4945 ctl_config_write_done(union ctl_io *io)
4946 {
4947         uint8_t *buf;
4948
4949         /*
4950          * If the IO_CONT flag is set, we need to call the supplied
4951          * function to continue processing the I/O, instead of completing
4952          * the I/O just yet.
4953          *
4954          * If there is an error, though, we don't want to keep processing.
4955          * Instead, just send status back to the initiator.
4956          */
4957         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4958             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4959             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4960              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4961                 io->scsiio.io_cont(io);
4962                 return;
4963         }
4964         /*
4965          * Since a configuration write can be done for commands that actually
4966          * have data allocated, like write buffer, and commands that have
4967          * no data, like start/stop unit, we need to check here.
4968          */
4969         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4970                 buf = io->scsiio.kern_data_ptr;
4971         else
4972                 buf = NULL;
4973         ctl_done(io);
4974         if (buf)
4975                 free(buf, M_CTL);
4976 }
4977
4978 void
4979 ctl_config_read_done(union ctl_io *io)
4980 {
4981         uint8_t *buf;
4982
4983         /*
4984          * If there is some error -- we are done, skip data transfer.
4985          */
4986         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4987             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4988              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4989                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4990                         buf = io->scsiio.kern_data_ptr;
4991                 else
4992                         buf = NULL;
4993                 ctl_done(io);
4994                 if (buf)
4995                         free(buf, M_CTL);
4996                 return;
4997         }
4998
4999         /*
5000          * If the IO_CONT flag is set, we need to call the supplied
5001          * function to continue processing the I/O, instead of completing
5002          * the I/O just yet.
5003          */
5004         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5005                 io->scsiio.io_cont(io);
5006                 return;
5007         }
5008
5009         ctl_datamove(io);
5010 }
5011
5012 /*
5013  * SCSI release command.
5014  */
5015 int
5016 ctl_scsi_release(struct ctl_scsiio *ctsio)
5017 {
5018         struct ctl_lun *lun;
5019         uint32_t residx;
5020
5021         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5022
5023         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5024         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5025
5026         /*
5027          * XXX KDM right now, we only support LUN reservation.  We don't
5028          * support 3rd party reservations, or extent reservations, which
5029          * might actually need the parameter list.  If we've gotten this
5030          * far, we've got a LUN reservation.  Anything else got kicked out
5031          * above.  So, according to SPC, ignore the length.
5032          */
5033
5034         mtx_lock(&lun->lun_lock);
5035
5036         /*
5037          * According to SPC, it is not an error for an intiator to attempt
5038          * to release a reservation on a LUN that isn't reserved, or that
5039          * is reserved by another initiator.  The reservation can only be
5040          * released, though, by the initiator who made it or by one of
5041          * several reset type events.
5042          */
5043         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5044                         lun->flags &= ~CTL_LUN_RESERVED;
5045
5046         mtx_unlock(&lun->lun_lock);
5047
5048         ctl_set_success(ctsio);
5049         ctl_done((union ctl_io *)ctsio);
5050         return (CTL_RETVAL_COMPLETE);
5051 }
5052
5053 int
5054 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5055 {
5056         struct ctl_lun *lun;
5057         uint32_t residx;
5058
5059         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5060
5061         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5062         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5063
5064         /*
5065          * XXX KDM right now, we only support LUN reservation.  We don't
5066          * support 3rd party reservations, or extent reservations, which
5067          * might actually need the parameter list.  If we've gotten this
5068          * far, we've got a LUN reservation.  Anything else got kicked out
5069          * above.  So, according to SPC, ignore the length.
5070          */
5071
5072         mtx_lock(&lun->lun_lock);
5073         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5074                 ctl_set_reservation_conflict(ctsio);
5075                 goto bailout;
5076         }
5077         lun->flags |= CTL_LUN_RESERVED;
5078         lun->res_idx = residx;
5079         ctl_set_success(ctsio);
5080
5081 bailout:
5082         mtx_unlock(&lun->lun_lock);
5083         ctl_done((union ctl_io *)ctsio);
5084         return (CTL_RETVAL_COMPLETE);
5085 }
5086
5087 int
5088 ctl_start_stop(struct ctl_scsiio *ctsio)
5089 {
5090         struct scsi_start_stop_unit *cdb;
5091         struct ctl_lun *lun;
5092         int retval;
5093
5094         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5095
5096         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5097         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5098
5099         /*
5100          * XXX KDM
5101          * We don't support the immediate bit on a stop unit.  In order to
5102          * do that, we would need to code up a way to know that a stop is
5103          * pending, and hold off any new commands until it completes, one
5104          * way or another.  Then we could accept or reject those commands
5105          * depending on its status.  We would almost need to do the reverse
5106          * of what we do below for an immediate start -- return the copy of
5107          * the ctl_io to the FETD with status to send to the host (and to
5108          * free the copy!) and then free the original I/O once the stop
5109          * actually completes.  That way, the OOA queue mechanism can work
5110          * to block commands that shouldn't proceed.  Another alternative
5111          * would be to put the copy in the queue in place of the original,
5112          * and return the original back to the caller.  That could be
5113          * slightly safer..
5114          */
5115         if ((cdb->byte2 & SSS_IMMED)
5116          && ((cdb->how & SSS_START) == 0)) {
5117                 ctl_set_invalid_field(ctsio,
5118                                       /*sks_valid*/ 1,
5119                                       /*command*/ 1,
5120                                       /*field*/ 1,
5121                                       /*bit_valid*/ 1,
5122                                       /*bit*/ 0);
5123                 ctl_done((union ctl_io *)ctsio);
5124                 return (CTL_RETVAL_COMPLETE);
5125         }
5126
5127         if ((lun->flags & CTL_LUN_PR_RESERVED)
5128          && ((cdb->how & SSS_START)==0)) {
5129                 uint32_t residx;
5130
5131                 residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5132                 if (ctl_get_prkey(lun, residx) == 0
5133                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5134
5135                         ctl_set_reservation_conflict(ctsio);
5136                         ctl_done((union ctl_io *)ctsio);
5137                         return (CTL_RETVAL_COMPLETE);
5138                 }
5139         }
5140
5141         /*
5142          * If there is no backend on this device, we can't start or stop
5143          * it.  In theory we shouldn't get any start/stop commands in the
5144          * first place at this level if the LUN doesn't have a backend.
5145          * That should get stopped by the command decode code.
5146          */
5147         if (lun->backend == NULL) {
5148                 ctl_set_invalid_opcode(ctsio);
5149                 ctl_done((union ctl_io *)ctsio);
5150                 return (CTL_RETVAL_COMPLETE);
5151         }
5152
5153         /*
5154          * In the non-immediate case, we send the request to
5155          * the backend and return status to the user when
5156          * it is done.
5157          *
5158          * In the immediate case, we allocate a new ctl_io
5159          * to hold a copy of the request, and send that to
5160          * the backend.  We then set good status on the
5161          * user's request and return it immediately.
5162          */
5163         if (cdb->byte2 & SSS_IMMED) {
5164                 union ctl_io *new_io;
5165
5166                 new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5167                 ctl_copy_io((union ctl_io *)ctsio, new_io);
5168                 retval = lun->backend->config_write(new_io);
5169                 ctl_set_success(ctsio);
5170                 ctl_done((union ctl_io *)ctsio);
5171         } else {
5172                 retval = lun->backend->config_write(
5173                         (union ctl_io *)ctsio);
5174         }
5175         return (retval);
5176 }
5177
5178 /*
5179  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5180  * we don't really do anything with the LBA and length fields if the user
5181  * passes them in.  Instead we'll just flush out the cache for the entire
5182  * LUN.
5183  */
5184 int
5185 ctl_sync_cache(struct ctl_scsiio *ctsio)
5186 {
5187         struct ctl_lun *lun;
5188         struct ctl_softc *softc;
5189         struct ctl_lba_len_flags *lbalen;
5190         uint64_t starting_lba;
5191         uint32_t block_count;
5192         int retval;
5193         uint8_t byte2;
5194
5195         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5196
5197         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5198         softc = lun->ctl_softc;
5199         retval = 0;
5200
5201         switch (ctsio->cdb[0]) {
5202         case SYNCHRONIZE_CACHE: {
5203                 struct scsi_sync_cache *cdb;
5204                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5205
5206                 starting_lba = scsi_4btoul(cdb->begin_lba);
5207                 block_count = scsi_2btoul(cdb->lb_count);
5208                 byte2 = cdb->byte2;
5209                 break;
5210         }
5211         case SYNCHRONIZE_CACHE_16: {
5212                 struct scsi_sync_cache_16 *cdb;
5213                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5214
5215                 starting_lba = scsi_8btou64(cdb->begin_lba);
5216                 block_count = scsi_4btoul(cdb->lb_count);
5217                 byte2 = cdb->byte2;
5218                 break;
5219         }
5220         default:
5221                 ctl_set_invalid_opcode(ctsio);
5222                 ctl_done((union ctl_io *)ctsio);
5223                 goto bailout;
5224                 break; /* NOTREACHED */
5225         }
5226
5227         /*
5228          * We check the LBA and length, but don't do anything with them.
5229          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5230          * get flushed.  This check will just help satisfy anyone who wants
5231          * to see an error for an out of range LBA.
5232          */
5233         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5234                 ctl_set_lba_out_of_range(ctsio);
5235                 ctl_done((union ctl_io *)ctsio);
5236                 goto bailout;
5237         }
5238
5239         /*
5240          * If this LUN has no backend, we can't flush the cache anyway.
5241          */
5242         if (lun->backend == NULL) {
5243                 ctl_set_invalid_opcode(ctsio);
5244                 ctl_done((union ctl_io *)ctsio);
5245                 goto bailout;
5246         }
5247
5248         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5249         lbalen->lba = starting_lba;
5250         lbalen->len = block_count;
5251         lbalen->flags = byte2;
5252         retval = lun->backend->config_write((union ctl_io *)ctsio);
5253
5254 bailout:
5255         return (retval);
5256 }
5257
5258 int
5259 ctl_format(struct ctl_scsiio *ctsio)
5260 {
5261         struct scsi_format *cdb;
5262         struct ctl_lun *lun;
5263         int length, defect_list_len;
5264
5265         CTL_DEBUG_PRINT(("ctl_format\n"));
5266
5267         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5268
5269         cdb = (struct scsi_format *)ctsio->cdb;
5270
5271         length = 0;
5272         if (cdb->byte2 & SF_FMTDATA) {
5273                 if (cdb->byte2 & SF_LONGLIST)
5274                         length = sizeof(struct scsi_format_header_long);
5275                 else
5276                         length = sizeof(struct scsi_format_header_short);
5277         }
5278
5279         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5280          && (length > 0)) {
5281                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5282                 ctsio->kern_data_len = length;
5283                 ctsio->kern_total_len = length;
5284                 ctsio->kern_data_resid = 0;
5285                 ctsio->kern_rel_offset = 0;
5286                 ctsio->kern_sg_entries = 0;
5287                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5288                 ctsio->be_move_done = ctl_config_move_done;
5289                 ctl_datamove((union ctl_io *)ctsio);
5290
5291                 return (CTL_RETVAL_COMPLETE);
5292         }
5293
5294         defect_list_len = 0;
5295
5296         if (cdb->byte2 & SF_FMTDATA) {
5297                 if (cdb->byte2 & SF_LONGLIST) {
5298                         struct scsi_format_header_long *header;
5299
5300                         header = (struct scsi_format_header_long *)
5301                                 ctsio->kern_data_ptr;
5302
5303                         defect_list_len = scsi_4btoul(header->defect_list_len);
5304                         if (defect_list_len != 0) {
5305                                 ctl_set_invalid_field(ctsio,
5306                                                       /*sks_valid*/ 1,
5307                                                       /*command*/ 0,
5308                                                       /*field*/ 2,
5309                                                       /*bit_valid*/ 0,
5310                                                       /*bit*/ 0);
5311                                 goto bailout;
5312                         }
5313                 } else {
5314                         struct scsi_format_header_short *header;
5315
5316                         header = (struct scsi_format_header_short *)
5317                                 ctsio->kern_data_ptr;
5318
5319                         defect_list_len = scsi_2btoul(header->defect_list_len);
5320                         if (defect_list_len != 0) {
5321                                 ctl_set_invalid_field(ctsio,
5322                                                       /*sks_valid*/ 1,
5323                                                       /*command*/ 0,
5324                                                       /*field*/ 2,
5325                                                       /*bit_valid*/ 0,
5326                                                       /*bit*/ 0);
5327                                 goto bailout;
5328                         }
5329                 }
5330         }
5331
5332         /*
5333          * The format command will clear out the "Medium format corrupted"
5334          * status if set by the configuration code.  That status is really
5335          * just a way to notify the host that we have lost the media, and
5336          * get them to issue a command that will basically make them think
5337          * they're blowing away the media.
5338          */
5339         mtx_lock(&lun->lun_lock);
5340         lun->flags &= ~CTL_LUN_INOPERABLE;
5341         mtx_unlock(&lun->lun_lock);
5342
5343         ctl_set_success(ctsio);
5344 bailout:
5345
5346         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5347                 free(ctsio->kern_data_ptr, M_CTL);
5348                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5349         }
5350
5351         ctl_done((union ctl_io *)ctsio);
5352         return (CTL_RETVAL_COMPLETE);
5353 }
5354
5355 int
5356 ctl_read_buffer(struct ctl_scsiio *ctsio)
5357 {
5358         struct ctl_lun *lun;
5359         uint64_t buffer_offset;
5360         uint32_t len;
5361         uint8_t byte2;
5362         static uint8_t descr[4];
5363         static uint8_t echo_descr[4] = { 0 };
5364
5365         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5366         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5367         switch (ctsio->cdb[0]) {
5368         case READ_BUFFER: {
5369                 struct scsi_read_buffer *cdb;
5370
5371                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5372                 buffer_offset = scsi_3btoul(cdb->offset);
5373                 len = scsi_3btoul(cdb->length);
5374                 byte2 = cdb->byte2;
5375                 break;
5376         }
5377         case READ_BUFFER_16: {
5378                 struct scsi_read_buffer_16 *cdb;
5379
5380                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5381                 buffer_offset = scsi_8btou64(cdb->offset);
5382                 len = scsi_4btoul(cdb->length);
5383                 byte2 = cdb->byte2;
5384                 break;
5385         }
5386         default: /* This shouldn't happen. */
5387                 ctl_set_invalid_opcode(ctsio);
5388                 ctl_done((union ctl_io *)ctsio);
5389                 return (CTL_RETVAL_COMPLETE);
5390         }
5391
5392         if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5393             (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5394             (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5395                 ctl_set_invalid_field(ctsio,
5396                                       /*sks_valid*/ 1,
5397                                       /*command*/ 1,
5398                                       /*field*/ 1,
5399                                       /*bit_valid*/ 1,
5400                                       /*bit*/ 4);
5401                 ctl_done((union ctl_io *)ctsio);
5402                 return (CTL_RETVAL_COMPLETE);
5403         }
5404
5405         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5406             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5407                 ctl_set_invalid_field(ctsio,
5408                                       /*sks_valid*/ 1,
5409                                       /*command*/ 1,
5410                                       /*field*/ 6,
5411                                       /*bit_valid*/ 0,
5412                                       /*bit*/ 0);
5413                 ctl_done((union ctl_io *)ctsio);
5414                 return (CTL_RETVAL_COMPLETE);
5415         }
5416
5417         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5418                 descr[0] = 0;
5419                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5420                 ctsio->kern_data_ptr = descr;
5421                 len = min(len, sizeof(descr));
5422         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5423                 ctsio->kern_data_ptr = echo_descr;
5424                 len = min(len, sizeof(echo_descr));
5425         } else {
5426                 if (lun->write_buffer == NULL) {
5427                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5428                             M_CTL, M_WAITOK);
5429                 }
5430                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5431         }
5432         ctsio->kern_data_len = len;
5433         ctsio->kern_total_len = len;
5434         ctsio->kern_data_resid = 0;
5435         ctsio->kern_rel_offset = 0;
5436         ctsio->kern_sg_entries = 0;
5437         ctl_set_success(ctsio);
5438         ctsio->be_move_done = ctl_config_move_done;
5439         ctl_datamove((union ctl_io *)ctsio);
5440         return (CTL_RETVAL_COMPLETE);
5441 }
5442
5443 int
5444 ctl_write_buffer(struct ctl_scsiio *ctsio)
5445 {
5446         struct scsi_write_buffer *cdb;
5447         struct ctl_lun *lun;
5448         int buffer_offset, len;
5449
5450         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5451
5452         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5453         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5454
5455         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5456                 ctl_set_invalid_field(ctsio,
5457                                       /*sks_valid*/ 1,
5458                                       /*command*/ 1,
5459                                       /*field*/ 1,
5460                                       /*bit_valid*/ 1,
5461                                       /*bit*/ 4);
5462                 ctl_done((union ctl_io *)ctsio);
5463                 return (CTL_RETVAL_COMPLETE);
5464         }
5465
5466         len = scsi_3btoul(cdb->length);
5467         buffer_offset = scsi_3btoul(cdb->offset);
5468
5469         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5470                 ctl_set_invalid_field(ctsio,
5471                                       /*sks_valid*/ 1,
5472                                       /*command*/ 1,
5473                                       /*field*/ 6,
5474                                       /*bit_valid*/ 0,
5475                                       /*bit*/ 0);
5476                 ctl_done((union ctl_io *)ctsio);
5477                 return (CTL_RETVAL_COMPLETE);
5478         }
5479
5480         /*
5481          * If we've got a kernel request that hasn't been malloced yet,
5482          * malloc it and tell the caller the data buffer is here.
5483          */
5484         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5485                 if (lun->write_buffer == NULL) {
5486                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5487                             M_CTL, M_WAITOK);
5488                 }
5489                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5490                 ctsio->kern_data_len = len;
5491                 ctsio->kern_total_len = len;
5492                 ctsio->kern_data_resid = 0;
5493                 ctsio->kern_rel_offset = 0;
5494                 ctsio->kern_sg_entries = 0;
5495                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5496                 ctsio->be_move_done = ctl_config_move_done;
5497                 ctl_datamove((union ctl_io *)ctsio);
5498
5499                 return (CTL_RETVAL_COMPLETE);
5500         }
5501
5502         ctl_set_success(ctsio);
5503         ctl_done((union ctl_io *)ctsio);
5504         return (CTL_RETVAL_COMPLETE);
5505 }
5506
5507 int
5508 ctl_write_same(struct ctl_scsiio *ctsio)
5509 {
5510         struct ctl_lun *lun;
5511         struct ctl_lba_len_flags *lbalen;
5512         uint64_t lba;
5513         uint32_t num_blocks;
5514         int len, retval;
5515         uint8_t byte2;
5516
5517         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5518
5519         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5520
5521         switch (ctsio->cdb[0]) {
5522         case WRITE_SAME_10: {
5523                 struct scsi_write_same_10 *cdb;
5524
5525                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5526
5527                 lba = scsi_4btoul(cdb->addr);
5528                 num_blocks = scsi_2btoul(cdb->length);
5529                 byte2 = cdb->byte2;
5530                 break;
5531         }
5532         case WRITE_SAME_16: {
5533                 struct scsi_write_same_16 *cdb;
5534
5535                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5536
5537                 lba = scsi_8btou64(cdb->addr);
5538                 num_blocks = scsi_4btoul(cdb->length);
5539                 byte2 = cdb->byte2;
5540                 break;
5541         }
5542         default:
5543                 /*
5544                  * We got a command we don't support.  This shouldn't
5545                  * happen, commands should be filtered out above us.
5546                  */
5547                 ctl_set_invalid_opcode(ctsio);
5548                 ctl_done((union ctl_io *)ctsio);
5549
5550                 return (CTL_RETVAL_COMPLETE);
5551                 break; /* NOTREACHED */
5552         }
5553
5554         /* ANCHOR flag can be used only together with UNMAP */
5555         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5556                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5557                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5558                 ctl_done((union ctl_io *)ctsio);
5559                 return (CTL_RETVAL_COMPLETE);
5560         }
5561
5562         /*
5563          * The first check is to make sure we're in bounds, the second
5564          * check is to catch wrap-around problems.  If the lba + num blocks
5565          * is less than the lba, then we've wrapped around and the block
5566          * range is invalid anyway.
5567          */
5568         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5569          || ((lba + num_blocks) < lba)) {
5570                 ctl_set_lba_out_of_range(ctsio);
5571                 ctl_done((union ctl_io *)ctsio);
5572                 return (CTL_RETVAL_COMPLETE);
5573         }
5574
5575         /* Zero number of blocks means "to the last logical block" */
5576         if (num_blocks == 0) {
5577                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5578                         ctl_set_invalid_field(ctsio,
5579                                               /*sks_valid*/ 0,
5580                                               /*command*/ 1,
5581                                               /*field*/ 0,
5582                                               /*bit_valid*/ 0,
5583                                               /*bit*/ 0);
5584                         ctl_done((union ctl_io *)ctsio);
5585                         return (CTL_RETVAL_COMPLETE);
5586                 }
5587                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5588         }
5589
5590         len = lun->be_lun->blocksize;
5591
5592         /*
5593          * If we've got a kernel request that hasn't been malloced yet,
5594          * malloc it and tell the caller the data buffer is here.
5595          */
5596         if ((byte2 & SWS_NDOB) == 0 &&
5597             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5598                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5599                 ctsio->kern_data_len = len;
5600                 ctsio->kern_total_len = len;
5601                 ctsio->kern_data_resid = 0;
5602                 ctsio->kern_rel_offset = 0;
5603                 ctsio->kern_sg_entries = 0;
5604                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5605                 ctsio->be_move_done = ctl_config_move_done;
5606                 ctl_datamove((union ctl_io *)ctsio);
5607
5608                 return (CTL_RETVAL_COMPLETE);
5609         }
5610
5611         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5612         lbalen->lba = lba;
5613         lbalen->len = num_blocks;
5614         lbalen->flags = byte2;
5615         retval = lun->backend->config_write((union ctl_io *)ctsio);
5616
5617         return (retval);
5618 }
5619
5620 int
5621 ctl_unmap(struct ctl_scsiio *ctsio)
5622 {
5623         struct ctl_lun *lun;
5624         struct scsi_unmap *cdb;
5625         struct ctl_ptr_len_flags *ptrlen;
5626         struct scsi_unmap_header *hdr;
5627         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5628         uint64_t lba;
5629         uint32_t num_blocks;
5630         int len, retval;
5631         uint8_t byte2;
5632
5633         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5634
5635         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5636         cdb = (struct scsi_unmap *)ctsio->cdb;
5637
5638         len = scsi_2btoul(cdb->length);
5639         byte2 = cdb->byte2;
5640
5641         /*
5642          * If we've got a kernel request that hasn't been malloced yet,
5643          * malloc it and tell the caller the data buffer is here.
5644          */
5645         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5646                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5647                 ctsio->kern_data_len = len;
5648                 ctsio->kern_total_len = len;
5649                 ctsio->kern_data_resid = 0;
5650                 ctsio->kern_rel_offset = 0;
5651                 ctsio->kern_sg_entries = 0;
5652                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5653                 ctsio->be_move_done = ctl_config_move_done;
5654                 ctl_datamove((union ctl_io *)ctsio);
5655
5656                 return (CTL_RETVAL_COMPLETE);
5657         }
5658
5659         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5660         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5661         if (len < sizeof (*hdr) ||
5662             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5663             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5664             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5665                 ctl_set_invalid_field(ctsio,
5666                                       /*sks_valid*/ 0,
5667                                       /*command*/ 0,
5668                                       /*field*/ 0,
5669                                       /*bit_valid*/ 0,
5670                                       /*bit*/ 0);
5671                 goto done;
5672         }
5673         len = scsi_2btoul(hdr->desc_length);
5674         buf = (struct scsi_unmap_desc *)(hdr + 1);
5675         end = buf + len / sizeof(*buf);
5676
5677         endnz = buf;
5678         for (range = buf; range < end; range++) {
5679                 lba = scsi_8btou64(range->lba);
5680                 num_blocks = scsi_4btoul(range->length);
5681                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5682                  || ((lba + num_blocks) < lba)) {
5683                         ctl_set_lba_out_of_range(ctsio);
5684                         ctl_done((union ctl_io *)ctsio);
5685                         return (CTL_RETVAL_COMPLETE);
5686                 }
5687                 if (num_blocks != 0)
5688                         endnz = range + 1;
5689         }
5690
5691         /*
5692          * Block backend can not handle zero last range.
5693          * Filter it out and return if there is nothing left.
5694          */
5695         len = (uint8_t *)endnz - (uint8_t *)buf;
5696         if (len == 0) {
5697                 ctl_set_success(ctsio);
5698                 goto done;
5699         }
5700
5701         mtx_lock(&lun->lun_lock);
5702         ptrlen = (struct ctl_ptr_len_flags *)
5703             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5704         ptrlen->ptr = (void *)buf;
5705         ptrlen->len = len;
5706         ptrlen->flags = byte2;
5707         ctl_check_blocked(lun);
5708         mtx_unlock(&lun->lun_lock);
5709
5710         retval = lun->backend->config_write((union ctl_io *)ctsio);
5711         return (retval);
5712
5713 done:
5714         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5715                 free(ctsio->kern_data_ptr, M_CTL);
5716                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5717         }
5718         ctl_done((union ctl_io *)ctsio);
5719         return (CTL_RETVAL_COMPLETE);
5720 }
5721
5722 /*
5723  * Note that this function currently doesn't actually do anything inside
5724  * CTL to enforce things if the DQue bit is turned on.
5725  *
5726  * Also note that this function can't be used in the default case, because
5727  * the DQue bit isn't set in the changeable mask for the control mode page
5728  * anyway.  This is just here as an example for how to implement a page
5729  * handler, and a placeholder in case we want to allow the user to turn
5730  * tagged queueing on and off.
5731  *
5732  * The D_SENSE bit handling is functional, however, and will turn
5733  * descriptor sense on and off for a given LUN.
5734  */
5735 int
5736 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5737                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5738 {
5739         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5740         struct ctl_lun *lun;
5741         int set_ua;
5742         uint32_t initidx;
5743
5744         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5745         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5746         set_ua = 0;
5747
5748         user_cp = (struct scsi_control_page *)page_ptr;
5749         current_cp = (struct scsi_control_page *)
5750                 (page_index->page_data + (page_index->page_len *
5751                 CTL_PAGE_CURRENT));
5752         saved_cp = (struct scsi_control_page *)
5753                 (page_index->page_data + (page_index->page_len *
5754                 CTL_PAGE_SAVED));
5755
5756         mtx_lock(&lun->lun_lock);
5757         if (((current_cp->rlec & SCP_DSENSE) == 0)
5758          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5759                 /*
5760                  * Descriptor sense is currently turned off and the user
5761                  * wants to turn it on.
5762                  */
5763                 current_cp->rlec |= SCP_DSENSE;
5764                 saved_cp->rlec |= SCP_DSENSE;
5765                 lun->flags |= CTL_LUN_SENSE_DESC;
5766                 set_ua = 1;
5767         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5768                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5769                 /*
5770                  * Descriptor sense is currently turned on, and the user
5771                  * wants to turn it off.
5772                  */
5773                 current_cp->rlec &= ~SCP_DSENSE;
5774                 saved_cp->rlec &= ~SCP_DSENSE;
5775                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5776                 set_ua = 1;
5777         }
5778         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5779             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5780                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5781                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5782                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5783                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5784                 set_ua = 1;
5785         }
5786         if ((current_cp->eca_and_aen & SCP_SWP) !=
5787             (user_cp->eca_and_aen & SCP_SWP)) {
5788                 current_cp->eca_and_aen &= ~SCP_SWP;
5789                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5790                 saved_cp->eca_and_aen &= ~SCP_SWP;
5791                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5792                 set_ua = 1;
5793         }
5794         if (set_ua != 0)
5795                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5796         mtx_unlock(&lun->lun_lock);
5797         if (set_ua) {
5798                 ctl_isc_announce_mode(lun,
5799                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5800                     page_index->page_code, page_index->subpage);
5801         }
5802         return (0);
5803 }
5804
5805 int
5806 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5807                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5808 {
5809         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5810         struct ctl_lun *lun;
5811         int set_ua;
5812         uint32_t initidx;
5813
5814         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5815         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5816         set_ua = 0;
5817
5818         user_cp = (struct scsi_caching_page *)page_ptr;
5819         current_cp = (struct scsi_caching_page *)
5820                 (page_index->page_data + (page_index->page_len *
5821                 CTL_PAGE_CURRENT));
5822         saved_cp = (struct scsi_caching_page *)
5823                 (page_index->page_data + (page_index->page_len *
5824                 CTL_PAGE_SAVED));
5825
5826         mtx_lock(&lun->lun_lock);
5827         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5828             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5829                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5830                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5831                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5832                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5833                 set_ua = 1;
5834         }
5835         if (set_ua != 0)
5836                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5837         mtx_unlock(&lun->lun_lock);
5838         if (set_ua) {
5839                 ctl_isc_announce_mode(lun,
5840                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5841                     page_index->page_code, page_index->subpage);
5842         }
5843         return (0);
5844 }
5845
5846 int
5847 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5848                                 struct ctl_page_index *page_index,
5849                                 uint8_t *page_ptr)
5850 {
5851         uint8_t *c;
5852         int i;
5853
5854         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5855         ctl_time_io_secs =
5856                 (c[0] << 8) |
5857                 (c[1] << 0) |
5858                 0;
5859         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5860         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5861         printf("page data:");
5862         for (i=0; i<8; i++)
5863                 printf(" %.2x",page_ptr[i]);
5864         printf("\n");
5865         return (0);
5866 }
5867
5868 int
5869 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5870                                struct ctl_page_index *page_index,
5871                                int pc)
5872 {
5873         struct copan_debugconf_subpage *page;
5874
5875         page = (struct copan_debugconf_subpage *)page_index->page_data +
5876                 (page_index->page_len * pc);
5877
5878         switch (pc) {
5879         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5880         case SMS_PAGE_CTRL_DEFAULT >> 6:
5881         case SMS_PAGE_CTRL_SAVED >> 6:
5882                 /*
5883                  * We don't update the changable or default bits for this page.
5884                  */
5885                 break;
5886         case SMS_PAGE_CTRL_CURRENT >> 6:
5887                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5888                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5889                 break;
5890         default:
5891                 break;
5892         }
5893         return (0);
5894 }
5895
5896
5897 static int
5898 ctl_do_mode_select(union ctl_io *io)
5899 {
5900         struct scsi_mode_page_header *page_header;
5901         struct ctl_page_index *page_index;
5902         struct ctl_scsiio *ctsio;
5903         int control_dev, page_len;
5904         int page_len_offset, page_len_size;
5905         union ctl_modepage_info *modepage_info;
5906         struct ctl_lun *lun;
5907         int *len_left, *len_used;
5908         int retval, i;
5909
5910         ctsio = &io->scsiio;
5911         page_index = NULL;
5912         page_len = 0;
5913         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5914
5915         if (lun->be_lun->lun_type != T_DIRECT)
5916                 control_dev = 1;
5917         else
5918                 control_dev = 0;
5919
5920         modepage_info = (union ctl_modepage_info *)
5921                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5922         len_left = &modepage_info->header.len_left;
5923         len_used = &modepage_info->header.len_used;
5924
5925 do_next_page:
5926
5927         page_header = (struct scsi_mode_page_header *)
5928                 (ctsio->kern_data_ptr + *len_used);
5929
5930         if (*len_left == 0) {
5931                 free(ctsio->kern_data_ptr, M_CTL);
5932                 ctl_set_success(ctsio);
5933                 ctl_done((union ctl_io *)ctsio);
5934                 return (CTL_RETVAL_COMPLETE);
5935         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5936
5937                 free(ctsio->kern_data_ptr, M_CTL);
5938                 ctl_set_param_len_error(ctsio);
5939                 ctl_done((union ctl_io *)ctsio);
5940                 return (CTL_RETVAL_COMPLETE);
5941
5942         } else if ((page_header->page_code & SMPH_SPF)
5943                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5944
5945                 free(ctsio->kern_data_ptr, M_CTL);
5946                 ctl_set_param_len_error(ctsio);
5947                 ctl_done((union ctl_io *)ctsio);
5948                 return (CTL_RETVAL_COMPLETE);
5949         }
5950
5951
5952         /*
5953          * XXX KDM should we do something with the block descriptor?
5954          */
5955         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5956
5957                 if ((control_dev != 0)
5958                  && (lun->mode_pages.index[i].page_flags &
5959                      CTL_PAGE_FLAG_DISK_ONLY))
5960                         continue;
5961
5962                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5963                     (page_header->page_code & SMPH_PC_MASK))
5964                         continue;
5965
5966                 /*
5967                  * If neither page has a subpage code, then we've got a
5968                  * match.
5969                  */
5970                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
5971                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5972                         page_index = &lun->mode_pages.index[i];
5973                         page_len = page_header->page_length;
5974                         break;
5975                 }
5976
5977                 /*
5978                  * If both pages have subpages, then the subpage numbers
5979                  * have to match.
5980                  */
5981                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
5982                   && (page_header->page_code & SMPH_SPF)) {
5983                         struct scsi_mode_page_header_sp *sph;
5984
5985                         sph = (struct scsi_mode_page_header_sp *)page_header;
5986
5987                         if (lun->mode_pages.index[i].subpage ==
5988                             sph->subpage) {
5989                                 page_index = &lun->mode_pages.index[i];
5990                                 page_len = scsi_2btoul(sph->page_length);
5991                                 break;
5992                         }
5993                 }
5994         }
5995
5996         /*
5997          * If we couldn't find the page, or if we don't have a mode select
5998          * handler for it, send back an error to the user.
5999          */
6000         if ((page_index == NULL)
6001          || (page_index->select_handler == NULL)) {
6002                 ctl_set_invalid_field(ctsio,
6003                                       /*sks_valid*/ 1,
6004                                       /*command*/ 0,
6005                                       /*field*/ *len_used,
6006                                       /*bit_valid*/ 0,
6007                                       /*bit*/ 0);
6008                 free(ctsio->kern_data_ptr, M_CTL);
6009                 ctl_done((union ctl_io *)ctsio);
6010                 return (CTL_RETVAL_COMPLETE);
6011         }
6012
6013         if (page_index->page_code & SMPH_SPF) {
6014                 page_len_offset = 2;
6015                 page_len_size = 2;
6016         } else {
6017                 page_len_size = 1;
6018                 page_len_offset = 1;
6019         }
6020
6021         /*
6022          * If the length the initiator gives us isn't the one we specify in
6023          * the mode page header, or if they didn't specify enough data in
6024          * the CDB to avoid truncating this page, kick out the request.
6025          */
6026         if ((page_len != (page_index->page_len - page_len_offset -
6027                           page_len_size))
6028          || (*len_left < page_index->page_len)) {
6029
6030
6031                 ctl_set_invalid_field(ctsio,
6032                                       /*sks_valid*/ 1,
6033                                       /*command*/ 0,
6034                                       /*field*/ *len_used + page_len_offset,
6035                                       /*bit_valid*/ 0,
6036                                       /*bit*/ 0);
6037                 free(ctsio->kern_data_ptr, M_CTL);
6038                 ctl_done((union ctl_io *)ctsio);
6039                 return (CTL_RETVAL_COMPLETE);
6040         }
6041
6042         /*
6043          * Run through the mode page, checking to make sure that the bits
6044          * the user changed are actually legal for him to change.
6045          */
6046         for (i = 0; i < page_index->page_len; i++) {
6047                 uint8_t *user_byte, *change_mask, *current_byte;
6048                 int bad_bit;
6049                 int j;
6050
6051                 user_byte = (uint8_t *)page_header + i;
6052                 change_mask = page_index->page_data +
6053                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6054                 current_byte = page_index->page_data +
6055                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6056
6057                 /*
6058                  * Check to see whether the user set any bits in this byte
6059                  * that he is not allowed to set.
6060                  */
6061                 if ((*user_byte & ~(*change_mask)) ==
6062                     (*current_byte & ~(*change_mask)))
6063                         continue;
6064
6065                 /*
6066                  * Go through bit by bit to determine which one is illegal.
6067                  */
6068                 bad_bit = 0;
6069                 for (j = 7; j >= 0; j--) {
6070                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6071                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6072                                 bad_bit = i;
6073                                 break;
6074                         }
6075                 }
6076                 ctl_set_invalid_field(ctsio,
6077                                       /*sks_valid*/ 1,
6078                                       /*command*/ 0,
6079                                       /*field*/ *len_used + i,
6080                                       /*bit_valid*/ 1,
6081                                       /*bit*/ bad_bit);
6082                 free(ctsio->kern_data_ptr, M_CTL);
6083                 ctl_done((union ctl_io *)ctsio);
6084                 return (CTL_RETVAL_COMPLETE);
6085         }
6086
6087         /*
6088          * Decrement these before we call the page handler, since we may
6089          * end up getting called back one way or another before the handler
6090          * returns to this context.
6091          */
6092         *len_left -= page_index->page_len;
6093         *len_used += page_index->page_len;
6094
6095         retval = page_index->select_handler(ctsio, page_index,
6096                                             (uint8_t *)page_header);
6097
6098         /*
6099          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6100          * wait until this queued command completes to finish processing
6101          * the mode page.  If it returns anything other than
6102          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6103          * already set the sense information, freed the data pointer, and
6104          * completed the io for us.
6105          */
6106         if (retval != CTL_RETVAL_COMPLETE)
6107                 goto bailout_no_done;
6108
6109         /*
6110          * If the initiator sent us more than one page, parse the next one.
6111          */
6112         if (*len_left > 0)
6113                 goto do_next_page;
6114
6115         ctl_set_success(ctsio);
6116         free(ctsio->kern_data_ptr, M_CTL);
6117         ctl_done((union ctl_io *)ctsio);
6118
6119 bailout_no_done:
6120
6121         return (CTL_RETVAL_COMPLETE);
6122
6123 }
6124
6125 int
6126 ctl_mode_select(struct ctl_scsiio *ctsio)
6127 {
6128         int param_len, pf, sp;
6129         int header_size, bd_len;
6130         union ctl_modepage_info *modepage_info;
6131
6132         switch (ctsio->cdb[0]) {
6133         case MODE_SELECT_6: {
6134                 struct scsi_mode_select_6 *cdb;
6135
6136                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6137
6138                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6139                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6140                 param_len = cdb->length;
6141                 header_size = sizeof(struct scsi_mode_header_6);
6142                 break;
6143         }
6144         case MODE_SELECT_10: {
6145                 struct scsi_mode_select_10 *cdb;
6146
6147                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6148
6149                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6150                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6151                 param_len = scsi_2btoul(cdb->length);
6152                 header_size = sizeof(struct scsi_mode_header_10);
6153                 break;
6154         }
6155         default:
6156                 ctl_set_invalid_opcode(ctsio);
6157                 ctl_done((union ctl_io *)ctsio);
6158                 return (CTL_RETVAL_COMPLETE);
6159         }
6160
6161         /*
6162          * From SPC-3:
6163          * "A parameter list length of zero indicates that the Data-Out Buffer
6164          * shall be empty. This condition shall not be considered as an error."
6165          */
6166         if (param_len == 0) {
6167                 ctl_set_success(ctsio);
6168                 ctl_done((union ctl_io *)ctsio);
6169                 return (CTL_RETVAL_COMPLETE);
6170         }
6171
6172         /*
6173          * Since we'll hit this the first time through, prior to
6174          * allocation, we don't need to free a data buffer here.
6175          */
6176         if (param_len < header_size) {
6177                 ctl_set_param_len_error(ctsio);
6178                 ctl_done((union ctl_io *)ctsio);
6179                 return (CTL_RETVAL_COMPLETE);
6180         }
6181
6182         /*
6183          * Allocate the data buffer and grab the user's data.  In theory,
6184          * we shouldn't have to sanity check the parameter list length here
6185          * because the maximum size is 64K.  We should be able to malloc
6186          * that much without too many problems.
6187          */
6188         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6189                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6190                 ctsio->kern_data_len = param_len;
6191                 ctsio->kern_total_len = param_len;
6192                 ctsio->kern_data_resid = 0;
6193                 ctsio->kern_rel_offset = 0;
6194                 ctsio->kern_sg_entries = 0;
6195                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6196                 ctsio->be_move_done = ctl_config_move_done;
6197                 ctl_datamove((union ctl_io *)ctsio);
6198
6199                 return (CTL_RETVAL_COMPLETE);
6200         }
6201
6202         switch (ctsio->cdb[0]) {
6203         case MODE_SELECT_6: {
6204                 struct scsi_mode_header_6 *mh6;
6205
6206                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6207                 bd_len = mh6->blk_desc_len;
6208                 break;
6209         }
6210         case MODE_SELECT_10: {
6211                 struct scsi_mode_header_10 *mh10;
6212
6213                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6214                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6215                 break;
6216         }
6217         default:
6218                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6219                 break;
6220         }
6221
6222         if (param_len < (header_size + bd_len)) {
6223                 free(ctsio->kern_data_ptr, M_CTL);
6224                 ctl_set_param_len_error(ctsio);
6225                 ctl_done((union ctl_io *)ctsio);
6226                 return (CTL_RETVAL_COMPLETE);
6227         }
6228
6229         /*
6230          * Set the IO_CONT flag, so that if this I/O gets passed to
6231          * ctl_config_write_done(), it'll get passed back to
6232          * ctl_do_mode_select() for further processing, or completion if
6233          * we're all done.
6234          */
6235         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6236         ctsio->io_cont = ctl_do_mode_select;
6237
6238         modepage_info = (union ctl_modepage_info *)
6239                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6240         memset(modepage_info, 0, sizeof(*modepage_info));
6241         modepage_info->header.len_left = param_len - header_size - bd_len;
6242         modepage_info->header.len_used = header_size + bd_len;
6243
6244         return (ctl_do_mode_select((union ctl_io *)ctsio));
6245 }
6246
6247 int
6248 ctl_mode_sense(struct ctl_scsiio *ctsio)
6249 {
6250         struct ctl_lun *lun;
6251         int pc, page_code, dbd, llba, subpage;
6252         int alloc_len, page_len, header_len, total_len;
6253         struct scsi_mode_block_descr *block_desc;
6254         struct ctl_page_index *page_index;
6255         int control_dev;
6256
6257         dbd = 0;
6258         llba = 0;
6259         block_desc = NULL;
6260         page_index = NULL;
6261
6262         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6263
6264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6265
6266         if (lun->be_lun->lun_type != T_DIRECT)
6267                 control_dev = 1;
6268         else
6269                 control_dev = 0;
6270
6271         switch (ctsio->cdb[0]) {
6272         case MODE_SENSE_6: {
6273                 struct scsi_mode_sense_6 *cdb;
6274
6275                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6276
6277                 header_len = sizeof(struct scsi_mode_hdr_6);
6278                 if (cdb->byte2 & SMS_DBD)
6279                         dbd = 1;
6280                 else
6281                         header_len += sizeof(struct scsi_mode_block_descr);
6282
6283                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6284                 page_code = cdb->page & SMS_PAGE_CODE;
6285                 subpage = cdb->subpage;
6286                 alloc_len = cdb->length;
6287                 break;
6288         }
6289         case MODE_SENSE_10: {
6290                 struct scsi_mode_sense_10 *cdb;
6291
6292                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6293
6294                 header_len = sizeof(struct scsi_mode_hdr_10);
6295
6296                 if (cdb->byte2 & SMS_DBD)
6297                         dbd = 1;
6298                 else
6299                         header_len += sizeof(struct scsi_mode_block_descr);
6300                 if (cdb->byte2 & SMS10_LLBAA)
6301                         llba = 1;
6302                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6303                 page_code = cdb->page & SMS_PAGE_CODE;
6304                 subpage = cdb->subpage;
6305                 alloc_len = scsi_2btoul(cdb->length);
6306                 break;
6307         }
6308         default:
6309                 ctl_set_invalid_opcode(ctsio);
6310                 ctl_done((union ctl_io *)ctsio);
6311                 return (CTL_RETVAL_COMPLETE);
6312                 break; /* NOTREACHED */
6313         }
6314
6315         /*
6316          * We have to make a first pass through to calculate the size of
6317          * the pages that match the user's query.  Then we allocate enough
6318          * memory to hold it, and actually copy the data into the buffer.
6319          */
6320         switch (page_code) {
6321         case SMS_ALL_PAGES_PAGE: {
6322                 int i;
6323
6324                 page_len = 0;
6325
6326                 /*
6327                  * At the moment, values other than 0 and 0xff here are
6328                  * reserved according to SPC-3.
6329                  */
6330                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6331                  && (subpage != SMS_SUBPAGE_ALL)) {
6332                         ctl_set_invalid_field(ctsio,
6333                                               /*sks_valid*/ 1,
6334                                               /*command*/ 1,
6335                                               /*field*/ 3,
6336                                               /*bit_valid*/ 0,
6337                                               /*bit*/ 0);
6338                         ctl_done((union ctl_io *)ctsio);
6339                         return (CTL_RETVAL_COMPLETE);
6340                 }
6341
6342                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6343                         if ((control_dev != 0)
6344                          && (lun->mode_pages.index[i].page_flags &
6345                              CTL_PAGE_FLAG_DISK_ONLY))
6346                                 continue;
6347
6348                         /*
6349                          * We don't use this subpage if the user didn't
6350                          * request all subpages.
6351                          */
6352                         if ((lun->mode_pages.index[i].subpage != 0)
6353                          && (subpage == SMS_SUBPAGE_PAGE_0))
6354                                 continue;
6355
6356 #if 0
6357                         printf("found page %#x len %d\n",
6358                                lun->mode_pages.index[i].page_code &
6359                                SMPH_PC_MASK,
6360                                lun->mode_pages.index[i].page_len);
6361 #endif
6362                         page_len += lun->mode_pages.index[i].page_len;
6363                 }
6364                 break;
6365         }
6366         default: {
6367                 int i;
6368
6369                 page_len = 0;
6370
6371                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6372                         /* Look for the right page code */
6373                         if ((lun->mode_pages.index[i].page_code &
6374                              SMPH_PC_MASK) != page_code)
6375                                 continue;
6376
6377                         /* Look for the right subpage or the subpage wildcard*/
6378                         if ((lun->mode_pages.index[i].subpage != subpage)
6379                          && (subpage != SMS_SUBPAGE_ALL))
6380                                 continue;
6381
6382                         /* Make sure the page is supported for this dev type */
6383                         if ((control_dev != 0)
6384                          && (lun->mode_pages.index[i].page_flags &
6385                              CTL_PAGE_FLAG_DISK_ONLY))
6386                                 continue;
6387
6388 #if 0
6389                         printf("found page %#x len %d\n",
6390                                lun->mode_pages.index[i].page_code &
6391                                SMPH_PC_MASK,
6392                                lun->mode_pages.index[i].page_len);
6393 #endif
6394
6395                         page_len += lun->mode_pages.index[i].page_len;
6396                 }
6397
6398                 if (page_len == 0) {
6399                         ctl_set_invalid_field(ctsio,
6400                                               /*sks_valid*/ 1,
6401                                               /*command*/ 1,
6402                                               /*field*/ 2,
6403                                               /*bit_valid*/ 1,
6404                                               /*bit*/ 5);
6405                         ctl_done((union ctl_io *)ctsio);
6406                         return (CTL_RETVAL_COMPLETE);
6407                 }
6408                 break;
6409         }
6410         }
6411
6412         total_len = header_len + page_len;
6413 #if 0
6414         printf("header_len = %d, page_len = %d, total_len = %d\n",
6415                header_len, page_len, total_len);
6416 #endif
6417
6418         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6419         ctsio->kern_sg_entries = 0;
6420         ctsio->kern_data_resid = 0;
6421         ctsio->kern_rel_offset = 0;
6422         if (total_len < alloc_len) {
6423                 ctsio->residual = alloc_len - total_len;
6424                 ctsio->kern_data_len = total_len;
6425                 ctsio->kern_total_len = total_len;
6426         } else {
6427                 ctsio->residual = 0;
6428                 ctsio->kern_data_len = alloc_len;
6429                 ctsio->kern_total_len = alloc_len;
6430         }
6431
6432         switch (ctsio->cdb[0]) {
6433         case MODE_SENSE_6: {
6434                 struct scsi_mode_hdr_6 *header;
6435
6436                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6437
6438                 header->datalen = MIN(total_len - 1, 254);
6439                 if (control_dev == 0) {
6440                         header->dev_specific = 0x10; /* DPOFUA */
6441                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6442                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6443                             .eca_and_aen & SCP_SWP) != 0)
6444                                     header->dev_specific |= 0x80; /* WP */
6445                 }
6446                 if (dbd)
6447                         header->block_descr_len = 0;
6448                 else
6449                         header->block_descr_len =
6450                                 sizeof(struct scsi_mode_block_descr);
6451                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6452                 break;
6453         }
6454         case MODE_SENSE_10: {
6455                 struct scsi_mode_hdr_10 *header;
6456                 int datalen;
6457
6458                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6459
6460                 datalen = MIN(total_len - 2, 65533);
6461                 scsi_ulto2b(datalen, header->datalen);
6462                 if (control_dev == 0) {
6463                         header->dev_specific = 0x10; /* DPOFUA */
6464                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6465                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6466                             .eca_and_aen & SCP_SWP) != 0)
6467                                     header->dev_specific |= 0x80; /* WP */
6468                 }
6469                 if (dbd)
6470                         scsi_ulto2b(0, header->block_descr_len);
6471                 else
6472                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6473                                     header->block_descr_len);
6474                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6475                 break;
6476         }
6477         default:
6478                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6479                 break; /* NOTREACHED */
6480         }
6481
6482         /*
6483          * If we've got a disk, use its blocksize in the block
6484          * descriptor.  Otherwise, just set it to 0.
6485          */
6486         if (dbd == 0) {
6487                 if (control_dev == 0)
6488                         scsi_ulto3b(lun->be_lun->blocksize,
6489                                     block_desc->block_len);
6490                 else
6491                         scsi_ulto3b(0, block_desc->block_len);
6492         }
6493
6494         switch (page_code) {
6495         case SMS_ALL_PAGES_PAGE: {
6496                 int i, data_used;
6497
6498                 data_used = header_len;
6499                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6500                         struct ctl_page_index *page_index;
6501
6502                         page_index = &lun->mode_pages.index[i];
6503
6504                         if ((control_dev != 0)
6505                          && (page_index->page_flags &
6506                             CTL_PAGE_FLAG_DISK_ONLY))
6507                                 continue;
6508
6509                         /*
6510                          * We don't use this subpage if the user didn't
6511                          * request all subpages.  We already checked (above)
6512                          * to make sure the user only specified a subpage
6513                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6514                          */
6515                         if ((page_index->subpage != 0)
6516                          && (subpage == SMS_SUBPAGE_PAGE_0))
6517                                 continue;
6518
6519                         /*
6520                          * Call the handler, if it exists, to update the
6521                          * page to the latest values.
6522                          */
6523                         if (page_index->sense_handler != NULL)
6524                                 page_index->sense_handler(ctsio, page_index,pc);
6525
6526                         memcpy(ctsio->kern_data_ptr + data_used,
6527                                page_index->page_data +
6528                                (page_index->page_len * pc),
6529                                page_index->page_len);
6530                         data_used += page_index->page_len;
6531                 }
6532                 break;
6533         }
6534         default: {
6535                 int i, data_used;
6536
6537                 data_used = header_len;
6538
6539                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6540                         struct ctl_page_index *page_index;
6541
6542                         page_index = &lun->mode_pages.index[i];
6543
6544                         /* Look for the right page code */
6545                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6546                                 continue;
6547
6548                         /* Look for the right subpage or the subpage wildcard*/
6549                         if ((page_index->subpage != subpage)
6550                          && (subpage != SMS_SUBPAGE_ALL))
6551                                 continue;
6552
6553                         /* Make sure the page is supported for this dev type */
6554                         if ((control_dev != 0)
6555                          && (page_index->page_flags &
6556                              CTL_PAGE_FLAG_DISK_ONLY))
6557                                 continue;
6558
6559                         /*
6560                          * Call the handler, if it exists, to update the
6561                          * page to the latest values.
6562                          */
6563                         if (page_index->sense_handler != NULL)
6564                                 page_index->sense_handler(ctsio, page_index,pc);
6565
6566                         memcpy(ctsio->kern_data_ptr + data_used,
6567                                page_index->page_data +
6568                                (page_index->page_len * pc),
6569                                page_index->page_len);
6570                         data_used += page_index->page_len;
6571                 }
6572                 break;
6573         }
6574         }
6575
6576         ctl_set_success(ctsio);
6577         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6578         ctsio->be_move_done = ctl_config_move_done;
6579         ctl_datamove((union ctl_io *)ctsio);
6580         return (CTL_RETVAL_COMPLETE);
6581 }
6582
6583 int
6584 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6585                                struct ctl_page_index *page_index,
6586                                int pc)
6587 {
6588         struct ctl_lun *lun;
6589         struct scsi_log_param_header *phdr;
6590         uint8_t *data;
6591         uint64_t val;
6592
6593         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6594         data = page_index->page_data;
6595
6596         if (lun->backend->lun_attr != NULL &&
6597             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6598              != UINT64_MAX) {
6599                 phdr = (struct scsi_log_param_header *)data;
6600                 scsi_ulto2b(0x0001, phdr->param_code);
6601                 phdr->param_control = SLP_LBIN | SLP_LP;
6602                 phdr->param_len = 8;
6603                 data = (uint8_t *)(phdr + 1);
6604                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6605                 data[4] = 0x02; /* per-pool */
6606                 data += phdr->param_len;
6607         }
6608
6609         if (lun->backend->lun_attr != NULL &&
6610             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6611              != UINT64_MAX) {
6612                 phdr = (struct scsi_log_param_header *)data;
6613                 scsi_ulto2b(0x0002, phdr->param_code);
6614                 phdr->param_control = SLP_LBIN | SLP_LP;
6615                 phdr->param_len = 8;
6616                 data = (uint8_t *)(phdr + 1);
6617                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6618                 data[4] = 0x01; /* per-LUN */
6619                 data += phdr->param_len;
6620         }
6621
6622         if (lun->backend->lun_attr != NULL &&
6623             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6624              != UINT64_MAX) {
6625                 phdr = (struct scsi_log_param_header *)data;
6626                 scsi_ulto2b(0x00f1, phdr->param_code);
6627                 phdr->param_control = SLP_LBIN | SLP_LP;
6628                 phdr->param_len = 8;
6629                 data = (uint8_t *)(phdr + 1);
6630                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6631                 data[4] = 0x02; /* per-pool */
6632                 data += phdr->param_len;
6633         }
6634
6635         if (lun->backend->lun_attr != NULL &&
6636             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6637              != UINT64_MAX) {
6638                 phdr = (struct scsi_log_param_header *)data;
6639                 scsi_ulto2b(0x00f2, phdr->param_code);
6640                 phdr->param_control = SLP_LBIN | SLP_LP;
6641                 phdr->param_len = 8;
6642                 data = (uint8_t *)(phdr + 1);
6643                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6644                 data[4] = 0x02; /* per-pool */
6645                 data += phdr->param_len;
6646         }
6647
6648         page_index->page_len = data - page_index->page_data;
6649         return (0);
6650 }
6651
6652 int
6653 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6654                                struct ctl_page_index *page_index,
6655                                int pc)
6656 {
6657         struct ctl_lun *lun;
6658         struct stat_page *data;
6659         uint64_t rn, wn, rb, wb;
6660         struct bintime rt, wt;
6661         int i;
6662
6663         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6664         data = (struct stat_page *)page_index->page_data;
6665
6666         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6667         data->sap.hdr.param_control = SLP_LBIN;
6668         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6669             sizeof(struct scsi_log_param_header);
6670         rn = wn = rb = wb = 0;
6671         bintime_clear(&rt);
6672         bintime_clear(&wt);
6673         for (i = 0; i < CTL_MAX_PORTS; i++) {
6674                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6675                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6676                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6677                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6678                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6679                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6680         }
6681         scsi_u64to8b(rn, data->sap.read_num);
6682         scsi_u64to8b(wn, data->sap.write_num);
6683         if (lun->stats.blocksize > 0) {
6684                 scsi_u64to8b(wb / lun->stats.blocksize,
6685                     data->sap.recvieved_lba);
6686                 scsi_u64to8b(rb / lun->stats.blocksize,
6687                     data->sap.transmitted_lba);
6688         }
6689         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6690             data->sap.read_int);
6691         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6692             data->sap.write_int);
6693         scsi_u64to8b(0, data->sap.weighted_num);
6694         scsi_u64to8b(0, data->sap.weighted_int);
6695         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6696         data->it.hdr.param_control = SLP_LBIN;
6697         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6698             sizeof(struct scsi_log_param_header);
6699 #ifdef CTL_TIME_IO
6700         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6701 #endif
6702         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6703         data->it.hdr.param_control = SLP_LBIN;
6704         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6705             sizeof(struct scsi_log_param_header);
6706         scsi_ulto4b(3, data->ti.exponent);
6707         scsi_ulto4b(1, data->ti.integer);
6708
6709         page_index->page_len = sizeof(*data);
6710         return (0);
6711 }
6712
6713 int
6714 ctl_log_sense(struct ctl_scsiio *ctsio)
6715 {
6716         struct ctl_lun *lun;
6717         int i, pc, page_code, subpage;
6718         int alloc_len, total_len;
6719         struct ctl_page_index *page_index;
6720         struct scsi_log_sense *cdb;
6721         struct scsi_log_header *header;
6722
6723         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6724
6725         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6726         cdb = (struct scsi_log_sense *)ctsio->cdb;
6727         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6728         page_code = cdb->page & SLS_PAGE_CODE;
6729         subpage = cdb->subpage;
6730         alloc_len = scsi_2btoul(cdb->length);
6731
6732         page_index = NULL;
6733         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6734                 page_index = &lun->log_pages.index[i];
6735
6736                 /* Look for the right page code */
6737                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6738                         continue;
6739
6740                 /* Look for the right subpage or the subpage wildcard*/
6741                 if (page_index->subpage != subpage)
6742                         continue;
6743
6744                 break;
6745         }
6746         if (i >= CTL_NUM_LOG_PAGES) {
6747                 ctl_set_invalid_field(ctsio,
6748                                       /*sks_valid*/ 1,
6749                                       /*command*/ 1,
6750                                       /*field*/ 2,
6751                                       /*bit_valid*/ 0,
6752                                       /*bit*/ 0);
6753                 ctl_done((union ctl_io *)ctsio);
6754                 return (CTL_RETVAL_COMPLETE);
6755         }
6756
6757         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6758
6759         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6760         ctsio->kern_sg_entries = 0;
6761         ctsio->kern_data_resid = 0;
6762         ctsio->kern_rel_offset = 0;
6763         if (total_len < alloc_len) {
6764                 ctsio->residual = alloc_len - total_len;
6765                 ctsio->kern_data_len = total_len;
6766                 ctsio->kern_total_len = total_len;
6767         } else {
6768                 ctsio->residual = 0;
6769                 ctsio->kern_data_len = alloc_len;
6770                 ctsio->kern_total_len = alloc_len;
6771         }
6772
6773         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6774         header->page = page_index->page_code;
6775         if (page_index->subpage) {
6776                 header->page |= SL_SPF;
6777                 header->subpage = page_index->subpage;
6778         }
6779         scsi_ulto2b(page_index->page_len, header->datalen);
6780
6781         /*
6782          * Call the handler, if it exists, to update the
6783          * page to the latest values.
6784          */
6785         if (page_index->sense_handler != NULL)
6786                 page_index->sense_handler(ctsio, page_index, pc);
6787
6788         memcpy(header + 1, page_index->page_data, page_index->page_len);
6789
6790         ctl_set_success(ctsio);
6791         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6792         ctsio->be_move_done = ctl_config_move_done;
6793         ctl_datamove((union ctl_io *)ctsio);
6794         return (CTL_RETVAL_COMPLETE);
6795 }
6796
6797 int
6798 ctl_read_capacity(struct ctl_scsiio *ctsio)
6799 {
6800         struct scsi_read_capacity *cdb;
6801         struct scsi_read_capacity_data *data;
6802         struct ctl_lun *lun;
6803         uint32_t lba;
6804
6805         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6806
6807         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6808
6809         lba = scsi_4btoul(cdb->addr);
6810         if (((cdb->pmi & SRC_PMI) == 0)
6811          && (lba != 0)) {
6812                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6813                                       /*sks_valid*/ 1,
6814                                       /*command*/ 1,
6815                                       /*field*/ 2,
6816                                       /*bit_valid*/ 0,
6817                                       /*bit*/ 0);
6818                 ctl_done((union ctl_io *)ctsio);
6819                 return (CTL_RETVAL_COMPLETE);
6820         }
6821
6822         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6823
6824         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6825         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6826         ctsio->residual = 0;
6827         ctsio->kern_data_len = sizeof(*data);
6828         ctsio->kern_total_len = sizeof(*data);
6829         ctsio->kern_data_resid = 0;
6830         ctsio->kern_rel_offset = 0;
6831         ctsio->kern_sg_entries = 0;
6832
6833         /*
6834          * If the maximum LBA is greater than 0xfffffffe, the user must
6835          * issue a SERVICE ACTION IN (16) command, with the read capacity
6836          * serivce action set.
6837          */
6838         if (lun->be_lun->maxlba > 0xfffffffe)
6839                 scsi_ulto4b(0xffffffff, data->addr);
6840         else
6841                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6842
6843         /*
6844          * XXX KDM this may not be 512 bytes...
6845          */
6846         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6847
6848         ctl_set_success(ctsio);
6849         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6850         ctsio->be_move_done = ctl_config_move_done;
6851         ctl_datamove((union ctl_io *)ctsio);
6852         return (CTL_RETVAL_COMPLETE);
6853 }
6854
6855 int
6856 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6857 {
6858         struct scsi_read_capacity_16 *cdb;
6859         struct scsi_read_capacity_data_long *data;
6860         struct ctl_lun *lun;
6861         uint64_t lba;
6862         uint32_t alloc_len;
6863
6864         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6865
6866         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6867
6868         alloc_len = scsi_4btoul(cdb->alloc_len);
6869         lba = scsi_8btou64(cdb->addr);
6870
6871         if ((cdb->reladr & SRC16_PMI)
6872          && (lba != 0)) {
6873                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6874                                       /*sks_valid*/ 1,
6875                                       /*command*/ 1,
6876                                       /*field*/ 2,
6877                                       /*bit_valid*/ 0,
6878                                       /*bit*/ 0);
6879                 ctl_done((union ctl_io *)ctsio);
6880                 return (CTL_RETVAL_COMPLETE);
6881         }
6882
6883         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6884
6885         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6886         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6887
6888         if (sizeof(*data) < alloc_len) {
6889                 ctsio->residual = alloc_len - sizeof(*data);
6890                 ctsio->kern_data_len = sizeof(*data);
6891                 ctsio->kern_total_len = sizeof(*data);
6892         } else {
6893                 ctsio->residual = 0;
6894                 ctsio->kern_data_len = alloc_len;
6895                 ctsio->kern_total_len = alloc_len;
6896         }
6897         ctsio->kern_data_resid = 0;
6898         ctsio->kern_rel_offset = 0;
6899         ctsio->kern_sg_entries = 0;
6900
6901         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6902         /* XXX KDM this may not be 512 bytes... */
6903         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6904         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6905         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6906         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6907                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6908
6909         ctl_set_success(ctsio);
6910         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6911         ctsio->be_move_done = ctl_config_move_done;
6912         ctl_datamove((union ctl_io *)ctsio);
6913         return (CTL_RETVAL_COMPLETE);
6914 }
6915
6916 int
6917 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6918 {
6919         struct scsi_get_lba_status *cdb;
6920         struct scsi_get_lba_status_data *data;
6921         struct ctl_lun *lun;
6922         struct ctl_lba_len_flags *lbalen;
6923         uint64_t lba;
6924         uint32_t alloc_len, total_len;
6925         int retval;
6926
6927         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6928
6929         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6930         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6931         lba = scsi_8btou64(cdb->addr);
6932         alloc_len = scsi_4btoul(cdb->alloc_len);
6933
6934         if (lba > lun->be_lun->maxlba) {
6935                 ctl_set_lba_out_of_range(ctsio);
6936                 ctl_done((union ctl_io *)ctsio);
6937                 return (CTL_RETVAL_COMPLETE);
6938         }
6939
6940         total_len = sizeof(*data) + sizeof(data->descr[0]);
6941         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6942         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6943
6944         if (total_len < alloc_len) {
6945                 ctsio->residual = alloc_len - total_len;
6946                 ctsio->kern_data_len = total_len;
6947                 ctsio->kern_total_len = total_len;
6948         } else {
6949                 ctsio->residual = 0;
6950                 ctsio->kern_data_len = alloc_len;
6951                 ctsio->kern_total_len = alloc_len;
6952         }
6953         ctsio->kern_data_resid = 0;
6954         ctsio->kern_rel_offset = 0;
6955         ctsio->kern_sg_entries = 0;
6956
6957         /* Fill dummy data in case backend can't tell anything. */
6958         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6959         scsi_u64to8b(lba, data->descr[0].addr);
6960         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6961             data->descr[0].length);
6962         data->descr[0].status = 0; /* Mapped or unknown. */
6963
6964         ctl_set_success(ctsio);
6965         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6966         ctsio->be_move_done = ctl_config_move_done;
6967
6968         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6969         lbalen->lba = lba;
6970         lbalen->len = total_len;
6971         lbalen->flags = 0;
6972         retval = lun->backend->config_read((union ctl_io *)ctsio);
6973         return (CTL_RETVAL_COMPLETE);
6974 }
6975
6976 int
6977 ctl_read_defect(struct ctl_scsiio *ctsio)
6978 {
6979         struct scsi_read_defect_data_10 *ccb10;
6980         struct scsi_read_defect_data_12 *ccb12;
6981         struct scsi_read_defect_data_hdr_10 *data10;
6982         struct scsi_read_defect_data_hdr_12 *data12;
6983         uint32_t alloc_len, data_len;
6984         uint8_t format;
6985
6986         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6987
6988         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6989                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6990                 format = ccb10->format;
6991                 alloc_len = scsi_2btoul(ccb10->alloc_length);
6992                 data_len = sizeof(*data10);
6993         } else {
6994                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6995                 format = ccb12->format;
6996                 alloc_len = scsi_4btoul(ccb12->alloc_length);
6997                 data_len = sizeof(*data12);
6998         }
6999         if (alloc_len == 0) {
7000                 ctl_set_success(ctsio);
7001                 ctl_done((union ctl_io *)ctsio);
7002                 return (CTL_RETVAL_COMPLETE);
7003         }
7004
7005         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7006         if (data_len < alloc_len) {
7007                 ctsio->residual = alloc_len - data_len;
7008                 ctsio->kern_data_len = data_len;
7009                 ctsio->kern_total_len = data_len;
7010         } else {
7011                 ctsio->residual = 0;
7012                 ctsio->kern_data_len = alloc_len;
7013                 ctsio->kern_total_len = alloc_len;
7014         }
7015         ctsio->kern_data_resid = 0;
7016         ctsio->kern_rel_offset = 0;
7017         ctsio->kern_sg_entries = 0;
7018
7019         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7020                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7021                     ctsio->kern_data_ptr;
7022                 data10->format = format;
7023                 scsi_ulto2b(0, data10->length);
7024         } else {
7025                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7026                     ctsio->kern_data_ptr;
7027                 data12->format = format;
7028                 scsi_ulto2b(0, data12->generation);
7029                 scsi_ulto4b(0, data12->length);
7030         }
7031
7032         ctl_set_success(ctsio);
7033         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7034         ctsio->be_move_done = ctl_config_move_done;
7035         ctl_datamove((union ctl_io *)ctsio);
7036         return (CTL_RETVAL_COMPLETE);
7037 }
7038
7039 int
7040 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7041 {
7042         struct scsi_maintenance_in *cdb;
7043         int retval;
7044         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7045         int num_target_port_groups, num_target_ports;
7046         struct ctl_lun *lun;
7047         struct ctl_softc *softc;
7048         struct ctl_port *port;
7049         struct scsi_target_group_data *rtg_ptr;
7050         struct scsi_target_group_data_extended *rtg_ext_ptr;
7051         struct scsi_target_port_group_descriptor *tpg_desc;
7052
7053         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7054
7055         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7056         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7057         softc = lun->ctl_softc;
7058
7059         retval = CTL_RETVAL_COMPLETE;
7060
7061         switch (cdb->byte2 & STG_PDF_MASK) {
7062         case STG_PDF_LENGTH:
7063                 ext = 0;
7064                 break;
7065         case STG_PDF_EXTENDED:
7066                 ext = 1;
7067                 break;
7068         default:
7069                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7070                                       /*sks_valid*/ 1,
7071                                       /*command*/ 1,
7072                                       /*field*/ 2,
7073                                       /*bit_valid*/ 1,
7074                                       /*bit*/ 5);
7075                 ctl_done((union ctl_io *)ctsio);
7076                 return(retval);
7077         }
7078
7079         if (softc->is_single)
7080                 num_target_port_groups = 1;
7081         else
7082                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7083         num_target_ports = 0;
7084         mtx_lock(&softc->ctl_lock);
7085         STAILQ_FOREACH(port, &softc->port_list, links) {
7086                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7087                         continue;
7088                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7089                         continue;
7090                 num_target_ports++;
7091         }
7092         mtx_unlock(&softc->ctl_lock);
7093
7094         if (ext)
7095                 total_len = sizeof(struct scsi_target_group_data_extended);
7096         else
7097                 total_len = sizeof(struct scsi_target_group_data);
7098         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7099                 num_target_port_groups +
7100             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7101
7102         alloc_len = scsi_4btoul(cdb->length);
7103
7104         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7105
7106         ctsio->kern_sg_entries = 0;
7107
7108         if (total_len < alloc_len) {
7109                 ctsio->residual = alloc_len - total_len;
7110                 ctsio->kern_data_len = total_len;
7111                 ctsio->kern_total_len = total_len;
7112         } else {
7113                 ctsio->residual = 0;
7114                 ctsio->kern_data_len = alloc_len;
7115                 ctsio->kern_total_len = alloc_len;
7116         }
7117         ctsio->kern_data_resid = 0;
7118         ctsio->kern_rel_offset = 0;
7119
7120         if (ext) {
7121                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7122                     ctsio->kern_data_ptr;
7123                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7124                 rtg_ext_ptr->format_type = 0x10;
7125                 rtg_ext_ptr->implicit_transition_time = 0;
7126                 tpg_desc = &rtg_ext_ptr->groups[0];
7127         } else {
7128                 rtg_ptr = (struct scsi_target_group_data *)
7129                     ctsio->kern_data_ptr;
7130                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7131                 tpg_desc = &rtg_ptr->groups[0];
7132         }
7133
7134         mtx_lock(&softc->ctl_lock);
7135         pg = softc->port_min / softc->port_cnt;
7136         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7137                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7138         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7139                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7140         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7141                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7142         else
7143                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7144         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7145                 os = gs;
7146                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7147         } else
7148                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7149         for (g = 0; g < num_target_port_groups; g++) {
7150                 tpg_desc->pref_state = (g == pg) ? gs : os;
7151                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7152                     TPG_U_SUP | TPG_T_SUP;
7153                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7154                 tpg_desc->status = TPG_IMPLICIT;
7155                 pc = 0;
7156                 STAILQ_FOREACH(port, &softc->port_list, links) {
7157                         if (port->targ_port < g * softc->port_cnt ||
7158                             port->targ_port >= (g + 1) * softc->port_cnt)
7159                                 continue;
7160                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7161                                 continue;
7162                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7163                                 continue;
7164                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7165                             relative_target_port_identifier);
7166                         pc++;
7167                 }
7168                 tpg_desc->target_port_count = pc;
7169                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7170                     &tpg_desc->descriptors[pc];
7171         }
7172         mtx_unlock(&softc->ctl_lock);
7173
7174         ctl_set_success(ctsio);
7175         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7176         ctsio->be_move_done = ctl_config_move_done;
7177         ctl_datamove((union ctl_io *)ctsio);
7178         return(retval);
7179 }
7180
7181 int
7182 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7183 {
7184         struct ctl_lun *lun;
7185         struct scsi_report_supported_opcodes *cdb;
7186         const struct ctl_cmd_entry *entry, *sentry;
7187         struct scsi_report_supported_opcodes_all *all;
7188         struct scsi_report_supported_opcodes_descr *descr;
7189         struct scsi_report_supported_opcodes_one *one;
7190         int retval;
7191         int alloc_len, total_len;
7192         int opcode, service_action, i, j, num;
7193
7194         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7195
7196         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7197         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7198
7199         retval = CTL_RETVAL_COMPLETE;
7200
7201         opcode = cdb->requested_opcode;
7202         service_action = scsi_2btoul(cdb->requested_service_action);
7203         switch (cdb->options & RSO_OPTIONS_MASK) {
7204         case RSO_OPTIONS_ALL:
7205                 num = 0;
7206                 for (i = 0; i < 256; i++) {
7207                         entry = &ctl_cmd_table[i];
7208                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7209                                 for (j = 0; j < 32; j++) {
7210                                         sentry = &((const struct ctl_cmd_entry *)
7211                                             entry->execute)[j];
7212                                         if (ctl_cmd_applicable(
7213                                             lun->be_lun->lun_type, sentry))
7214                                                 num++;
7215                                 }
7216                         } else {
7217                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7218                                     entry))
7219                                         num++;
7220                         }
7221                 }
7222                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7223                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7224                 break;
7225         case RSO_OPTIONS_OC:
7226                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7227                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7228                                               /*sks_valid*/ 1,
7229                                               /*command*/ 1,
7230                                               /*field*/ 2,
7231                                               /*bit_valid*/ 1,
7232                                               /*bit*/ 2);
7233                         ctl_done((union ctl_io *)ctsio);
7234                         return (CTL_RETVAL_COMPLETE);
7235                 }
7236                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7237                 break;
7238         case RSO_OPTIONS_OC_SA:
7239                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7240                     service_action >= 32) {
7241                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7242                                               /*sks_valid*/ 1,
7243                                               /*command*/ 1,
7244                                               /*field*/ 2,
7245                                               /*bit_valid*/ 1,
7246                                               /*bit*/ 2);
7247                         ctl_done((union ctl_io *)ctsio);
7248                         return (CTL_RETVAL_COMPLETE);
7249                 }
7250                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7251                 break;
7252         default:
7253                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7254                                       /*sks_valid*/ 1,
7255                                       /*command*/ 1,
7256                                       /*field*/ 2,
7257                                       /*bit_valid*/ 1,
7258                                       /*bit*/ 2);
7259                 ctl_done((union ctl_io *)ctsio);
7260                 return (CTL_RETVAL_COMPLETE);
7261         }
7262
7263         alloc_len = scsi_4btoul(cdb->length);
7264
7265         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7266
7267         ctsio->kern_sg_entries = 0;
7268
7269         if (total_len < alloc_len) {
7270                 ctsio->residual = alloc_len - total_len;
7271                 ctsio->kern_data_len = total_len;
7272                 ctsio->kern_total_len = total_len;
7273         } else {
7274                 ctsio->residual = 0;
7275                 ctsio->kern_data_len = alloc_len;
7276                 ctsio->kern_total_len = alloc_len;
7277         }
7278         ctsio->kern_data_resid = 0;
7279         ctsio->kern_rel_offset = 0;
7280
7281         switch (cdb->options & RSO_OPTIONS_MASK) {
7282         case RSO_OPTIONS_ALL:
7283                 all = (struct scsi_report_supported_opcodes_all *)
7284                     ctsio->kern_data_ptr;
7285                 num = 0;
7286                 for (i = 0; i < 256; i++) {
7287                         entry = &ctl_cmd_table[i];
7288                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7289                                 for (j = 0; j < 32; j++) {
7290                                         sentry = &((const struct ctl_cmd_entry *)
7291                                             entry->execute)[j];
7292                                         if (!ctl_cmd_applicable(
7293                                             lun->be_lun->lun_type, sentry))
7294                                                 continue;
7295                                         descr = &all->descr[num++];
7296                                         descr->opcode = i;
7297                                         scsi_ulto2b(j, descr->service_action);
7298                                         descr->flags = RSO_SERVACTV;
7299                                         scsi_ulto2b(sentry->length,
7300                                             descr->cdb_length);
7301                                 }
7302                         } else {
7303                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7304                                     entry))
7305                                         continue;
7306                                 descr = &all->descr[num++];
7307                                 descr->opcode = i;
7308                                 scsi_ulto2b(0, descr->service_action);
7309                                 descr->flags = 0;
7310                                 scsi_ulto2b(entry->length, descr->cdb_length);
7311                         }
7312                 }
7313                 scsi_ulto4b(
7314                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7315                     all->length);
7316                 break;
7317         case RSO_OPTIONS_OC:
7318                 one = (struct scsi_report_supported_opcodes_one *)
7319                     ctsio->kern_data_ptr;
7320                 entry = &ctl_cmd_table[opcode];
7321                 goto fill_one;
7322         case RSO_OPTIONS_OC_SA:
7323                 one = (struct scsi_report_supported_opcodes_one *)
7324                     ctsio->kern_data_ptr;
7325                 entry = &ctl_cmd_table[opcode];
7326                 entry = &((const struct ctl_cmd_entry *)
7327                     entry->execute)[service_action];
7328 fill_one:
7329                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7330                         one->support = 3;
7331                         scsi_ulto2b(entry->length, one->cdb_length);
7332                         one->cdb_usage[0] = opcode;
7333                         memcpy(&one->cdb_usage[1], entry->usage,
7334                             entry->length - 1);
7335                 } else
7336                         one->support = 1;
7337                 break;
7338         }
7339
7340         ctl_set_success(ctsio);
7341         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7342         ctsio->be_move_done = ctl_config_move_done;
7343         ctl_datamove((union ctl_io *)ctsio);
7344         return(retval);
7345 }
7346
7347 int
7348 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7349 {
7350         struct scsi_report_supported_tmf *cdb;
7351         struct scsi_report_supported_tmf_data *data;
7352         int retval;
7353         int alloc_len, total_len;
7354
7355         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7356
7357         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7358
7359         retval = CTL_RETVAL_COMPLETE;
7360
7361         total_len = sizeof(struct scsi_report_supported_tmf_data);
7362         alloc_len = scsi_4btoul(cdb->length);
7363
7364         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7365
7366         ctsio->kern_sg_entries = 0;
7367
7368         if (total_len < alloc_len) {
7369                 ctsio->residual = alloc_len - total_len;
7370                 ctsio->kern_data_len = total_len;
7371                 ctsio->kern_total_len = total_len;
7372         } else {
7373                 ctsio->residual = 0;
7374                 ctsio->kern_data_len = alloc_len;
7375                 ctsio->kern_total_len = alloc_len;
7376         }
7377         ctsio->kern_data_resid = 0;
7378         ctsio->kern_rel_offset = 0;
7379
7380         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7381         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7382             RST_TRS;
7383         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7384
7385         ctl_set_success(ctsio);
7386         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7387         ctsio->be_move_done = ctl_config_move_done;
7388         ctl_datamove((union ctl_io *)ctsio);
7389         return (retval);
7390 }
7391
7392 int
7393 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7394 {
7395         struct scsi_report_timestamp *cdb;
7396         struct scsi_report_timestamp_data *data;
7397         struct timeval tv;
7398         int64_t timestamp;
7399         int retval;
7400         int alloc_len, total_len;
7401
7402         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7403
7404         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7405
7406         retval = CTL_RETVAL_COMPLETE;
7407
7408         total_len = sizeof(struct scsi_report_timestamp_data);
7409         alloc_len = scsi_4btoul(cdb->length);
7410
7411         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7412
7413         ctsio->kern_sg_entries = 0;
7414
7415         if (total_len < alloc_len) {
7416                 ctsio->residual = alloc_len - total_len;
7417                 ctsio->kern_data_len = total_len;
7418                 ctsio->kern_total_len = total_len;
7419         } else {
7420                 ctsio->residual = 0;
7421                 ctsio->kern_data_len = alloc_len;
7422                 ctsio->kern_total_len = alloc_len;
7423         }
7424         ctsio->kern_data_resid = 0;
7425         ctsio->kern_rel_offset = 0;
7426
7427         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7428         scsi_ulto2b(sizeof(*data) - 2, data->length);
7429         data->origin = RTS_ORIG_OUTSIDE;
7430         getmicrotime(&tv);
7431         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7432         scsi_ulto4b(timestamp >> 16, data->timestamp);
7433         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7434
7435         ctl_set_success(ctsio);
7436         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7437         ctsio->be_move_done = ctl_config_move_done;
7438         ctl_datamove((union ctl_io *)ctsio);
7439         return (retval);
7440 }
7441
7442 int
7443 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7444 {
7445         struct scsi_per_res_in *cdb;
7446         int alloc_len, total_len = 0;
7447         /* struct scsi_per_res_in_rsrv in_data; */
7448         struct ctl_lun *lun;
7449         struct ctl_softc *softc;
7450         uint64_t key;
7451
7452         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7453
7454         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7455
7456         alloc_len = scsi_2btoul(cdb->length);
7457
7458         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7459         softc = lun->ctl_softc;
7460
7461 retry:
7462         mtx_lock(&lun->lun_lock);
7463         switch (cdb->action) {
7464         case SPRI_RK: /* read keys */
7465                 total_len = sizeof(struct scsi_per_res_in_keys) +
7466                         lun->pr_key_count *
7467                         sizeof(struct scsi_per_res_key);
7468                 break;
7469         case SPRI_RR: /* read reservation */
7470                 if (lun->flags & CTL_LUN_PR_RESERVED)
7471                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7472                 else
7473                         total_len = sizeof(struct scsi_per_res_in_header);
7474                 break;
7475         case SPRI_RC: /* report capabilities */
7476                 total_len = sizeof(struct scsi_per_res_cap);
7477                 break;
7478         case SPRI_RS: /* read full status */
7479                 total_len = sizeof(struct scsi_per_res_in_header) +
7480                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7481                     lun->pr_key_count;
7482                 break;
7483         default:
7484                 panic("Invalid PR type %x", cdb->action);
7485         }
7486         mtx_unlock(&lun->lun_lock);
7487
7488         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7489
7490         if (total_len < alloc_len) {
7491                 ctsio->residual = alloc_len - total_len;
7492                 ctsio->kern_data_len = total_len;
7493                 ctsio->kern_total_len = total_len;
7494         } else {
7495                 ctsio->residual = 0;
7496                 ctsio->kern_data_len = alloc_len;
7497                 ctsio->kern_total_len = alloc_len;
7498         }
7499
7500         ctsio->kern_data_resid = 0;
7501         ctsio->kern_rel_offset = 0;
7502         ctsio->kern_sg_entries = 0;
7503
7504         mtx_lock(&lun->lun_lock);
7505         switch (cdb->action) {
7506         case SPRI_RK: { // read keys
7507         struct scsi_per_res_in_keys *res_keys;
7508                 int i, key_count;
7509
7510                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7511
7512                 /*
7513                  * We had to drop the lock to allocate our buffer, which
7514                  * leaves time for someone to come in with another
7515                  * persistent reservation.  (That is unlikely, though,
7516                  * since this should be the only persistent reservation
7517                  * command active right now.)
7518                  */
7519                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7520                     (lun->pr_key_count *
7521                      sizeof(struct scsi_per_res_key)))){
7522                         mtx_unlock(&lun->lun_lock);
7523                         free(ctsio->kern_data_ptr, M_CTL);
7524                         printf("%s: reservation length changed, retrying\n",
7525                                __func__);
7526                         goto retry;
7527                 }
7528
7529                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7530
7531                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7532                              lun->pr_key_count, res_keys->header.length);
7533
7534                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7535                         if ((key = ctl_get_prkey(lun, i)) == 0)
7536                                 continue;
7537
7538                         /*
7539                          * We used lun->pr_key_count to calculate the
7540                          * size to allocate.  If it turns out the number of
7541                          * initiators with the registered flag set is
7542                          * larger than that (i.e. they haven't been kept in
7543                          * sync), we've got a problem.
7544                          */
7545                         if (key_count >= lun->pr_key_count) {
7546                                 key_count++;
7547                                 continue;
7548                         }
7549                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7550                         key_count++;
7551                 }
7552                 break;
7553         }
7554         case SPRI_RR: { // read reservation
7555                 struct scsi_per_res_in_rsrv *res;
7556                 int tmp_len, header_only;
7557
7558                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7559
7560                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7561
7562                 if (lun->flags & CTL_LUN_PR_RESERVED)
7563                 {
7564                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7565                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7566                                     res->header.length);
7567                         header_only = 0;
7568                 } else {
7569                         tmp_len = sizeof(struct scsi_per_res_in_header);
7570                         scsi_ulto4b(0, res->header.length);
7571                         header_only = 1;
7572                 }
7573
7574                 /*
7575                  * We had to drop the lock to allocate our buffer, which
7576                  * leaves time for someone to come in with another
7577                  * persistent reservation.  (That is unlikely, though,
7578                  * since this should be the only persistent reservation
7579                  * command active right now.)
7580                  */
7581                 if (tmp_len != total_len) {
7582                         mtx_unlock(&lun->lun_lock);
7583                         free(ctsio->kern_data_ptr, M_CTL);
7584                         printf("%s: reservation status changed, retrying\n",
7585                                __func__);
7586                         goto retry;
7587                 }
7588
7589                 /*
7590                  * No reservation held, so we're done.
7591                  */
7592                 if (header_only != 0)
7593                         break;
7594
7595                 /*
7596                  * If the registration is an All Registrants type, the key
7597                  * is 0, since it doesn't really matter.
7598                  */
7599                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7600                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7601                             res->data.reservation);
7602                 }
7603                 res->data.scopetype = lun->res_type;
7604                 break;
7605         }
7606         case SPRI_RC:     //report capabilities
7607         {
7608                 struct scsi_per_res_cap *res_cap;
7609                 uint16_t type_mask;
7610
7611                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7612                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7613                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7614                 type_mask = SPRI_TM_WR_EX_AR |
7615                             SPRI_TM_EX_AC_RO |
7616                             SPRI_TM_WR_EX_RO |
7617                             SPRI_TM_EX_AC |
7618                             SPRI_TM_WR_EX |
7619                             SPRI_TM_EX_AC_AR;
7620                 scsi_ulto2b(type_mask, res_cap->type_mask);
7621                 break;
7622         }
7623         case SPRI_RS: { // read full status
7624                 struct scsi_per_res_in_full *res_status;
7625                 struct scsi_per_res_in_full_desc *res_desc;
7626                 struct ctl_port *port;
7627                 int i, len;
7628
7629                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7630
7631                 /*
7632                  * We had to drop the lock to allocate our buffer, which
7633                  * leaves time for someone to come in with another
7634                  * persistent reservation.  (That is unlikely, though,
7635                  * since this should be the only persistent reservation
7636                  * command active right now.)
7637                  */
7638                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7639                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7640                      lun->pr_key_count)){
7641                         mtx_unlock(&lun->lun_lock);
7642                         free(ctsio->kern_data_ptr, M_CTL);
7643                         printf("%s: reservation length changed, retrying\n",
7644                                __func__);
7645                         goto retry;
7646                 }
7647
7648                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7649
7650                 res_desc = &res_status->desc[0];
7651                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7652                         if ((key = ctl_get_prkey(lun, i)) == 0)
7653                                 continue;
7654
7655                         scsi_u64to8b(key, res_desc->res_key.key);
7656                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7657                             (lun->pr_res_idx == i ||
7658                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7659                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7660                                 res_desc->scopetype = lun->res_type;
7661                         }
7662                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7663                             res_desc->rel_trgt_port_id);
7664                         len = 0;
7665                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7666                         if (port != NULL)
7667                                 len = ctl_create_iid(port,
7668                                     i % CTL_MAX_INIT_PER_PORT,
7669                                     res_desc->transport_id);
7670                         scsi_ulto4b(len, res_desc->additional_length);
7671                         res_desc = (struct scsi_per_res_in_full_desc *)
7672                             &res_desc->transport_id[len];
7673                 }
7674                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7675                     res_status->header.length);
7676                 break;
7677         }
7678         default:
7679                 /*
7680                  * This is a bug, because we just checked for this above,
7681                  * and should have returned an error.
7682                  */
7683                 panic("Invalid PR type %x", cdb->action);
7684                 break; /* NOTREACHED */
7685         }
7686         mtx_unlock(&lun->lun_lock);
7687
7688         ctl_set_success(ctsio);
7689         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7690         ctsio->be_move_done = ctl_config_move_done;
7691         ctl_datamove((union ctl_io *)ctsio);
7692         return (CTL_RETVAL_COMPLETE);
7693 }
7694
7695 /*
7696  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7697  * it should return.
7698  */
7699 static int
7700 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7701                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7702                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7703                 struct scsi_per_res_out_parms* param)
7704 {
7705         union ctl_ha_msg persis_io;
7706         int i;
7707
7708         mtx_lock(&lun->lun_lock);
7709         if (sa_res_key == 0) {
7710                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7711                         /* validate scope and type */
7712                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7713                              SPR_LU_SCOPE) {
7714                                 mtx_unlock(&lun->lun_lock);
7715                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7716                                                       /*sks_valid*/ 1,
7717                                                       /*command*/ 1,
7718                                                       /*field*/ 2,
7719                                                       /*bit_valid*/ 1,
7720                                                       /*bit*/ 4);
7721                                 ctl_done((union ctl_io *)ctsio);
7722                                 return (1);
7723                         }
7724
7725                         if (type>8 || type==2 || type==4 || type==0) {
7726                                 mtx_unlock(&lun->lun_lock);
7727                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7728                                                       /*sks_valid*/ 1,
7729                                                       /*command*/ 1,
7730                                                       /*field*/ 2,
7731                                                       /*bit_valid*/ 1,
7732                                                       /*bit*/ 0);
7733                                 ctl_done((union ctl_io *)ctsio);
7734                                 return (1);
7735                         }
7736
7737                         /*
7738                          * Unregister everybody else and build UA for
7739                          * them
7740                          */
7741                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7742                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7743                                         continue;
7744
7745                                 ctl_clr_prkey(lun, i);
7746                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7747                         }
7748                         lun->pr_key_count = 1;
7749                         lun->res_type = type;
7750                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7751                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7752                                 lun->pr_res_idx = residx;
7753                         lun->PRGeneration++;
7754                         mtx_unlock(&lun->lun_lock);
7755
7756                         /* send msg to other side */
7757                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7758                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7759                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7760                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7761                         persis_io.pr.pr_info.res_type = type;
7762                         memcpy(persis_io.pr.pr_info.sa_res_key,
7763                                param->serv_act_res_key,
7764                                sizeof(param->serv_act_res_key));
7765                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7766                             sizeof(persis_io.pr), M_WAITOK);
7767                 } else {
7768                         /* not all registrants */
7769                         mtx_unlock(&lun->lun_lock);
7770                         free(ctsio->kern_data_ptr, M_CTL);
7771                         ctl_set_invalid_field(ctsio,
7772                                               /*sks_valid*/ 1,
7773                                               /*command*/ 0,
7774                                               /*field*/ 8,
7775                                               /*bit_valid*/ 0,
7776                                               /*bit*/ 0);
7777                         ctl_done((union ctl_io *)ctsio);
7778                         return (1);
7779                 }
7780         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7781                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7782                 int found = 0;
7783
7784                 if (res_key == sa_res_key) {
7785                         /* special case */
7786                         /*
7787                          * The spec implies this is not good but doesn't
7788                          * say what to do. There are two choices either
7789                          * generate a res conflict or check condition
7790                          * with illegal field in parameter data. Since
7791                          * that is what is done when the sa_res_key is
7792                          * zero I'll take that approach since this has
7793                          * to do with the sa_res_key.
7794                          */
7795                         mtx_unlock(&lun->lun_lock);
7796                         free(ctsio->kern_data_ptr, M_CTL);
7797                         ctl_set_invalid_field(ctsio,
7798                                               /*sks_valid*/ 1,
7799                                               /*command*/ 0,
7800                                               /*field*/ 8,
7801                                               /*bit_valid*/ 0,
7802                                               /*bit*/ 0);
7803                         ctl_done((union ctl_io *)ctsio);
7804                         return (1);
7805                 }
7806
7807                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7808                         if (ctl_get_prkey(lun, i) != sa_res_key)
7809                                 continue;
7810
7811                         found = 1;
7812                         ctl_clr_prkey(lun, i);
7813                         lun->pr_key_count--;
7814                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7815                 }
7816                 if (!found) {
7817                         mtx_unlock(&lun->lun_lock);
7818                         free(ctsio->kern_data_ptr, M_CTL);
7819                         ctl_set_reservation_conflict(ctsio);
7820                         ctl_done((union ctl_io *)ctsio);
7821                         return (CTL_RETVAL_COMPLETE);
7822                 }
7823                 lun->PRGeneration++;
7824                 mtx_unlock(&lun->lun_lock);
7825
7826                 /* send msg to other side */
7827                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7828                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7829                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7830                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7831                 persis_io.pr.pr_info.res_type = type;
7832                 memcpy(persis_io.pr.pr_info.sa_res_key,
7833                        param->serv_act_res_key,
7834                        sizeof(param->serv_act_res_key));
7835                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7836                     sizeof(persis_io.pr), M_WAITOK);
7837         } else {
7838                 /* Reserved but not all registrants */
7839                 /* sa_res_key is res holder */
7840                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7841                         /* validate scope and type */
7842                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7843                              SPR_LU_SCOPE) {
7844                                 mtx_unlock(&lun->lun_lock);
7845                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7846                                                       /*sks_valid*/ 1,
7847                                                       /*command*/ 1,
7848                                                       /*field*/ 2,
7849                                                       /*bit_valid*/ 1,
7850                                                       /*bit*/ 4);
7851                                 ctl_done((union ctl_io *)ctsio);
7852                                 return (1);
7853                         }
7854
7855                         if (type>8 || type==2 || type==4 || type==0) {
7856                                 mtx_unlock(&lun->lun_lock);
7857                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7858                                                       /*sks_valid*/ 1,
7859                                                       /*command*/ 1,
7860                                                       /*field*/ 2,
7861                                                       /*bit_valid*/ 1,
7862                                                       /*bit*/ 0);
7863                                 ctl_done((union ctl_io *)ctsio);
7864                                 return (1);
7865                         }
7866
7867                         /*
7868                          * Do the following:
7869                          * if sa_res_key != res_key remove all
7870                          * registrants w/sa_res_key and generate UA
7871                          * for these registrants(Registrations
7872                          * Preempted) if it wasn't an exclusive
7873                          * reservation generate UA(Reservations
7874                          * Preempted) for all other registered nexuses
7875                          * if the type has changed. Establish the new
7876                          * reservation and holder. If res_key and
7877                          * sa_res_key are the same do the above
7878                          * except don't unregister the res holder.
7879                          */
7880
7881                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7882                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7883                                         continue;
7884
7885                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7886                                         ctl_clr_prkey(lun, i);
7887                                         lun->pr_key_count--;
7888                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7889                                 } else if (type != lun->res_type
7890                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
7891                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7892                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7893                                 }
7894                         }
7895                         lun->res_type = type;
7896                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7897                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7898                                 lun->pr_res_idx = residx;
7899                         else
7900                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7901                         lun->PRGeneration++;
7902                         mtx_unlock(&lun->lun_lock);
7903
7904                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7905                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7906                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7907                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7908                         persis_io.pr.pr_info.res_type = type;
7909                         memcpy(persis_io.pr.pr_info.sa_res_key,
7910                                param->serv_act_res_key,
7911                                sizeof(param->serv_act_res_key));
7912                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7913                             sizeof(persis_io.pr), M_WAITOK);
7914                 } else {
7915                         /*
7916                          * sa_res_key is not the res holder just
7917                          * remove registrants
7918                          */
7919                         int found=0;
7920
7921                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7922                                 if (sa_res_key != ctl_get_prkey(lun, i))
7923                                         continue;
7924
7925                                 found = 1;
7926                                 ctl_clr_prkey(lun, i);
7927                                 lun->pr_key_count--;
7928                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7929                         }
7930
7931                         if (!found) {
7932                                 mtx_unlock(&lun->lun_lock);
7933                                 free(ctsio->kern_data_ptr, M_CTL);
7934                                 ctl_set_reservation_conflict(ctsio);
7935                                 ctl_done((union ctl_io *)ctsio);
7936                                 return (1);
7937                         }
7938                         lun->PRGeneration++;
7939                         mtx_unlock(&lun->lun_lock);
7940
7941                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7942                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7943                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7944                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7945                         persis_io.pr.pr_info.res_type = type;
7946                         memcpy(persis_io.pr.pr_info.sa_res_key,
7947                                param->serv_act_res_key,
7948                                sizeof(param->serv_act_res_key));
7949                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7950                             sizeof(persis_io.pr), M_WAITOK);
7951                 }
7952         }
7953         return (0);
7954 }
7955
7956 static void
7957 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7958 {
7959         uint64_t sa_res_key;
7960         int i;
7961
7962         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7963
7964         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7965          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7966          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7967                 if (sa_res_key == 0) {
7968                         /*
7969                          * Unregister everybody else and build UA for
7970                          * them
7971                          */
7972                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7973                                 if (i == msg->pr.pr_info.residx ||
7974                                     ctl_get_prkey(lun, i) == 0)
7975                                         continue;
7976
7977                                 ctl_clr_prkey(lun, i);
7978                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7979                         }
7980
7981                         lun->pr_key_count = 1;
7982                         lun->res_type = msg->pr.pr_info.res_type;
7983                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7984                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7985                                 lun->pr_res_idx = msg->pr.pr_info.residx;
7986                 } else {
7987                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7988                                 if (sa_res_key == ctl_get_prkey(lun, i))
7989                                         continue;
7990
7991                                 ctl_clr_prkey(lun, i);
7992                                 lun->pr_key_count--;
7993                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7994                         }
7995                 }
7996         } else {
7997                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7998                         if (i == msg->pr.pr_info.residx ||
7999                             ctl_get_prkey(lun, i) == 0)
8000                                 continue;
8001
8002                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8003                                 ctl_clr_prkey(lun, i);
8004                                 lun->pr_key_count--;
8005                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8006                         } else if (msg->pr.pr_info.res_type != lun->res_type
8007                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8008                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8009                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8010                         }
8011                 }
8012                 lun->res_type = msg->pr.pr_info.res_type;
8013                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8014                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8015                         lun->pr_res_idx = msg->pr.pr_info.residx;
8016                 else
8017                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8018         }
8019         lun->PRGeneration++;
8020
8021 }
8022
8023
8024 int
8025 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8026 {
8027         int retval;
8028         u_int32_t param_len;
8029         struct scsi_per_res_out *cdb;
8030         struct ctl_lun *lun;
8031         struct scsi_per_res_out_parms* param;
8032         struct ctl_softc *softc;
8033         uint32_t residx;
8034         uint64_t res_key, sa_res_key, key;
8035         uint8_t type;
8036         union ctl_ha_msg persis_io;
8037         int    i;
8038
8039         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8040
8041         retval = CTL_RETVAL_COMPLETE;
8042
8043         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8044         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8045         softc = lun->ctl_softc;
8046
8047         /*
8048          * We only support whole-LUN scope.  The scope & type are ignored for
8049          * register, register and ignore existing key and clear.
8050          * We sometimes ignore scope and type on preempts too!!
8051          * Verify reservation type here as well.
8052          */
8053         type = cdb->scope_type & SPR_TYPE_MASK;
8054         if ((cdb->action == SPRO_RESERVE)
8055          || (cdb->action == SPRO_RELEASE)) {
8056                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8057                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8058                                               /*sks_valid*/ 1,
8059                                               /*command*/ 1,
8060                                               /*field*/ 2,
8061                                               /*bit_valid*/ 1,
8062                                               /*bit*/ 4);
8063                         ctl_done((union ctl_io *)ctsio);
8064                         return (CTL_RETVAL_COMPLETE);
8065                 }
8066
8067                 if (type>8 || type==2 || type==4 || type==0) {
8068                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8069                                               /*sks_valid*/ 1,
8070                                               /*command*/ 1,
8071                                               /*field*/ 2,
8072                                               /*bit_valid*/ 1,
8073                                               /*bit*/ 0);
8074                         ctl_done((union ctl_io *)ctsio);
8075                         return (CTL_RETVAL_COMPLETE);
8076                 }
8077         }
8078
8079         param_len = scsi_4btoul(cdb->length);
8080
8081         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8082                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8083                 ctsio->kern_data_len = param_len;
8084                 ctsio->kern_total_len = param_len;
8085                 ctsio->kern_data_resid = 0;
8086                 ctsio->kern_rel_offset = 0;
8087                 ctsio->kern_sg_entries = 0;
8088                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8089                 ctsio->be_move_done = ctl_config_move_done;
8090                 ctl_datamove((union ctl_io *)ctsio);
8091
8092                 return (CTL_RETVAL_COMPLETE);
8093         }
8094
8095         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8096
8097         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8098         res_key = scsi_8btou64(param->res_key.key);
8099         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8100
8101         /*
8102          * Validate the reservation key here except for SPRO_REG_IGNO
8103          * This must be done for all other service actions
8104          */
8105         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8106                 mtx_lock(&lun->lun_lock);
8107                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8108                         if (res_key != key) {
8109                                 /*
8110                                  * The current key passed in doesn't match
8111                                  * the one the initiator previously
8112                                  * registered.
8113                                  */
8114                                 mtx_unlock(&lun->lun_lock);
8115                                 free(ctsio->kern_data_ptr, M_CTL);
8116                                 ctl_set_reservation_conflict(ctsio);
8117                                 ctl_done((union ctl_io *)ctsio);
8118                                 return (CTL_RETVAL_COMPLETE);
8119                         }
8120                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8121                         /*
8122                          * We are not registered
8123                          */
8124                         mtx_unlock(&lun->lun_lock);
8125                         free(ctsio->kern_data_ptr, M_CTL);
8126                         ctl_set_reservation_conflict(ctsio);
8127                         ctl_done((union ctl_io *)ctsio);
8128                         return (CTL_RETVAL_COMPLETE);
8129                 } else if (res_key != 0) {
8130                         /*
8131                          * We are not registered and trying to register but
8132                          * the register key isn't zero.
8133                          */
8134                         mtx_unlock(&lun->lun_lock);
8135                         free(ctsio->kern_data_ptr, M_CTL);
8136                         ctl_set_reservation_conflict(ctsio);
8137                         ctl_done((union ctl_io *)ctsio);
8138                         return (CTL_RETVAL_COMPLETE);
8139                 }
8140                 mtx_unlock(&lun->lun_lock);
8141         }
8142
8143         switch (cdb->action & SPRO_ACTION_MASK) {
8144         case SPRO_REGISTER:
8145         case SPRO_REG_IGNO: {
8146
8147 #if 0
8148                 printf("Registration received\n");
8149 #endif
8150
8151                 /*
8152                  * We don't support any of these options, as we report in
8153                  * the read capabilities request (see
8154                  * ctl_persistent_reserve_in(), above).
8155                  */
8156                 if ((param->flags & SPR_SPEC_I_PT)
8157                  || (param->flags & SPR_ALL_TG_PT)
8158                  || (param->flags & SPR_APTPL)) {
8159                         int bit_ptr;
8160
8161                         if (param->flags & SPR_APTPL)
8162                                 bit_ptr = 0;
8163                         else if (param->flags & SPR_ALL_TG_PT)
8164                                 bit_ptr = 2;
8165                         else /* SPR_SPEC_I_PT */
8166                                 bit_ptr = 3;
8167
8168                         free(ctsio->kern_data_ptr, M_CTL);
8169                         ctl_set_invalid_field(ctsio,
8170                                               /*sks_valid*/ 1,
8171                                               /*command*/ 0,
8172                                               /*field*/ 20,
8173                                               /*bit_valid*/ 1,
8174                                               /*bit*/ bit_ptr);
8175                         ctl_done((union ctl_io *)ctsio);
8176                         return (CTL_RETVAL_COMPLETE);
8177                 }
8178
8179                 mtx_lock(&lun->lun_lock);
8180
8181                 /*
8182                  * The initiator wants to clear the
8183                  * key/unregister.
8184                  */
8185                 if (sa_res_key == 0) {
8186                         if ((res_key == 0
8187                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8188                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8189                           && ctl_get_prkey(lun, residx) == 0)) {
8190                                 mtx_unlock(&lun->lun_lock);
8191                                 goto done;
8192                         }
8193
8194                         ctl_clr_prkey(lun, residx);
8195                         lun->pr_key_count--;
8196
8197                         if (residx == lun->pr_res_idx) {
8198                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8199                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8200
8201                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8202                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8203                                  && lun->pr_key_count) {
8204                                         /*
8205                                          * If the reservation is a registrants
8206                                          * only type we need to generate a UA
8207                                          * for other registered inits.  The
8208                                          * sense code should be RESERVATIONS
8209                                          * RELEASED
8210                                          */
8211
8212                                         for (i = softc->init_min; i < softc->init_max; i++){
8213                                                 if (ctl_get_prkey(lun, i) == 0)
8214                                                         continue;
8215                                                 ctl_est_ua(lun, i,
8216                                                     CTL_UA_RES_RELEASE);
8217                                         }
8218                                 }
8219                                 lun->res_type = 0;
8220                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8221                                 if (lun->pr_key_count==0) {
8222                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8223                                         lun->res_type = 0;
8224                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8225                                 }
8226                         }
8227                         lun->PRGeneration++;
8228                         mtx_unlock(&lun->lun_lock);
8229
8230                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8231                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8232                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8233                         persis_io.pr.pr_info.residx = residx;
8234                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8235                             sizeof(persis_io.pr), M_WAITOK);
8236                 } else /* sa_res_key != 0 */ {
8237
8238                         /*
8239                          * If we aren't registered currently then increment
8240                          * the key count and set the registered flag.
8241                          */
8242                         ctl_alloc_prkey(lun, residx);
8243                         if (ctl_get_prkey(lun, residx) == 0)
8244                                 lun->pr_key_count++;
8245                         ctl_set_prkey(lun, residx, sa_res_key);
8246                         lun->PRGeneration++;
8247                         mtx_unlock(&lun->lun_lock);
8248
8249                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8250                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8251                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8252                         persis_io.pr.pr_info.residx = residx;
8253                         memcpy(persis_io.pr.pr_info.sa_res_key,
8254                                param->serv_act_res_key,
8255                                sizeof(param->serv_act_res_key));
8256                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8257                             sizeof(persis_io.pr), M_WAITOK);
8258                 }
8259
8260                 break;
8261         }
8262         case SPRO_RESERVE:
8263 #if 0
8264                 printf("Reserve executed type %d\n", type);
8265 #endif
8266                 mtx_lock(&lun->lun_lock);
8267                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8268                         /*
8269                          * if this isn't the reservation holder and it's
8270                          * not a "all registrants" type or if the type is
8271                          * different then we have a conflict
8272                          */
8273                         if ((lun->pr_res_idx != residx
8274                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8275                          || lun->res_type != type) {
8276                                 mtx_unlock(&lun->lun_lock);
8277                                 free(ctsio->kern_data_ptr, M_CTL);
8278                                 ctl_set_reservation_conflict(ctsio);
8279                                 ctl_done((union ctl_io *)ctsio);
8280                                 return (CTL_RETVAL_COMPLETE);
8281                         }
8282                         mtx_unlock(&lun->lun_lock);
8283                 } else /* create a reservation */ {
8284                         /*
8285                          * If it's not an "all registrants" type record
8286                          * reservation holder
8287                          */
8288                         if (type != SPR_TYPE_WR_EX_AR
8289                          && type != SPR_TYPE_EX_AC_AR)
8290                                 lun->pr_res_idx = residx; /* Res holder */
8291                         else
8292                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8293
8294                         lun->flags |= CTL_LUN_PR_RESERVED;
8295                         lun->res_type = type;
8296
8297                         mtx_unlock(&lun->lun_lock);
8298
8299                         /* send msg to other side */
8300                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8301                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8302                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8303                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8304                         persis_io.pr.pr_info.res_type = type;
8305                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8306                             sizeof(persis_io.pr), M_WAITOK);
8307                 }
8308                 break;
8309
8310         case SPRO_RELEASE:
8311                 mtx_lock(&lun->lun_lock);
8312                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8313                         /* No reservation exists return good status */
8314                         mtx_unlock(&lun->lun_lock);
8315                         goto done;
8316                 }
8317                 /*
8318                  * Is this nexus a reservation holder?
8319                  */
8320                 if (lun->pr_res_idx != residx
8321                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8322                         /*
8323                          * not a res holder return good status but
8324                          * do nothing
8325                          */
8326                         mtx_unlock(&lun->lun_lock);
8327                         goto done;
8328                 }
8329
8330                 if (lun->res_type != type) {
8331                         mtx_unlock(&lun->lun_lock);
8332                         free(ctsio->kern_data_ptr, M_CTL);
8333                         ctl_set_illegal_pr_release(ctsio);
8334                         ctl_done((union ctl_io *)ctsio);
8335                         return (CTL_RETVAL_COMPLETE);
8336                 }
8337
8338                 /* okay to release */
8339                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8340                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8341                 lun->res_type = 0;
8342
8343                 /*
8344                  * if this isn't an exclusive access
8345                  * res generate UA for all other
8346                  * registrants.
8347                  */
8348                 if (type != SPR_TYPE_EX_AC
8349                  && type != SPR_TYPE_WR_EX) {
8350                         for (i = softc->init_min; i < softc->init_max; i++) {
8351                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8352                                         continue;
8353                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8354                         }
8355                 }
8356                 mtx_unlock(&lun->lun_lock);
8357
8358                 /* Send msg to other side */
8359                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8360                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8361                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8362                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8363                      sizeof(persis_io.pr), M_WAITOK);
8364                 break;
8365
8366         case SPRO_CLEAR:
8367                 /* send msg to other side */
8368
8369                 mtx_lock(&lun->lun_lock);
8370                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8371                 lun->res_type = 0;
8372                 lun->pr_key_count = 0;
8373                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8374
8375                 ctl_clr_prkey(lun, residx);
8376                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8377                         if (ctl_get_prkey(lun, i) != 0) {
8378                                 ctl_clr_prkey(lun, i);
8379                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8380                         }
8381                 lun->PRGeneration++;
8382                 mtx_unlock(&lun->lun_lock);
8383
8384                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8385                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8386                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8387                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8388                      sizeof(persis_io.pr), M_WAITOK);
8389                 break;
8390
8391         case SPRO_PREEMPT:
8392         case SPRO_PRE_ABO: {
8393                 int nretval;
8394
8395                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8396                                           residx, ctsio, cdb, param);
8397                 if (nretval != 0)
8398                         return (CTL_RETVAL_COMPLETE);
8399                 break;
8400         }
8401         default:
8402                 panic("Invalid PR type %x", cdb->action);
8403         }
8404
8405 done:
8406         free(ctsio->kern_data_ptr, M_CTL);
8407         ctl_set_success(ctsio);
8408         ctl_done((union ctl_io *)ctsio);
8409
8410         return (retval);
8411 }
8412
8413 /*
8414  * This routine is for handling a message from the other SC pertaining to
8415  * persistent reserve out. All the error checking will have been done
8416  * so only perorming the action need be done here to keep the two
8417  * in sync.
8418  */
8419 static void
8420 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8421 {
8422         struct ctl_softc *softc = control_softc;
8423         struct ctl_lun *lun;
8424         int i;
8425         uint32_t residx, targ_lun;
8426
8427         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8428         mtx_lock(&softc->ctl_lock);
8429         if ((targ_lun >= CTL_MAX_LUNS) ||
8430             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8431                 mtx_unlock(&softc->ctl_lock);
8432                 return;
8433         }
8434         mtx_lock(&lun->lun_lock);
8435         mtx_unlock(&softc->ctl_lock);
8436         if (lun->flags & CTL_LUN_DISABLED) {
8437                 mtx_unlock(&lun->lun_lock);
8438                 return;
8439         }
8440         residx = ctl_get_initindex(&msg->hdr.nexus);
8441         switch(msg->pr.pr_info.action) {
8442         case CTL_PR_REG_KEY:
8443                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8444                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8445                         lun->pr_key_count++;
8446                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8447                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8448                 lun->PRGeneration++;
8449                 break;
8450
8451         case CTL_PR_UNREG_KEY:
8452                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8453                 lun->pr_key_count--;
8454
8455                 /* XXX Need to see if the reservation has been released */
8456                 /* if so do we need to generate UA? */
8457                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8458                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8459                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8460
8461                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8462                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8463                          && lun->pr_key_count) {
8464                                 /*
8465                                  * If the reservation is a registrants
8466                                  * only type we need to generate a UA
8467                                  * for other registered inits.  The
8468                                  * sense code should be RESERVATIONS
8469                                  * RELEASED
8470                                  */
8471
8472                                 for (i = softc->init_min; i < softc->init_max; i++) {
8473                                         if (ctl_get_prkey(lun, i) == 0)
8474                                                 continue;
8475
8476                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8477                                 }
8478                         }
8479                         lun->res_type = 0;
8480                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8481                         if (lun->pr_key_count==0) {
8482                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8483                                 lun->res_type = 0;
8484                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8485                         }
8486                 }
8487                 lun->PRGeneration++;
8488                 break;
8489
8490         case CTL_PR_RESERVE:
8491                 lun->flags |= CTL_LUN_PR_RESERVED;
8492                 lun->res_type = msg->pr.pr_info.res_type;
8493                 lun->pr_res_idx = msg->pr.pr_info.residx;
8494
8495                 break;
8496
8497         case CTL_PR_RELEASE:
8498                 /*
8499                  * if this isn't an exclusive access res generate UA for all
8500                  * other registrants.
8501                  */
8502                 if (lun->res_type != SPR_TYPE_EX_AC
8503                  && lun->res_type != SPR_TYPE_WR_EX) {
8504                         for (i = softc->init_min; i < softc->init_max; i++)
8505                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8506                                         continue;
8507                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8508                 }
8509
8510                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8511                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8512                 lun->res_type = 0;
8513                 break;
8514
8515         case CTL_PR_PREEMPT:
8516                 ctl_pro_preempt_other(lun, msg);
8517                 break;
8518         case CTL_PR_CLEAR:
8519                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8520                 lun->res_type = 0;
8521                 lun->pr_key_count = 0;
8522                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8523
8524                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8525                         if (ctl_get_prkey(lun, i) == 0)
8526                                 continue;
8527                         ctl_clr_prkey(lun, i);
8528                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8529                 }
8530                 lun->PRGeneration++;
8531                 break;
8532         }
8533
8534         mtx_unlock(&lun->lun_lock);
8535 }
8536
8537 int
8538 ctl_read_write(struct ctl_scsiio *ctsio)
8539 {
8540         struct ctl_lun *lun;
8541         struct ctl_lba_len_flags *lbalen;
8542         uint64_t lba;
8543         uint32_t num_blocks;
8544         int flags, retval;
8545         int isread;
8546
8547         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8548
8549         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8550
8551         flags = 0;
8552         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8553               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8554         switch (ctsio->cdb[0]) {
8555         case READ_6:
8556         case WRITE_6: {
8557                 struct scsi_rw_6 *cdb;
8558
8559                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8560
8561                 lba = scsi_3btoul(cdb->addr);
8562                 /* only 5 bits are valid in the most significant address byte */
8563                 lba &= 0x1fffff;
8564                 num_blocks = cdb->length;
8565                 /*
8566                  * This is correct according to SBC-2.
8567                  */
8568                 if (num_blocks == 0)
8569                         num_blocks = 256;
8570                 break;
8571         }
8572         case READ_10:
8573         case WRITE_10: {
8574                 struct scsi_rw_10 *cdb;
8575
8576                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8577                 if (cdb->byte2 & SRW10_FUA)
8578                         flags |= CTL_LLF_FUA;
8579                 if (cdb->byte2 & SRW10_DPO)
8580                         flags |= CTL_LLF_DPO;
8581                 lba = scsi_4btoul(cdb->addr);
8582                 num_blocks = scsi_2btoul(cdb->length);
8583                 break;
8584         }
8585         case WRITE_VERIFY_10: {
8586                 struct scsi_write_verify_10 *cdb;
8587
8588                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8589                 flags |= CTL_LLF_FUA;
8590                 if (cdb->byte2 & SWV_DPO)
8591                         flags |= CTL_LLF_DPO;
8592                 lba = scsi_4btoul(cdb->addr);
8593                 num_blocks = scsi_2btoul(cdb->length);
8594                 break;
8595         }
8596         case READ_12:
8597         case WRITE_12: {
8598                 struct scsi_rw_12 *cdb;
8599
8600                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8601                 if (cdb->byte2 & SRW12_FUA)
8602                         flags |= CTL_LLF_FUA;
8603                 if (cdb->byte2 & SRW12_DPO)
8604                         flags |= CTL_LLF_DPO;
8605                 lba = scsi_4btoul(cdb->addr);
8606                 num_blocks = scsi_4btoul(cdb->length);
8607                 break;
8608         }
8609         case WRITE_VERIFY_12: {
8610                 struct scsi_write_verify_12 *cdb;
8611
8612                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8613                 flags |= CTL_LLF_FUA;
8614                 if (cdb->byte2 & SWV_DPO)
8615                         flags |= CTL_LLF_DPO;
8616                 lba = scsi_4btoul(cdb->addr);
8617                 num_blocks = scsi_4btoul(cdb->length);
8618                 break;
8619         }
8620         case READ_16:
8621         case WRITE_16: {
8622                 struct scsi_rw_16 *cdb;
8623
8624                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8625                 if (cdb->byte2 & SRW12_FUA)
8626                         flags |= CTL_LLF_FUA;
8627                 if (cdb->byte2 & SRW12_DPO)
8628                         flags |= CTL_LLF_DPO;
8629                 lba = scsi_8btou64(cdb->addr);
8630                 num_blocks = scsi_4btoul(cdb->length);
8631                 break;
8632         }
8633         case WRITE_ATOMIC_16: {
8634                 struct scsi_write_atomic_16 *cdb;
8635
8636                 if (lun->be_lun->atomicblock == 0) {
8637                         ctl_set_invalid_opcode(ctsio);
8638                         ctl_done((union ctl_io *)ctsio);
8639                         return (CTL_RETVAL_COMPLETE);
8640                 }
8641
8642                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8643                 if (cdb->byte2 & SRW12_FUA)
8644                         flags |= CTL_LLF_FUA;
8645                 if (cdb->byte2 & SRW12_DPO)
8646                         flags |= CTL_LLF_DPO;
8647                 lba = scsi_8btou64(cdb->addr);
8648                 num_blocks = scsi_2btoul(cdb->length);
8649                 if (num_blocks > lun->be_lun->atomicblock) {
8650                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8651                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8652                             /*bit*/ 0);
8653                         ctl_done((union ctl_io *)ctsio);
8654                         return (CTL_RETVAL_COMPLETE);
8655                 }
8656                 break;
8657         }
8658         case WRITE_VERIFY_16: {
8659                 struct scsi_write_verify_16 *cdb;
8660
8661                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8662                 flags |= CTL_LLF_FUA;
8663                 if (cdb->byte2 & SWV_DPO)
8664                         flags |= CTL_LLF_DPO;
8665                 lba = scsi_8btou64(cdb->addr);
8666                 num_blocks = scsi_4btoul(cdb->length);
8667                 break;
8668         }
8669         default:
8670                 /*
8671                  * We got a command we don't support.  This shouldn't
8672                  * happen, commands should be filtered out above us.
8673                  */
8674                 ctl_set_invalid_opcode(ctsio);
8675                 ctl_done((union ctl_io *)ctsio);
8676
8677                 return (CTL_RETVAL_COMPLETE);
8678                 break; /* NOTREACHED */
8679         }
8680
8681         /*
8682          * The first check is to make sure we're in bounds, the second
8683          * check is to catch wrap-around problems.  If the lba + num blocks
8684          * is less than the lba, then we've wrapped around and the block
8685          * range is invalid anyway.
8686          */
8687         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8688          || ((lba + num_blocks) < lba)) {
8689                 ctl_set_lba_out_of_range(ctsio);
8690                 ctl_done((union ctl_io *)ctsio);
8691                 return (CTL_RETVAL_COMPLETE);
8692         }
8693
8694         /*
8695          * According to SBC-3, a transfer length of 0 is not an error.
8696          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8697          * translates to 256 blocks for those commands.
8698          */
8699         if (num_blocks == 0) {
8700                 ctl_set_success(ctsio);
8701                 ctl_done((union ctl_io *)ctsio);
8702                 return (CTL_RETVAL_COMPLETE);
8703         }
8704
8705         /* Set FUA and/or DPO if caches are disabled. */
8706         if (isread) {
8707                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8708                     SCP_RCD) != 0)
8709                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8710         } else {
8711                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8712                     SCP_WCE) == 0)
8713                         flags |= CTL_LLF_FUA;
8714         }
8715
8716         lbalen = (struct ctl_lba_len_flags *)
8717             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8718         lbalen->lba = lba;
8719         lbalen->len = num_blocks;
8720         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8721
8722         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8723         ctsio->kern_rel_offset = 0;
8724
8725         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8726
8727         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8728         return (retval);
8729 }
8730
8731 static int
8732 ctl_cnw_cont(union ctl_io *io)
8733 {
8734         struct ctl_scsiio *ctsio;
8735         struct ctl_lun *lun;
8736         struct ctl_lba_len_flags *lbalen;
8737         int retval;
8738
8739         ctsio = &io->scsiio;
8740         ctsio->io_hdr.status = CTL_STATUS_NONE;
8741         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8742         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8743         lbalen = (struct ctl_lba_len_flags *)
8744             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8745         lbalen->flags &= ~CTL_LLF_COMPARE;
8746         lbalen->flags |= CTL_LLF_WRITE;
8747
8748         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8749         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8750         return (retval);
8751 }
8752
8753 int
8754 ctl_cnw(struct ctl_scsiio *ctsio)
8755 {
8756         struct ctl_lun *lun;
8757         struct ctl_lba_len_flags *lbalen;
8758         uint64_t lba;
8759         uint32_t num_blocks;
8760         int flags, retval;
8761
8762         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8763
8764         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8765
8766         flags = 0;
8767         switch (ctsio->cdb[0]) {
8768         case COMPARE_AND_WRITE: {
8769                 struct scsi_compare_and_write *cdb;
8770
8771                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8772                 if (cdb->byte2 & SRW10_FUA)
8773                         flags |= CTL_LLF_FUA;
8774                 if (cdb->byte2 & SRW10_DPO)
8775                         flags |= CTL_LLF_DPO;
8776                 lba = scsi_8btou64(cdb->addr);
8777                 num_blocks = cdb->length;
8778                 break;
8779         }
8780         default:
8781                 /*
8782                  * We got a command we don't support.  This shouldn't
8783                  * happen, commands should be filtered out above us.
8784                  */
8785                 ctl_set_invalid_opcode(ctsio);
8786                 ctl_done((union ctl_io *)ctsio);
8787
8788                 return (CTL_RETVAL_COMPLETE);
8789                 break; /* NOTREACHED */
8790         }
8791
8792         /*
8793          * The first check is to make sure we're in bounds, the second
8794          * check is to catch wrap-around problems.  If the lba + num blocks
8795          * is less than the lba, then we've wrapped around and the block
8796          * range is invalid anyway.
8797          */
8798         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8799          || ((lba + num_blocks) < lba)) {
8800                 ctl_set_lba_out_of_range(ctsio);
8801                 ctl_done((union ctl_io *)ctsio);
8802                 return (CTL_RETVAL_COMPLETE);
8803         }
8804
8805         /*
8806          * According to SBC-3, a transfer length of 0 is not an error.
8807          */
8808         if (num_blocks == 0) {
8809                 ctl_set_success(ctsio);
8810                 ctl_done((union ctl_io *)ctsio);
8811                 return (CTL_RETVAL_COMPLETE);
8812         }
8813
8814         /* Set FUA if write cache is disabled. */
8815         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8816             SCP_WCE) == 0)
8817                 flags |= CTL_LLF_FUA;
8818
8819         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8820         ctsio->kern_rel_offset = 0;
8821
8822         /*
8823          * Set the IO_CONT flag, so that if this I/O gets passed to
8824          * ctl_data_submit_done(), it'll get passed back to
8825          * ctl_ctl_cnw_cont() for further processing.
8826          */
8827         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8828         ctsio->io_cont = ctl_cnw_cont;
8829
8830         lbalen = (struct ctl_lba_len_flags *)
8831             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8832         lbalen->lba = lba;
8833         lbalen->len = num_blocks;
8834         lbalen->flags = CTL_LLF_COMPARE | flags;
8835
8836         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8837         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8838         return (retval);
8839 }
8840
8841 int
8842 ctl_verify(struct ctl_scsiio *ctsio)
8843 {
8844         struct ctl_lun *lun;
8845         struct ctl_lba_len_flags *lbalen;
8846         uint64_t lba;
8847         uint32_t num_blocks;
8848         int bytchk, flags;
8849         int retval;
8850
8851         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8852
8853         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8854
8855         bytchk = 0;
8856         flags = CTL_LLF_FUA;
8857         switch (ctsio->cdb[0]) {
8858         case VERIFY_10: {
8859                 struct scsi_verify_10 *cdb;
8860
8861                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8862                 if (cdb->byte2 & SVFY_BYTCHK)
8863                         bytchk = 1;
8864                 if (cdb->byte2 & SVFY_DPO)
8865                         flags |= CTL_LLF_DPO;
8866                 lba = scsi_4btoul(cdb->addr);
8867                 num_blocks = scsi_2btoul(cdb->length);
8868                 break;
8869         }
8870         case VERIFY_12: {
8871                 struct scsi_verify_12 *cdb;
8872
8873                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8874                 if (cdb->byte2 & SVFY_BYTCHK)
8875                         bytchk = 1;
8876                 if (cdb->byte2 & SVFY_DPO)
8877                         flags |= CTL_LLF_DPO;
8878                 lba = scsi_4btoul(cdb->addr);
8879                 num_blocks = scsi_4btoul(cdb->length);
8880                 break;
8881         }
8882         case VERIFY_16: {
8883                 struct scsi_rw_16 *cdb;
8884
8885                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8886                 if (cdb->byte2 & SVFY_BYTCHK)
8887                         bytchk = 1;
8888                 if (cdb->byte2 & SVFY_DPO)
8889                         flags |= CTL_LLF_DPO;
8890                 lba = scsi_8btou64(cdb->addr);
8891                 num_blocks = scsi_4btoul(cdb->length);
8892                 break;
8893         }
8894         default:
8895                 /*
8896                  * We got a command we don't support.  This shouldn't
8897                  * happen, commands should be filtered out above us.
8898                  */
8899                 ctl_set_invalid_opcode(ctsio);
8900                 ctl_done((union ctl_io *)ctsio);
8901                 return (CTL_RETVAL_COMPLETE);
8902         }
8903
8904         /*
8905          * The first check is to make sure we're in bounds, the second
8906          * check is to catch wrap-around problems.  If the lba + num blocks
8907          * is less than the lba, then we've wrapped around and the block
8908          * range is invalid anyway.
8909          */
8910         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8911          || ((lba + num_blocks) < lba)) {
8912                 ctl_set_lba_out_of_range(ctsio);
8913                 ctl_done((union ctl_io *)ctsio);
8914                 return (CTL_RETVAL_COMPLETE);
8915         }
8916
8917         /*
8918          * According to SBC-3, a transfer length of 0 is not an error.
8919          */
8920         if (num_blocks == 0) {
8921                 ctl_set_success(ctsio);
8922                 ctl_done((union ctl_io *)ctsio);
8923                 return (CTL_RETVAL_COMPLETE);
8924         }
8925
8926         lbalen = (struct ctl_lba_len_flags *)
8927             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8928         lbalen->lba = lba;
8929         lbalen->len = num_blocks;
8930         if (bytchk) {
8931                 lbalen->flags = CTL_LLF_COMPARE | flags;
8932                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8933         } else {
8934                 lbalen->flags = CTL_LLF_VERIFY | flags;
8935                 ctsio->kern_total_len = 0;
8936         }
8937         ctsio->kern_rel_offset = 0;
8938
8939         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8940         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8941         return (retval);
8942 }
8943
8944 int
8945 ctl_report_luns(struct ctl_scsiio *ctsio)
8946 {
8947         struct ctl_softc *softc;
8948         struct scsi_report_luns *cdb;
8949         struct scsi_report_luns_data *lun_data;
8950         struct ctl_lun *lun, *request_lun;
8951         struct ctl_port *port;
8952         int num_luns, retval;
8953         uint32_t alloc_len, lun_datalen;
8954         int num_filled;
8955         uint32_t initidx, targ_lun_id, lun_id;
8956
8957         retval = CTL_RETVAL_COMPLETE;
8958         cdb = (struct scsi_report_luns *)ctsio->cdb;
8959         port = ctl_io_port(&ctsio->io_hdr);
8960         softc = port->ctl_softc;
8961
8962         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8963
8964         mtx_lock(&softc->ctl_lock);
8965         num_luns = 0;
8966         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8967                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8968                         num_luns++;
8969         }
8970         mtx_unlock(&softc->ctl_lock);
8971
8972         switch (cdb->select_report) {
8973         case RPL_REPORT_DEFAULT:
8974         case RPL_REPORT_ALL:
8975         case RPL_REPORT_NONSUBSID:
8976                 break;
8977         case RPL_REPORT_WELLKNOWN:
8978         case RPL_REPORT_ADMIN:
8979         case RPL_REPORT_CONGLOM:
8980                 num_luns = 0;
8981                 break;
8982         default:
8983                 ctl_set_invalid_field(ctsio,
8984                                       /*sks_valid*/ 1,
8985                                       /*command*/ 1,
8986                                       /*field*/ 2,
8987                                       /*bit_valid*/ 0,
8988                                       /*bit*/ 0);
8989                 ctl_done((union ctl_io *)ctsio);
8990                 return (retval);
8991                 break; /* NOTREACHED */
8992         }
8993
8994         alloc_len = scsi_4btoul(cdb->length);
8995         /*
8996          * The initiator has to allocate at least 16 bytes for this request,
8997          * so he can at least get the header and the first LUN.  Otherwise
8998          * we reject the request (per SPC-3 rev 14, section 6.21).
8999          */
9000         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9001             sizeof(struct scsi_report_luns_lundata))) {
9002                 ctl_set_invalid_field(ctsio,
9003                                       /*sks_valid*/ 1,
9004                                       /*command*/ 1,
9005                                       /*field*/ 6,
9006                                       /*bit_valid*/ 0,
9007                                       /*bit*/ 0);
9008                 ctl_done((union ctl_io *)ctsio);
9009                 return (retval);
9010         }
9011
9012         request_lun = (struct ctl_lun *)
9013                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9014
9015         lun_datalen = sizeof(*lun_data) +
9016                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9017
9018         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9019         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9020         ctsio->kern_sg_entries = 0;
9021
9022         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9023
9024         mtx_lock(&softc->ctl_lock);
9025         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9026                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9027                 if (lun_id >= CTL_MAX_LUNS)
9028                         continue;
9029                 lun = softc->ctl_luns[lun_id];
9030                 if (lun == NULL)
9031                         continue;
9032
9033                 if (targ_lun_id <= 0xff) {
9034                         /*
9035                          * Peripheral addressing method, bus number 0.
9036                          */
9037                         lun_data->luns[num_filled].lundata[0] =
9038                                 RPL_LUNDATA_ATYP_PERIPH;
9039                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9040                         num_filled++;
9041                 } else if (targ_lun_id <= 0x3fff) {
9042                         /*
9043                          * Flat addressing method.
9044                          */
9045                         lun_data->luns[num_filled].lundata[0] =
9046                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9047                         lun_data->luns[num_filled].lundata[1] =
9048                                 (targ_lun_id & 0xff);
9049                         num_filled++;
9050                 } else if (targ_lun_id <= 0xffffff) {
9051                         /*
9052                          * Extended flat addressing method.
9053                          */
9054                         lun_data->luns[num_filled].lundata[0] =
9055                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9056                         scsi_ulto3b(targ_lun_id,
9057                             &lun_data->luns[num_filled].lundata[1]);
9058                         num_filled++;
9059                 } else {
9060                         printf("ctl_report_luns: bogus LUN number %jd, "
9061                                "skipping\n", (intmax_t)targ_lun_id);
9062                 }
9063                 /*
9064                  * According to SPC-3, rev 14 section 6.21:
9065                  *
9066                  * "The execution of a REPORT LUNS command to any valid and
9067                  * installed logical unit shall clear the REPORTED LUNS DATA
9068                  * HAS CHANGED unit attention condition for all logical
9069                  * units of that target with respect to the requesting
9070                  * initiator. A valid and installed logical unit is one
9071                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9072                  * INQUIRY data (see 6.4.2)."
9073                  *
9074                  * If request_lun is NULL, the LUN this report luns command
9075                  * was issued to is either disabled or doesn't exist. In that
9076                  * case, we shouldn't clear any pending lun change unit
9077                  * attention.
9078                  */
9079                 if (request_lun != NULL) {
9080                         mtx_lock(&lun->lun_lock);
9081                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9082                         mtx_unlock(&lun->lun_lock);
9083                 }
9084         }
9085         mtx_unlock(&softc->ctl_lock);
9086
9087         /*
9088          * It's quite possible that we've returned fewer LUNs than we allocated
9089          * space for.  Trim it.
9090          */
9091         lun_datalen = sizeof(*lun_data) +
9092                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9093
9094         if (lun_datalen < alloc_len) {
9095                 ctsio->residual = alloc_len - lun_datalen;
9096                 ctsio->kern_data_len = lun_datalen;
9097                 ctsio->kern_total_len = lun_datalen;
9098         } else {
9099                 ctsio->residual = 0;
9100                 ctsio->kern_data_len = alloc_len;
9101                 ctsio->kern_total_len = alloc_len;
9102         }
9103         ctsio->kern_data_resid = 0;
9104         ctsio->kern_rel_offset = 0;
9105         ctsio->kern_sg_entries = 0;
9106
9107         /*
9108          * We set this to the actual data length, regardless of how much
9109          * space we actually have to return results.  If the user looks at
9110          * this value, he'll know whether or not he allocated enough space
9111          * and reissue the command if necessary.  We don't support well
9112          * known logical units, so if the user asks for that, return none.
9113          */
9114         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9115
9116         /*
9117          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9118          * this request.
9119          */
9120         ctl_set_success(ctsio);
9121         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9122         ctsio->be_move_done = ctl_config_move_done;
9123         ctl_datamove((union ctl_io *)ctsio);
9124         return (retval);
9125 }
9126
9127 int
9128 ctl_request_sense(struct ctl_scsiio *ctsio)
9129 {
9130         struct scsi_request_sense *cdb;
9131         struct scsi_sense_data *sense_ptr;
9132         struct ctl_softc *ctl_softc;
9133         struct ctl_lun *lun;
9134         uint32_t initidx;
9135         int have_error;
9136         scsi_sense_data_type sense_format;
9137         ctl_ua_type ua_type;
9138
9139         cdb = (struct scsi_request_sense *)ctsio->cdb;
9140
9141         ctl_softc = control_softc;
9142         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9143
9144         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9145
9146         /*
9147          * Determine which sense format the user wants.
9148          */
9149         if (cdb->byte2 & SRS_DESC)
9150                 sense_format = SSD_TYPE_DESC;
9151         else
9152                 sense_format = SSD_TYPE_FIXED;
9153
9154         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9155         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9156         ctsio->kern_sg_entries = 0;
9157
9158         /*
9159          * struct scsi_sense_data, which is currently set to 256 bytes, is
9160          * larger than the largest allowed value for the length field in the
9161          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9162          */
9163         ctsio->residual = 0;
9164         ctsio->kern_data_len = cdb->length;
9165         ctsio->kern_total_len = cdb->length;
9166
9167         ctsio->kern_data_resid = 0;
9168         ctsio->kern_rel_offset = 0;
9169         ctsio->kern_sg_entries = 0;
9170
9171         /*
9172          * If we don't have a LUN, we don't have any pending sense.
9173          */
9174         if (lun == NULL)
9175                 goto no_sense;
9176
9177         have_error = 0;
9178         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9179         /*
9180          * Check for pending sense, and then for pending unit attentions.
9181          * Pending sense gets returned first, then pending unit attentions.
9182          */
9183         mtx_lock(&lun->lun_lock);
9184 #ifdef CTL_WITH_CA
9185         if (ctl_is_set(lun->have_ca, initidx)) {
9186                 scsi_sense_data_type stored_format;
9187
9188                 /*
9189                  * Check to see which sense format was used for the stored
9190                  * sense data.
9191                  */
9192                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9193
9194                 /*
9195                  * If the user requested a different sense format than the
9196                  * one we stored, then we need to convert it to the other
9197                  * format.  If we're going from descriptor to fixed format
9198                  * sense data, we may lose things in translation, depending
9199                  * on what options were used.
9200                  *
9201                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9202                  * for some reason we'll just copy it out as-is.
9203                  */
9204                 if ((stored_format == SSD_TYPE_FIXED)
9205                  && (sense_format == SSD_TYPE_DESC))
9206                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9207                             &lun->pending_sense[initidx],
9208                             (struct scsi_sense_data_desc *)sense_ptr);
9209                 else if ((stored_format == SSD_TYPE_DESC)
9210                       && (sense_format == SSD_TYPE_FIXED))
9211                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9212                             &lun->pending_sense[initidx],
9213                             (struct scsi_sense_data_fixed *)sense_ptr);
9214                 else
9215                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9216                                MIN(sizeof(*sense_ptr),
9217                                sizeof(lun->pending_sense[initidx])));
9218
9219                 ctl_clear_mask(lun->have_ca, initidx);
9220                 have_error = 1;
9221         } else
9222 #endif
9223         {
9224                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9225                 if (ua_type != CTL_UA_NONE)
9226                         have_error = 1;
9227                 if (ua_type == CTL_UA_LUN_CHANGE) {
9228                         mtx_unlock(&lun->lun_lock);
9229                         mtx_lock(&ctl_softc->ctl_lock);
9230                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9231                         mtx_unlock(&ctl_softc->ctl_lock);
9232                         mtx_lock(&lun->lun_lock);
9233                 }
9234
9235         }
9236         mtx_unlock(&lun->lun_lock);
9237
9238         /*
9239          * We already have a pending error, return it.
9240          */
9241         if (have_error != 0) {
9242                 /*
9243                  * We report the SCSI status as OK, since the status of the
9244                  * request sense command itself is OK.
9245                  * We report 0 for the sense length, because we aren't doing
9246                  * autosense in this case.  We're reporting sense as
9247                  * parameter data.
9248                  */
9249                 ctl_set_success(ctsio);
9250                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9251                 ctsio->be_move_done = ctl_config_move_done;
9252                 ctl_datamove((union ctl_io *)ctsio);
9253                 return (CTL_RETVAL_COMPLETE);
9254         }
9255
9256 no_sense:
9257
9258         /*
9259          * No sense information to report, so we report that everything is
9260          * okay.
9261          */
9262         ctl_set_sense_data(sense_ptr,
9263                            lun,
9264                            sense_format,
9265                            /*current_error*/ 1,
9266                            /*sense_key*/ SSD_KEY_NO_SENSE,
9267                            /*asc*/ 0x00,
9268                            /*ascq*/ 0x00,
9269                            SSD_ELEM_NONE);
9270
9271         /*
9272          * We report 0 for the sense length, because we aren't doing
9273          * autosense in this case.  We're reporting sense as parameter data.
9274          */
9275         ctl_set_success(ctsio);
9276         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9277         ctsio->be_move_done = ctl_config_move_done;
9278         ctl_datamove((union ctl_io *)ctsio);
9279         return (CTL_RETVAL_COMPLETE);
9280 }
9281
9282 int
9283 ctl_tur(struct ctl_scsiio *ctsio)
9284 {
9285
9286         CTL_DEBUG_PRINT(("ctl_tur\n"));
9287
9288         ctl_set_success(ctsio);
9289         ctl_done((union ctl_io *)ctsio);
9290
9291         return (CTL_RETVAL_COMPLETE);
9292 }
9293
9294 /*
9295  * SCSI VPD page 0x00, the Supported VPD Pages page.
9296  */
9297 static int
9298 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9299 {
9300         struct scsi_vpd_supported_pages *pages;
9301         int sup_page_size;
9302         struct ctl_lun *lun;
9303         int p;
9304
9305         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9306
9307         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9308             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9309         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9310         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9311         ctsio->kern_sg_entries = 0;
9312
9313         if (sup_page_size < alloc_len) {
9314                 ctsio->residual = alloc_len - sup_page_size;
9315                 ctsio->kern_data_len = sup_page_size;
9316                 ctsio->kern_total_len = sup_page_size;
9317         } else {
9318                 ctsio->residual = 0;
9319                 ctsio->kern_data_len = alloc_len;
9320                 ctsio->kern_total_len = alloc_len;
9321         }
9322         ctsio->kern_data_resid = 0;
9323         ctsio->kern_rel_offset = 0;
9324         ctsio->kern_sg_entries = 0;
9325
9326         /*
9327          * The control device is always connected.  The disk device, on the
9328          * other hand, may not be online all the time.  Need to change this
9329          * to figure out whether the disk device is actually online or not.
9330          */
9331         if (lun != NULL)
9332                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9333                                 lun->be_lun->lun_type;
9334         else
9335                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9336
9337         p = 0;
9338         /* Supported VPD pages */
9339         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9340         /* Serial Number */
9341         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9342         /* Device Identification */
9343         pages->page_list[p++] = SVPD_DEVICE_ID;
9344         /* Extended INQUIRY Data */
9345         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9346         /* Mode Page Policy */
9347         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9348         /* SCSI Ports */
9349         pages->page_list[p++] = SVPD_SCSI_PORTS;
9350         /* Third-party Copy */
9351         pages->page_list[p++] = SVPD_SCSI_TPC;
9352         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9353                 /* Block limits */
9354                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9355                 /* Block Device Characteristics */
9356                 pages->page_list[p++] = SVPD_BDC;
9357                 /* Logical Block Provisioning */
9358                 pages->page_list[p++] = SVPD_LBP;
9359         }
9360         pages->length = p;
9361
9362         ctl_set_success(ctsio);
9363         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9364         ctsio->be_move_done = ctl_config_move_done;
9365         ctl_datamove((union ctl_io *)ctsio);
9366         return (CTL_RETVAL_COMPLETE);
9367 }
9368
9369 /*
9370  * SCSI VPD page 0x80, the Unit Serial Number page.
9371  */
9372 static int
9373 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9374 {
9375         struct scsi_vpd_unit_serial_number *sn_ptr;
9376         struct ctl_lun *lun;
9377         int data_len;
9378
9379         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9380
9381         data_len = 4 + CTL_SN_LEN;
9382         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9383         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9384         if (data_len < alloc_len) {
9385                 ctsio->residual = alloc_len - data_len;
9386                 ctsio->kern_data_len = data_len;
9387                 ctsio->kern_total_len = data_len;
9388         } else {
9389                 ctsio->residual = 0;
9390                 ctsio->kern_data_len = alloc_len;
9391                 ctsio->kern_total_len = alloc_len;
9392         }
9393         ctsio->kern_data_resid = 0;
9394         ctsio->kern_rel_offset = 0;
9395         ctsio->kern_sg_entries = 0;
9396
9397         /*
9398          * The control device is always connected.  The disk device, on the
9399          * other hand, may not be online all the time.  Need to change this
9400          * to figure out whether the disk device is actually online or not.
9401          */
9402         if (lun != NULL)
9403                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9404                                   lun->be_lun->lun_type;
9405         else
9406                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9407
9408         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9409         sn_ptr->length = CTL_SN_LEN;
9410         /*
9411          * If we don't have a LUN, we just leave the serial number as
9412          * all spaces.
9413          */
9414         if (lun != NULL) {
9415                 strncpy((char *)sn_ptr->serial_num,
9416                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9417         } else
9418                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9419
9420         ctl_set_success(ctsio);
9421         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9422         ctsio->be_move_done = ctl_config_move_done;
9423         ctl_datamove((union ctl_io *)ctsio);
9424         return (CTL_RETVAL_COMPLETE);
9425 }
9426
9427
9428 /*
9429  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9430  */
9431 static int
9432 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9433 {
9434         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9435         struct ctl_lun *lun;
9436         int data_len;
9437
9438         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9439
9440         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9441         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9442         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9443         ctsio->kern_sg_entries = 0;
9444
9445         if (data_len < alloc_len) {
9446                 ctsio->residual = alloc_len - data_len;
9447                 ctsio->kern_data_len = data_len;
9448                 ctsio->kern_total_len = data_len;
9449         } else {
9450                 ctsio->residual = 0;
9451                 ctsio->kern_data_len = alloc_len;
9452                 ctsio->kern_total_len = alloc_len;
9453         }
9454         ctsio->kern_data_resid = 0;
9455         ctsio->kern_rel_offset = 0;
9456         ctsio->kern_sg_entries = 0;
9457
9458         /*
9459          * The control device is always connected.  The disk device, on the
9460          * other hand, may not be online all the time.
9461          */
9462         if (lun != NULL)
9463                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9464                                      lun->be_lun->lun_type;
9465         else
9466                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9467         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9468         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9469         /*
9470          * We support head of queue, ordered and simple tags.
9471          */
9472         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9473         /*
9474          * Volatile cache supported.
9475          */
9476         eid_ptr->flags3 = SVPD_EID_V_SUP;
9477
9478         /*
9479          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9480          * attention for a particular IT nexus on all LUNs once we report
9481          * it to that nexus once.  This bit is required as of SPC-4.
9482          */
9483         eid_ptr->flags4 = SVPD_EID_LUICLT;
9484
9485         /*
9486          * XXX KDM in order to correctly answer this, we would need
9487          * information from the SIM to determine how much sense data it
9488          * can send.  So this would really be a path inquiry field, most
9489          * likely.  This can be set to a maximum of 252 according to SPC-4,
9490          * but the hardware may or may not be able to support that much.
9491          * 0 just means that the maximum sense data length is not reported.
9492          */
9493         eid_ptr->max_sense_length = 0;
9494
9495         ctl_set_success(ctsio);
9496         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9497         ctsio->be_move_done = ctl_config_move_done;
9498         ctl_datamove((union ctl_io *)ctsio);
9499         return (CTL_RETVAL_COMPLETE);
9500 }
9501
9502 static int
9503 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9504 {
9505         struct scsi_vpd_mode_page_policy *mpp_ptr;
9506         struct ctl_lun *lun;
9507         int data_len;
9508
9509         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9510
9511         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9512             sizeof(struct scsi_vpd_mode_page_policy_descr);
9513
9514         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9515         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9516         ctsio->kern_sg_entries = 0;
9517
9518         if (data_len < alloc_len) {
9519                 ctsio->residual = alloc_len - data_len;
9520                 ctsio->kern_data_len = data_len;
9521                 ctsio->kern_total_len = data_len;
9522         } else {
9523                 ctsio->residual = 0;
9524                 ctsio->kern_data_len = alloc_len;
9525                 ctsio->kern_total_len = alloc_len;
9526         }
9527         ctsio->kern_data_resid = 0;
9528         ctsio->kern_rel_offset = 0;
9529         ctsio->kern_sg_entries = 0;
9530
9531         /*
9532          * The control device is always connected.  The disk device, on the
9533          * other hand, may not be online all the time.
9534          */
9535         if (lun != NULL)
9536                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9537                                      lun->be_lun->lun_type;
9538         else
9539                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9540         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9541         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9542         mpp_ptr->descr[0].page_code = 0x3f;
9543         mpp_ptr->descr[0].subpage_code = 0xff;
9544         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9545
9546         ctl_set_success(ctsio);
9547         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9548         ctsio->be_move_done = ctl_config_move_done;
9549         ctl_datamove((union ctl_io *)ctsio);
9550         return (CTL_RETVAL_COMPLETE);
9551 }
9552
9553 /*
9554  * SCSI VPD page 0x83, the Device Identification page.
9555  */
9556 static int
9557 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9558 {
9559         struct scsi_vpd_device_id *devid_ptr;
9560         struct scsi_vpd_id_descriptor *desc;
9561         struct ctl_softc *softc;
9562         struct ctl_lun *lun;
9563         struct ctl_port *port;
9564         int data_len;
9565         uint8_t proto;
9566
9567         softc = control_softc;
9568
9569         port = ctl_io_port(&ctsio->io_hdr);
9570         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9571
9572         data_len = sizeof(struct scsi_vpd_device_id) +
9573             sizeof(struct scsi_vpd_id_descriptor) +
9574                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9575             sizeof(struct scsi_vpd_id_descriptor) +
9576                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9577         if (lun && lun->lun_devid)
9578                 data_len += lun->lun_devid->len;
9579         if (port && port->port_devid)
9580                 data_len += port->port_devid->len;
9581         if (port && port->target_devid)
9582                 data_len += port->target_devid->len;
9583
9584         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9585         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9586         ctsio->kern_sg_entries = 0;
9587
9588         if (data_len < alloc_len) {
9589                 ctsio->residual = alloc_len - data_len;
9590                 ctsio->kern_data_len = data_len;
9591                 ctsio->kern_total_len = data_len;
9592         } else {
9593                 ctsio->residual = 0;
9594                 ctsio->kern_data_len = alloc_len;
9595                 ctsio->kern_total_len = alloc_len;
9596         }
9597         ctsio->kern_data_resid = 0;
9598         ctsio->kern_rel_offset = 0;
9599         ctsio->kern_sg_entries = 0;
9600
9601         /*
9602          * The control device is always connected.  The disk device, on the
9603          * other hand, may not be online all the time.
9604          */
9605         if (lun != NULL)
9606                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9607                                      lun->be_lun->lun_type;
9608         else
9609                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9610         devid_ptr->page_code = SVPD_DEVICE_ID;
9611         scsi_ulto2b(data_len - 4, devid_ptr->length);
9612
9613         if (port && port->port_type == CTL_PORT_FC)
9614                 proto = SCSI_PROTO_FC << 4;
9615         else if (port && port->port_type == CTL_PORT_ISCSI)
9616                 proto = SCSI_PROTO_ISCSI << 4;
9617         else
9618                 proto = SCSI_PROTO_SPI << 4;
9619         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9620
9621         /*
9622          * We're using a LUN association here.  i.e., this device ID is a
9623          * per-LUN identifier.
9624          */
9625         if (lun && lun->lun_devid) {
9626                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9627                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9628                     lun->lun_devid->len);
9629         }
9630
9631         /*
9632          * This is for the WWPN which is a port association.
9633          */
9634         if (port && port->port_devid) {
9635                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9636                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9637                     port->port_devid->len);
9638         }
9639
9640         /*
9641          * This is for the Relative Target Port(type 4h) identifier
9642          */
9643         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9644         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9645             SVPD_ID_TYPE_RELTARG;
9646         desc->length = 4;
9647         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9648         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9649             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9650
9651         /*
9652          * This is for the Target Port Group(type 5h) identifier
9653          */
9654         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9655         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9656             SVPD_ID_TYPE_TPORTGRP;
9657         desc->length = 4;
9658         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9659             &desc->identifier[2]);
9660         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9661             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9662
9663         /*
9664          * This is for the Target identifier
9665          */
9666         if (port && port->target_devid) {
9667                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9668         }
9669
9670         ctl_set_success(ctsio);
9671         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9672         ctsio->be_move_done = ctl_config_move_done;
9673         ctl_datamove((union ctl_io *)ctsio);
9674         return (CTL_RETVAL_COMPLETE);
9675 }
9676
9677 static int
9678 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9679 {
9680         struct ctl_softc *softc = control_softc;
9681         struct scsi_vpd_scsi_ports *sp;
9682         struct scsi_vpd_port_designation *pd;
9683         struct scsi_vpd_port_designation_cont *pdc;
9684         struct ctl_lun *lun;
9685         struct ctl_port *port;
9686         int data_len, num_target_ports, iid_len, id_len;
9687
9688         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9689
9690         num_target_ports = 0;
9691         iid_len = 0;
9692         id_len = 0;
9693         mtx_lock(&softc->ctl_lock);
9694         STAILQ_FOREACH(port, &softc->port_list, links) {
9695                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9696                         continue;
9697                 if (lun != NULL &&
9698                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9699                         continue;
9700                 num_target_ports++;
9701                 if (port->init_devid)
9702                         iid_len += port->init_devid->len;
9703                 if (port->port_devid)
9704                         id_len += port->port_devid->len;
9705         }
9706         mtx_unlock(&softc->ctl_lock);
9707
9708         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9709             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9710              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9711         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9712         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9713         ctsio->kern_sg_entries = 0;
9714
9715         if (data_len < alloc_len) {
9716                 ctsio->residual = alloc_len - data_len;
9717                 ctsio->kern_data_len = data_len;
9718                 ctsio->kern_total_len = data_len;
9719         } else {
9720                 ctsio->residual = 0;
9721                 ctsio->kern_data_len = alloc_len;
9722                 ctsio->kern_total_len = alloc_len;
9723         }
9724         ctsio->kern_data_resid = 0;
9725         ctsio->kern_rel_offset = 0;
9726         ctsio->kern_sg_entries = 0;
9727
9728         /*
9729          * The control device is always connected.  The disk device, on the
9730          * other hand, may not be online all the time.  Need to change this
9731          * to figure out whether the disk device is actually online or not.
9732          */
9733         if (lun != NULL)
9734                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9735                                   lun->be_lun->lun_type;
9736         else
9737                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9738
9739         sp->page_code = SVPD_SCSI_PORTS;
9740         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9741             sp->page_length);
9742         pd = &sp->design[0];
9743
9744         mtx_lock(&softc->ctl_lock);
9745         STAILQ_FOREACH(port, &softc->port_list, links) {
9746                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9747                         continue;
9748                 if (lun != NULL &&
9749                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9750                         continue;
9751                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9752                 if (port->init_devid) {
9753                         iid_len = port->init_devid->len;
9754                         memcpy(pd->initiator_transportid,
9755                             port->init_devid->data, port->init_devid->len);
9756                 } else
9757                         iid_len = 0;
9758                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9759                 pdc = (struct scsi_vpd_port_designation_cont *)
9760                     (&pd->initiator_transportid[iid_len]);
9761                 if (port->port_devid) {
9762                         id_len = port->port_devid->len;
9763                         memcpy(pdc->target_port_descriptors,
9764                             port->port_devid->data, port->port_devid->len);
9765                 } else
9766                         id_len = 0;
9767                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9768                 pd = (struct scsi_vpd_port_designation *)
9769                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9770         }
9771         mtx_unlock(&softc->ctl_lock);
9772
9773         ctl_set_success(ctsio);
9774         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9775         ctsio->be_move_done = ctl_config_move_done;
9776         ctl_datamove((union ctl_io *)ctsio);
9777         return (CTL_RETVAL_COMPLETE);
9778 }
9779
9780 static int
9781 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9782 {
9783         struct scsi_vpd_block_limits *bl_ptr;
9784         struct ctl_lun *lun;
9785
9786         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9787
9788         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9789         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9790         ctsio->kern_sg_entries = 0;
9791
9792         if (sizeof(*bl_ptr) < alloc_len) {
9793                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9794                 ctsio->kern_data_len = sizeof(*bl_ptr);
9795                 ctsio->kern_total_len = sizeof(*bl_ptr);
9796         } else {
9797                 ctsio->residual = 0;
9798                 ctsio->kern_data_len = alloc_len;
9799                 ctsio->kern_total_len = alloc_len;
9800         }
9801         ctsio->kern_data_resid = 0;
9802         ctsio->kern_rel_offset = 0;
9803         ctsio->kern_sg_entries = 0;
9804
9805         /*
9806          * The control device is always connected.  The disk device, on the
9807          * other hand, may not be online all the time.  Need to change this
9808          * to figure out whether the disk device is actually online or not.
9809          */
9810         if (lun != NULL)
9811                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9812                                   lun->be_lun->lun_type;
9813         else
9814                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9815
9816         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9817         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9818         bl_ptr->max_cmp_write_len = 0xff;
9819         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9820         if (lun != NULL) {
9821                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9822                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9823                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9824                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9825                         if (lun->be_lun->ublockexp != 0) {
9826                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9827                                     bl_ptr->opt_unmap_grain);
9828                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9829                                     bl_ptr->unmap_grain_align);
9830                         }
9831                 }
9832                 scsi_ulto4b(lun->be_lun->atomicblock,
9833                     bl_ptr->max_atomic_transfer_length);
9834                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9835                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9836                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9837                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9838         }
9839         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9840
9841         ctl_set_success(ctsio);
9842         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9843         ctsio->be_move_done = ctl_config_move_done;
9844         ctl_datamove((union ctl_io *)ctsio);
9845         return (CTL_RETVAL_COMPLETE);
9846 }
9847
9848 static int
9849 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9850 {
9851         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9852         struct ctl_lun *lun;
9853         const char *value;
9854         u_int i;
9855
9856         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9857
9858         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9859         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9860         ctsio->kern_sg_entries = 0;
9861
9862         if (sizeof(*bdc_ptr) < alloc_len) {
9863                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9864                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9865                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9866         } else {
9867                 ctsio->residual = 0;
9868                 ctsio->kern_data_len = alloc_len;
9869                 ctsio->kern_total_len = alloc_len;
9870         }
9871         ctsio->kern_data_resid = 0;
9872         ctsio->kern_rel_offset = 0;
9873         ctsio->kern_sg_entries = 0;
9874
9875         /*
9876          * The control device is always connected.  The disk device, on the
9877          * other hand, may not be online all the time.  Need to change this
9878          * to figure out whether the disk device is actually online or not.
9879          */
9880         if (lun != NULL)
9881                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9882                                   lun->be_lun->lun_type;
9883         else
9884                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9885         bdc_ptr->page_code = SVPD_BDC;
9886         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9887         if (lun != NULL &&
9888             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9889                 i = strtol(value, NULL, 0);
9890         else
9891                 i = CTL_DEFAULT_ROTATION_RATE;
9892         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9893         if (lun != NULL &&
9894             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9895                 i = strtol(value, NULL, 0);
9896         else
9897                 i = 0;
9898         bdc_ptr->wab_wac_ff = (i & 0x0f);
9899         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9900
9901         ctl_set_success(ctsio);
9902         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9903         ctsio->be_move_done = ctl_config_move_done;
9904         ctl_datamove((union ctl_io *)ctsio);
9905         return (CTL_RETVAL_COMPLETE);
9906 }
9907
9908 static int
9909 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9910 {
9911         struct scsi_vpd_logical_block_prov *lbp_ptr;
9912         struct ctl_lun *lun;
9913
9914         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9915
9916         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9917         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9918         ctsio->kern_sg_entries = 0;
9919
9920         if (sizeof(*lbp_ptr) < alloc_len) {
9921                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9922                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9923                 ctsio->kern_total_len = sizeof(*lbp_ptr);
9924         } else {
9925                 ctsio->residual = 0;
9926                 ctsio->kern_data_len = alloc_len;
9927                 ctsio->kern_total_len = alloc_len;
9928         }
9929         ctsio->kern_data_resid = 0;
9930         ctsio->kern_rel_offset = 0;
9931         ctsio->kern_sg_entries = 0;
9932
9933         /*
9934          * The control device is always connected.  The disk device, on the
9935          * other hand, may not be online all the time.  Need to change this
9936          * to figure out whether the disk device is actually online or not.
9937          */
9938         if (lun != NULL)
9939                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9940                                   lun->be_lun->lun_type;
9941         else
9942                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9943
9944         lbp_ptr->page_code = SVPD_LBP;
9945         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9946         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9947         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9948                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9949                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9950                 lbp_ptr->prov_type = SVPD_LBP_THIN;
9951         }
9952
9953         ctl_set_success(ctsio);
9954         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9955         ctsio->be_move_done = ctl_config_move_done;
9956         ctl_datamove((union ctl_io *)ctsio);
9957         return (CTL_RETVAL_COMPLETE);
9958 }
9959
9960 /*
9961  * INQUIRY with the EVPD bit set.
9962  */
9963 static int
9964 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9965 {
9966         struct ctl_lun *lun;
9967         struct scsi_inquiry *cdb;
9968         int alloc_len, retval;
9969
9970         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9971         cdb = (struct scsi_inquiry *)ctsio->cdb;
9972         alloc_len = scsi_2btoul(cdb->length);
9973
9974         switch (cdb->page_code) {
9975         case SVPD_SUPPORTED_PAGES:
9976                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9977                 break;
9978         case SVPD_UNIT_SERIAL_NUMBER:
9979                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9980                 break;
9981         case SVPD_DEVICE_ID:
9982                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9983                 break;
9984         case SVPD_EXTENDED_INQUIRY_DATA:
9985                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9986                 break;
9987         case SVPD_MODE_PAGE_POLICY:
9988                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9989                 break;
9990         case SVPD_SCSI_PORTS:
9991                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9992                 break;
9993         case SVPD_SCSI_TPC:
9994                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9995                 break;
9996         case SVPD_BLOCK_LIMITS:
9997                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9998                         goto err;
9999                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10000                 break;
10001         case SVPD_BDC:
10002                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10003                         goto err;
10004                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10005                 break;
10006         case SVPD_LBP:
10007                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10008                         goto err;
10009                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10010                 break;
10011         default:
10012 err:
10013                 ctl_set_invalid_field(ctsio,
10014                                       /*sks_valid*/ 1,
10015                                       /*command*/ 1,
10016                                       /*field*/ 2,
10017                                       /*bit_valid*/ 0,
10018                                       /*bit*/ 0);
10019                 ctl_done((union ctl_io *)ctsio);
10020                 retval = CTL_RETVAL_COMPLETE;
10021                 break;
10022         }
10023
10024         return (retval);
10025 }
10026
10027 /*
10028  * Standard INQUIRY data.
10029  */
10030 static int
10031 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10032 {
10033         struct scsi_inquiry_data *inq_ptr;
10034         struct scsi_inquiry *cdb;
10035         struct ctl_softc *softc = control_softc;
10036         struct ctl_port *port;
10037         struct ctl_lun *lun;
10038         char *val;
10039         uint32_t alloc_len, data_len;
10040         ctl_port_type port_type;
10041
10042         port = ctl_io_port(&ctsio->io_hdr);
10043         port_type = port->port_type;
10044         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10045                 port_type = CTL_PORT_SCSI;
10046
10047         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10048         cdb = (struct scsi_inquiry *)ctsio->cdb;
10049         alloc_len = scsi_2btoul(cdb->length);
10050
10051         /*
10052          * We malloc the full inquiry data size here and fill it
10053          * in.  If the user only asks for less, we'll give him
10054          * that much.
10055          */
10056         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10057         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10058         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10059         ctsio->kern_sg_entries = 0;
10060         ctsio->kern_data_resid = 0;
10061         ctsio->kern_rel_offset = 0;
10062
10063         if (data_len < alloc_len) {
10064                 ctsio->residual = alloc_len - data_len;
10065                 ctsio->kern_data_len = data_len;
10066                 ctsio->kern_total_len = data_len;
10067         } else {
10068                 ctsio->residual = 0;
10069                 ctsio->kern_data_len = alloc_len;
10070                 ctsio->kern_total_len = alloc_len;
10071         }
10072
10073         if (lun != NULL) {
10074                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10075                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10076                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10077                             lun->be_lun->lun_type;
10078                 } else {
10079                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10080                             lun->be_lun->lun_type;
10081                 }
10082         } else
10083                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10084
10085         /* RMB in byte 2 is 0 */
10086         inq_ptr->version = SCSI_REV_SPC4;
10087
10088         /*
10089          * According to SAM-3, even if a device only supports a single
10090          * level of LUN addressing, it should still set the HISUP bit:
10091          *
10092          * 4.9.1 Logical unit numbers overview
10093          *
10094          * All logical unit number formats described in this standard are
10095          * hierarchical in structure even when only a single level in that
10096          * hierarchy is used. The HISUP bit shall be set to one in the
10097          * standard INQUIRY data (see SPC-2) when any logical unit number
10098          * format described in this standard is used.  Non-hierarchical
10099          * formats are outside the scope of this standard.
10100          *
10101          * Therefore we set the HiSup bit here.
10102          *
10103          * The reponse format is 2, per SPC-3.
10104          */
10105         inq_ptr->response_format = SID_HiSup | 2;
10106
10107         inq_ptr->additional_length = data_len -
10108             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10109         CTL_DEBUG_PRINT(("additional_length = %d\n",
10110                          inq_ptr->additional_length));
10111
10112         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10113         /* 16 bit addressing */
10114         if (port_type == CTL_PORT_SCSI)
10115                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10116         /* XXX set the SID_MultiP bit here if we're actually going to
10117            respond on multiple ports */
10118         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10119
10120         /* 16 bit data bus, synchronous transfers */
10121         if (port_type == CTL_PORT_SCSI)
10122                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10123         /*
10124          * XXX KDM do we want to support tagged queueing on the control
10125          * device at all?
10126          */
10127         if ((lun == NULL)
10128          || (lun->be_lun->lun_type != T_PROCESSOR))
10129                 inq_ptr->flags |= SID_CmdQue;
10130         /*
10131          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10132          * We have 8 bytes for the vendor name, and 16 bytes for the device
10133          * name and 4 bytes for the revision.
10134          */
10135         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10136             "vendor")) == NULL) {
10137                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10138         } else {
10139                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10140                 strncpy(inq_ptr->vendor, val,
10141                     min(sizeof(inq_ptr->vendor), strlen(val)));
10142         }
10143         if (lun == NULL) {
10144                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10145                     sizeof(inq_ptr->product));
10146         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10147                 switch (lun->be_lun->lun_type) {
10148                 case T_DIRECT:
10149                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10150                             sizeof(inq_ptr->product));
10151                         break;
10152                 case T_PROCESSOR:
10153                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10154                             sizeof(inq_ptr->product));
10155                         break;
10156                 default:
10157                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10158                             sizeof(inq_ptr->product));
10159                         break;
10160                 }
10161         } else {
10162                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10163                 strncpy(inq_ptr->product, val,
10164                     min(sizeof(inq_ptr->product), strlen(val)));
10165         }
10166
10167         /*
10168          * XXX make this a macro somewhere so it automatically gets
10169          * incremented when we make changes.
10170          */
10171         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10172             "revision")) == NULL) {
10173                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10174         } else {
10175                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10176                 strncpy(inq_ptr->revision, val,
10177                     min(sizeof(inq_ptr->revision), strlen(val)));
10178         }
10179
10180         /*
10181          * For parallel SCSI, we support double transition and single
10182          * transition clocking.  We also support QAS (Quick Arbitration
10183          * and Selection) and Information Unit transfers on both the
10184          * control and array devices.
10185          */
10186         if (port_type == CTL_PORT_SCSI)
10187                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10188                                     SID_SPI_IUS;
10189
10190         /* SAM-5 (no version claimed) */
10191         scsi_ulto2b(0x00A0, inq_ptr->version1);
10192         /* SPC-4 (no version claimed) */
10193         scsi_ulto2b(0x0460, inq_ptr->version2);
10194         if (port_type == CTL_PORT_FC) {
10195                 /* FCP-2 ANSI INCITS.350:2003 */
10196                 scsi_ulto2b(0x0917, inq_ptr->version3);
10197         } else if (port_type == CTL_PORT_SCSI) {
10198                 /* SPI-4 ANSI INCITS.362:200x */
10199                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10200         } else if (port_type == CTL_PORT_ISCSI) {
10201                 /* iSCSI (no version claimed) */
10202                 scsi_ulto2b(0x0960, inq_ptr->version3);
10203         } else if (port_type == CTL_PORT_SAS) {
10204                 /* SAS (no version claimed) */
10205                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10206         }
10207
10208         if (lun == NULL) {
10209                 /* SBC-4 (no version claimed) */
10210                 scsi_ulto2b(0x0600, inq_ptr->version4);
10211         } else {
10212                 switch (lun->be_lun->lun_type) {
10213                 case T_DIRECT:
10214                         /* SBC-4 (no version claimed) */
10215                         scsi_ulto2b(0x0600, inq_ptr->version4);
10216                         break;
10217                 case T_PROCESSOR:
10218                 default:
10219                         break;
10220                 }
10221         }
10222
10223         ctl_set_success(ctsio);
10224         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10225         ctsio->be_move_done = ctl_config_move_done;
10226         ctl_datamove((union ctl_io *)ctsio);
10227         return (CTL_RETVAL_COMPLETE);
10228 }
10229
10230 int
10231 ctl_inquiry(struct ctl_scsiio *ctsio)
10232 {
10233         struct scsi_inquiry *cdb;
10234         int retval;
10235
10236         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10237
10238         cdb = (struct scsi_inquiry *)ctsio->cdb;
10239         if (cdb->byte2 & SI_EVPD)
10240                 retval = ctl_inquiry_evpd(ctsio);
10241         else if (cdb->page_code == 0)
10242                 retval = ctl_inquiry_std(ctsio);
10243         else {
10244                 ctl_set_invalid_field(ctsio,
10245                                       /*sks_valid*/ 1,
10246                                       /*command*/ 1,
10247                                       /*field*/ 2,
10248                                       /*bit_valid*/ 0,
10249                                       /*bit*/ 0);
10250                 ctl_done((union ctl_io *)ctsio);
10251                 return (CTL_RETVAL_COMPLETE);
10252         }
10253
10254         return (retval);
10255 }
10256
10257 /*
10258  * For known CDB types, parse the LBA and length.
10259  */
10260 static int
10261 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10262 {
10263         if (io->io_hdr.io_type != CTL_IO_SCSI)
10264                 return (1);
10265
10266         switch (io->scsiio.cdb[0]) {
10267         case COMPARE_AND_WRITE: {
10268                 struct scsi_compare_and_write *cdb;
10269
10270                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10271
10272                 *lba = scsi_8btou64(cdb->addr);
10273                 *len = cdb->length;
10274                 break;
10275         }
10276         case READ_6:
10277         case WRITE_6: {
10278                 struct scsi_rw_6 *cdb;
10279
10280                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10281
10282                 *lba = scsi_3btoul(cdb->addr);
10283                 /* only 5 bits are valid in the most significant address byte */
10284                 *lba &= 0x1fffff;
10285                 *len = cdb->length;
10286                 break;
10287         }
10288         case READ_10:
10289         case WRITE_10: {
10290                 struct scsi_rw_10 *cdb;
10291
10292                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10293
10294                 *lba = scsi_4btoul(cdb->addr);
10295                 *len = scsi_2btoul(cdb->length);
10296                 break;
10297         }
10298         case WRITE_VERIFY_10: {
10299                 struct scsi_write_verify_10 *cdb;
10300
10301                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10302
10303                 *lba = scsi_4btoul(cdb->addr);
10304                 *len = scsi_2btoul(cdb->length);
10305                 break;
10306         }
10307         case READ_12:
10308         case WRITE_12: {
10309                 struct scsi_rw_12 *cdb;
10310
10311                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10312
10313                 *lba = scsi_4btoul(cdb->addr);
10314                 *len = scsi_4btoul(cdb->length);
10315                 break;
10316         }
10317         case WRITE_VERIFY_12: {
10318                 struct scsi_write_verify_12 *cdb;
10319
10320                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10321
10322                 *lba = scsi_4btoul(cdb->addr);
10323                 *len = scsi_4btoul(cdb->length);
10324                 break;
10325         }
10326         case READ_16:
10327         case WRITE_16: {
10328                 struct scsi_rw_16 *cdb;
10329
10330                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10331
10332                 *lba = scsi_8btou64(cdb->addr);
10333                 *len = scsi_4btoul(cdb->length);
10334                 break;
10335         }
10336         case WRITE_ATOMIC_16: {
10337                 struct scsi_write_atomic_16 *cdb;
10338
10339                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10340
10341                 *lba = scsi_8btou64(cdb->addr);
10342                 *len = scsi_2btoul(cdb->length);
10343                 break;
10344         }
10345         case WRITE_VERIFY_16: {
10346                 struct scsi_write_verify_16 *cdb;
10347
10348                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10349
10350                 *lba = scsi_8btou64(cdb->addr);
10351                 *len = scsi_4btoul(cdb->length);
10352                 break;
10353         }
10354         case WRITE_SAME_10: {
10355                 struct scsi_write_same_10 *cdb;
10356
10357                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10358
10359                 *lba = scsi_4btoul(cdb->addr);
10360                 *len = scsi_2btoul(cdb->length);
10361                 break;
10362         }
10363         case WRITE_SAME_16: {
10364                 struct scsi_write_same_16 *cdb;
10365
10366                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10367
10368                 *lba = scsi_8btou64(cdb->addr);
10369                 *len = scsi_4btoul(cdb->length);
10370                 break;
10371         }
10372         case VERIFY_10: {
10373                 struct scsi_verify_10 *cdb;
10374
10375                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10376
10377                 *lba = scsi_4btoul(cdb->addr);
10378                 *len = scsi_2btoul(cdb->length);
10379                 break;
10380         }
10381         case VERIFY_12: {
10382                 struct scsi_verify_12 *cdb;
10383
10384                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10385
10386                 *lba = scsi_4btoul(cdb->addr);
10387                 *len = scsi_4btoul(cdb->length);
10388                 break;
10389         }
10390         case VERIFY_16: {
10391                 struct scsi_verify_16 *cdb;
10392
10393                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10394
10395                 *lba = scsi_8btou64(cdb->addr);
10396                 *len = scsi_4btoul(cdb->length);
10397                 break;
10398         }
10399         case UNMAP: {
10400                 *lba = 0;
10401                 *len = UINT64_MAX;
10402                 break;
10403         }
10404         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10405                 struct scsi_get_lba_status *cdb;
10406
10407                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10408                 *lba = scsi_8btou64(cdb->addr);
10409                 *len = UINT32_MAX;
10410                 break;
10411         }
10412         default:
10413                 return (1);
10414                 break; /* NOTREACHED */
10415         }
10416
10417         return (0);
10418 }
10419
10420 static ctl_action
10421 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10422     bool seq)
10423 {
10424         uint64_t endlba1, endlba2;
10425
10426         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10427         endlba2 = lba2 + len2 - 1;
10428
10429         if ((endlba1 < lba2) || (endlba2 < lba1))
10430                 return (CTL_ACTION_PASS);
10431         else
10432                 return (CTL_ACTION_BLOCK);
10433 }
10434
10435 static int
10436 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10437 {
10438         struct ctl_ptr_len_flags *ptrlen;
10439         struct scsi_unmap_desc *buf, *end, *range;
10440         uint64_t lba;
10441         uint32_t len;
10442
10443         /* If not UNMAP -- go other way. */
10444         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10445             io->scsiio.cdb[0] != UNMAP)
10446                 return (CTL_ACTION_ERROR);
10447
10448         /* If UNMAP without data -- block and wait for data. */
10449         ptrlen = (struct ctl_ptr_len_flags *)
10450             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10451         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10452             ptrlen->ptr == NULL)
10453                 return (CTL_ACTION_BLOCK);
10454
10455         /* UNMAP with data -- check for collision. */
10456         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10457         end = buf + ptrlen->len / sizeof(*buf);
10458         for (range = buf; range < end; range++) {
10459                 lba = scsi_8btou64(range->lba);
10460                 len = scsi_4btoul(range->length);
10461                 if ((lba < lba2 + len2) && (lba + len > lba2))
10462                         return (CTL_ACTION_BLOCK);
10463         }
10464         return (CTL_ACTION_PASS);
10465 }
10466
10467 static ctl_action
10468 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10469 {
10470         uint64_t lba1, lba2;
10471         uint64_t len1, len2;
10472         int retval;
10473
10474         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10475                 return (CTL_ACTION_ERROR);
10476
10477         retval = ctl_extent_check_unmap(io1, lba2, len2);
10478         if (retval != CTL_ACTION_ERROR)
10479                 return (retval);
10480
10481         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10482                 return (CTL_ACTION_ERROR);
10483
10484         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10485                 seq = FALSE;
10486         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10487 }
10488
10489 static ctl_action
10490 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10491 {
10492         uint64_t lba1, lba2;
10493         uint64_t len1, len2;
10494
10495         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10496                 return (CTL_ACTION_PASS);
10497         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10498                 return (CTL_ACTION_ERROR);
10499         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10500                 return (CTL_ACTION_ERROR);
10501
10502         if (lba1 + len1 == lba2)
10503                 return (CTL_ACTION_BLOCK);
10504         return (CTL_ACTION_PASS);
10505 }
10506
10507 static ctl_action
10508 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10509     union ctl_io *ooa_io)
10510 {
10511         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10512         const ctl_serialize_action *serialize_row;
10513
10514         /*
10515          * The initiator attempted multiple untagged commands at the same
10516          * time.  Can't do that.
10517          */
10518         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10519          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10520          && ((pending_io->io_hdr.nexus.targ_port ==
10521               ooa_io->io_hdr.nexus.targ_port)
10522           && (pending_io->io_hdr.nexus.initid ==
10523               ooa_io->io_hdr.nexus.initid))
10524          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10525               CTL_FLAG_STATUS_SENT)) == 0))
10526                 return (CTL_ACTION_OVERLAP);
10527
10528         /*
10529          * The initiator attempted to send multiple tagged commands with
10530          * the same ID.  (It's fine if different initiators have the same
10531          * tag ID.)
10532          *
10533          * Even if all of those conditions are true, we don't kill the I/O
10534          * if the command ahead of us has been aborted.  We won't end up
10535          * sending it to the FETD, and it's perfectly legal to resend a
10536          * command with the same tag number as long as the previous
10537          * instance of this tag number has been aborted somehow.
10538          */
10539         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10540          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10541          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10542          && ((pending_io->io_hdr.nexus.targ_port ==
10543               ooa_io->io_hdr.nexus.targ_port)
10544           && (pending_io->io_hdr.nexus.initid ==
10545               ooa_io->io_hdr.nexus.initid))
10546          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10547               CTL_FLAG_STATUS_SENT)) == 0))
10548                 return (CTL_ACTION_OVERLAP_TAG);
10549
10550         /*
10551          * If we get a head of queue tag, SAM-3 says that we should
10552          * immediately execute it.
10553          *
10554          * What happens if this command would normally block for some other
10555          * reason?  e.g. a request sense with a head of queue tag
10556          * immediately after a write.  Normally that would block, but this
10557          * will result in its getting executed immediately...
10558          *
10559          * We currently return "pass" instead of "skip", so we'll end up
10560          * going through the rest of the queue to check for overlapped tags.
10561          *
10562          * XXX KDM check for other types of blockage first??
10563          */
10564         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10565                 return (CTL_ACTION_PASS);
10566
10567         /*
10568          * Ordered tags have to block until all items ahead of them
10569          * have completed.  If we get called with an ordered tag, we always
10570          * block, if something else is ahead of us in the queue.
10571          */
10572         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10573                 return (CTL_ACTION_BLOCK);
10574
10575         /*
10576          * Simple tags get blocked until all head of queue and ordered tags
10577          * ahead of them have completed.  I'm lumping untagged commands in
10578          * with simple tags here.  XXX KDM is that the right thing to do?
10579          */
10580         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10581           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10582          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10583           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10584                 return (CTL_ACTION_BLOCK);
10585
10586         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10587         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10588
10589         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10590
10591         switch (serialize_row[pending_entry->seridx]) {
10592         case CTL_SER_BLOCK:
10593                 return (CTL_ACTION_BLOCK);
10594         case CTL_SER_EXTENT:
10595                 return (ctl_extent_check(ooa_io, pending_io,
10596                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10597         case CTL_SER_EXTENTOPT:
10598                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10599                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10600                         return (ctl_extent_check(ooa_io, pending_io,
10601                             (lun->be_lun &&
10602                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10603                 return (CTL_ACTION_PASS);
10604         case CTL_SER_EXTENTSEQ:
10605                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10606                         return (ctl_extent_check_seq(ooa_io, pending_io));
10607                 return (CTL_ACTION_PASS);
10608         case CTL_SER_PASS:
10609                 return (CTL_ACTION_PASS);
10610         case CTL_SER_BLOCKOPT:
10611                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10612                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10613                         return (CTL_ACTION_BLOCK);
10614                 return (CTL_ACTION_PASS);
10615         case CTL_SER_SKIP:
10616                 return (CTL_ACTION_SKIP);
10617         default:
10618                 panic("invalid serialization value %d",
10619                       serialize_row[pending_entry->seridx]);
10620         }
10621
10622         return (CTL_ACTION_ERROR);
10623 }
10624
10625 /*
10626  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10627  * Assumptions:
10628  * - pending_io is generally either incoming, or on the blocked queue
10629  * - starting I/O is the I/O we want to start the check with.
10630  */
10631 static ctl_action
10632 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10633               union ctl_io *starting_io)
10634 {
10635         union ctl_io *ooa_io;
10636         ctl_action action;
10637
10638         mtx_assert(&lun->lun_lock, MA_OWNED);
10639
10640         /*
10641          * Run back along the OOA queue, starting with the current
10642          * blocked I/O and going through every I/O before it on the
10643          * queue.  If starting_io is NULL, we'll just end up returning
10644          * CTL_ACTION_PASS.
10645          */
10646         for (ooa_io = starting_io; ooa_io != NULL;
10647              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10648              ooa_links)){
10649
10650                 /*
10651                  * This routine just checks to see whether
10652                  * cur_blocked is blocked by ooa_io, which is ahead
10653                  * of it in the queue.  It doesn't queue/dequeue
10654                  * cur_blocked.
10655                  */
10656                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10657                 switch (action) {
10658                 case CTL_ACTION_BLOCK:
10659                 case CTL_ACTION_OVERLAP:
10660                 case CTL_ACTION_OVERLAP_TAG:
10661                 case CTL_ACTION_SKIP:
10662                 case CTL_ACTION_ERROR:
10663                         return (action);
10664                         break; /* NOTREACHED */
10665                 case CTL_ACTION_PASS:
10666                         break;
10667                 default:
10668                         panic("invalid action %d", action);
10669                         break;  /* NOTREACHED */
10670                 }
10671         }
10672
10673         return (CTL_ACTION_PASS);
10674 }
10675
10676 /*
10677  * Assumptions:
10678  * - An I/O has just completed, and has been removed from the per-LUN OOA
10679  *   queue, so some items on the blocked queue may now be unblocked.
10680  */
10681 static int
10682 ctl_check_blocked(struct ctl_lun *lun)
10683 {
10684         struct ctl_softc *softc = lun->ctl_softc;
10685         union ctl_io *cur_blocked, *next_blocked;
10686
10687         mtx_assert(&lun->lun_lock, MA_OWNED);
10688
10689         /*
10690          * Run forward from the head of the blocked queue, checking each
10691          * entry against the I/Os prior to it on the OOA queue to see if
10692          * there is still any blockage.
10693          *
10694          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10695          * with our removing a variable on it while it is traversing the
10696          * list.
10697          */
10698         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10699              cur_blocked != NULL; cur_blocked = next_blocked) {
10700                 union ctl_io *prev_ooa;
10701                 ctl_action action;
10702
10703                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10704                                                           blocked_links);
10705
10706                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10707                                                       ctl_ooaq, ooa_links);
10708
10709                 /*
10710                  * If cur_blocked happens to be the first item in the OOA
10711                  * queue now, prev_ooa will be NULL, and the action
10712                  * returned will just be CTL_ACTION_PASS.
10713                  */
10714                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10715
10716                 switch (action) {
10717                 case CTL_ACTION_BLOCK:
10718                         /* Nothing to do here, still blocked */
10719                         break;
10720                 case CTL_ACTION_OVERLAP:
10721                 case CTL_ACTION_OVERLAP_TAG:
10722                         /*
10723                          * This shouldn't happen!  In theory we've already
10724                          * checked this command for overlap...
10725                          */
10726                         break;
10727                 case CTL_ACTION_PASS:
10728                 case CTL_ACTION_SKIP: {
10729                         const struct ctl_cmd_entry *entry;
10730
10731                         /*
10732                          * The skip case shouldn't happen, this transaction
10733                          * should have never made it onto the blocked queue.
10734                          */
10735                         /*
10736                          * This I/O is no longer blocked, we can remove it
10737                          * from the blocked queue.  Since this is a TAILQ
10738                          * (doubly linked list), we can do O(1) removals
10739                          * from any place on the list.
10740                          */
10741                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10742                                      blocked_links);
10743                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10744
10745                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
10746                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
10747                                 /*
10748                                  * Need to send IO back to original side to
10749                                  * run
10750                                  */
10751                                 union ctl_ha_msg msg_info;
10752
10753                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10754                                 msg_info.hdr.original_sc =
10755                                         cur_blocked->io_hdr.original_sc;
10756                                 msg_info.hdr.serializing_sc = cur_blocked;
10757                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10758                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10759                                     sizeof(msg_info.hdr), M_NOWAIT);
10760                                 break;
10761                         }
10762                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10763
10764                         /*
10765                          * Check this I/O for LUN state changes that may
10766                          * have happened while this command was blocked.
10767                          * The LUN state may have been changed by a command
10768                          * ahead of us in the queue, so we need to re-check
10769                          * for any states that can be caused by SCSI
10770                          * commands.
10771                          */
10772                         if (ctl_scsiio_lun_check(lun, entry,
10773                                                  &cur_blocked->scsiio) == 0) {
10774                                 cur_blocked->io_hdr.flags |=
10775                                                       CTL_FLAG_IS_WAS_ON_RTR;
10776                                 ctl_enqueue_rtr(cur_blocked);
10777                         } else
10778                                 ctl_done(cur_blocked);
10779                         break;
10780                 }
10781                 default:
10782                         /*
10783                          * This probably shouldn't happen -- we shouldn't
10784                          * get CTL_ACTION_ERROR, or anything else.
10785                          */
10786                         break;
10787                 }
10788         }
10789
10790         return (CTL_RETVAL_COMPLETE);
10791 }
10792
10793 /*
10794  * This routine (with one exception) checks LUN flags that can be set by
10795  * commands ahead of us in the OOA queue.  These flags have to be checked
10796  * when a command initially comes in, and when we pull a command off the
10797  * blocked queue and are preparing to execute it.  The reason we have to
10798  * check these flags for commands on the blocked queue is that the LUN
10799  * state may have been changed by a command ahead of us while we're on the
10800  * blocked queue.
10801  *
10802  * Ordering is somewhat important with these checks, so please pay
10803  * careful attention to the placement of any new checks.
10804  */
10805 static int
10806 ctl_scsiio_lun_check(struct ctl_lun *lun,
10807     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10808 {
10809         struct ctl_softc *softc = lun->ctl_softc;
10810         int retval;
10811         uint32_t residx;
10812
10813         retval = 0;
10814
10815         mtx_assert(&lun->lun_lock, MA_OWNED);
10816
10817         /*
10818          * If this shelf is a secondary shelf controller, we may have to
10819          * reject some commands disallowed by HA mode and link state.
10820          */
10821         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10822                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
10823                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10824                         ctl_set_lun_unavail(ctsio);
10825                         retval = 1;
10826                         goto bailout;
10827                 }
10828                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
10829                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10830                         ctl_set_lun_transit(ctsio);
10831                         retval = 1;
10832                         goto bailout;
10833                 }
10834                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
10835                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
10836                         ctl_set_lun_standby(ctsio);
10837                         retval = 1;
10838                         goto bailout;
10839                 }
10840
10841                 /* The rest of checks are only done on executing side */
10842                 if (softc->ha_mode == CTL_HA_MODE_XFER)
10843                         goto bailout;
10844         }
10845
10846         if (entry->pattern & CTL_LUN_PAT_WRITE) {
10847                 if (lun->be_lun &&
10848                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
10849                         ctl_set_hw_write_protected(ctsio);
10850                         retval = 1;
10851                         goto bailout;
10852                 }
10853                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10854                     .eca_and_aen & SCP_SWP) != 0) {
10855                         ctl_set_sense(ctsio, /*current_error*/ 1,
10856                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
10857                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10858                         retval = 1;
10859                         goto bailout;
10860                 }
10861         }
10862
10863         /*
10864          * Check for a reservation conflict.  If this command isn't allowed
10865          * even on reserved LUNs, and if this initiator isn't the one who
10866          * reserved us, reject the command with a reservation conflict.
10867          */
10868         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10869         if ((lun->flags & CTL_LUN_RESERVED)
10870          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10871                 if (lun->res_idx != residx) {
10872                         ctl_set_reservation_conflict(ctsio);
10873                         retval = 1;
10874                         goto bailout;
10875                 }
10876         }
10877
10878         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10879             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10880                 /* No reservation or command is allowed. */;
10881         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10882             (lun->res_type == SPR_TYPE_WR_EX ||
10883              lun->res_type == SPR_TYPE_WR_EX_RO ||
10884              lun->res_type == SPR_TYPE_WR_EX_AR)) {
10885                 /* The command is allowed for Write Exclusive resv. */;
10886         } else {
10887                 /*
10888                  * if we aren't registered or it's a res holder type
10889                  * reservation and this isn't the res holder then set a
10890                  * conflict.
10891                  */
10892                 if (ctl_get_prkey(lun, residx) == 0
10893                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10894                         ctl_set_reservation_conflict(ctsio);
10895                         retval = 1;
10896                         goto bailout;
10897                 }
10898         }
10899
10900         if ((lun->flags & CTL_LUN_OFFLINE)
10901          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
10902                 ctl_set_lun_not_ready(ctsio);
10903                 retval = 1;
10904                 goto bailout;
10905         }
10906
10907         if ((lun->flags & CTL_LUN_STOPPED)
10908          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10909                 /* "Logical unit not ready, initializing cmd. required" */
10910                 ctl_set_lun_stopped(ctsio);
10911                 retval = 1;
10912                 goto bailout;
10913         }
10914
10915         if ((lun->flags & CTL_LUN_INOPERABLE)
10916          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10917                 /* "Medium format corrupted" */
10918                 ctl_set_medium_format_corrupted(ctsio);
10919                 retval = 1;
10920                 goto bailout;
10921         }
10922
10923 bailout:
10924         return (retval);
10925 }
10926
10927 static void
10928 ctl_failover_io(union ctl_io *io, int have_lock)
10929 {
10930         ctl_set_busy(&io->scsiio);
10931         ctl_done(io);
10932 }
10933
10934 static void
10935 ctl_failover_lun(union ctl_io *rio)
10936 {
10937         struct ctl_softc *softc = control_softc;
10938         struct ctl_lun *lun;
10939         struct ctl_io_hdr *io, *next_io;
10940         uint32_t targ_lun;
10941
10942         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
10943         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
10944
10945         /* Find and lock the LUN. */
10946         mtx_lock(&softc->ctl_lock);
10947         if ((targ_lun < CTL_MAX_LUNS) &&
10948             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
10949                 mtx_lock(&lun->lun_lock);
10950                 mtx_unlock(&softc->ctl_lock);
10951                 if (lun->flags & CTL_LUN_DISABLED) {
10952                         mtx_unlock(&lun->lun_lock);
10953                         return;
10954                 }
10955         } else {
10956                 mtx_unlock(&softc->ctl_lock);
10957                 return;
10958         }
10959
10960         if (softc->ha_mode == CTL_HA_MODE_XFER) {
10961                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10962                         /* We are master */
10963                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10964                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
10965                                         io->flags |= CTL_FLAG_ABORT;
10966                                         io->flags |= CTL_FLAG_FAILOVER;
10967                                 } else { /* This can be only due to DATAMOVE */
10968                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
10969                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
10970                                         io->flags |= CTL_FLAG_IO_ACTIVE;
10971                                         io->port_status = 31340;
10972                                         ctl_enqueue_isc((union ctl_io *)io);
10973                                 }
10974                         }
10975                         /* We are slave */
10976                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10977                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10978                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
10979                                         io->flags |= CTL_FLAG_FAILOVER;
10980                                 } else {
10981                                         ctl_set_busy(&((union ctl_io *)io)->
10982                                             scsiio);
10983                                         ctl_done((union ctl_io *)io);
10984                                 }
10985                         }
10986                 }
10987         } else { /* SERIALIZE modes */
10988                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
10989                     next_io) {
10990                         /* We are master */
10991                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10992                                 TAILQ_REMOVE(&lun->blocked_queue, io,
10993                                     blocked_links);
10994                                 io->flags &= ~CTL_FLAG_BLOCKED;
10995                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10996                                 ctl_free_io((union ctl_io *)io);
10997                         }
10998                 }
10999                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11000                         /* We are master */
11001                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11002                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11003                                 ctl_free_io((union ctl_io *)io);
11004                         }
11005                         /* We are slave */
11006                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11007                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11008                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11009                                         ctl_set_busy(&((union ctl_io *)io)->
11010                                             scsiio);
11011                                         ctl_done((union ctl_io *)io);
11012                                 }
11013                         }
11014                 }
11015                 ctl_check_blocked(lun);
11016         }
11017         mtx_unlock(&lun->lun_lock);
11018 }
11019
11020 static int
11021 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11022 {
11023         struct ctl_lun *lun;
11024         const struct ctl_cmd_entry *entry;
11025         uint32_t initidx, targ_lun;
11026         int retval;
11027
11028         retval = 0;
11029
11030         lun = NULL;
11031
11032         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11033         if ((targ_lun < CTL_MAX_LUNS)
11034          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11035                 /*
11036                  * If the LUN is invalid, pretend that it doesn't exist.
11037                  * It will go away as soon as all pending I/O has been
11038                  * completed.
11039                  */
11040                 mtx_lock(&lun->lun_lock);
11041                 if (lun->flags & CTL_LUN_DISABLED) {
11042                         mtx_unlock(&lun->lun_lock);
11043                         lun = NULL;
11044                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11045                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11046                 } else {
11047                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11048                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11049                                 lun->be_lun;
11050
11051                         /*
11052                          * Every I/O goes into the OOA queue for a
11053                          * particular LUN, and stays there until completion.
11054                          */
11055 #ifdef CTL_TIME_IO
11056                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11057                                 lun->idle_time += getsbinuptime() -
11058                                     lun->last_busy;
11059                         }
11060 #endif
11061                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11062                             ooa_links);
11063                 }
11064         } else {
11065                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11066                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11067         }
11068
11069         /* Get command entry and return error if it is unsuppotyed. */
11070         entry = ctl_validate_command(ctsio);
11071         if (entry == NULL) {
11072                 if (lun)
11073                         mtx_unlock(&lun->lun_lock);
11074                 return (retval);
11075         }
11076
11077         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11078         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11079
11080         /*
11081          * Check to see whether we can send this command to LUNs that don't
11082          * exist.  This should pretty much only be the case for inquiry
11083          * and request sense.  Further checks, below, really require having
11084          * a LUN, so we can't really check the command anymore.  Just put
11085          * it on the rtr queue.
11086          */
11087         if (lun == NULL) {
11088                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11089                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11090                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11091                         return (retval);
11092                 }
11093
11094                 ctl_set_unsupported_lun(ctsio);
11095                 ctl_done((union ctl_io *)ctsio);
11096                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11097                 return (retval);
11098         } else {
11099                 /*
11100                  * Make sure we support this particular command on this LUN.
11101                  * e.g., we don't support writes to the control LUN.
11102                  */
11103                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11104                         mtx_unlock(&lun->lun_lock);
11105                         ctl_set_invalid_opcode(ctsio);
11106                         ctl_done((union ctl_io *)ctsio);
11107                         return (retval);
11108                 }
11109         }
11110
11111         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11112
11113 #ifdef CTL_WITH_CA
11114         /*
11115          * If we've got a request sense, it'll clear the contingent
11116          * allegiance condition.  Otherwise, if we have a CA condition for
11117          * this initiator, clear it, because it sent down a command other
11118          * than request sense.
11119          */
11120         if ((ctsio->cdb[0] != REQUEST_SENSE)
11121          && (ctl_is_set(lun->have_ca, initidx)))
11122                 ctl_clear_mask(lun->have_ca, initidx);
11123 #endif
11124
11125         /*
11126          * If the command has this flag set, it handles its own unit
11127          * attention reporting, we shouldn't do anything.  Otherwise we
11128          * check for any pending unit attentions, and send them back to the
11129          * initiator.  We only do this when a command initially comes in,
11130          * not when we pull it off the blocked queue.
11131          *
11132          * According to SAM-3, section 5.3.2, the order that things get
11133          * presented back to the host is basically unit attentions caused
11134          * by some sort of reset event, busy status, reservation conflicts
11135          * or task set full, and finally any other status.
11136          *
11137          * One issue here is that some of the unit attentions we report
11138          * don't fall into the "reset" category (e.g. "reported luns data
11139          * has changed").  So reporting it here, before the reservation
11140          * check, may be technically wrong.  I guess the only thing to do
11141          * would be to check for and report the reset events here, and then
11142          * check for the other unit attention types after we check for a
11143          * reservation conflict.
11144          *
11145          * XXX KDM need to fix this
11146          */
11147         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11148                 ctl_ua_type ua_type;
11149
11150                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11151                     SSD_TYPE_NONE);
11152                 if (ua_type != CTL_UA_NONE) {
11153                         mtx_unlock(&lun->lun_lock);
11154                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11155                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11156                         ctsio->sense_len = SSD_FULL_SIZE;
11157                         ctl_done((union ctl_io *)ctsio);
11158                         return (retval);
11159                 }
11160         }
11161
11162
11163         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11164                 mtx_unlock(&lun->lun_lock);
11165                 ctl_done((union ctl_io *)ctsio);
11166                 return (retval);
11167         }
11168
11169         /*
11170          * XXX CHD this is where we want to send IO to other side if
11171          * this LUN is secondary on this SC. We will need to make a copy
11172          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11173          * the copy we send as FROM_OTHER.
11174          * We also need to stuff the address of the original IO so we can
11175          * find it easily. Something similar will need be done on the other
11176          * side so when we are done we can find the copy.
11177          */
11178         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11179             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11180             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11181                 union ctl_ha_msg msg_info;
11182                 int isc_retval;
11183
11184                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11185                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11186                 mtx_unlock(&lun->lun_lock);
11187
11188                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11189                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11190                 msg_info.hdr.serializing_sc = NULL;
11191                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11192                 msg_info.scsi.tag_num = ctsio->tag_num;
11193                 msg_info.scsi.tag_type = ctsio->tag_type;
11194                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11195                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11196
11197                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11198                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11199                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11200                         ctl_set_busy(ctsio);
11201                         ctl_done((union ctl_io *)ctsio);
11202                         return (retval);
11203                 }
11204                 return (retval);
11205         }
11206
11207         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11208                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11209                               ctl_ooaq, ooa_links))) {
11210         case CTL_ACTION_BLOCK:
11211                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11212                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11213                                   blocked_links);
11214                 mtx_unlock(&lun->lun_lock);
11215                 return (retval);
11216         case CTL_ACTION_PASS:
11217         case CTL_ACTION_SKIP:
11218                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11219                 mtx_unlock(&lun->lun_lock);
11220                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11221                 break;
11222         case CTL_ACTION_OVERLAP:
11223                 mtx_unlock(&lun->lun_lock);
11224                 ctl_set_overlapped_cmd(ctsio);
11225                 ctl_done((union ctl_io *)ctsio);
11226                 break;
11227         case CTL_ACTION_OVERLAP_TAG:
11228                 mtx_unlock(&lun->lun_lock);
11229                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11230                 ctl_done((union ctl_io *)ctsio);
11231                 break;
11232         case CTL_ACTION_ERROR:
11233         default:
11234                 mtx_unlock(&lun->lun_lock);
11235                 ctl_set_internal_failure(ctsio,
11236                                          /*sks_valid*/ 0,
11237                                          /*retry_count*/ 0);
11238                 ctl_done((union ctl_io *)ctsio);
11239                 break;
11240         }
11241         return (retval);
11242 }
11243
11244 const struct ctl_cmd_entry *
11245 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11246 {
11247         const struct ctl_cmd_entry *entry;
11248         int service_action;
11249
11250         entry = &ctl_cmd_table[ctsio->cdb[0]];
11251         if (sa)
11252                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11253         if (entry->flags & CTL_CMD_FLAG_SA5) {
11254                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11255                 entry = &((const struct ctl_cmd_entry *)
11256                     entry->execute)[service_action];
11257         }
11258         return (entry);
11259 }
11260
11261 const struct ctl_cmd_entry *
11262 ctl_validate_command(struct ctl_scsiio *ctsio)
11263 {
11264         const struct ctl_cmd_entry *entry;
11265         int i, sa;
11266         uint8_t diff;
11267
11268         entry = ctl_get_cmd_entry(ctsio, &sa);
11269         if (entry->execute == NULL) {
11270                 if (sa)
11271                         ctl_set_invalid_field(ctsio,
11272                                               /*sks_valid*/ 1,
11273                                               /*command*/ 1,
11274                                               /*field*/ 1,
11275                                               /*bit_valid*/ 1,
11276                                               /*bit*/ 4);
11277                 else
11278                         ctl_set_invalid_opcode(ctsio);
11279                 ctl_done((union ctl_io *)ctsio);
11280                 return (NULL);
11281         }
11282         KASSERT(entry->length > 0,
11283             ("Not defined length for command 0x%02x/0x%02x",
11284              ctsio->cdb[0], ctsio->cdb[1]));
11285         for (i = 1; i < entry->length; i++) {
11286                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11287                 if (diff == 0)
11288                         continue;
11289                 ctl_set_invalid_field(ctsio,
11290                                       /*sks_valid*/ 1,
11291                                       /*command*/ 1,
11292                                       /*field*/ i,
11293                                       /*bit_valid*/ 1,
11294                                       /*bit*/ fls(diff) - 1);
11295                 ctl_done((union ctl_io *)ctsio);
11296                 return (NULL);
11297         }
11298         return (entry);
11299 }
11300
11301 static int
11302 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11303 {
11304
11305         switch (lun_type) {
11306         case T_PROCESSOR:
11307                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11308                         return (0);
11309                 break;
11310         case T_DIRECT:
11311                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11312                         return (0);
11313                 break;
11314         default:
11315                 return (0);
11316         }
11317         return (1);
11318 }
11319
11320 static int
11321 ctl_scsiio(struct ctl_scsiio *ctsio)
11322 {
11323         int retval;
11324         const struct ctl_cmd_entry *entry;
11325
11326         retval = CTL_RETVAL_COMPLETE;
11327
11328         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11329
11330         entry = ctl_get_cmd_entry(ctsio, NULL);
11331
11332         /*
11333          * If this I/O has been aborted, just send it straight to
11334          * ctl_done() without executing it.
11335          */
11336         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11337                 ctl_done((union ctl_io *)ctsio);
11338                 goto bailout;
11339         }
11340
11341         /*
11342          * All the checks should have been handled by ctl_scsiio_precheck().
11343          * We should be clear now to just execute the I/O.
11344          */
11345         retval = entry->execute(ctsio);
11346
11347 bailout:
11348         return (retval);
11349 }
11350
11351 /*
11352  * Since we only implement one target right now, a bus reset simply resets
11353  * our single target.
11354  */
11355 static int
11356 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11357 {
11358         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11359 }
11360
11361 static int
11362 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11363                  ctl_ua_type ua_type)
11364 {
11365         struct ctl_port *port;
11366         struct ctl_lun *lun;
11367         int retval;
11368
11369         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11370                 union ctl_ha_msg msg_info;
11371
11372                 msg_info.hdr.nexus = io->io_hdr.nexus;
11373                 if (ua_type==CTL_UA_TARG_RESET)
11374                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11375                 else
11376                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11377                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11378                 msg_info.hdr.original_sc = NULL;
11379                 msg_info.hdr.serializing_sc = NULL;
11380                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11381                     sizeof(msg_info.task), M_WAITOK);
11382         }
11383         retval = 0;
11384
11385         mtx_lock(&softc->ctl_lock);
11386         port = ctl_io_port(&io->io_hdr);
11387         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11388                 if (port != NULL &&
11389                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11390                         continue;
11391                 retval += ctl_do_lun_reset(lun, io, ua_type);
11392         }
11393         mtx_unlock(&softc->ctl_lock);
11394         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11395         return (retval);
11396 }
11397
11398 /*
11399  * The LUN should always be set.  The I/O is optional, and is used to
11400  * distinguish between I/Os sent by this initiator, and by other
11401  * initiators.  We set unit attention for initiators other than this one.
11402  * SAM-3 is vague on this point.  It does say that a unit attention should
11403  * be established for other initiators when a LUN is reset (see section
11404  * 5.7.3), but it doesn't specifically say that the unit attention should
11405  * be established for this particular initiator when a LUN is reset.  Here
11406  * is the relevant text, from SAM-3 rev 8:
11407  *
11408  * 5.7.2 When a SCSI initiator port aborts its own tasks
11409  *
11410  * When a SCSI initiator port causes its own task(s) to be aborted, no
11411  * notification that the task(s) have been aborted shall be returned to
11412  * the SCSI initiator port other than the completion response for the
11413  * command or task management function action that caused the task(s) to
11414  * be aborted and notification(s) associated with related effects of the
11415  * action (e.g., a reset unit attention condition).
11416  *
11417  * XXX KDM for now, we're setting unit attention for all initiators.
11418  */
11419 static int
11420 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11421 {
11422         union ctl_io *xio;
11423 #if 0
11424         uint32_t initidx;
11425 #endif
11426 #ifdef CTL_WITH_CA
11427         int i;
11428 #endif
11429
11430         mtx_lock(&lun->lun_lock);
11431         /*
11432          * Run through the OOA queue and abort each I/O.
11433          */
11434         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11435              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11436                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11437         }
11438
11439         /*
11440          * This version sets unit attention for every
11441          */
11442 #if 0
11443         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11444         ctl_est_ua_all(lun, initidx, ua_type);
11445 #else
11446         ctl_est_ua_all(lun, -1, ua_type);
11447 #endif
11448
11449         /*
11450          * A reset (any kind, really) clears reservations established with
11451          * RESERVE/RELEASE.  It does not clear reservations established
11452          * with PERSISTENT RESERVE OUT, but we don't support that at the
11453          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11454          * reservations made with the RESERVE/RELEASE commands, because
11455          * those commands are obsolete in SPC-3.
11456          */
11457         lun->flags &= ~CTL_LUN_RESERVED;
11458
11459 #ifdef CTL_WITH_CA
11460         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11461                 ctl_clear_mask(lun->have_ca, i);
11462 #endif
11463         mtx_unlock(&lun->lun_lock);
11464
11465         return (0);
11466 }
11467
11468 static int
11469 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11470 {
11471         struct ctl_lun *lun;
11472         uint32_t targ_lun;
11473         int retval;
11474
11475         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11476         mtx_lock(&softc->ctl_lock);
11477         if ((targ_lun >= CTL_MAX_LUNS) ||
11478             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11479                 mtx_unlock(&softc->ctl_lock);
11480                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11481                 return (1);
11482         }
11483         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11484         mtx_unlock(&softc->ctl_lock);
11485         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11486
11487         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11488                 union ctl_ha_msg msg_info;
11489
11490                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11491                 msg_info.hdr.nexus = io->io_hdr.nexus;
11492                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11493                 msg_info.hdr.original_sc = NULL;
11494                 msg_info.hdr.serializing_sc = NULL;
11495                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11496                     sizeof(msg_info.task), M_WAITOK);
11497         }
11498         return (retval);
11499 }
11500
11501 static void
11502 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11503     int other_sc)
11504 {
11505         union ctl_io *xio;
11506
11507         mtx_assert(&lun->lun_lock, MA_OWNED);
11508
11509         /*
11510          * Run through the OOA queue and attempt to find the given I/O.
11511          * The target port, initiator ID, tag type and tag number have to
11512          * match the values that we got from the initiator.  If we have an
11513          * untagged command to abort, simply abort the first untagged command
11514          * we come to.  We only allow one untagged command at a time of course.
11515          */
11516         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11517              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11518
11519                 if ((targ_port == UINT32_MAX ||
11520                      targ_port == xio->io_hdr.nexus.targ_port) &&
11521                     (init_id == UINT32_MAX ||
11522                      init_id == xio->io_hdr.nexus.initid)) {
11523                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11524                             init_id != xio->io_hdr.nexus.initid)
11525                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11526                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11527                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11528                                 union ctl_ha_msg msg_info;
11529
11530                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11531                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11532                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11533                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11534                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11535                                 msg_info.hdr.original_sc = NULL;
11536                                 msg_info.hdr.serializing_sc = NULL;
11537                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11538                                     sizeof(msg_info.task), M_NOWAIT);
11539                         }
11540                 }
11541         }
11542 }
11543
11544 static int
11545 ctl_abort_task_set(union ctl_io *io)
11546 {
11547         struct ctl_softc *softc = control_softc;
11548         struct ctl_lun *lun;
11549         uint32_t targ_lun;
11550
11551         /*
11552          * Look up the LUN.
11553          */
11554         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11555         mtx_lock(&softc->ctl_lock);
11556         if ((targ_lun >= CTL_MAX_LUNS) ||
11557             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11558                 mtx_unlock(&softc->ctl_lock);
11559                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11560                 return (1);
11561         }
11562
11563         mtx_lock(&lun->lun_lock);
11564         mtx_unlock(&softc->ctl_lock);
11565         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11566                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11567                     io->io_hdr.nexus.initid,
11568                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11569         } else { /* CTL_TASK_CLEAR_TASK_SET */
11570                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11571                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11572         }
11573         mtx_unlock(&lun->lun_lock);
11574         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11575         return (0);
11576 }
11577
11578 static int
11579 ctl_i_t_nexus_reset(union ctl_io *io)
11580 {
11581         struct ctl_softc *softc = control_softc;
11582         struct ctl_lun *lun;
11583         uint32_t initidx;
11584
11585         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11586                 union ctl_ha_msg msg_info;
11587
11588                 msg_info.hdr.nexus = io->io_hdr.nexus;
11589                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11590                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11591                 msg_info.hdr.original_sc = NULL;
11592                 msg_info.hdr.serializing_sc = NULL;
11593                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11594                     sizeof(msg_info.task), M_WAITOK);
11595         }
11596
11597         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11598         mtx_lock(&softc->ctl_lock);
11599         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11600                 mtx_lock(&lun->lun_lock);
11601                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11602                     io->io_hdr.nexus.initid, 1);
11603 #ifdef CTL_WITH_CA
11604                 ctl_clear_mask(lun->have_ca, initidx);
11605 #endif
11606                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11607                         lun->flags &= ~CTL_LUN_RESERVED;
11608                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11609                 mtx_unlock(&lun->lun_lock);
11610         }
11611         mtx_unlock(&softc->ctl_lock);
11612         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11613         return (0);
11614 }
11615
11616 static int
11617 ctl_abort_task(union ctl_io *io)
11618 {
11619         union ctl_io *xio;
11620         struct ctl_lun *lun;
11621         struct ctl_softc *softc;
11622 #if 0
11623         struct sbuf sb;
11624         char printbuf[128];
11625 #endif
11626         int found;
11627         uint32_t targ_lun;
11628
11629         softc = control_softc;
11630         found = 0;
11631
11632         /*
11633          * Look up the LUN.
11634          */
11635         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11636         mtx_lock(&softc->ctl_lock);
11637         if ((targ_lun >= CTL_MAX_LUNS) ||
11638             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11639                 mtx_unlock(&softc->ctl_lock);
11640                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11641                 return (1);
11642         }
11643
11644 #if 0
11645         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11646                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11647 #endif
11648
11649         mtx_lock(&lun->lun_lock);
11650         mtx_unlock(&softc->ctl_lock);
11651         /*
11652          * Run through the OOA queue and attempt to find the given I/O.
11653          * The target port, initiator ID, tag type and tag number have to
11654          * match the values that we got from the initiator.  If we have an
11655          * untagged command to abort, simply abort the first untagged command
11656          * we come to.  We only allow one untagged command at a time of course.
11657          */
11658         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11659              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11660 #if 0
11661                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11662
11663                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11664                             lun->lun, xio->scsiio.tag_num,
11665                             xio->scsiio.tag_type,
11666                             (xio->io_hdr.blocked_links.tqe_prev
11667                             == NULL) ? "" : " BLOCKED",
11668                             (xio->io_hdr.flags &
11669                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11670                             (xio->io_hdr.flags &
11671                             CTL_FLAG_ABORT) ? " ABORT" : "",
11672                             (xio->io_hdr.flags &
11673                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11674                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11675                 sbuf_finish(&sb);
11676                 printf("%s\n", sbuf_data(&sb));
11677 #endif
11678
11679                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11680                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11681                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11682                         continue;
11683
11684                 /*
11685                  * If the abort says that the task is untagged, the
11686                  * task in the queue must be untagged.  Otherwise,
11687                  * we just check to see whether the tag numbers
11688                  * match.  This is because the QLogic firmware
11689                  * doesn't pass back the tag type in an abort
11690                  * request.
11691                  */
11692 #if 0
11693                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11694                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11695                  || (xio->scsiio.tag_num == io->taskio.tag_num))
11696 #endif
11697                 /*
11698                  * XXX KDM we've got problems with FC, because it
11699                  * doesn't send down a tag type with aborts.  So we
11700                  * can only really go by the tag number...
11701                  * This may cause problems with parallel SCSI.
11702                  * Need to figure that out!!
11703                  */
11704                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
11705                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11706                         found = 1;
11707                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11708                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11709                                 union ctl_ha_msg msg_info;
11710
11711                                 msg_info.hdr.nexus = io->io_hdr.nexus;
11712                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11713                                 msg_info.task.tag_num = io->taskio.tag_num;
11714                                 msg_info.task.tag_type = io->taskio.tag_type;
11715                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11716                                 msg_info.hdr.original_sc = NULL;
11717                                 msg_info.hdr.serializing_sc = NULL;
11718 #if 0
11719                                 printf("Sent Abort to other side\n");
11720 #endif
11721                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11722                                     sizeof(msg_info.task), M_NOWAIT);
11723                         }
11724 #if 0
11725                         printf("ctl_abort_task: found I/O to abort\n");
11726 #endif
11727                 }
11728         }
11729         mtx_unlock(&lun->lun_lock);
11730
11731         if (found == 0) {
11732                 /*
11733                  * This isn't really an error.  It's entirely possible for
11734                  * the abort and command completion to cross on the wire.
11735                  * This is more of an informative/diagnostic error.
11736                  */
11737 #if 0
11738                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11739                        "%u:%u:%u tag %d type %d\n",
11740                        io->io_hdr.nexus.initid,
11741                        io->io_hdr.nexus.targ_port,
11742                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11743                        io->taskio.tag_type);
11744 #endif
11745         }
11746         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11747         return (0);
11748 }
11749
11750 static int
11751 ctl_query_task(union ctl_io *io, int task_set)
11752 {
11753         union ctl_io *xio;
11754         struct ctl_lun *lun;
11755         struct ctl_softc *softc;
11756         int found = 0;
11757         uint32_t targ_lun;
11758
11759         softc = control_softc;
11760         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11761         mtx_lock(&softc->ctl_lock);
11762         if ((targ_lun >= CTL_MAX_LUNS) ||
11763             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11764                 mtx_unlock(&softc->ctl_lock);
11765                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11766                 return (1);
11767         }
11768         mtx_lock(&lun->lun_lock);
11769         mtx_unlock(&softc->ctl_lock);
11770         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11771              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11772
11773                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11774                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11775                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11776                         continue;
11777
11778                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11779                         found = 1;
11780                         break;
11781                 }
11782         }
11783         mtx_unlock(&lun->lun_lock);
11784         if (found)
11785                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11786         else
11787                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11788         return (0);
11789 }
11790
11791 static int
11792 ctl_query_async_event(union ctl_io *io)
11793 {
11794         struct ctl_lun *lun;
11795         struct ctl_softc *softc;
11796         ctl_ua_type ua;
11797         uint32_t targ_lun, initidx;
11798
11799         softc = control_softc;
11800         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11801         mtx_lock(&softc->ctl_lock);
11802         if ((targ_lun >= CTL_MAX_LUNS) ||
11803             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11804                 mtx_unlock(&softc->ctl_lock);
11805                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11806                 return (1);
11807         }
11808         mtx_lock(&lun->lun_lock);
11809         mtx_unlock(&softc->ctl_lock);
11810         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11811         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
11812         mtx_unlock(&lun->lun_lock);
11813         if (ua != CTL_UA_NONE)
11814                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11815         else
11816                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11817         return (0);
11818 }
11819
11820 static void
11821 ctl_run_task(union ctl_io *io)
11822 {
11823         struct ctl_softc *softc = control_softc;
11824         int retval = 1;
11825
11826         CTL_DEBUG_PRINT(("ctl_run_task\n"));
11827         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11828             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
11829         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
11830         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
11831         switch (io->taskio.task_action) {
11832         case CTL_TASK_ABORT_TASK:
11833                 retval = ctl_abort_task(io);
11834                 break;
11835         case CTL_TASK_ABORT_TASK_SET:
11836         case CTL_TASK_CLEAR_TASK_SET:
11837                 retval = ctl_abort_task_set(io);
11838                 break;
11839         case CTL_TASK_CLEAR_ACA:
11840                 break;
11841         case CTL_TASK_I_T_NEXUS_RESET:
11842                 retval = ctl_i_t_nexus_reset(io);
11843                 break;
11844         case CTL_TASK_LUN_RESET:
11845                 retval = ctl_lun_reset(softc, io);
11846                 break;
11847         case CTL_TASK_TARGET_RESET:
11848                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11849                 break;
11850         case CTL_TASK_BUS_RESET:
11851                 retval = ctl_bus_reset(softc, io);
11852                 break;
11853         case CTL_TASK_PORT_LOGIN:
11854                 break;
11855         case CTL_TASK_PORT_LOGOUT:
11856                 break;
11857         case CTL_TASK_QUERY_TASK:
11858                 retval = ctl_query_task(io, 0);
11859                 break;
11860         case CTL_TASK_QUERY_TASK_SET:
11861                 retval = ctl_query_task(io, 1);
11862                 break;
11863         case CTL_TASK_QUERY_ASYNC_EVENT:
11864                 retval = ctl_query_async_event(io);
11865                 break;
11866         default:
11867                 printf("%s: got unknown task management event %d\n",
11868                        __func__, io->taskio.task_action);
11869                 break;
11870         }
11871         if (retval == 0)
11872                 io->io_hdr.status = CTL_SUCCESS;
11873         else
11874                 io->io_hdr.status = CTL_ERROR;
11875         ctl_done(io);
11876 }
11877
11878 /*
11879  * For HA operation.  Handle commands that come in from the other
11880  * controller.
11881  */
11882 static void
11883 ctl_handle_isc(union ctl_io *io)
11884 {
11885         int free_io;
11886         struct ctl_lun *lun;
11887         struct ctl_softc *softc = control_softc;
11888         uint32_t targ_lun;
11889
11890         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11891         lun = softc->ctl_luns[targ_lun];
11892
11893         switch (io->io_hdr.msg_type) {
11894         case CTL_MSG_SERIALIZE:
11895                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11896                 break;
11897         case CTL_MSG_R2R: {
11898                 const struct ctl_cmd_entry *entry;
11899
11900                 /*
11901                  * This is only used in SER_ONLY mode.
11902                  */
11903                 free_io = 0;
11904                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11905                 mtx_lock(&lun->lun_lock);
11906                 if (ctl_scsiio_lun_check(lun,
11907                     entry, (struct ctl_scsiio *)io) != 0) {
11908                         mtx_unlock(&lun->lun_lock);
11909                         ctl_done(io);
11910                         break;
11911                 }
11912                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11913                 mtx_unlock(&lun->lun_lock);
11914                 ctl_enqueue_rtr(io);
11915                 break;
11916         }
11917         case CTL_MSG_FINISH_IO:
11918                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
11919                         free_io = 0;
11920                         ctl_done(io);
11921                 } else {
11922                         free_io = 1;
11923                         mtx_lock(&lun->lun_lock);
11924                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11925                                      ooa_links);
11926                         ctl_check_blocked(lun);
11927                         mtx_unlock(&lun->lun_lock);
11928                 }
11929                 break;
11930         case CTL_MSG_PERS_ACTION:
11931                 ctl_hndl_per_res_out_on_other_sc(
11932                         (union ctl_ha_msg *)&io->presio.pr_msg);
11933                 free_io = 1;
11934                 break;
11935         case CTL_MSG_BAD_JUJU:
11936                 free_io = 0;
11937                 ctl_done(io);
11938                 break;
11939         case CTL_MSG_DATAMOVE:
11940                 /* Only used in XFER mode */
11941                 free_io = 0;
11942                 ctl_datamove_remote(io);
11943                 break;
11944         case CTL_MSG_DATAMOVE_DONE:
11945                 /* Only used in XFER mode */
11946                 free_io = 0;
11947                 io->scsiio.be_move_done(io);
11948                 break;
11949         case CTL_MSG_FAILOVER:
11950                 ctl_failover_lun(io);
11951                 free_io = 1;
11952                 break;
11953         default:
11954                 free_io = 1;
11955                 printf("%s: Invalid message type %d\n",
11956                        __func__, io->io_hdr.msg_type);
11957                 break;
11958         }
11959         if (free_io)
11960                 ctl_free_io(io);
11961
11962 }
11963
11964
11965 /*
11966  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11967  * there is no match.
11968  */
11969 static ctl_lun_error_pattern
11970 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11971 {
11972         const struct ctl_cmd_entry *entry;
11973         ctl_lun_error_pattern filtered_pattern, pattern;
11974
11975         pattern = desc->error_pattern;
11976
11977         /*
11978          * XXX KDM we need more data passed into this function to match a
11979          * custom pattern, and we actually need to implement custom pattern
11980          * matching.
11981          */
11982         if (pattern & CTL_LUN_PAT_CMD)
11983                 return (CTL_LUN_PAT_CMD);
11984
11985         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11986                 return (CTL_LUN_PAT_ANY);
11987
11988         entry = ctl_get_cmd_entry(ctsio, NULL);
11989
11990         filtered_pattern = entry->pattern & pattern;
11991
11992         /*
11993          * If the user requested specific flags in the pattern (e.g.
11994          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11995          * flags.
11996          *
11997          * If the user did not specify any flags, it doesn't matter whether
11998          * or not the command supports the flags.
11999          */
12000         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12001              (pattern & ~CTL_LUN_PAT_MASK))
12002                 return (CTL_LUN_PAT_NONE);
12003
12004         /*
12005          * If the user asked for a range check, see if the requested LBA
12006          * range overlaps with this command's LBA range.
12007          */
12008         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12009                 uint64_t lba1;
12010                 uint64_t len1;
12011                 ctl_action action;
12012                 int retval;
12013
12014                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12015                 if (retval != 0)
12016                         return (CTL_LUN_PAT_NONE);
12017
12018                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12019                                               desc->lba_range.len, FALSE);
12020                 /*
12021                  * A "pass" means that the LBA ranges don't overlap, so
12022                  * this doesn't match the user's range criteria.
12023                  */
12024                 if (action == CTL_ACTION_PASS)
12025                         return (CTL_LUN_PAT_NONE);
12026         }
12027
12028         return (filtered_pattern);
12029 }
12030
12031 static void
12032 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12033 {
12034         struct ctl_error_desc *desc, *desc2;
12035
12036         mtx_assert(&lun->lun_lock, MA_OWNED);
12037
12038         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12039                 ctl_lun_error_pattern pattern;
12040                 /*
12041                  * Check to see whether this particular command matches
12042                  * the pattern in the descriptor.
12043                  */
12044                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12045                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12046                         continue;
12047
12048                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12049                 case CTL_LUN_INJ_ABORTED:
12050                         ctl_set_aborted(&io->scsiio);
12051                         break;
12052                 case CTL_LUN_INJ_MEDIUM_ERR:
12053                         ctl_set_medium_error(&io->scsiio,
12054                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12055                              CTL_FLAG_DATA_OUT);
12056                         break;
12057                 case CTL_LUN_INJ_UA:
12058                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12059                          * OCCURRED */
12060                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12061                         break;
12062                 case CTL_LUN_INJ_CUSTOM:
12063                         /*
12064                          * We're assuming the user knows what he is doing.
12065                          * Just copy the sense information without doing
12066                          * checks.
12067                          */
12068                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12069                               MIN(sizeof(desc->custom_sense),
12070                                   sizeof(io->scsiio.sense_data)));
12071                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12072                         io->scsiio.sense_len = SSD_FULL_SIZE;
12073                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12074                         break;
12075                 case CTL_LUN_INJ_NONE:
12076                 default:
12077                         /*
12078                          * If this is an error injection type we don't know
12079                          * about, clear the continuous flag (if it is set)
12080                          * so it will get deleted below.
12081                          */
12082                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12083                         break;
12084                 }
12085                 /*
12086                  * By default, each error injection action is a one-shot
12087                  */
12088                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12089                         continue;
12090
12091                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12092
12093                 free(desc, M_CTL);
12094         }
12095 }
12096
12097 #ifdef CTL_IO_DELAY
12098 static void
12099 ctl_datamove_timer_wakeup(void *arg)
12100 {
12101         union ctl_io *io;
12102
12103         io = (union ctl_io *)arg;
12104
12105         ctl_datamove(io);
12106 }
12107 #endif /* CTL_IO_DELAY */
12108
12109 void
12110 ctl_datamove(union ctl_io *io)
12111 {
12112         struct ctl_lun *lun;
12113         void (*fe_datamove)(union ctl_io *io);
12114
12115         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12116
12117         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12118
12119         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12120 #ifdef CTL_TIME_IO
12121         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12122                 char str[256];
12123                 char path_str[64];
12124                 struct sbuf sb;
12125
12126                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12127                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12128
12129                 sbuf_cat(&sb, path_str);
12130                 switch (io->io_hdr.io_type) {
12131                 case CTL_IO_SCSI:
12132                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12133                         sbuf_printf(&sb, "\n");
12134                         sbuf_cat(&sb, path_str);
12135                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12136                                     io->scsiio.tag_num, io->scsiio.tag_type);
12137                         break;
12138                 case CTL_IO_TASK:
12139                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12140                                     "Tag Type: %d\n", io->taskio.task_action,
12141                                     io->taskio.tag_num, io->taskio.tag_type);
12142                         break;
12143                 default:
12144                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12145                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12146                         break;
12147                 }
12148                 sbuf_cat(&sb, path_str);
12149                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12150                             (intmax_t)time_uptime - io->io_hdr.start_time);
12151                 sbuf_finish(&sb);
12152                 printf("%s", sbuf_data(&sb));
12153         }
12154 #endif /* CTL_TIME_IO */
12155
12156 #ifdef CTL_IO_DELAY
12157         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12158                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12159         } else {
12160                 if ((lun != NULL)
12161                  && (lun->delay_info.datamove_delay > 0)) {
12162
12163                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12164                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12165                         callout_reset(&io->io_hdr.delay_callout,
12166                                       lun->delay_info.datamove_delay * hz,
12167                                       ctl_datamove_timer_wakeup, io);
12168                         if (lun->delay_info.datamove_type ==
12169                             CTL_DELAY_TYPE_ONESHOT)
12170                                 lun->delay_info.datamove_delay = 0;
12171                         return;
12172                 }
12173         }
12174 #endif
12175
12176         /*
12177          * This command has been aborted.  Set the port status, so we fail
12178          * the data move.
12179          */
12180         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12181                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12182                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12183                        io->io_hdr.nexus.targ_port,
12184                        io->io_hdr.nexus.targ_lun);
12185                 io->io_hdr.port_status = 31337;
12186                 /*
12187                  * Note that the backend, in this case, will get the
12188                  * callback in its context.  In other cases it may get
12189                  * called in the frontend's interrupt thread context.
12190                  */
12191                 io->scsiio.be_move_done(io);
12192                 return;
12193         }
12194
12195         /* Don't confuse frontend with zero length data move. */
12196         if (io->scsiio.kern_data_len == 0) {
12197                 io->scsiio.be_move_done(io);
12198                 return;
12199         }
12200
12201         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12202         fe_datamove(io);
12203 }
12204
12205 static void
12206 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12207 {
12208         union ctl_ha_msg msg;
12209 #ifdef CTL_TIME_IO
12210         struct bintime cur_bt;
12211 #endif
12212
12213         memset(&msg, 0, sizeof(msg));
12214         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12215         msg.hdr.original_sc = io;
12216         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12217         msg.hdr.nexus = io->io_hdr.nexus;
12218         msg.hdr.status = io->io_hdr.status;
12219         msg.scsi.tag_num = io->scsiio.tag_num;
12220         msg.scsi.tag_type = io->scsiio.tag_type;
12221         msg.scsi.scsi_status = io->scsiio.scsi_status;
12222         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12223                io->scsiio.sense_len);
12224         msg.scsi.sense_len = io->scsiio.sense_len;
12225         msg.scsi.sense_residual = io->scsiio.sense_residual;
12226         msg.scsi.fetd_status = io->io_hdr.port_status;
12227         msg.scsi.residual = io->scsiio.residual;
12228         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12229         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12230                 ctl_failover_io(io, /*have_lock*/ have_lock);
12231                 return;
12232         }
12233         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12234             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12235             msg.scsi.sense_len, M_WAITOK);
12236
12237 #ifdef CTL_TIME_IO
12238         getbinuptime(&cur_bt);
12239         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12240         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12241 #endif
12242         io->io_hdr.num_dmas++;
12243 }
12244
12245 /*
12246  * The DMA to the remote side is done, now we need to tell the other side
12247  * we're done so it can continue with its data movement.
12248  */
12249 static void
12250 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12251 {
12252         union ctl_io *io;
12253         int i;
12254
12255         io = rq->context;
12256
12257         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12258                 printf("%s: ISC DMA write failed with error %d", __func__,
12259                        rq->ret);
12260                 ctl_set_internal_failure(&io->scsiio,
12261                                          /*sks_valid*/ 1,
12262                                          /*retry_count*/ rq->ret);
12263         }
12264
12265         ctl_dt_req_free(rq);
12266
12267         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12268                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12269         free(io->io_hdr.remote_sglist, M_CTL);
12270         io->io_hdr.remote_sglist = NULL;
12271         io->io_hdr.local_sglist = NULL;
12272
12273         /*
12274          * The data is in local and remote memory, so now we need to send
12275          * status (good or back) back to the other side.
12276          */
12277         ctl_send_datamove_done(io, /*have_lock*/ 0);
12278 }
12279
12280 /*
12281  * We've moved the data from the host/controller into local memory.  Now we
12282  * need to push it over to the remote controller's memory.
12283  */
12284 static int
12285 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12286 {
12287         int retval;
12288
12289         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12290                                           ctl_datamove_remote_write_cb);
12291         return (retval);
12292 }
12293
12294 static void
12295 ctl_datamove_remote_write(union ctl_io *io)
12296 {
12297         int retval;
12298         void (*fe_datamove)(union ctl_io *io);
12299
12300         /*
12301          * - Get the data from the host/HBA into local memory.
12302          * - DMA memory from the local controller to the remote controller.
12303          * - Send status back to the remote controller.
12304          */
12305
12306         retval = ctl_datamove_remote_sgl_setup(io);
12307         if (retval != 0)
12308                 return;
12309
12310         /* Switch the pointer over so the FETD knows what to do */
12311         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12312
12313         /*
12314          * Use a custom move done callback, since we need to send completion
12315          * back to the other controller, not to the backend on this side.
12316          */
12317         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12318
12319         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12320         fe_datamove(io);
12321 }
12322
12323 static int
12324 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12325 {
12326 #if 0
12327         char str[256];
12328         char path_str[64];
12329         struct sbuf sb;
12330 #endif
12331         int i;
12332
12333         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12334                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12335         free(io->io_hdr.remote_sglist, M_CTL);
12336         io->io_hdr.remote_sglist = NULL;
12337         io->io_hdr.local_sglist = NULL;
12338
12339 #if 0
12340         scsi_path_string(io, path_str, sizeof(path_str));
12341         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12342         sbuf_cat(&sb, path_str);
12343         scsi_command_string(&io->scsiio, NULL, &sb);
12344         sbuf_printf(&sb, "\n");
12345         sbuf_cat(&sb, path_str);
12346         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12347                     io->scsiio.tag_num, io->scsiio.tag_type);
12348         sbuf_cat(&sb, path_str);
12349         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12350                     io->io_hdr.flags, io->io_hdr.status);
12351         sbuf_finish(&sb);
12352         printk("%s", sbuf_data(&sb));
12353 #endif
12354
12355
12356         /*
12357          * The read is done, now we need to send status (good or bad) back
12358          * to the other side.
12359          */
12360         ctl_send_datamove_done(io, /*have_lock*/ 0);
12361
12362         return (0);
12363 }
12364
12365 static void
12366 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12367 {
12368         union ctl_io *io;
12369         void (*fe_datamove)(union ctl_io *io);
12370
12371         io = rq->context;
12372
12373         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12374                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12375                        rq->ret);
12376                 ctl_set_internal_failure(&io->scsiio,
12377                                          /*sks_valid*/ 1,
12378                                          /*retry_count*/ rq->ret);
12379         }
12380
12381         ctl_dt_req_free(rq);
12382
12383         /* Switch the pointer over so the FETD knows what to do */
12384         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12385
12386         /*
12387          * Use a custom move done callback, since we need to send completion
12388          * back to the other controller, not to the backend on this side.
12389          */
12390         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12391
12392         /* XXX KDM add checks like the ones in ctl_datamove? */
12393
12394         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12395         fe_datamove(io);
12396 }
12397
12398 static int
12399 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12400 {
12401         struct ctl_sg_entry *local_sglist;
12402         uint32_t len_to_go;
12403         int retval;
12404         int i;
12405
12406         retval = 0;
12407         local_sglist = io->io_hdr.local_sglist;
12408         len_to_go = io->scsiio.kern_data_len;
12409
12410         /*
12411          * The difficult thing here is that the size of the various
12412          * S/G segments may be different than the size from the
12413          * remote controller.  That'll make it harder when DMAing
12414          * the data back to the other side.
12415          */
12416         for (i = 0; len_to_go > 0; i++) {
12417                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12418                 local_sglist[i].addr =
12419                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12420
12421                 len_to_go -= local_sglist[i].len;
12422         }
12423         /*
12424          * Reset the number of S/G entries accordingly.  The original
12425          * number of S/G entries is available in rem_sg_entries.
12426          */
12427         io->scsiio.kern_sg_entries = i;
12428
12429 #if 0
12430         printf("%s: kern_sg_entries = %d\n", __func__,
12431                io->scsiio.kern_sg_entries);
12432         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12433                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12434                        local_sglist[i].addr, local_sglist[i].len);
12435 #endif
12436
12437         return (retval);
12438 }
12439
12440 static int
12441 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12442                          ctl_ha_dt_cb callback)
12443 {
12444         struct ctl_ha_dt_req *rq;
12445         struct ctl_sg_entry *remote_sglist, *local_sglist;
12446         uint32_t local_used, remote_used, total_used;
12447         int i, j, isc_ret;
12448
12449         rq = ctl_dt_req_alloc();
12450
12451         /*
12452          * If we failed to allocate the request, and if the DMA didn't fail
12453          * anyway, set busy status.  This is just a resource allocation
12454          * failure.
12455          */
12456         if ((rq == NULL)
12457          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12458              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12459                 ctl_set_busy(&io->scsiio);
12460
12461         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12462             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12463
12464                 if (rq != NULL)
12465                         ctl_dt_req_free(rq);
12466
12467                 /*
12468                  * The data move failed.  We need to return status back
12469                  * to the other controller.  No point in trying to DMA
12470                  * data to the remote controller.
12471                  */
12472
12473                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12474
12475                 return (1);
12476         }
12477
12478         local_sglist = io->io_hdr.local_sglist;
12479         remote_sglist = io->io_hdr.remote_sglist;
12480         local_used = 0;
12481         remote_used = 0;
12482         total_used = 0;
12483
12484         /*
12485          * Pull/push the data over the wire from/to the other controller.
12486          * This takes into account the possibility that the local and
12487          * remote sglists may not be identical in terms of the size of
12488          * the elements and the number of elements.
12489          *
12490          * One fundamental assumption here is that the length allocated for
12491          * both the local and remote sglists is identical.  Otherwise, we've
12492          * essentially got a coding error of some sort.
12493          */
12494         isc_ret = CTL_HA_STATUS_SUCCESS;
12495         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12496                 uint32_t cur_len;
12497                 uint8_t *tmp_ptr;
12498
12499                 rq->command = command;
12500                 rq->context = io;
12501
12502                 /*
12503                  * Both pointers should be aligned.  But it is possible
12504                  * that the allocation length is not.  They should both
12505                  * also have enough slack left over at the end, though,
12506                  * to round up to the next 8 byte boundary.
12507                  */
12508                 cur_len = MIN(local_sglist[i].len - local_used,
12509                               remote_sglist[j].len - remote_used);
12510                 rq->size = cur_len;
12511
12512                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12513                 tmp_ptr += local_used;
12514
12515 #if 0
12516                 /* Use physical addresses when talking to ISC hardware */
12517                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12518                         /* XXX KDM use busdma */
12519                         rq->local = vtophys(tmp_ptr);
12520                 } else
12521                         rq->local = tmp_ptr;
12522 #else
12523                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12524                     ("HA does not support BUS_ADDR"));
12525                 rq->local = tmp_ptr;
12526 #endif
12527
12528                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12529                 tmp_ptr += remote_used;
12530                 rq->remote = tmp_ptr;
12531
12532                 rq->callback = NULL;
12533
12534                 local_used += cur_len;
12535                 if (local_used >= local_sglist[i].len) {
12536                         i++;
12537                         local_used = 0;
12538                 }
12539
12540                 remote_used += cur_len;
12541                 if (remote_used >= remote_sglist[j].len) {
12542                         j++;
12543                         remote_used = 0;
12544                 }
12545                 total_used += cur_len;
12546
12547                 if (total_used >= io->scsiio.kern_data_len)
12548                         rq->callback = callback;
12549
12550 #if 0
12551                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12552                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12553                        rq->local, rq->remote, rq->size);
12554 #endif
12555
12556                 isc_ret = ctl_dt_single(rq);
12557                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12558                         break;
12559         }
12560         if (isc_ret != CTL_HA_STATUS_WAIT) {
12561                 rq->ret = isc_ret;
12562                 callback(rq);
12563         }
12564
12565         return (0);
12566 }
12567
12568 static void
12569 ctl_datamove_remote_read(union ctl_io *io)
12570 {
12571         int retval;
12572         int i;
12573
12574         /*
12575          * This will send an error to the other controller in the case of a
12576          * failure.
12577          */
12578         retval = ctl_datamove_remote_sgl_setup(io);
12579         if (retval != 0)
12580                 return;
12581
12582         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12583                                           ctl_datamove_remote_read_cb);
12584         if (retval != 0) {
12585                 /*
12586                  * Make sure we free memory if there was an error..  The
12587                  * ctl_datamove_remote_xfer() function will send the
12588                  * datamove done message, or call the callback with an
12589                  * error if there is a problem.
12590                  */
12591                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12592                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12593                 free(io->io_hdr.remote_sglist, M_CTL);
12594                 io->io_hdr.remote_sglist = NULL;
12595                 io->io_hdr.local_sglist = NULL;
12596         }
12597 }
12598
12599 /*
12600  * Process a datamove request from the other controller.  This is used for
12601  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12602  * first.  Once that is complete, the data gets DMAed into the remote
12603  * controller's memory.  For reads, we DMA from the remote controller's
12604  * memory into our memory first, and then move it out to the FETD.
12605  */
12606 static void
12607 ctl_datamove_remote(union ctl_io *io)
12608 {
12609
12610         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12611
12612         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12613                 ctl_failover_io(io, /*have_lock*/ 0);
12614                 return;
12615         }
12616
12617         /*
12618          * Note that we look for an aborted I/O here, but don't do some of
12619          * the other checks that ctl_datamove() normally does.
12620          * We don't need to run the datamove delay code, since that should
12621          * have been done if need be on the other controller.
12622          */
12623         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12624                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12625                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12626                        io->io_hdr.nexus.targ_port,
12627                        io->io_hdr.nexus.targ_lun);
12628                 io->io_hdr.port_status = 31338;
12629                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12630                 return;
12631         }
12632
12633         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12634                 ctl_datamove_remote_write(io);
12635         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12636                 ctl_datamove_remote_read(io);
12637         else {
12638                 io->io_hdr.port_status = 31339;
12639                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12640         }
12641 }
12642
12643 static void
12644 ctl_process_done(union ctl_io *io)
12645 {
12646         struct ctl_lun *lun;
12647         struct ctl_softc *softc = control_softc;
12648         void (*fe_done)(union ctl_io *io);
12649         union ctl_ha_msg msg;
12650         uint32_t targ_port = io->io_hdr.nexus.targ_port;
12651
12652         CTL_DEBUG_PRINT(("ctl_process_done\n"));
12653         fe_done = softc->ctl_ports[targ_port]->fe_done;
12654
12655 #ifdef CTL_TIME_IO
12656         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12657                 char str[256];
12658                 char path_str[64];
12659                 struct sbuf sb;
12660
12661                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12662                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12663
12664                 sbuf_cat(&sb, path_str);
12665                 switch (io->io_hdr.io_type) {
12666                 case CTL_IO_SCSI:
12667                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12668                         sbuf_printf(&sb, "\n");
12669                         sbuf_cat(&sb, path_str);
12670                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12671                                     io->scsiio.tag_num, io->scsiio.tag_type);
12672                         break;
12673                 case CTL_IO_TASK:
12674                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12675                                     "Tag Type: %d\n", io->taskio.task_action,
12676                                     io->taskio.tag_num, io->taskio.tag_type);
12677                         break;
12678                 default:
12679                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12680                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12681                         break;
12682                 }
12683                 sbuf_cat(&sb, path_str);
12684                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12685                             (intmax_t)time_uptime - io->io_hdr.start_time);
12686                 sbuf_finish(&sb);
12687                 printf("%s", sbuf_data(&sb));
12688         }
12689 #endif /* CTL_TIME_IO */
12690
12691         switch (io->io_hdr.io_type) {
12692         case CTL_IO_SCSI:
12693                 break;
12694         case CTL_IO_TASK:
12695                 if (ctl_debug & CTL_DEBUG_INFO)
12696                         ctl_io_error_print(io, NULL);
12697                 fe_done(io);
12698                 return;
12699         default:
12700                 panic("ctl_process_done: invalid io type %d\n",
12701                       io->io_hdr.io_type);
12702                 break; /* NOTREACHED */
12703         }
12704
12705         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12706         if (lun == NULL) {
12707                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12708                                  io->io_hdr.nexus.targ_mapped_lun));
12709                 goto bailout;
12710         }
12711
12712         mtx_lock(&lun->lun_lock);
12713
12714         /*
12715          * Check to see if we have any errors to inject here.  We only
12716          * inject errors for commands that don't already have errors set.
12717          */
12718         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
12719             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12720             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12721                 ctl_inject_error(lun, io);
12722
12723         /*
12724          * XXX KDM how do we treat commands that aren't completed
12725          * successfully?
12726          *
12727          * XXX KDM should we also track I/O latency?
12728          */
12729         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12730             io->io_hdr.io_type == CTL_IO_SCSI) {
12731 #ifdef CTL_TIME_IO
12732                 struct bintime cur_bt;
12733 #endif
12734                 int type;
12735
12736                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12737                     CTL_FLAG_DATA_IN)
12738                         type = CTL_STATS_READ;
12739                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12740                     CTL_FLAG_DATA_OUT)
12741                         type = CTL_STATS_WRITE;
12742                 else
12743                         type = CTL_STATS_NO_IO;
12744
12745                 lun->stats.ports[targ_port].bytes[type] +=
12746                     io->scsiio.kern_total_len;
12747                 lun->stats.ports[targ_port].operations[type]++;
12748 #ifdef CTL_TIME_IO
12749                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
12750                    &io->io_hdr.dma_bt);
12751                 getbinuptime(&cur_bt);
12752                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12753                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
12754 #endif
12755                 lun->stats.ports[targ_port].num_dmas[type] +=
12756                     io->io_hdr.num_dmas;
12757         }
12758
12759         /*
12760          * Remove this from the OOA queue.
12761          */
12762         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12763 #ifdef CTL_TIME_IO
12764         if (TAILQ_EMPTY(&lun->ooa_queue))
12765                 lun->last_busy = getsbinuptime();
12766 #endif
12767
12768         /*
12769          * Run through the blocked queue on this LUN and see if anything
12770          * has become unblocked, now that this transaction is done.
12771          */
12772         ctl_check_blocked(lun);
12773
12774         /*
12775          * If the LUN has been invalidated, free it if there is nothing
12776          * left on its OOA queue.
12777          */
12778         if ((lun->flags & CTL_LUN_INVALID)
12779          && TAILQ_EMPTY(&lun->ooa_queue)) {
12780                 mtx_unlock(&lun->lun_lock);
12781                 mtx_lock(&softc->ctl_lock);
12782                 ctl_free_lun(lun);
12783                 mtx_unlock(&softc->ctl_lock);
12784         } else
12785                 mtx_unlock(&lun->lun_lock);
12786
12787 bailout:
12788
12789         /*
12790          * If this command has been aborted, make sure we set the status
12791          * properly.  The FETD is responsible for freeing the I/O and doing
12792          * whatever it needs to do to clean up its state.
12793          */
12794         if (io->io_hdr.flags & CTL_FLAG_ABORT)
12795                 ctl_set_task_aborted(&io->scsiio);
12796
12797         /*
12798          * If enabled, print command error status.
12799          */
12800         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12801             (ctl_debug & CTL_DEBUG_INFO) != 0)
12802                 ctl_io_error_print(io, NULL);
12803
12804         /*
12805          * Tell the FETD or the other shelf controller we're done with this
12806          * command.  Note that only SCSI commands get to this point.  Task
12807          * management commands are completed above.
12808          */
12809         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
12810             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
12811                 memset(&msg, 0, sizeof(msg));
12812                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12813                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12814                 msg.hdr.nexus = io->io_hdr.nexus;
12815                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12816                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
12817                     M_WAITOK);
12818         }
12819
12820         fe_done(io);
12821 }
12822
12823 #ifdef CTL_WITH_CA
12824 /*
12825  * Front end should call this if it doesn't do autosense.  When the request
12826  * sense comes back in from the initiator, we'll dequeue this and send it.
12827  */
12828 int
12829 ctl_queue_sense(union ctl_io *io)
12830 {
12831         struct ctl_lun *lun;
12832         struct ctl_port *port;
12833         struct ctl_softc *softc;
12834         uint32_t initidx, targ_lun;
12835
12836         softc = control_softc;
12837
12838         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
12839
12840         /*
12841          * LUN lookup will likely move to the ctl_work_thread() once we
12842          * have our new queueing infrastructure (that doesn't put things on
12843          * a per-LUN queue initially).  That is so that we can handle
12844          * things like an INQUIRY to a LUN that we don't have enabled.  We
12845          * can't deal with that right now.
12846          */
12847         mtx_lock(&softc->ctl_lock);
12848
12849         /*
12850          * If we don't have a LUN for this, just toss the sense
12851          * information.
12852          */
12853         port = ctl_io_port(&ctsio->io_hdr);
12854         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
12855         if ((targ_lun < CTL_MAX_LUNS)
12856          && (softc->ctl_luns[targ_lun] != NULL))
12857                 lun = softc->ctl_luns[targ_lun];
12858         else
12859                 goto bailout;
12860
12861         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12862
12863         mtx_lock(&lun->lun_lock);
12864         /*
12865          * Already have CA set for this LUN...toss the sense information.
12866          */
12867         if (ctl_is_set(lun->have_ca, initidx)) {
12868                 mtx_unlock(&lun->lun_lock);
12869                 goto bailout;
12870         }
12871
12872         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
12873                MIN(sizeof(lun->pending_sense[initidx]),
12874                sizeof(io->scsiio.sense_data)));
12875         ctl_set_mask(lun->have_ca, initidx);
12876         mtx_unlock(&lun->lun_lock);
12877
12878 bailout:
12879         mtx_unlock(&softc->ctl_lock);
12880
12881         ctl_free_io(io);
12882
12883         return (CTL_RETVAL_COMPLETE);
12884 }
12885 #endif
12886
12887 /*
12888  * Primary command inlet from frontend ports.  All SCSI and task I/O
12889  * requests must go through this function.
12890  */
12891 int
12892 ctl_queue(union ctl_io *io)
12893 {
12894         struct ctl_port *port;
12895
12896         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
12897
12898 #ifdef CTL_TIME_IO
12899         io->io_hdr.start_time = time_uptime;
12900         getbinuptime(&io->io_hdr.start_bt);
12901 #endif /* CTL_TIME_IO */
12902
12903         /* Map FE-specific LUN ID into global one. */
12904         port = ctl_io_port(&io->io_hdr);
12905         io->io_hdr.nexus.targ_mapped_lun =
12906             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
12907
12908         switch (io->io_hdr.io_type) {
12909         case CTL_IO_SCSI:
12910         case CTL_IO_TASK:
12911                 if (ctl_debug & CTL_DEBUG_CDB)
12912                         ctl_io_print(io);
12913                 ctl_enqueue_incoming(io);
12914                 break;
12915         default:
12916                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
12917                 return (EINVAL);
12918         }
12919
12920         return (CTL_RETVAL_COMPLETE);
12921 }
12922
12923 #ifdef CTL_IO_DELAY
12924 static void
12925 ctl_done_timer_wakeup(void *arg)
12926 {
12927         union ctl_io *io;
12928
12929         io = (union ctl_io *)arg;
12930         ctl_done(io);
12931 }
12932 #endif /* CTL_IO_DELAY */
12933
12934 void
12935 ctl_serseq_done(union ctl_io *io)
12936 {
12937         struct ctl_lun *lun;
12938
12939         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12940         if (lun->be_lun == NULL ||
12941             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
12942                 return;
12943         mtx_lock(&lun->lun_lock);
12944         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
12945         ctl_check_blocked(lun);
12946         mtx_unlock(&lun->lun_lock);
12947 }
12948
12949 void
12950 ctl_done(union ctl_io *io)
12951 {
12952
12953         /*
12954          * Enable this to catch duplicate completion issues.
12955          */
12956 #if 0
12957         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
12958                 printf("%s: type %d msg %d cdb %x iptl: "
12959                        "%u:%u:%u tag 0x%04x "
12960                        "flag %#x status %x\n",
12961                         __func__,
12962                         io->io_hdr.io_type,
12963                         io->io_hdr.msg_type,
12964                         io->scsiio.cdb[0],
12965                         io->io_hdr.nexus.initid,
12966                         io->io_hdr.nexus.targ_port,
12967                         io->io_hdr.nexus.targ_lun,
12968                         (io->io_hdr.io_type ==
12969                         CTL_IO_TASK) ?
12970                         io->taskio.tag_num :
12971                         io->scsiio.tag_num,
12972                         io->io_hdr.flags,
12973                         io->io_hdr.status);
12974         } else
12975                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
12976 #endif
12977
12978         /*
12979          * This is an internal copy of an I/O, and should not go through
12980          * the normal done processing logic.
12981          */
12982         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
12983                 return;
12984
12985 #ifdef CTL_IO_DELAY
12986         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12987                 struct ctl_lun *lun;
12988
12989                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12990
12991                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12992         } else {
12993                 struct ctl_lun *lun;
12994
12995                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12996
12997                 if ((lun != NULL)
12998                  && (lun->delay_info.done_delay > 0)) {
12999
13000                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13001                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13002                         callout_reset(&io->io_hdr.delay_callout,
13003                                       lun->delay_info.done_delay * hz,
13004                                       ctl_done_timer_wakeup, io);
13005                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13006                                 lun->delay_info.done_delay = 0;
13007                         return;
13008                 }
13009         }
13010 #endif /* CTL_IO_DELAY */
13011
13012         ctl_enqueue_done(io);
13013 }
13014
13015 static void
13016 ctl_work_thread(void *arg)
13017 {
13018         struct ctl_thread *thr = (struct ctl_thread *)arg;
13019         struct ctl_softc *softc = thr->ctl_softc;
13020         union ctl_io *io;
13021         int retval;
13022
13023         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13024
13025         for (;;) {
13026                 /*
13027                  * We handle the queues in this order:
13028                  * - ISC
13029                  * - done queue (to free up resources, unblock other commands)
13030                  * - RtR queue
13031                  * - incoming queue
13032                  *
13033                  * If those queues are empty, we break out of the loop and
13034                  * go to sleep.
13035                  */
13036                 mtx_lock(&thr->queue_lock);
13037                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13038                 if (io != NULL) {
13039                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13040                         mtx_unlock(&thr->queue_lock);
13041                         ctl_handle_isc(io);
13042                         continue;
13043                 }
13044                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13045                 if (io != NULL) {
13046                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13047                         /* clear any blocked commands, call fe_done */
13048                         mtx_unlock(&thr->queue_lock);
13049                         ctl_process_done(io);
13050                         continue;
13051                 }
13052                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13053                 if (io != NULL) {
13054                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13055                         mtx_unlock(&thr->queue_lock);
13056                         if (io->io_hdr.io_type == CTL_IO_TASK)
13057                                 ctl_run_task(io);
13058                         else
13059                                 ctl_scsiio_precheck(softc, &io->scsiio);
13060                         continue;
13061                 }
13062                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13063                 if (io != NULL) {
13064                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13065                         mtx_unlock(&thr->queue_lock);
13066                         retval = ctl_scsiio(&io->scsiio);
13067                         if (retval != CTL_RETVAL_COMPLETE)
13068                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13069                         continue;
13070                 }
13071
13072                 /* Sleep until we have something to do. */
13073                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13074         }
13075 }
13076
13077 static void
13078 ctl_lun_thread(void *arg)
13079 {
13080         struct ctl_softc *softc = (struct ctl_softc *)arg;
13081         struct ctl_be_lun *be_lun;
13082
13083         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13084
13085         for (;;) {
13086                 mtx_lock(&softc->ctl_lock);
13087                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13088                 if (be_lun != NULL) {
13089                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13090                         mtx_unlock(&softc->ctl_lock);
13091                         ctl_create_lun(be_lun);
13092                         continue;
13093                 }
13094
13095                 /* Sleep until we have something to do. */
13096                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13097                     PDROP | PRIBIO, "-", 0);
13098         }
13099 }
13100
13101 static void
13102 ctl_thresh_thread(void *arg)
13103 {
13104         struct ctl_softc *softc = (struct ctl_softc *)arg;
13105         struct ctl_lun *lun;
13106         struct scsi_da_rw_recovery_page *rwpage;
13107         struct ctl_logical_block_provisioning_page *page;
13108         const char *attr;
13109         union ctl_ha_msg msg;
13110         uint64_t thres, val;
13111         int i, e, set;
13112
13113         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13114
13115         for (;;) {
13116                 mtx_lock(&softc->ctl_lock);
13117                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13118                         if ((lun->flags & CTL_LUN_DISABLED) ||
13119                             (lun->flags & CTL_LUN_OFFLINE) ||
13120                             lun->backend->lun_attr == NULL)
13121                                 continue;
13122                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13123                             softc->ha_mode == CTL_HA_MODE_XFER)
13124                                 continue;
13125                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13126                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13127                                 continue;
13128                         e = 0;
13129                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13130                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13131                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13132                                         continue;
13133                                 thres = scsi_4btoul(page->descr[i].count);
13134                                 thres <<= CTL_LBP_EXPONENT;
13135                                 switch (page->descr[i].resource) {
13136                                 case 0x01:
13137                                         attr = "blocksavail";
13138                                         break;
13139                                 case 0x02:
13140                                         attr = "blocksused";
13141                                         break;
13142                                 case 0xf1:
13143                                         attr = "poolblocksavail";
13144                                         break;
13145                                 case 0xf2:
13146                                         attr = "poolblocksused";
13147                                         break;
13148                                 default:
13149                                         continue;
13150                                 }
13151                                 mtx_unlock(&softc->ctl_lock); // XXX
13152                                 val = lun->backend->lun_attr(
13153                                     lun->be_lun->be_lun, attr);
13154                                 mtx_lock(&softc->ctl_lock);
13155                                 if (val == UINT64_MAX)
13156                                         continue;
13157                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13158                                     == SLBPPD_ARMING_INC)
13159                                         e = (val >= thres);
13160                                 else
13161                                         e = (val <= thres);
13162                                 if (e)
13163                                         break;
13164                         }
13165                         mtx_lock(&lun->lun_lock);
13166                         if (e) {
13167                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13168                                     (uint8_t *)page, lun->ua_tpt_info);
13169                                 if (lun->lasttpt == 0 ||
13170                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13171                                         lun->lasttpt = time_uptime;
13172                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13173                                         set = 1;
13174                                 } else
13175                                         set = 0;
13176                         } else {
13177                                 lun->lasttpt = 0;
13178                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13179                                 set = -1;
13180                         }
13181                         mtx_unlock(&lun->lun_lock);
13182                         if (set != 0 &&
13183                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13184                                 /* Send msg to other side. */
13185                                 bzero(&msg.ua, sizeof(msg.ua));
13186                                 msg.hdr.msg_type = CTL_MSG_UA;
13187                                 msg.hdr.nexus.initid = -1;
13188                                 msg.hdr.nexus.targ_port = -1;
13189                                 msg.hdr.nexus.targ_lun = lun->lun;
13190                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13191                                 msg.ua.ua_all = 1;
13192                                 msg.ua.ua_set = (set > 0);
13193                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13194                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13195                                 mtx_unlock(&softc->ctl_lock); // XXX
13196                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13197                                     sizeof(msg.ua), M_WAITOK);
13198                                 mtx_lock(&softc->ctl_lock);
13199                         }
13200                 }
13201                 mtx_unlock(&softc->ctl_lock);
13202                 pause("-", CTL_LBP_PERIOD * hz);
13203         }
13204 }
13205
13206 static void
13207 ctl_enqueue_incoming(union ctl_io *io)
13208 {
13209         struct ctl_softc *softc = control_softc;
13210         struct ctl_thread *thr;
13211         u_int idx;
13212
13213         idx = (io->io_hdr.nexus.targ_port * 127 +
13214                io->io_hdr.nexus.initid) % worker_threads;
13215         thr = &softc->threads[idx];
13216         mtx_lock(&thr->queue_lock);
13217         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13218         mtx_unlock(&thr->queue_lock);
13219         wakeup(thr);
13220 }
13221
13222 static void
13223 ctl_enqueue_rtr(union ctl_io *io)
13224 {
13225         struct ctl_softc *softc = control_softc;
13226         struct ctl_thread *thr;
13227
13228         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13229         mtx_lock(&thr->queue_lock);
13230         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13231         mtx_unlock(&thr->queue_lock);
13232         wakeup(thr);
13233 }
13234
13235 static void
13236 ctl_enqueue_done(union ctl_io *io)
13237 {
13238         struct ctl_softc *softc = control_softc;
13239         struct ctl_thread *thr;
13240
13241         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13242         mtx_lock(&thr->queue_lock);
13243         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13244         mtx_unlock(&thr->queue_lock);
13245         wakeup(thr);
13246 }
13247
13248 static void
13249 ctl_enqueue_isc(union ctl_io *io)
13250 {
13251         struct ctl_softc *softc = control_softc;
13252         struct ctl_thread *thr;
13253
13254         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13255         mtx_lock(&thr->queue_lock);
13256         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13257         mtx_unlock(&thr->queue_lock);
13258         wakeup(thr);
13259 }
13260
13261 /*
13262  *  vim: ts=8
13263  */