]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r311787: Allocate memory for prevent flags only for removable LUs.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42
43 #define _CTL_C
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_cd.h>
73 #include <cam/scsi/scsi_da.h>
74 #include <cam/ctl/ctl_io.h>
75 #include <cam/ctl/ctl.h>
76 #include <cam/ctl/ctl_frontend.h>
77 #include <cam/ctl/ctl_util.h>
78 #include <cam/ctl/ctl_backend.h>
79 #include <cam/ctl/ctl_ioctl.h>
80 #include <cam/ctl/ctl_ha.h>
81 #include <cam/ctl/ctl_private.h>
82 #include <cam/ctl/ctl_debug.h>
83 #include <cam/ctl/ctl_scsi_all.h>
84 #include <cam/ctl/ctl_error.h>
85
86 struct ctl_softc *control_softc = NULL;
87
88 /*
89  * Template mode pages.
90  */
91
92 /*
93  * Note that these are default values only.  The actual values will be
94  * filled in when the user does a mode sense.
95  */
96 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
97         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100         /*read_retry_count*/0,
101         /*correction_span*/0,
102         /*head_offset_count*/0,
103         /*data_strobe_offset_cnt*/0,
104         /*byte8*/SMS_RWER_LBPERE,
105         /*write_retry_count*/0,
106         /*reserved2*/0,
107         /*recovery_time_limit*/{0, 0},
108 };
109
110 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113         /*byte3*/SMS_RWER_PER,
114         /*read_retry_count*/0,
115         /*correction_span*/0,
116         /*head_offset_count*/0,
117         /*data_strobe_offset_cnt*/0,
118         /*byte8*/SMS_RWER_LBPERE,
119         /*write_retry_count*/0,
120         /*reserved2*/0,
121         /*recovery_time_limit*/{0, 0},
122 };
123
124 const static struct scsi_format_page format_page_default = {
125         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
126         /*page_length*/sizeof(struct scsi_format_page) - 2,
127         /*tracks_per_zone*/ {0, 0},
128         /*alt_sectors_per_zone*/ {0, 0},
129         /*alt_tracks_per_zone*/ {0, 0},
130         /*alt_tracks_per_lun*/ {0, 0},
131         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133         /*bytes_per_sector*/ {0, 0},
134         /*interleave*/ {0, 0},
135         /*track_skew*/ {0, 0},
136         /*cylinder_skew*/ {0, 0},
137         /*flags*/ SFP_HSEC,
138         /*reserved*/ {0, 0, 0}
139 };
140
141 const static struct scsi_format_page format_page_changeable = {
142         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
143         /*page_length*/sizeof(struct scsi_format_page) - 2,
144         /*tracks_per_zone*/ {0, 0},
145         /*alt_sectors_per_zone*/ {0, 0},
146         /*alt_tracks_per_zone*/ {0, 0},
147         /*alt_tracks_per_lun*/ {0, 0},
148         /*sectors_per_track*/ {0, 0},
149         /*bytes_per_sector*/ {0, 0},
150         /*interleave*/ {0, 0},
151         /*track_skew*/ {0, 0},
152         /*cylinder_skew*/ {0, 0},
153         /*flags*/ 0,
154         /*reserved*/ {0, 0, 0}
155 };
156
157 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158         /*page_code*/SMS_RIGID_DISK_PAGE,
159         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160         /*cylinders*/ {0, 0, 0},
161         /*heads*/ CTL_DEFAULT_HEADS,
162         /*start_write_precomp*/ {0, 0, 0},
163         /*start_reduced_current*/ {0, 0, 0},
164         /*step_rate*/ {0, 0},
165         /*landing_zone_cylinder*/ {0, 0, 0},
166         /*rpl*/ SRDP_RPL_DISABLED,
167         /*rotational_offset*/ 0,
168         /*reserved1*/ 0,
169         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170                            CTL_DEFAULT_ROTATION_RATE & 0xff},
171         /*reserved2*/ {0, 0}
172 };
173
174 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175         /*page_code*/SMS_RIGID_DISK_PAGE,
176         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177         /*cylinders*/ {0, 0, 0},
178         /*heads*/ 0,
179         /*start_write_precomp*/ {0, 0, 0},
180         /*start_reduced_current*/ {0, 0, 0},
181         /*step_rate*/ {0, 0},
182         /*landing_zone_cylinder*/ {0, 0, 0},
183         /*rpl*/ 0,
184         /*rotational_offset*/ 0,
185         /*reserved1*/ 0,
186         /*rotation_rate*/ {0, 0},
187         /*reserved2*/ {0, 0}
188 };
189
190 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193         /*byte3*/0,
194         /*read_retry_count*/0,
195         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
196         /*recovery_time_limit*/{0, 0},
197 };
198
199 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202         /*byte3*/SMS_VER_PER,
203         /*read_retry_count*/0,
204         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
205         /*recovery_time_limit*/{0, 0},
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
265
266 const static struct scsi_control_ext_page control_ext_page_default = {
267         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268         /*subpage_code*/0x01,
269         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270         /*flags*/0,
271         /*prio*/0,
272         /*max_sense*/0
273 };
274
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277         /*subpage_code*/0x01,
278         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279         /*flags*/0,
280         /*prio*/0,
281         /*max_sense*/0xff
282 };
283
284 const static struct scsi_info_exceptions_page ie_page_default = {
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287         /*info_flags*/SIEP_FLAGS_EWASC,
288         /*mrie*/SIEP_MRIE_NO,
289         /*interval_timer*/{0, 0, 0, 0},
290         /*report_count*/{0, 0, 0, 1}
291 };
292
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296         /*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297             SIEP_FLAGS_LOGERR,
298         /*mrie*/0x0f,
299         /*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300         /*report_count*/{0xff, 0xff, 0xff, 0xff}
301 };
302
303 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307         /*subpage_code*/0x02,
308         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309         /*flags*/0,
310         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311         /*descr*/{}},
312         {{/*flags*/0,
313           /*resource*/0x01,
314           /*reserved*/{0, 0},
315           /*count*/{0, 0, 0, 0}},
316          {/*flags*/0,
317           /*resource*/0x02,
318           /*reserved*/{0, 0},
319           /*count*/{0, 0, 0, 0}},
320          {/*flags*/0,
321           /*resource*/0xf1,
322           /*reserved*/{0, 0},
323           /*count*/{0, 0, 0, 0}},
324          {/*flags*/0,
325           /*resource*/0xf2,
326           /*reserved*/{0, 0},
327           /*count*/{0, 0, 0, 0}}
328         }
329 };
330
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333         /*subpage_code*/0x02,
334         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335         /*flags*/SLBPP_SITUA,
336         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337         /*descr*/{}},
338         {{/*flags*/0,
339           /*resource*/0,
340           /*reserved*/{0, 0},
341           /*count*/{0, 0, 0, 0}},
342          {/*flags*/0,
343           /*resource*/0,
344           /*reserved*/{0, 0},
345           /*count*/{0, 0, 0, 0}},
346          {/*flags*/0,
347           /*resource*/0,
348           /*reserved*/{0, 0},
349           /*count*/{0, 0, 0, 0}},
350          {/*flags*/0,
351           /*resource*/0,
352           /*reserved*/{0, 0},
353           /*count*/{0, 0, 0, 0}}
354         }
355 };
356
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358         /*page_code*/SMS_CDDVD_CAPS_PAGE,
359         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360         /*caps1*/0x3f,
361         /*caps2*/0x00,
362         /*caps3*/0xf0,
363         /*caps4*/0x00,
364         /*caps5*/0x29,
365         /*caps6*/0x00,
366         /*obsolete*/{0, 0},
367         /*nvol_levels*/{0, 0},
368         /*buffer_size*/{8, 0},
369         /*obsolete2*/{0, 0},
370         /*reserved*/0,
371         /*digital*/0,
372         /*obsolete3*/0,
373         /*copy_management*/0,
374         /*reserved2*/0,
375         /*rotation_control*/0,
376         /*cur_write_speed*/0,
377         /*num_speed_descr*/0,
378 };
379
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381         /*page_code*/SMS_CDDVD_CAPS_PAGE,
382         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383         /*caps1*/0,
384         /*caps2*/0,
385         /*caps3*/0,
386         /*caps4*/0,
387         /*caps5*/0,
388         /*caps6*/0,
389         /*obsolete*/{0, 0},
390         /*nvol_levels*/{0, 0},
391         /*buffer_size*/{0, 0},
392         /*obsolete2*/{0, 0},
393         /*reserved*/0,
394         /*digital*/0,
395         /*obsolete3*/0,
396         /*copy_management*/0,
397         /*reserved2*/0,
398         /*rotation_control*/0,
399         /*cur_write_speed*/0,
400         /*num_speed_descr*/0,
401 };
402
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407     &worker_threads, 1, "Number of worker threads");
408 static int ctl_debug = CTL_DEBUG_NONE;
409 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411     &ctl_debug, 0, "Enabled debug flags");
412 static int ctl_lun_map_size = 1024;
413 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
414     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
415
416 /*
417  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
418  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
419  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
420  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
421  */
422 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
423
424 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
425                                   int param);
426 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
427 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
428 static int ctl_init(void);
429 void ctl_shutdown(void);
430 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
431 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
432 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
433 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
434                               struct ctl_ooa *ooa_hdr,
435                               struct ctl_ooa_entry *kern_entries);
436 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
437                      struct thread *td);
438 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
439                          struct ctl_be_lun *be_lun);
440 static int ctl_free_lun(struct ctl_lun *lun);
441 static void ctl_create_lun(struct ctl_be_lun *be_lun);
442
443 static int ctl_do_mode_select(union ctl_io *io);
444 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
445                            uint64_t res_key, uint64_t sa_res_key,
446                            uint8_t type, uint32_t residx,
447                            struct ctl_scsiio *ctsio,
448                            struct scsi_per_res_out *cdb,
449                            struct scsi_per_res_out_parms* param);
450 static void ctl_pro_preempt_other(struct ctl_lun *lun,
451                                   union ctl_ha_msg *msg);
452 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
453 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
457 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
458 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
459                                          int alloc_len);
460 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
461                                          int alloc_len);
462 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
463 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
464 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
465 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
466 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
467 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
468     bool seq);
469 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
470 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
471     union ctl_io *pending_io, union ctl_io *ooa_io);
472 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
473                                 union ctl_io *starting_io);
474 static int ctl_check_blocked(struct ctl_lun *lun);
475 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
476                                 const struct ctl_cmd_entry *entry,
477                                 struct ctl_scsiio *ctsio);
478 static void ctl_failover_lun(union ctl_io *io);
479 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
480                                struct ctl_scsiio *ctsio);
481 static int ctl_scsiio(struct ctl_scsiio *ctsio);
482
483 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
484 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
485                             ctl_ua_type ua_type);
486 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
487                          ctl_ua_type ua_type);
488 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
489 static int ctl_abort_task(union ctl_io *io);
490 static int ctl_abort_task_set(union ctl_io *io);
491 static int ctl_query_task(union ctl_io *io, int task_set);
492 static int ctl_i_t_nexus_reset(union ctl_io *io);
493 static int ctl_query_async_event(union ctl_io *io);
494 static void ctl_run_task(union ctl_io *io);
495 #ifdef CTL_IO_DELAY
496 static void ctl_datamove_timer_wakeup(void *arg);
497 static void ctl_done_timer_wakeup(void *arg);
498 #endif /* CTL_IO_DELAY */
499
500 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
501 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
502 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
503 static void ctl_datamove_remote_write(union ctl_io *io);
504 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
505 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
506 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
507 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
508                                     ctl_ha_dt_cb callback);
509 static void ctl_datamove_remote_read(union ctl_io *io);
510 static void ctl_datamove_remote(union ctl_io *io);
511 static void ctl_process_done(union ctl_io *io);
512 static void ctl_lun_thread(void *arg);
513 static void ctl_thresh_thread(void *arg);
514 static void ctl_work_thread(void *arg);
515 static void ctl_enqueue_incoming(union ctl_io *io);
516 static void ctl_enqueue_rtr(union ctl_io *io);
517 static void ctl_enqueue_done(union ctl_io *io);
518 static void ctl_enqueue_isc(union ctl_io *io);
519 static const struct ctl_cmd_entry *
520     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
521 static const struct ctl_cmd_entry *
522     ctl_validate_command(struct ctl_scsiio *ctsio);
523 static int ctl_cmd_applicable(uint8_t lun_type,
524     const struct ctl_cmd_entry *entry);
525
526 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
528 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
529 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
530
531 /*
532  * Load the serialization table.  This isn't very pretty, but is probably
533  * the easiest way to do it.
534  */
535 #include "ctl_ser_table.c"
536
537 /*
538  * We only need to define open, close and ioctl routines for this driver.
539  */
540 static struct cdevsw ctl_cdevsw = {
541         .d_version =    D_VERSION,
542         .d_flags =      0,
543         .d_open =       ctl_open,
544         .d_close =      ctl_close,
545         .d_ioctl =      ctl_ioctl,
546         .d_name =       "ctl",
547 };
548
549
550 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
551
552 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
553
554 static moduledata_t ctl_moduledata = {
555         "ctl",
556         ctl_module_event_handler,
557         NULL
558 };
559
560 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
561 MODULE_VERSION(ctl, 1);
562
563 static struct ctl_frontend ha_frontend =
564 {
565         .name = "ha",
566 };
567
568 static void
569 ctl_ha_datamove(union ctl_io *io)
570 {
571         struct ctl_lun *lun = CTL_LUN(io);
572         struct ctl_sg_entry *sgl;
573         union ctl_ha_msg msg;
574         uint32_t sg_entries_sent;
575         int do_sg_copy, i, j;
576
577         memset(&msg.dt, 0, sizeof(msg.dt));
578         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
579         msg.hdr.original_sc = io->io_hdr.original_sc;
580         msg.hdr.serializing_sc = io;
581         msg.hdr.nexus = io->io_hdr.nexus;
582         msg.hdr.status = io->io_hdr.status;
583         msg.dt.flags = io->io_hdr.flags;
584
585         /*
586          * We convert everything into a S/G list here.  We can't
587          * pass by reference, only by value between controllers.
588          * So we can't pass a pointer to the S/G list, only as many
589          * S/G entries as we can fit in here.  If it's possible for
590          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
591          * then we need to break this up into multiple transfers.
592          */
593         if (io->scsiio.kern_sg_entries == 0) {
594                 msg.dt.kern_sg_entries = 1;
595 #if 0
596                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
597                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
598                 } else {
599                         /* XXX KDM use busdma here! */
600                         msg.dt.sg_list[0].addr =
601                             (void *)vtophys(io->scsiio.kern_data_ptr);
602                 }
603 #else
604                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
605                     ("HA does not support BUS_ADDR"));
606                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
607 #endif
608                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
609                 do_sg_copy = 0;
610         } else {
611                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
612                 do_sg_copy = 1;
613         }
614
615         msg.dt.kern_data_len = io->scsiio.kern_data_len;
616         msg.dt.kern_total_len = io->scsiio.kern_total_len;
617         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
618         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
619         msg.dt.sg_sequence = 0;
620
621         /*
622          * Loop until we've sent all of the S/G entries.  On the
623          * other end, we'll recompose these S/G entries into one
624          * contiguous list before processing.
625          */
626         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
627             msg.dt.sg_sequence++) {
628                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
629                     sizeof(msg.dt.sg_list[0])),
630                     msg.dt.kern_sg_entries - sg_entries_sent);
631                 if (do_sg_copy != 0) {
632                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
633                         for (i = sg_entries_sent, j = 0;
634                              i < msg.dt.cur_sg_entries; i++, j++) {
635 #if 0
636                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
637                                         msg.dt.sg_list[j].addr = sgl[i].addr;
638                                 } else {
639                                         /* XXX KDM use busdma here! */
640                                         msg.dt.sg_list[j].addr =
641                                             (void *)vtophys(sgl[i].addr);
642                                 }
643 #else
644                                 KASSERT((io->io_hdr.flags &
645                                     CTL_FLAG_BUS_ADDR) == 0,
646                                     ("HA does not support BUS_ADDR"));
647                                 msg.dt.sg_list[j].addr = sgl[i].addr;
648 #endif
649                                 msg.dt.sg_list[j].len = sgl[i].len;
650                         }
651                 }
652
653                 sg_entries_sent += msg.dt.cur_sg_entries;
654                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
655                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
656                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
657                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
658                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
659                         io->io_hdr.port_status = 31341;
660                         io->scsiio.be_move_done(io);
661                         return;
662                 }
663                 msg.dt.sent_sg_entries = sg_entries_sent;
664         }
665
666         /*
667          * Officially handover the request from us to peer.
668          * If failover has just happened, then we must return error.
669          * If failover happen just after, then it is not our problem.
670          */
671         if (lun)
672                 mtx_lock(&lun->lun_lock);
673         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
674                 if (lun)
675                         mtx_unlock(&lun->lun_lock);
676                 io->io_hdr.port_status = 31342;
677                 io->scsiio.be_move_done(io);
678                 return;
679         }
680         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
681         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
682         if (lun)
683                 mtx_unlock(&lun->lun_lock);
684 }
685
686 static void
687 ctl_ha_done(union ctl_io *io)
688 {
689         union ctl_ha_msg msg;
690
691         if (io->io_hdr.io_type == CTL_IO_SCSI) {
692                 memset(&msg, 0, sizeof(msg));
693                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
694                 msg.hdr.original_sc = io->io_hdr.original_sc;
695                 msg.hdr.nexus = io->io_hdr.nexus;
696                 msg.hdr.status = io->io_hdr.status;
697                 msg.scsi.scsi_status = io->scsiio.scsi_status;
698                 msg.scsi.tag_num = io->scsiio.tag_num;
699                 msg.scsi.tag_type = io->scsiio.tag_type;
700                 msg.scsi.sense_len = io->scsiio.sense_len;
701                 msg.scsi.sense_residual = io->scsiio.sense_residual;
702                 msg.scsi.residual = io->scsiio.residual;
703                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
704                     io->scsiio.sense_len);
705                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
706                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
707                     msg.scsi.sense_len, M_WAITOK);
708         }
709         ctl_free_io(io);
710 }
711
712 static void
713 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
714                             union ctl_ha_msg *msg_info)
715 {
716         struct ctl_scsiio *ctsio;
717
718         if (msg_info->hdr.original_sc == NULL) {
719                 printf("%s: original_sc == NULL!\n", __func__);
720                 /* XXX KDM now what? */
721                 return;
722         }
723
724         ctsio = &msg_info->hdr.original_sc->scsiio;
725         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
726         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
727         ctsio->io_hdr.status = msg_info->hdr.status;
728         ctsio->scsi_status = msg_info->scsi.scsi_status;
729         ctsio->sense_len = msg_info->scsi.sense_len;
730         ctsio->sense_residual = msg_info->scsi.sense_residual;
731         ctsio->residual = msg_info->scsi.residual;
732         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
733                msg_info->scsi.sense_len);
734         ctl_enqueue_isc((union ctl_io *)ctsio);
735 }
736
737 static void
738 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
739                                 union ctl_ha_msg *msg_info)
740 {
741         struct ctl_scsiio *ctsio;
742
743         if (msg_info->hdr.serializing_sc == NULL) {
744                 printf("%s: serializing_sc == NULL!\n", __func__);
745                 /* XXX KDM now what? */
746                 return;
747         }
748
749         ctsio = &msg_info->hdr.serializing_sc->scsiio;
750         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
751         ctl_enqueue_isc((union ctl_io *)ctsio);
752 }
753
754 void
755 ctl_isc_announce_lun(struct ctl_lun *lun)
756 {
757         struct ctl_softc *softc = lun->ctl_softc;
758         union ctl_ha_msg *msg;
759         struct ctl_ha_msg_lun_pr_key pr_key;
760         int i, k;
761
762         if (softc->ha_link != CTL_HA_LINK_ONLINE)
763                 return;
764         mtx_lock(&lun->lun_lock);
765         i = sizeof(msg->lun);
766         if (lun->lun_devid)
767                 i += lun->lun_devid->len;
768         i += sizeof(pr_key) * lun->pr_key_count;
769 alloc:
770         mtx_unlock(&lun->lun_lock);
771         msg = malloc(i, M_CTL, M_WAITOK);
772         mtx_lock(&lun->lun_lock);
773         k = sizeof(msg->lun);
774         if (lun->lun_devid)
775                 k += lun->lun_devid->len;
776         k += sizeof(pr_key) * lun->pr_key_count;
777         if (i < k) {
778                 free(msg, M_CTL);
779                 i = k;
780                 goto alloc;
781         }
782         bzero(&msg->lun, sizeof(msg->lun));
783         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
784         msg->hdr.nexus.targ_lun = lun->lun;
785         msg->hdr.nexus.targ_mapped_lun = lun->lun;
786         msg->lun.flags = lun->flags;
787         msg->lun.pr_generation = lun->pr_generation;
788         msg->lun.pr_res_idx = lun->pr_res_idx;
789         msg->lun.pr_res_type = lun->pr_res_type;
790         msg->lun.pr_key_count = lun->pr_key_count;
791         i = 0;
792         if (lun->lun_devid) {
793                 msg->lun.lun_devid_len = lun->lun_devid->len;
794                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
795                     msg->lun.lun_devid_len);
796                 i += msg->lun.lun_devid_len;
797         }
798         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
799                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
800                         continue;
801                 pr_key.pr_iid = k;
802                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
803                 i += sizeof(pr_key);
804         }
805         mtx_unlock(&lun->lun_lock);
806         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
807             M_WAITOK);
808         free(msg, M_CTL);
809
810         if (lun->flags & CTL_LUN_PRIMARY_SC) {
811                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
812                         ctl_isc_announce_mode(lun, -1,
813                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
814                             lun->mode_pages.index[i].subpage);
815                 }
816         }
817 }
818
819 void
820 ctl_isc_announce_port(struct ctl_port *port)
821 {
822         struct ctl_softc *softc = port->ctl_softc;
823         union ctl_ha_msg *msg;
824         int i;
825
826         if (port->targ_port < softc->port_min ||
827             port->targ_port >= softc->port_max ||
828             softc->ha_link != CTL_HA_LINK_ONLINE)
829                 return;
830         i = sizeof(msg->port) + strlen(port->port_name) + 1;
831         if (port->lun_map)
832                 i += port->lun_map_size * sizeof(uint32_t);
833         if (port->port_devid)
834                 i += port->port_devid->len;
835         if (port->target_devid)
836                 i += port->target_devid->len;
837         if (port->init_devid)
838                 i += port->init_devid->len;
839         msg = malloc(i, M_CTL, M_WAITOK);
840         bzero(&msg->port, sizeof(msg->port));
841         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
842         msg->hdr.nexus.targ_port = port->targ_port;
843         msg->port.port_type = port->port_type;
844         msg->port.physical_port = port->physical_port;
845         msg->port.virtual_port = port->virtual_port;
846         msg->port.status = port->status;
847         i = 0;
848         msg->port.name_len = sprintf(&msg->port.data[i],
849             "%d:%s", softc->ha_id, port->port_name) + 1;
850         i += msg->port.name_len;
851         if (port->lun_map) {
852                 msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
853                 memcpy(&msg->port.data[i], port->lun_map,
854                     msg->port.lun_map_len);
855                 i += msg->port.lun_map_len;
856         }
857         if (port->port_devid) {
858                 msg->port.port_devid_len = port->port_devid->len;
859                 memcpy(&msg->port.data[i], port->port_devid->data,
860                     msg->port.port_devid_len);
861                 i += msg->port.port_devid_len;
862         }
863         if (port->target_devid) {
864                 msg->port.target_devid_len = port->target_devid->len;
865                 memcpy(&msg->port.data[i], port->target_devid->data,
866                     msg->port.target_devid_len);
867                 i += msg->port.target_devid_len;
868         }
869         if (port->init_devid) {
870                 msg->port.init_devid_len = port->init_devid->len;
871                 memcpy(&msg->port.data[i], port->init_devid->data,
872                     msg->port.init_devid_len);
873                 i += msg->port.init_devid_len;
874         }
875         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
876             M_WAITOK);
877         free(msg, M_CTL);
878 }
879
880 void
881 ctl_isc_announce_iid(struct ctl_port *port, int iid)
882 {
883         struct ctl_softc *softc = port->ctl_softc;
884         union ctl_ha_msg *msg;
885         int i, l;
886
887         if (port->targ_port < softc->port_min ||
888             port->targ_port >= softc->port_max ||
889             softc->ha_link != CTL_HA_LINK_ONLINE)
890                 return;
891         mtx_lock(&softc->ctl_lock);
892         i = sizeof(msg->iid);
893         l = 0;
894         if (port->wwpn_iid[iid].name)
895                 l = strlen(port->wwpn_iid[iid].name) + 1;
896         i += l;
897         msg = malloc(i, M_CTL, M_NOWAIT);
898         if (msg == NULL) {
899                 mtx_unlock(&softc->ctl_lock);
900                 return;
901         }
902         bzero(&msg->iid, sizeof(msg->iid));
903         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
904         msg->hdr.nexus.targ_port = port->targ_port;
905         msg->hdr.nexus.initid = iid;
906         msg->iid.in_use = port->wwpn_iid[iid].in_use;
907         msg->iid.name_len = l;
908         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
909         if (port->wwpn_iid[iid].name)
910                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
911         mtx_unlock(&softc->ctl_lock);
912         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
913         free(msg, M_CTL);
914 }
915
916 void
917 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
918     uint8_t page, uint8_t subpage)
919 {
920         struct ctl_softc *softc = lun->ctl_softc;
921         union ctl_ha_msg msg;
922         u_int i;
923
924         if (softc->ha_link != CTL_HA_LINK_ONLINE)
925                 return;
926         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
927                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
928                     page && lun->mode_pages.index[i].subpage == subpage)
929                         break;
930         }
931         if (i == CTL_NUM_MODE_PAGES)
932                 return;
933
934         /* Don't try to replicate pages not present on this device. */
935         if (lun->mode_pages.index[i].page_data == NULL)
936                 return;
937
938         bzero(&msg.mode, sizeof(msg.mode));
939         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
940         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
941         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
942         msg.hdr.nexus.targ_lun = lun->lun;
943         msg.hdr.nexus.targ_mapped_lun = lun->lun;
944         msg.mode.page_code = page;
945         msg.mode.subpage = subpage;
946         msg.mode.page_len = lun->mode_pages.index[i].page_len;
947         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
948             msg.mode.page_len);
949         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
950             M_WAITOK);
951 }
952
953 static void
954 ctl_isc_ha_link_up(struct ctl_softc *softc)
955 {
956         struct ctl_port *port;
957         struct ctl_lun *lun;
958         union ctl_ha_msg msg;
959         int i;
960
961         /* Announce this node parameters to peer for validation. */
962         msg.login.msg_type = CTL_MSG_LOGIN;
963         msg.login.version = CTL_HA_VERSION;
964         msg.login.ha_mode = softc->ha_mode;
965         msg.login.ha_id = softc->ha_id;
966         msg.login.max_luns = CTL_MAX_LUNS;
967         msg.login.max_ports = CTL_MAX_PORTS;
968         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
969         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
970             M_WAITOK);
971
972         STAILQ_FOREACH(port, &softc->port_list, links) {
973                 ctl_isc_announce_port(port);
974                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
975                         if (port->wwpn_iid[i].in_use)
976                                 ctl_isc_announce_iid(port, i);
977                 }
978         }
979         STAILQ_FOREACH(lun, &softc->lun_list, links)
980                 ctl_isc_announce_lun(lun);
981 }
982
983 static void
984 ctl_isc_ha_link_down(struct ctl_softc *softc)
985 {
986         struct ctl_port *port;
987         struct ctl_lun *lun;
988         union ctl_io *io;
989         int i;
990
991         mtx_lock(&softc->ctl_lock);
992         STAILQ_FOREACH(lun, &softc->lun_list, links) {
993                 mtx_lock(&lun->lun_lock);
994                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
995                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
996                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
997                 }
998                 mtx_unlock(&lun->lun_lock);
999
1000                 mtx_unlock(&softc->ctl_lock);
1001                 io = ctl_alloc_io(softc->othersc_pool);
1002                 mtx_lock(&softc->ctl_lock);
1003                 ctl_zero_io(io);
1004                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1005                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1006                 ctl_enqueue_isc(io);
1007         }
1008
1009         STAILQ_FOREACH(port, &softc->port_list, links) {
1010                 if (port->targ_port >= softc->port_min &&
1011                     port->targ_port < softc->port_max)
1012                         continue;
1013                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1014                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1015                         port->wwpn_iid[i].in_use = 0;
1016                         free(port->wwpn_iid[i].name, M_CTL);
1017                         port->wwpn_iid[i].name = NULL;
1018                 }
1019         }
1020         mtx_unlock(&softc->ctl_lock);
1021 }
1022
1023 static void
1024 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1025 {
1026         struct ctl_lun *lun;
1027         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1028
1029         mtx_lock(&softc->ctl_lock);
1030         if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1031             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1032                 mtx_unlock(&softc->ctl_lock);
1033                 return;
1034         }
1035         mtx_lock(&lun->lun_lock);
1036         mtx_unlock(&softc->ctl_lock);
1037         if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1038                 memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1039         if (msg->ua.ua_all) {
1040                 if (msg->ua.ua_set)
1041                         ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1042                 else
1043                         ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1044         } else {
1045                 if (msg->ua.ua_set)
1046                         ctl_est_ua(lun, iid, msg->ua.ua_type);
1047                 else
1048                         ctl_clr_ua(lun, iid, msg->ua.ua_type);
1049         }
1050         mtx_unlock(&lun->lun_lock);
1051 }
1052
1053 static void
1054 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1055 {
1056         struct ctl_lun *lun;
1057         struct ctl_ha_msg_lun_pr_key pr_key;
1058         int i, k;
1059         ctl_lun_flags oflags;
1060         uint32_t targ_lun;
1061
1062         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1063         mtx_lock(&softc->ctl_lock);
1064         if (targ_lun >= CTL_MAX_LUNS ||
1065             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1066                 mtx_unlock(&softc->ctl_lock);
1067                 return;
1068         }
1069         mtx_lock(&lun->lun_lock);
1070         mtx_unlock(&softc->ctl_lock);
1071         if (lun->flags & CTL_LUN_DISABLED) {
1072                 mtx_unlock(&lun->lun_lock);
1073                 return;
1074         }
1075         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1076         if (msg->lun.lun_devid_len != i || (i > 0 &&
1077             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1078                 mtx_unlock(&lun->lun_lock);
1079                 printf("%s: Received conflicting HA LUN %d\n",
1080                     __func__, targ_lun);
1081                 return;
1082         } else {
1083                 /* Record whether peer is primary. */
1084                 oflags = lun->flags;
1085                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1086                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1087                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1088                 else
1089                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1090                 if (oflags != lun->flags)
1091                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1092
1093                 /* If peer is primary and we are not -- use data */
1094                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1095                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1096                         lun->pr_generation = msg->lun.pr_generation;
1097                         lun->pr_res_idx = msg->lun.pr_res_idx;
1098                         lun->pr_res_type = msg->lun.pr_res_type;
1099                         lun->pr_key_count = msg->lun.pr_key_count;
1100                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1101                                 ctl_clr_prkey(lun, k);
1102                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1103                                 memcpy(&pr_key, &msg->lun.data[i],
1104                                     sizeof(pr_key));
1105                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1106                                 ctl_set_prkey(lun, pr_key.pr_iid,
1107                                     pr_key.pr_key);
1108                                 i += sizeof(pr_key);
1109                         }
1110                 }
1111
1112                 mtx_unlock(&lun->lun_lock);
1113                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1114                     __func__, targ_lun,
1115                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1116                     "primary" : "secondary"));
1117
1118                 /* If we are primary but peer doesn't know -- notify */
1119                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1120                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1121                         ctl_isc_announce_lun(lun);
1122         }
1123 }
1124
1125 static void
1126 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1127 {
1128         struct ctl_port *port;
1129         struct ctl_lun *lun;
1130         int i, new;
1131
1132         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1133         if (port == NULL) {
1134                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1135                     msg->hdr.nexus.targ_port));
1136                 new = 1;
1137                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1138                 port->frontend = &ha_frontend;
1139                 port->targ_port = msg->hdr.nexus.targ_port;
1140                 port->fe_datamove = ctl_ha_datamove;
1141                 port->fe_done = ctl_ha_done;
1142         } else if (port->frontend == &ha_frontend) {
1143                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1144                     msg->hdr.nexus.targ_port));
1145                 new = 0;
1146         } else {
1147                 printf("%s: Received conflicting HA port %d\n",
1148                     __func__, msg->hdr.nexus.targ_port);
1149                 return;
1150         }
1151         port->port_type = msg->port.port_type;
1152         port->physical_port = msg->port.physical_port;
1153         port->virtual_port = msg->port.virtual_port;
1154         port->status = msg->port.status;
1155         i = 0;
1156         free(port->port_name, M_CTL);
1157         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1158             M_CTL);
1159         i += msg->port.name_len;
1160         if (msg->port.lun_map_len != 0) {
1161                 if (port->lun_map == NULL ||
1162                     port->lun_map_size * sizeof(uint32_t) <
1163                     msg->port.lun_map_len) {
1164                         port->lun_map_size = 0;
1165                         free(port->lun_map, M_CTL);
1166                         port->lun_map = malloc(msg->port.lun_map_len,
1167                             M_CTL, M_WAITOK);
1168                 }
1169                 memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1170                 port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1171                 i += msg->port.lun_map_len;
1172         } else {
1173                 port->lun_map_size = 0;
1174                 free(port->lun_map, M_CTL);
1175                 port->lun_map = NULL;
1176         }
1177         if (msg->port.port_devid_len != 0) {
1178                 if (port->port_devid == NULL ||
1179                     port->port_devid->len < msg->port.port_devid_len) {
1180                         free(port->port_devid, M_CTL);
1181                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1182                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1183                 }
1184                 memcpy(port->port_devid->data, &msg->port.data[i],
1185                     msg->port.port_devid_len);
1186                 port->port_devid->len = msg->port.port_devid_len;
1187                 i += msg->port.port_devid_len;
1188         } else {
1189                 free(port->port_devid, M_CTL);
1190                 port->port_devid = NULL;
1191         }
1192         if (msg->port.target_devid_len != 0) {
1193                 if (port->target_devid == NULL ||
1194                     port->target_devid->len < msg->port.target_devid_len) {
1195                         free(port->target_devid, M_CTL);
1196                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1197                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1198                 }
1199                 memcpy(port->target_devid->data, &msg->port.data[i],
1200                     msg->port.target_devid_len);
1201                 port->target_devid->len = msg->port.target_devid_len;
1202                 i += msg->port.target_devid_len;
1203         } else {
1204                 free(port->target_devid, M_CTL);
1205                 port->target_devid = NULL;
1206         }
1207         if (msg->port.init_devid_len != 0) {
1208                 if (port->init_devid == NULL ||
1209                     port->init_devid->len < msg->port.init_devid_len) {
1210                         free(port->init_devid, M_CTL);
1211                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1212                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1213                 }
1214                 memcpy(port->init_devid->data, &msg->port.data[i],
1215                     msg->port.init_devid_len);
1216                 port->init_devid->len = msg->port.init_devid_len;
1217                 i += msg->port.init_devid_len;
1218         } else {
1219                 free(port->init_devid, M_CTL);
1220                 port->init_devid = NULL;
1221         }
1222         if (new) {
1223                 if (ctl_port_register(port) != 0) {
1224                         printf("%s: ctl_port_register() failed with error\n",
1225                             __func__);
1226                 }
1227         }
1228         mtx_lock(&softc->ctl_lock);
1229         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1230                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1231                         continue;
1232                 mtx_lock(&lun->lun_lock);
1233                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1234                 mtx_unlock(&lun->lun_lock);
1235         }
1236         mtx_unlock(&softc->ctl_lock);
1237 }
1238
1239 static void
1240 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1241 {
1242         struct ctl_port *port;
1243         int iid;
1244
1245         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1246         if (port == NULL) {
1247                 printf("%s: Received IID for unknown port %d\n",
1248                     __func__, msg->hdr.nexus.targ_port);
1249                 return;
1250         }
1251         iid = msg->hdr.nexus.initid;
1252         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1253         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1254         free(port->wwpn_iid[iid].name, M_CTL);
1255         if (msg->iid.name_len) {
1256                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1257                     msg->iid.name_len, M_CTL);
1258         } else
1259                 port->wwpn_iid[iid].name = NULL;
1260 }
1261
1262 static void
1263 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1264 {
1265
1266         if (msg->login.version != CTL_HA_VERSION) {
1267                 printf("CTL HA peers have different versions %d != %d\n",
1268                     msg->login.version, CTL_HA_VERSION);
1269                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1270                 return;
1271         }
1272         if (msg->login.ha_mode != softc->ha_mode) {
1273                 printf("CTL HA peers have different ha_mode %d != %d\n",
1274                     msg->login.ha_mode, softc->ha_mode);
1275                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1276                 return;
1277         }
1278         if (msg->login.ha_id == softc->ha_id) {
1279                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1280                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281                 return;
1282         }
1283         if (msg->login.max_luns != CTL_MAX_LUNS ||
1284             msg->login.max_ports != CTL_MAX_PORTS ||
1285             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1286                 printf("CTL HA peers have different limits\n");
1287                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1288                 return;
1289         }
1290 }
1291
1292 static void
1293 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1294 {
1295         struct ctl_lun *lun;
1296         u_int i;
1297         uint32_t initidx, targ_lun;
1298
1299         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1300         mtx_lock(&softc->ctl_lock);
1301         if (targ_lun >= CTL_MAX_LUNS ||
1302             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1303                 mtx_unlock(&softc->ctl_lock);
1304                 return;
1305         }
1306         mtx_lock(&lun->lun_lock);
1307         mtx_unlock(&softc->ctl_lock);
1308         if (lun->flags & CTL_LUN_DISABLED) {
1309                 mtx_unlock(&lun->lun_lock);
1310                 return;
1311         }
1312         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1313                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1314                     msg->mode.page_code &&
1315                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1316                         break;
1317         }
1318         if (i == CTL_NUM_MODE_PAGES) {
1319                 mtx_unlock(&lun->lun_lock);
1320                 return;
1321         }
1322         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1323             lun->mode_pages.index[i].page_len);
1324         initidx = ctl_get_initindex(&msg->hdr.nexus);
1325         if (initidx != -1)
1326                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1327         mtx_unlock(&lun->lun_lock);
1328 }
1329
1330 /*
1331  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1332  * subsystem come in here.
1333  */
1334 static void
1335 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1336 {
1337         struct ctl_softc *softc = control_softc;
1338         union ctl_io *io;
1339         struct ctl_prio *presio;
1340         ctl_ha_status isc_status;
1341
1342         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1343         if (event == CTL_HA_EVT_MSG_RECV) {
1344                 union ctl_ha_msg *msg, msgbuf;
1345
1346                 if (param > sizeof(msgbuf))
1347                         msg = malloc(param, M_CTL, M_WAITOK);
1348                 else
1349                         msg = &msgbuf;
1350                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1351                     M_WAITOK);
1352                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1353                         printf("%s: Error receiving message: %d\n",
1354                             __func__, isc_status);
1355                         if (msg != &msgbuf)
1356                                 free(msg, M_CTL);
1357                         return;
1358                 }
1359
1360                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1361                 switch (msg->hdr.msg_type) {
1362                 case CTL_MSG_SERIALIZE:
1363                         io = ctl_alloc_io(softc->othersc_pool);
1364                         ctl_zero_io(io);
1365                         // populate ctsio from msg
1366                         io->io_hdr.io_type = CTL_IO_SCSI;
1367                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1368                         io->io_hdr.original_sc = msg->hdr.original_sc;
1369                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1370                                             CTL_FLAG_IO_ACTIVE;
1371                         /*
1372                          * If we're in serialization-only mode, we don't
1373                          * want to go through full done processing.  Thus
1374                          * the COPY flag.
1375                          *
1376                          * XXX KDM add another flag that is more specific.
1377                          */
1378                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1379                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1380                         io->io_hdr.nexus = msg->hdr.nexus;
1381 #if 0
1382                         printf("port %u, iid %u, lun %u\n",
1383                                io->io_hdr.nexus.targ_port,
1384                                io->io_hdr.nexus.initid,
1385                                io->io_hdr.nexus.targ_lun);
1386 #endif
1387                         io->scsiio.tag_num = msg->scsi.tag_num;
1388                         io->scsiio.tag_type = msg->scsi.tag_type;
1389 #ifdef CTL_TIME_IO
1390                         io->io_hdr.start_time = time_uptime;
1391                         getbinuptime(&io->io_hdr.start_bt);
1392 #endif /* CTL_TIME_IO */
1393                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1394                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1395                                CTL_MAX_CDBLEN);
1396                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1397                                 const struct ctl_cmd_entry *entry;
1398
1399                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1400                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1401                                 io->io_hdr.flags |=
1402                                         entry->flags & CTL_FLAG_DATA_MASK;
1403                         }
1404                         ctl_enqueue_isc(io);
1405                         break;
1406
1407                 /* Performed on the Originating SC, XFER mode only */
1408                 case CTL_MSG_DATAMOVE: {
1409                         struct ctl_sg_entry *sgl;
1410                         int i, j;
1411
1412                         io = msg->hdr.original_sc;
1413                         if (io == NULL) {
1414                                 printf("%s: original_sc == NULL!\n", __func__);
1415                                 /* XXX KDM do something here */
1416                                 break;
1417                         }
1418                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1419                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1420                         /*
1421                          * Keep track of this, we need to send it back over
1422                          * when the datamove is complete.
1423                          */
1424                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1425                         if (msg->hdr.status == CTL_SUCCESS)
1426                                 io->io_hdr.status = msg->hdr.status;
1427
1428                         if (msg->dt.sg_sequence == 0) {
1429 #ifdef CTL_TIME_IO
1430                                 getbinuptime(&io->io_hdr.dma_start_bt);
1431 #endif
1432                                 i = msg->dt.kern_sg_entries +
1433                                     msg->dt.kern_data_len /
1434                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1435                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1436                                     M_WAITOK | M_ZERO);
1437                                 io->io_hdr.remote_sglist = sgl;
1438                                 io->io_hdr.local_sglist =
1439                                     &sgl[msg->dt.kern_sg_entries];
1440
1441                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1442
1443                                 io->scsiio.kern_sg_entries =
1444                                         msg->dt.kern_sg_entries;
1445                                 io->scsiio.rem_sg_entries =
1446                                         msg->dt.kern_sg_entries;
1447                                 io->scsiio.kern_data_len =
1448                                         msg->dt.kern_data_len;
1449                                 io->scsiio.kern_total_len =
1450                                         msg->dt.kern_total_len;
1451                                 io->scsiio.kern_data_resid =
1452                                         msg->dt.kern_data_resid;
1453                                 io->scsiio.kern_rel_offset =
1454                                         msg->dt.kern_rel_offset;
1455                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1456                                 io->io_hdr.flags |= msg->dt.flags &
1457                                     CTL_FLAG_BUS_ADDR;
1458                         } else
1459                                 sgl = (struct ctl_sg_entry *)
1460                                         io->scsiio.kern_data_ptr;
1461
1462                         for (i = msg->dt.sent_sg_entries, j = 0;
1463                              i < (msg->dt.sent_sg_entries +
1464                              msg->dt.cur_sg_entries); i++, j++) {
1465                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1466                                 sgl[i].len = msg->dt.sg_list[j].len;
1467
1468 #if 0
1469                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1470                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1471 #endif
1472                         }
1473
1474                         /*
1475                          * If this is the last piece of the I/O, we've got
1476                          * the full S/G list.  Queue processing in the thread.
1477                          * Otherwise wait for the next piece.
1478                          */
1479                         if (msg->dt.sg_last != 0)
1480                                 ctl_enqueue_isc(io);
1481                         break;
1482                 }
1483                 /* Performed on the Serializing (primary) SC, XFER mode only */
1484                 case CTL_MSG_DATAMOVE_DONE: {
1485                         if (msg->hdr.serializing_sc == NULL) {
1486                                 printf("%s: serializing_sc == NULL!\n",
1487                                        __func__);
1488                                 /* XXX KDM now what? */
1489                                 break;
1490                         }
1491                         /*
1492                          * We grab the sense information here in case
1493                          * there was a failure, so we can return status
1494                          * back to the initiator.
1495                          */
1496                         io = msg->hdr.serializing_sc;
1497                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1498                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1499                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1500                         io->io_hdr.port_status = msg->scsi.fetd_status;
1501                         io->scsiio.residual = msg->scsi.residual;
1502                         if (msg->hdr.status != CTL_STATUS_NONE) {
1503                                 io->io_hdr.status = msg->hdr.status;
1504                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1505                                 io->scsiio.sense_len = msg->scsi.sense_len;
1506                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1507                                 memcpy(&io->scsiio.sense_data,
1508                                     &msg->scsi.sense_data,
1509                                     msg->scsi.sense_len);
1510                                 if (msg->hdr.status == CTL_SUCCESS)
1511                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1512                         }
1513                         ctl_enqueue_isc(io);
1514                         break;
1515                 }
1516
1517                 /* Preformed on Originating SC, SER_ONLY mode */
1518                 case CTL_MSG_R2R:
1519                         io = msg->hdr.original_sc;
1520                         if (io == NULL) {
1521                                 printf("%s: original_sc == NULL!\n",
1522                                     __func__);
1523                                 break;
1524                         }
1525                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1526                         io->io_hdr.msg_type = CTL_MSG_R2R;
1527                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1528                         ctl_enqueue_isc(io);
1529                         break;
1530
1531                 /*
1532                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1533                  * mode.
1534                  * Performed on the Originating (i.e. secondary) SC in XFER
1535                  * mode
1536                  */
1537                 case CTL_MSG_FINISH_IO:
1538                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1539                                 ctl_isc_handler_finish_xfer(softc, msg);
1540                         else
1541                                 ctl_isc_handler_finish_ser_only(softc, msg);
1542                         break;
1543
1544                 /* Preformed on Originating SC */
1545                 case CTL_MSG_BAD_JUJU:
1546                         io = msg->hdr.original_sc;
1547                         if (io == NULL) {
1548                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1549                                        __func__);
1550                                 break;
1551                         }
1552                         ctl_copy_sense_data(msg, io);
1553                         /*
1554                          * IO should have already been cleaned up on other
1555                          * SC so clear this flag so we won't send a message
1556                          * back to finish the IO there.
1557                          */
1558                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1559                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1560
1561                         /* io = msg->hdr.serializing_sc; */
1562                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1563                         ctl_enqueue_isc(io);
1564                         break;
1565
1566                 /* Handle resets sent from the other side */
1567                 case CTL_MSG_MANAGE_TASKS: {
1568                         struct ctl_taskio *taskio;
1569                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1570                             softc->othersc_pool);
1571                         ctl_zero_io((union ctl_io *)taskio);
1572                         taskio->io_hdr.io_type = CTL_IO_TASK;
1573                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1574                         taskio->io_hdr.nexus = msg->hdr.nexus;
1575                         taskio->task_action = msg->task.task_action;
1576                         taskio->tag_num = msg->task.tag_num;
1577                         taskio->tag_type = msg->task.tag_type;
1578 #ifdef CTL_TIME_IO
1579                         taskio->io_hdr.start_time = time_uptime;
1580                         getbinuptime(&taskio->io_hdr.start_bt);
1581 #endif /* CTL_TIME_IO */
1582                         ctl_run_task((union ctl_io *)taskio);
1583                         break;
1584                 }
1585                 /* Persistent Reserve action which needs attention */
1586                 case CTL_MSG_PERS_ACTION:
1587                         presio = (struct ctl_prio *)ctl_alloc_io(
1588                             softc->othersc_pool);
1589                         ctl_zero_io((union ctl_io *)presio);
1590                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1591                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1592                         presio->io_hdr.nexus = msg->hdr.nexus;
1593                         presio->pr_msg = msg->pr;
1594                         ctl_enqueue_isc((union ctl_io *)presio);
1595                         break;
1596                 case CTL_MSG_UA:
1597                         ctl_isc_ua(softc, msg, param);
1598                         break;
1599                 case CTL_MSG_PORT_SYNC:
1600                         ctl_isc_port_sync(softc, msg, param);
1601                         break;
1602                 case CTL_MSG_LUN_SYNC:
1603                         ctl_isc_lun_sync(softc, msg, param);
1604                         break;
1605                 case CTL_MSG_IID_SYNC:
1606                         ctl_isc_iid_sync(softc, msg, param);
1607                         break;
1608                 case CTL_MSG_LOGIN:
1609                         ctl_isc_login(softc, msg, param);
1610                         break;
1611                 case CTL_MSG_MODE_SYNC:
1612                         ctl_isc_mode_sync(softc, msg, param);
1613                         break;
1614                 default:
1615                         printf("Received HA message of unknown type %d\n",
1616                             msg->hdr.msg_type);
1617                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1618                         break;
1619                 }
1620                 if (msg != &msgbuf)
1621                         free(msg, M_CTL);
1622         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1623                 printf("CTL: HA link status changed from %d to %d\n",
1624                     softc->ha_link, param);
1625                 if (param == softc->ha_link)
1626                         return;
1627                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1628                         softc->ha_link = param;
1629                         ctl_isc_ha_link_down(softc);
1630                 } else {
1631                         softc->ha_link = param;
1632                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1633                                 ctl_isc_ha_link_up(softc);
1634                 }
1635                 return;
1636         } else {
1637                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1638                 return;
1639         }
1640 }
1641
1642 static void
1643 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1644 {
1645
1646         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1647             src->scsi.sense_len);
1648         dest->scsiio.scsi_status = src->scsi.scsi_status;
1649         dest->scsiio.sense_len = src->scsi.sense_len;
1650         dest->io_hdr.status = src->hdr.status;
1651 }
1652
1653 static void
1654 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1655 {
1656
1657         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1658             src->scsiio.sense_len);
1659         dest->scsi.scsi_status = src->scsiio.scsi_status;
1660         dest->scsi.sense_len = src->scsiio.sense_len;
1661         dest->hdr.status = src->io_hdr.status;
1662 }
1663
1664 void
1665 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1666 {
1667         struct ctl_softc *softc = lun->ctl_softc;
1668         ctl_ua_type *pu;
1669
1670         if (initidx < softc->init_min || initidx >= softc->init_max)
1671                 return;
1672         mtx_assert(&lun->lun_lock, MA_OWNED);
1673         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1674         if (pu == NULL)
1675                 return;
1676         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1677 }
1678
1679 void
1680 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1681 {
1682         int i;
1683
1684         mtx_assert(&lun->lun_lock, MA_OWNED);
1685         if (lun->pending_ua[port] == NULL)
1686                 return;
1687         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1688                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1689                         continue;
1690                 lun->pending_ua[port][i] |= ua;
1691         }
1692 }
1693
1694 void
1695 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1696 {
1697         struct ctl_softc *softc = lun->ctl_softc;
1698         int i;
1699
1700         mtx_assert(&lun->lun_lock, MA_OWNED);
1701         for (i = softc->port_min; i < softc->port_max; i++)
1702                 ctl_est_ua_port(lun, i, except, ua);
1703 }
1704
1705 void
1706 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1707 {
1708         struct ctl_softc *softc = lun->ctl_softc;
1709         ctl_ua_type *pu;
1710
1711         if (initidx < softc->init_min || initidx >= softc->init_max)
1712                 return;
1713         mtx_assert(&lun->lun_lock, MA_OWNED);
1714         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1715         if (pu == NULL)
1716                 return;
1717         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1718 }
1719
1720 void
1721 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1722 {
1723         struct ctl_softc *softc = lun->ctl_softc;
1724         int i, j;
1725
1726         mtx_assert(&lun->lun_lock, MA_OWNED);
1727         for (i = softc->port_min; i < softc->port_max; i++) {
1728                 if (lun->pending_ua[i] == NULL)
1729                         continue;
1730                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1731                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1732                                 continue;
1733                         lun->pending_ua[i][j] &= ~ua;
1734                 }
1735         }
1736 }
1737
1738 void
1739 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1740     ctl_ua_type ua_type)
1741 {
1742         struct ctl_lun *lun;
1743
1744         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1745         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1746                 mtx_lock(&lun->lun_lock);
1747                 ctl_clr_ua(lun, initidx, ua_type);
1748                 mtx_unlock(&lun->lun_lock);
1749         }
1750 }
1751
1752 static int
1753 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1754 {
1755         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1756         struct ctl_lun *lun;
1757         struct ctl_lun_req ireq;
1758         int error, value;
1759
1760         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1761         error = sysctl_handle_int(oidp, &value, 0, req);
1762         if ((error != 0) || (req->newptr == NULL))
1763                 return (error);
1764
1765         mtx_lock(&softc->ctl_lock);
1766         if (value == 0)
1767                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1768         else
1769                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1770         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1771                 mtx_unlock(&softc->ctl_lock);
1772                 bzero(&ireq, sizeof(ireq));
1773                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1774                 ireq.reqdata.modify.lun_id = lun->lun;
1775                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1776                     curthread);
1777                 if (ireq.status != CTL_LUN_OK) {
1778                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1779                             __func__, ireq.status, ireq.error_str);
1780                 }
1781                 mtx_lock(&softc->ctl_lock);
1782         }
1783         mtx_unlock(&softc->ctl_lock);
1784         return (0);
1785 }
1786
1787 static int
1788 ctl_init(void)
1789 {
1790         struct make_dev_args args;
1791         struct ctl_softc *softc;
1792         void *other_pool;
1793         int i, error;
1794
1795         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1796                                M_WAITOK | M_ZERO);
1797
1798         make_dev_args_init(&args);
1799         args.mda_devsw = &ctl_cdevsw;
1800         args.mda_uid = UID_ROOT;
1801         args.mda_gid = GID_OPERATOR;
1802         args.mda_mode = 0600;
1803         args.mda_si_drv1 = softc;
1804         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1805         if (error != 0) {
1806                 free(softc, M_DEVBUF);
1807                 control_softc = NULL;
1808                 return (error);
1809         }
1810
1811         sysctl_ctx_init(&softc->sysctl_ctx);
1812         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1813                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1814                 CTLFLAG_RD, 0, "CAM Target Layer");
1815
1816         if (softc->sysctl_tree == NULL) {
1817                 printf("%s: unable to allocate sysctl tree\n", __func__);
1818                 destroy_dev(softc->dev);
1819                 free(softc, M_DEVBUF);
1820                 control_softc = NULL;
1821                 return (ENOMEM);
1822         }
1823
1824         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1825         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1826             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1827         softc->flags = 0;
1828
1829         TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1830         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1831             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1832             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1833
1834         /*
1835          * In Copan's HA scheme, the "master" and "slave" roles are
1836          * figured out through the slot the controller is in.  Although it
1837          * is an active/active system, someone has to be in charge.
1838          */
1839         TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1840         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1841             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1842             "HA head ID (0 - no HA)");
1843         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1844                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1845                 softc->is_single = 1;
1846                 softc->port_cnt = CTL_MAX_PORTS;
1847                 softc->port_min = 0;
1848         } else {
1849                 softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1850                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1851         }
1852         softc->port_max = softc->port_min + softc->port_cnt;
1853         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1854         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1855
1856         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1857             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1858             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1859
1860         STAILQ_INIT(&softc->lun_list);
1861         STAILQ_INIT(&softc->pending_lun_queue);
1862         STAILQ_INIT(&softc->fe_list);
1863         STAILQ_INIT(&softc->port_list);
1864         STAILQ_INIT(&softc->be_list);
1865         ctl_tpc_init(softc);
1866
1867         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1868                             &other_pool) != 0)
1869         {
1870                 printf("ctl: can't allocate %d entry other SC pool, "
1871                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1872                 return (ENOMEM);
1873         }
1874         softc->othersc_pool = other_pool;
1875
1876         if (worker_threads <= 0)
1877                 worker_threads = max(1, mp_ncpus / 4);
1878         if (worker_threads > CTL_MAX_THREADS)
1879                 worker_threads = CTL_MAX_THREADS;
1880
1881         for (i = 0; i < worker_threads; i++) {
1882                 struct ctl_thread *thr = &softc->threads[i];
1883
1884                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1885                 thr->ctl_softc = softc;
1886                 STAILQ_INIT(&thr->incoming_queue);
1887                 STAILQ_INIT(&thr->rtr_queue);
1888                 STAILQ_INIT(&thr->done_queue);
1889                 STAILQ_INIT(&thr->isc_queue);
1890
1891                 error = kproc_kthread_add(ctl_work_thread, thr,
1892                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1893                 if (error != 0) {
1894                         printf("error creating CTL work thread!\n");
1895                         ctl_pool_free(other_pool);
1896                         return (error);
1897                 }
1898         }
1899         error = kproc_kthread_add(ctl_lun_thread, softc,
1900             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1901         if (error != 0) {
1902                 printf("error creating CTL lun thread!\n");
1903                 ctl_pool_free(other_pool);
1904                 return (error);
1905         }
1906         error = kproc_kthread_add(ctl_thresh_thread, softc,
1907             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1908         if (error != 0) {
1909                 printf("error creating CTL threshold thread!\n");
1910                 ctl_pool_free(other_pool);
1911                 return (error);
1912         }
1913
1914         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1915             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1916             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1917
1918         if (softc->is_single == 0) {
1919                 ctl_frontend_register(&ha_frontend);
1920                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1921                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1922                         softc->is_single = 1;
1923                 } else
1924                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1925                     != CTL_HA_STATUS_SUCCESS) {
1926                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1927                         softc->is_single = 1;
1928                 }
1929         }
1930         return (0);
1931 }
1932
1933 void
1934 ctl_shutdown(void)
1935 {
1936         struct ctl_softc *softc = control_softc;
1937         struct ctl_lun *lun, *next_lun;
1938
1939         if (softc->is_single == 0) {
1940                 ctl_ha_msg_shutdown(softc);
1941                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1942                     != CTL_HA_STATUS_SUCCESS)
1943                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1944                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1945                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1946                 ctl_frontend_deregister(&ha_frontend);
1947         }
1948
1949         mtx_lock(&softc->ctl_lock);
1950
1951         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1952                 ctl_free_lun(lun);
1953
1954         mtx_unlock(&softc->ctl_lock);
1955
1956 #if 0
1957         ctl_shutdown_thread(softc->work_thread);
1958         mtx_destroy(&softc->queue_lock);
1959 #endif
1960
1961         ctl_tpc_shutdown(softc);
1962         uma_zdestroy(softc->io_zone);
1963         mtx_destroy(&softc->ctl_lock);
1964
1965         destroy_dev(softc->dev);
1966
1967         sysctl_ctx_free(&softc->sysctl_ctx);
1968
1969         free(softc, M_DEVBUF);
1970         control_softc = NULL;
1971 }
1972
1973 static int
1974 ctl_module_event_handler(module_t mod, int what, void *arg)
1975 {
1976
1977         switch (what) {
1978         case MOD_LOAD:
1979                 return (ctl_init());
1980         case MOD_UNLOAD:
1981                 return (EBUSY);
1982         default:
1983                 return (EOPNOTSUPP);
1984         }
1985 }
1986
1987 /*
1988  * XXX KDM should we do some access checks here?  Bump a reference count to
1989  * prevent a CTL module from being unloaded while someone has it open?
1990  */
1991 static int
1992 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1993 {
1994         return (0);
1995 }
1996
1997 static int
1998 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1999 {
2000         return (0);
2001 }
2002
2003 /*
2004  * Remove an initiator by port number and initiator ID.
2005  * Returns 0 for success, -1 for failure.
2006  */
2007 int
2008 ctl_remove_initiator(struct ctl_port *port, int iid)
2009 {
2010         struct ctl_softc *softc = port->ctl_softc;
2011
2012         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2013
2014         if (iid > CTL_MAX_INIT_PER_PORT) {
2015                 printf("%s: initiator ID %u > maximun %u!\n",
2016                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2017                 return (-1);
2018         }
2019
2020         mtx_lock(&softc->ctl_lock);
2021         port->wwpn_iid[iid].in_use--;
2022         port->wwpn_iid[iid].last_use = time_uptime;
2023         mtx_unlock(&softc->ctl_lock);
2024         ctl_isc_announce_iid(port, iid);
2025
2026         return (0);
2027 }
2028
2029 /*
2030  * Add an initiator to the initiator map.
2031  * Returns iid for success, < 0 for failure.
2032  */
2033 int
2034 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2035 {
2036         struct ctl_softc *softc = port->ctl_softc;
2037         time_t best_time;
2038         int i, best;
2039
2040         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2041
2042         if (iid >= CTL_MAX_INIT_PER_PORT) {
2043                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2044                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2045                 free(name, M_CTL);
2046                 return (-1);
2047         }
2048
2049         mtx_lock(&softc->ctl_lock);
2050
2051         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2052                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2053                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2054                                 iid = i;
2055                                 break;
2056                         }
2057                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2058                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2059                                 iid = i;
2060                                 break;
2061                         }
2062                 }
2063         }
2064
2065         if (iid < 0) {
2066                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2067                         if (port->wwpn_iid[i].in_use == 0 &&
2068                             port->wwpn_iid[i].wwpn == 0 &&
2069                             port->wwpn_iid[i].name == NULL) {
2070                                 iid = i;
2071                                 break;
2072                         }
2073                 }
2074         }
2075
2076         if (iid < 0) {
2077                 best = -1;
2078                 best_time = INT32_MAX;
2079                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2080                         if (port->wwpn_iid[i].in_use == 0) {
2081                                 if (port->wwpn_iid[i].last_use < best_time) {
2082                                         best = i;
2083                                         best_time = port->wwpn_iid[i].last_use;
2084                                 }
2085                         }
2086                 }
2087                 iid = best;
2088         }
2089
2090         if (iid < 0) {
2091                 mtx_unlock(&softc->ctl_lock);
2092                 free(name, M_CTL);
2093                 return (-2);
2094         }
2095
2096         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2097                 /*
2098                  * This is not an error yet.
2099                  */
2100                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2101 #if 0
2102                         printf("%s: port %d iid %u WWPN %#jx arrived"
2103                             " again\n", __func__, port->targ_port,
2104                             iid, (uintmax_t)wwpn);
2105 #endif
2106                         goto take;
2107                 }
2108                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2109                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2110 #if 0
2111                         printf("%s: port %d iid %u name '%s' arrived"
2112                             " again\n", __func__, port->targ_port,
2113                             iid, name);
2114 #endif
2115                         goto take;
2116                 }
2117
2118                 /*
2119                  * This is an error, but what do we do about it?  The
2120                  * driver is telling us we have a new WWPN for this
2121                  * initiator ID, so we pretty much need to use it.
2122                  */
2123                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2124                     " but WWPN %#jx '%s' is still at that address\n",
2125                     __func__, port->targ_port, iid, wwpn, name,
2126                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2127                     port->wwpn_iid[iid].name);
2128
2129                 /*
2130                  * XXX KDM clear have_ca and ua_pending on each LUN for
2131                  * this initiator.
2132                  */
2133         }
2134 take:
2135         free(port->wwpn_iid[iid].name, M_CTL);
2136         port->wwpn_iid[iid].name = name;
2137         port->wwpn_iid[iid].wwpn = wwpn;
2138         port->wwpn_iid[iid].in_use++;
2139         mtx_unlock(&softc->ctl_lock);
2140         ctl_isc_announce_iid(port, iid);
2141
2142         return (iid);
2143 }
2144
2145 static int
2146 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2147 {
2148         int len;
2149
2150         switch (port->port_type) {
2151         case CTL_PORT_FC:
2152         {
2153                 struct scsi_transportid_fcp *id =
2154                     (struct scsi_transportid_fcp *)buf;
2155                 if (port->wwpn_iid[iid].wwpn == 0)
2156                         return (0);
2157                 memset(id, 0, sizeof(*id));
2158                 id->format_protocol = SCSI_PROTO_FC;
2159                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2160                 return (sizeof(*id));
2161         }
2162         case CTL_PORT_ISCSI:
2163         {
2164                 struct scsi_transportid_iscsi_port *id =
2165                     (struct scsi_transportid_iscsi_port *)buf;
2166                 if (port->wwpn_iid[iid].name == NULL)
2167                         return (0);
2168                 memset(id, 0, 256);
2169                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2170                     SCSI_PROTO_ISCSI;
2171                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2172                 len = roundup2(min(len, 252), 4);
2173                 scsi_ulto2b(len, id->additional_length);
2174                 return (sizeof(*id) + len);
2175         }
2176         case CTL_PORT_SAS:
2177         {
2178                 struct scsi_transportid_sas *id =
2179                     (struct scsi_transportid_sas *)buf;
2180                 if (port->wwpn_iid[iid].wwpn == 0)
2181                         return (0);
2182                 memset(id, 0, sizeof(*id));
2183                 id->format_protocol = SCSI_PROTO_SAS;
2184                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2185                 return (sizeof(*id));
2186         }
2187         default:
2188         {
2189                 struct scsi_transportid_spi *id =
2190                     (struct scsi_transportid_spi *)buf;
2191                 memset(id, 0, sizeof(*id));
2192                 id->format_protocol = SCSI_PROTO_SPI;
2193                 scsi_ulto2b(iid, id->scsi_addr);
2194                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2195                 return (sizeof(*id));
2196         }
2197         }
2198 }
2199
2200 /*
2201  * Serialize a command that went down the "wrong" side, and so was sent to
2202  * this controller for execution.  The logic is a little different than the
2203  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2204  * sent back to the other side, but in the success case, we execute the
2205  * command on this side (XFER mode) or tell the other side to execute it
2206  * (SER_ONLY mode).
2207  */
2208 static void
2209 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2210 {
2211         struct ctl_softc *softc = CTL_SOFTC(ctsio);
2212         struct ctl_port *port = CTL_PORT(ctsio);
2213         union ctl_ha_msg msg_info;
2214         struct ctl_lun *lun;
2215         const struct ctl_cmd_entry *entry;
2216         uint32_t targ_lun;
2217
2218         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2219
2220         /* Make sure that we know about this port. */
2221         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2222                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2223                                          /*retry_count*/ 1);
2224                 goto badjuju;
2225         }
2226
2227         /* Make sure that we know about this LUN. */
2228         mtx_lock(&softc->ctl_lock);
2229         if (targ_lun >= CTL_MAX_LUNS ||
2230             (lun = softc->ctl_luns[targ_lun]) == NULL) {
2231                 mtx_unlock(&softc->ctl_lock);
2232
2233                 /*
2234                  * The other node would not send this request to us unless
2235                  * received announce that we are primary node for this LUN.
2236                  * If this LUN does not exist now, it is probably result of
2237                  * a race, so respond to initiator in the most opaque way.
2238                  */
2239                 ctl_set_busy(ctsio);
2240                 goto badjuju;
2241         }
2242         mtx_lock(&lun->lun_lock);
2243         mtx_unlock(&softc->ctl_lock);
2244
2245         /*
2246          * If the LUN is invalid, pretend that it doesn't exist.
2247          * It will go away as soon as all pending I/Os completed.
2248          */
2249         if (lun->flags & CTL_LUN_DISABLED) {
2250                 mtx_unlock(&lun->lun_lock);
2251                 ctl_set_busy(ctsio);
2252                 goto badjuju;
2253         }
2254
2255         entry = ctl_get_cmd_entry(ctsio, NULL);
2256         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2257                 mtx_unlock(&lun->lun_lock);
2258                 goto badjuju;
2259         }
2260
2261         CTL_LUN(ctsio) = lun;
2262         CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2263
2264         /*
2265          * Every I/O goes into the OOA queue for a
2266          * particular LUN, and stays there until completion.
2267          */
2268 #ifdef CTL_TIME_IO
2269         if (TAILQ_EMPTY(&lun->ooa_queue))
2270                 lun->idle_time += getsbinuptime() - lun->last_busy;
2271 #endif
2272         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2273
2274         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2275                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2276                  ooa_links))) {
2277         case CTL_ACTION_BLOCK:
2278                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2279                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2280                                   blocked_links);
2281                 mtx_unlock(&lun->lun_lock);
2282                 break;
2283         case CTL_ACTION_PASS:
2284         case CTL_ACTION_SKIP:
2285                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2286                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2287                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2288                         mtx_unlock(&lun->lun_lock);
2289                 } else {
2290                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2291                         mtx_unlock(&lun->lun_lock);
2292
2293                         /* send msg back to other side */
2294                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2295                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2296                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2297                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2298                             sizeof(msg_info.hdr), M_WAITOK);
2299                 }
2300                 break;
2301         case CTL_ACTION_OVERLAP:
2302                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2303                 mtx_unlock(&lun->lun_lock);
2304                 ctl_set_overlapped_cmd(ctsio);
2305                 goto badjuju;
2306         case CTL_ACTION_OVERLAP_TAG:
2307                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2308                 mtx_unlock(&lun->lun_lock);
2309                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2310                 goto badjuju;
2311         case CTL_ACTION_ERROR:
2312         default:
2313                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2314                 mtx_unlock(&lun->lun_lock);
2315
2316                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2317                                          /*retry_count*/ 0);
2318 badjuju:
2319                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2320                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2321                 msg_info.hdr.serializing_sc = NULL;
2322                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2323                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2324                     sizeof(msg_info.scsi), M_WAITOK);
2325                 ctl_free_io((union ctl_io *)ctsio);
2326                 break;
2327         }
2328 }
2329
2330 /*
2331  * Returns 0 for success, errno for failure.
2332  */
2333 static void
2334 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2335                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2336 {
2337         union ctl_io *io;
2338
2339         mtx_lock(&lun->lun_lock);
2340         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2341              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2342              ooa_links)) {
2343                 struct ctl_ooa_entry *entry;
2344
2345                 /*
2346                  * If we've got more than we can fit, just count the
2347                  * remaining entries.
2348                  */
2349                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2350                         continue;
2351
2352                 entry = &kern_entries[*cur_fill_num];
2353
2354                 entry->tag_num = io->scsiio.tag_num;
2355                 entry->lun_num = lun->lun;
2356 #ifdef CTL_TIME_IO
2357                 entry->start_bt = io->io_hdr.start_bt;
2358 #endif
2359                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2360                 entry->cdb_len = io->scsiio.cdb_len;
2361                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2362                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2363
2364                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2365                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2366
2367                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2368                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2369
2370                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2371                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2372
2373                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2374                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2375         }
2376         mtx_unlock(&lun->lun_lock);
2377 }
2378
2379 static void *
2380 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2381                  size_t error_str_len)
2382 {
2383         void *kptr;
2384
2385         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2386
2387         if (copyin(user_addr, kptr, len) != 0) {
2388                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2389                          "from user address %p to kernel address %p", len,
2390                          user_addr, kptr);
2391                 free(kptr, M_CTL);
2392                 return (NULL);
2393         }
2394
2395         return (kptr);
2396 }
2397
2398 static void
2399 ctl_free_args(int num_args, struct ctl_be_arg *args)
2400 {
2401         int i;
2402
2403         if (args == NULL)
2404                 return;
2405
2406         for (i = 0; i < num_args; i++) {
2407                 free(args[i].kname, M_CTL);
2408                 free(args[i].kvalue, M_CTL);
2409         }
2410
2411         free(args, M_CTL);
2412 }
2413
2414 static struct ctl_be_arg *
2415 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2416                 char *error_str, size_t error_str_len)
2417 {
2418         struct ctl_be_arg *args;
2419         int i;
2420
2421         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2422                                 error_str, error_str_len);
2423
2424         if (args == NULL)
2425                 goto bailout;
2426
2427         for (i = 0; i < num_args; i++) {
2428                 args[i].kname = NULL;
2429                 args[i].kvalue = NULL;
2430         }
2431
2432         for (i = 0; i < num_args; i++) {
2433                 uint8_t *tmpptr;
2434
2435                 args[i].kname = ctl_copyin_alloc(args[i].name,
2436                         args[i].namelen, error_str, error_str_len);
2437                 if (args[i].kname == NULL)
2438                         goto bailout;
2439
2440                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2441                         snprintf(error_str, error_str_len, "Argument %d "
2442                                  "name is not NUL-terminated", i);
2443                         goto bailout;
2444                 }
2445
2446                 if (args[i].flags & CTL_BEARG_RD) {
2447                         tmpptr = ctl_copyin_alloc(args[i].value,
2448                                 args[i].vallen, error_str, error_str_len);
2449                         if (tmpptr == NULL)
2450                                 goto bailout;
2451                         if ((args[i].flags & CTL_BEARG_ASCII)
2452                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2453                                 snprintf(error_str, error_str_len, "Argument "
2454                                     "%d value is not NUL-terminated", i);
2455                                 free(tmpptr, M_CTL);
2456                                 goto bailout;
2457                         }
2458                         args[i].kvalue = tmpptr;
2459                 } else {
2460                         args[i].kvalue = malloc(args[i].vallen,
2461                             M_CTL, M_WAITOK | M_ZERO);
2462                 }
2463         }
2464
2465         return (args);
2466 bailout:
2467
2468         ctl_free_args(num_args, args);
2469
2470         return (NULL);
2471 }
2472
2473 static void
2474 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2475 {
2476         int i;
2477
2478         for (i = 0; i < num_args; i++) {
2479                 if (args[i].flags & CTL_BEARG_WR)
2480                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2481         }
2482 }
2483
2484 /*
2485  * Escape characters that are illegal or not recommended in XML.
2486  */
2487 int
2488 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2489 {
2490         char *end = str + size;
2491         int retval;
2492
2493         retval = 0;
2494
2495         for (; *str && str < end; str++) {
2496                 switch (*str) {
2497                 case '&':
2498                         retval = sbuf_printf(sb, "&amp;");
2499                         break;
2500                 case '>':
2501                         retval = sbuf_printf(sb, "&gt;");
2502                         break;
2503                 case '<':
2504                         retval = sbuf_printf(sb, "&lt;");
2505                         break;
2506                 default:
2507                         retval = sbuf_putc(sb, *str);
2508                         break;
2509                 }
2510
2511                 if (retval != 0)
2512                         break;
2513
2514         }
2515
2516         return (retval);
2517 }
2518
2519 static void
2520 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2521 {
2522         struct scsi_vpd_id_descriptor *desc;
2523         int i;
2524
2525         if (id == NULL || id->len < 4)
2526                 return;
2527         desc = (struct scsi_vpd_id_descriptor *)id->data;
2528         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2529         case SVPD_ID_TYPE_T10:
2530                 sbuf_printf(sb, "t10.");
2531                 break;
2532         case SVPD_ID_TYPE_EUI64:
2533                 sbuf_printf(sb, "eui.");
2534                 break;
2535         case SVPD_ID_TYPE_NAA:
2536                 sbuf_printf(sb, "naa.");
2537                 break;
2538         case SVPD_ID_TYPE_SCSI_NAME:
2539                 break;
2540         }
2541         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2542         case SVPD_ID_CODESET_BINARY:
2543                 for (i = 0; i < desc->length; i++)
2544                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2545                 break;
2546         case SVPD_ID_CODESET_ASCII:
2547                 sbuf_printf(sb, "%.*s", (int)desc->length,
2548                     (char *)desc->identifier);
2549                 break;
2550         case SVPD_ID_CODESET_UTF8:
2551                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2552                 break;
2553         }
2554 }
2555
2556 static int
2557 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2558           struct thread *td)
2559 {
2560         struct ctl_softc *softc = dev->si_drv1;
2561         struct ctl_lun *lun;
2562         int retval;
2563
2564         retval = 0;
2565
2566         switch (cmd) {
2567         case CTL_IO:
2568                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2569                 break;
2570         case CTL_ENABLE_PORT:
2571         case CTL_DISABLE_PORT:
2572         case CTL_SET_PORT_WWNS: {
2573                 struct ctl_port *port;
2574                 struct ctl_port_entry *entry;
2575
2576                 entry = (struct ctl_port_entry *)addr;
2577                 
2578                 mtx_lock(&softc->ctl_lock);
2579                 STAILQ_FOREACH(port, &softc->port_list, links) {
2580                         int action, done;
2581
2582                         if (port->targ_port < softc->port_min ||
2583                             port->targ_port >= softc->port_max)
2584                                 continue;
2585
2586                         action = 0;
2587                         done = 0;
2588                         if ((entry->port_type == CTL_PORT_NONE)
2589                          && (entry->targ_port == port->targ_port)) {
2590                                 /*
2591                                  * If the user only wants to enable or
2592                                  * disable or set WWNs on a specific port,
2593                                  * do the operation and we're done.
2594                                  */
2595                                 action = 1;
2596                                 done = 1;
2597                         } else if (entry->port_type & port->port_type) {
2598                                 /*
2599                                  * Compare the user's type mask with the
2600                                  * particular frontend type to see if we
2601                                  * have a match.
2602                                  */
2603                                 action = 1;
2604                                 done = 0;
2605
2606                                 /*
2607                                  * Make sure the user isn't trying to set
2608                                  * WWNs on multiple ports at the same time.
2609                                  */
2610                                 if (cmd == CTL_SET_PORT_WWNS) {
2611                                         printf("%s: Can't set WWNs on "
2612                                                "multiple ports\n", __func__);
2613                                         retval = EINVAL;
2614                                         break;
2615                                 }
2616                         }
2617                         if (action == 0)
2618                                 continue;
2619
2620                         /*
2621                          * XXX KDM we have to drop the lock here, because
2622                          * the online/offline operations can potentially
2623                          * block.  We need to reference count the frontends
2624                          * so they can't go away,
2625                          */
2626                         if (cmd == CTL_ENABLE_PORT) {
2627                                 mtx_unlock(&softc->ctl_lock);
2628                                 ctl_port_online(port);
2629                                 mtx_lock(&softc->ctl_lock);
2630                         } else if (cmd == CTL_DISABLE_PORT) {
2631                                 mtx_unlock(&softc->ctl_lock);
2632                                 ctl_port_offline(port);
2633                                 mtx_lock(&softc->ctl_lock);
2634                         } else if (cmd == CTL_SET_PORT_WWNS) {
2635                                 ctl_port_set_wwns(port,
2636                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2637                                     1 : 0, entry->wwnn,
2638                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2639                                     1 : 0, entry->wwpn);
2640                         }
2641                         if (done != 0)
2642                                 break;
2643                 }
2644                 mtx_unlock(&softc->ctl_lock);
2645                 break;
2646         }
2647         case CTL_GET_OOA: {
2648                 struct ctl_ooa *ooa_hdr;
2649                 struct ctl_ooa_entry *entries;
2650                 uint32_t cur_fill_num;
2651
2652                 ooa_hdr = (struct ctl_ooa *)addr;
2653
2654                 if ((ooa_hdr->alloc_len == 0)
2655                  || (ooa_hdr->alloc_num == 0)) {
2656                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2657                                "must be non-zero\n", __func__,
2658                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2659                         retval = EINVAL;
2660                         break;
2661                 }
2662
2663                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2664                     sizeof(struct ctl_ooa_entry))) {
2665                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2666                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2667                                __func__, ooa_hdr->alloc_len,
2668                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2669                         retval = EINVAL;
2670                         break;
2671                 }
2672
2673                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2674                 if (entries == NULL) {
2675                         printf("%s: could not allocate %d bytes for OOA "
2676                                "dump\n", __func__, ooa_hdr->alloc_len);
2677                         retval = ENOMEM;
2678                         break;
2679                 }
2680
2681                 mtx_lock(&softc->ctl_lock);
2682                 if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2683                     (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2684                      softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2685                         mtx_unlock(&softc->ctl_lock);
2686                         free(entries, M_CTL);
2687                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2688                                __func__, (uintmax_t)ooa_hdr->lun_num);
2689                         retval = EINVAL;
2690                         break;
2691                 }
2692
2693                 cur_fill_num = 0;
2694
2695                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2696                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2697                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2698                                     ooa_hdr, entries);
2699                         }
2700                 } else {
2701                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2702                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2703                             entries);
2704                 }
2705                 mtx_unlock(&softc->ctl_lock);
2706
2707                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2708                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2709                         sizeof(struct ctl_ooa_entry);
2710                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2711                 if (retval != 0) {
2712                         printf("%s: error copying out %d bytes for OOA dump\n", 
2713                                __func__, ooa_hdr->fill_len);
2714                 }
2715
2716                 getbinuptime(&ooa_hdr->cur_bt);
2717
2718                 if (cur_fill_num > ooa_hdr->alloc_num) {
2719                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2720                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2721                 } else {
2722                         ooa_hdr->dropped_num = 0;
2723                         ooa_hdr->status = CTL_OOA_OK;
2724                 }
2725
2726                 free(entries, M_CTL);
2727                 break;
2728         }
2729         case CTL_DELAY_IO: {
2730                 struct ctl_io_delay_info *delay_info;
2731
2732                 delay_info = (struct ctl_io_delay_info *)addr;
2733
2734 #ifdef CTL_IO_DELAY
2735                 mtx_lock(&softc->ctl_lock);
2736                 if (delay_info->lun_id >= CTL_MAX_LUNS ||
2737                     (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2738                         mtx_unlock(&softc->ctl_lock);
2739                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2740                         break;
2741                 }
2742                 mtx_lock(&lun->lun_lock);
2743                 mtx_unlock(&softc->ctl_lock);
2744                 delay_info->status = CTL_DELAY_STATUS_OK;
2745                 switch (delay_info->delay_type) {
2746                 case CTL_DELAY_TYPE_CONT:
2747                 case CTL_DELAY_TYPE_ONESHOT:
2748                         break;
2749                 default:
2750                         delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2751                         break;
2752                 }
2753                 switch (delay_info->delay_loc) {
2754                 case CTL_DELAY_LOC_DATAMOVE:
2755                         lun->delay_info.datamove_type = delay_info->delay_type;
2756                         lun->delay_info.datamove_delay = delay_info->delay_secs;
2757                         break;
2758                 case CTL_DELAY_LOC_DONE:
2759                         lun->delay_info.done_type = delay_info->delay_type;
2760                         lun->delay_info.done_delay = delay_info->delay_secs;
2761                         break;
2762                 default:
2763                         delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2764                         break;
2765                 }
2766                 mtx_unlock(&lun->lun_lock);
2767 #else
2768                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2769 #endif /* CTL_IO_DELAY */
2770                 break;
2771         }
2772         case CTL_GETSTATS: {
2773                 struct ctl_stats *stats = (struct ctl_stats *)addr;
2774                 int i;
2775
2776                 /*
2777                  * XXX KDM no locking here.  If the LUN list changes,
2778                  * things can blow up.
2779                  */
2780                 i = 0;
2781                 stats->status = CTL_SS_OK;
2782                 stats->fill_len = 0;
2783                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2784                         if (stats->fill_len + sizeof(lun->stats) >
2785                             stats->alloc_len) {
2786                                 stats->status = CTL_SS_NEED_MORE_SPACE;
2787                                 break;
2788                         }
2789                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2790                                          sizeof(lun->stats));
2791                         if (retval != 0)
2792                                 break;
2793                         stats->fill_len += sizeof(lun->stats);
2794                 }
2795                 stats->num_luns = softc->num_luns;
2796 #ifdef CTL_TIME_IO
2797                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2798 #else
2799                 stats->flags = CTL_STATS_FLAG_NONE;
2800 #endif
2801                 getnanouptime(&stats->timestamp);
2802                 break;
2803         }
2804         case CTL_ERROR_INJECT: {
2805                 struct ctl_error_desc *err_desc, *new_err_desc;
2806
2807                 err_desc = (struct ctl_error_desc *)addr;
2808
2809                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2810                                       M_WAITOK | M_ZERO);
2811                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2812
2813                 mtx_lock(&softc->ctl_lock);
2814                 if (err_desc->lun_id >= CTL_MAX_LUNS ||
2815                     (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2816                         mtx_unlock(&softc->ctl_lock);
2817                         free(new_err_desc, M_CTL);
2818                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2819                                __func__, (uintmax_t)err_desc->lun_id);
2820                         retval = EINVAL;
2821                         break;
2822                 }
2823                 mtx_lock(&lun->lun_lock);
2824                 mtx_unlock(&softc->ctl_lock);
2825
2826                 /*
2827                  * We could do some checking here to verify the validity
2828                  * of the request, but given the complexity of error
2829                  * injection requests, the checking logic would be fairly
2830                  * complex.
2831                  *
2832                  * For now, if the request is invalid, it just won't get
2833                  * executed and might get deleted.
2834                  */
2835                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2836
2837                 /*
2838                  * XXX KDM check to make sure the serial number is unique,
2839                  * in case we somehow manage to wrap.  That shouldn't
2840                  * happen for a very long time, but it's the right thing to
2841                  * do.
2842                  */
2843                 new_err_desc->serial = lun->error_serial;
2844                 err_desc->serial = lun->error_serial;
2845                 lun->error_serial++;
2846
2847                 mtx_unlock(&lun->lun_lock);
2848                 break;
2849         }
2850         case CTL_ERROR_INJECT_DELETE: {
2851                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2852                 int delete_done;
2853
2854                 delete_desc = (struct ctl_error_desc *)addr;
2855                 delete_done = 0;
2856
2857                 mtx_lock(&softc->ctl_lock);
2858                 if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2859                     (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2860                         mtx_unlock(&softc->ctl_lock);
2861                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2862                                __func__, (uintmax_t)delete_desc->lun_id);
2863                         retval = EINVAL;
2864                         break;
2865                 }
2866                 mtx_lock(&lun->lun_lock);
2867                 mtx_unlock(&softc->ctl_lock);
2868                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2869                         if (desc->serial != delete_desc->serial)
2870                                 continue;
2871
2872                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2873                                       links);
2874                         free(desc, M_CTL);
2875                         delete_done = 1;
2876                 }
2877                 mtx_unlock(&lun->lun_lock);
2878                 if (delete_done == 0) {
2879                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2880                                "error serial %ju on LUN %u\n", __func__, 
2881                                delete_desc->serial, delete_desc->lun_id);
2882                         retval = EINVAL;
2883                         break;
2884                 }
2885                 break;
2886         }
2887         case CTL_DUMP_STRUCTS: {
2888                 int j, k;
2889                 struct ctl_port *port;
2890                 struct ctl_frontend *fe;
2891
2892                 mtx_lock(&softc->ctl_lock);
2893                 printf("CTL Persistent Reservation information start:\n");
2894                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2895                         mtx_lock(&lun->lun_lock);
2896                         if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2897                                 mtx_unlock(&lun->lun_lock);
2898                                 continue;
2899                         }
2900
2901                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2902                                 if (lun->pr_keys[j] == NULL)
2903                                         continue;
2904                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2905                                         if (lun->pr_keys[j][k] == 0)
2906                                                 continue;
2907                                         printf("  LUN %ju port %d iid %d key "
2908                                                "%#jx\n", lun->lun, j, k,
2909                                                (uintmax_t)lun->pr_keys[j][k]);
2910                                 }
2911                         }
2912                         mtx_unlock(&lun->lun_lock);
2913                 }
2914                 printf("CTL Persistent Reservation information end\n");
2915                 printf("CTL Ports:\n");
2916                 STAILQ_FOREACH(port, &softc->port_list, links) {
2917                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2918                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2919                                port->frontend->name, port->port_type,
2920                                port->physical_port, port->virtual_port,
2921                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2922                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2923                                 if (port->wwpn_iid[j].in_use == 0 &&
2924                                     port->wwpn_iid[j].wwpn == 0 &&
2925                                     port->wwpn_iid[j].name == NULL)
2926                                         continue;
2927
2928                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2929                                     j, port->wwpn_iid[j].in_use,
2930                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2931                                     port->wwpn_iid[j].name);
2932                         }
2933                 }
2934                 printf("CTL Port information end\n");
2935                 mtx_unlock(&softc->ctl_lock);
2936                 /*
2937                  * XXX KDM calling this without a lock.  We'd likely want
2938                  * to drop the lock before calling the frontend's dump
2939                  * routine anyway.
2940                  */
2941                 printf("CTL Frontends:\n");
2942                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2943                         printf("  Frontend '%s'\n", fe->name);
2944                         if (fe->fe_dump != NULL)
2945                                 fe->fe_dump();
2946                 }
2947                 printf("CTL Frontend information end\n");
2948                 break;
2949         }
2950         case CTL_LUN_REQ: {
2951                 struct ctl_lun_req *lun_req;
2952                 struct ctl_backend_driver *backend;
2953
2954                 lun_req = (struct ctl_lun_req *)addr;
2955
2956                 backend = ctl_backend_find(lun_req->backend);
2957                 if (backend == NULL) {
2958                         lun_req->status = CTL_LUN_ERROR;
2959                         snprintf(lun_req->error_str,
2960                                  sizeof(lun_req->error_str),
2961                                  "Backend \"%s\" not found.",
2962                                  lun_req->backend);
2963                         break;
2964                 }
2965                 if (lun_req->num_be_args > 0) {
2966                         lun_req->kern_be_args = ctl_copyin_args(
2967                                 lun_req->num_be_args,
2968                                 lun_req->be_args,
2969                                 lun_req->error_str,
2970                                 sizeof(lun_req->error_str));
2971                         if (lun_req->kern_be_args == NULL) {
2972                                 lun_req->status = CTL_LUN_ERROR;
2973                                 break;
2974                         }
2975                 }
2976
2977                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2978
2979                 if (lun_req->num_be_args > 0) {
2980                         ctl_copyout_args(lun_req->num_be_args,
2981                                       lun_req->kern_be_args);
2982                         ctl_free_args(lun_req->num_be_args,
2983                                       lun_req->kern_be_args);
2984                 }
2985                 break;
2986         }
2987         case CTL_LUN_LIST: {
2988                 struct sbuf *sb;
2989                 struct ctl_lun_list *list;
2990                 struct ctl_option *opt;
2991
2992                 list = (struct ctl_lun_list *)addr;
2993
2994                 /*
2995                  * Allocate a fixed length sbuf here, based on the length
2996                  * of the user's buffer.  We could allocate an auto-extending
2997                  * buffer, and then tell the user how much larger our
2998                  * amount of data is than his buffer, but that presents
2999                  * some problems:
3000                  *
3001                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3002                  *     we can't hold a lock while calling them with an
3003                  *     auto-extending buffer.
3004                  *
3005                  * 2.  There is not currently a LUN reference counting
3006                  *     mechanism, outside of outstanding transactions on
3007                  *     the LUN's OOA queue.  So a LUN could go away on us
3008                  *     while we're getting the LUN number, backend-specific
3009                  *     information, etc.  Thus, given the way things
3010                  *     currently work, we need to hold the CTL lock while
3011                  *     grabbing LUN information.
3012                  *
3013                  * So, from the user's standpoint, the best thing to do is
3014                  * allocate what he thinks is a reasonable buffer length,
3015                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3016                  * double the buffer length and try again.  (And repeat
3017                  * that until he succeeds.)
3018                  */
3019                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3020                 if (sb == NULL) {
3021                         list->status = CTL_LUN_LIST_ERROR;
3022                         snprintf(list->error_str, sizeof(list->error_str),
3023                                  "Unable to allocate %d bytes for LUN list",
3024                                  list->alloc_len);
3025                         break;
3026                 }
3027
3028                 sbuf_printf(sb, "<ctllunlist>\n");
3029
3030                 mtx_lock(&softc->ctl_lock);
3031                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3032                         mtx_lock(&lun->lun_lock);
3033                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3034                                              (uintmax_t)lun->lun);
3035
3036                         /*
3037                          * Bail out as soon as we see that we've overfilled
3038                          * the buffer.
3039                          */
3040                         if (retval != 0)
3041                                 break;
3042
3043                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3044                                              "</backend_type>\n",
3045                                              (lun->backend == NULL) ?  "none" :
3046                                              lun->backend->name);
3047
3048                         if (retval != 0)
3049                                 break;
3050
3051                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3052                                              lun->be_lun->lun_type);
3053
3054                         if (retval != 0)
3055                                 break;
3056
3057                         if (lun->backend == NULL) {
3058                                 retval = sbuf_printf(sb, "</lun>\n");
3059                                 if (retval != 0)
3060                                         break;
3061                                 continue;
3062                         }
3063
3064                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3065                                              (lun->be_lun->maxlba > 0) ?
3066                                              lun->be_lun->maxlba + 1 : 0);
3067
3068                         if (retval != 0)
3069                                 break;
3070
3071                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3072                                              lun->be_lun->blocksize);
3073
3074                         if (retval != 0)
3075                                 break;
3076
3077                         retval = sbuf_printf(sb, "\t<serial_number>");
3078
3079                         if (retval != 0)
3080                                 break;
3081
3082                         retval = ctl_sbuf_printf_esc(sb,
3083                             lun->be_lun->serial_num,
3084                             sizeof(lun->be_lun->serial_num));
3085
3086                         if (retval != 0)
3087                                 break;
3088
3089                         retval = sbuf_printf(sb, "</serial_number>\n");
3090                 
3091                         if (retval != 0)
3092                                 break;
3093
3094                         retval = sbuf_printf(sb, "\t<device_id>");
3095
3096                         if (retval != 0)
3097                                 break;
3098
3099                         retval = ctl_sbuf_printf_esc(sb,
3100                             lun->be_lun->device_id,
3101                             sizeof(lun->be_lun->device_id));
3102
3103                         if (retval != 0)
3104                                 break;
3105
3106                         retval = sbuf_printf(sb, "</device_id>\n");
3107
3108                         if (retval != 0)
3109                                 break;
3110
3111                         if (lun->backend->lun_info != NULL) {
3112                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3113                                 if (retval != 0)
3114                                         break;
3115                         }
3116                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3117                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3118                                     opt->name, opt->value, opt->name);
3119                                 if (retval != 0)
3120                                         break;
3121                         }
3122
3123                         retval = sbuf_printf(sb, "</lun>\n");
3124
3125                         if (retval != 0)
3126                                 break;
3127                         mtx_unlock(&lun->lun_lock);
3128                 }
3129                 if (lun != NULL)
3130                         mtx_unlock(&lun->lun_lock);
3131                 mtx_unlock(&softc->ctl_lock);
3132
3133                 if ((retval != 0)
3134                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3135                         retval = 0;
3136                         sbuf_delete(sb);
3137                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3138                         snprintf(list->error_str, sizeof(list->error_str),
3139                                  "Out of space, %d bytes is too small",
3140                                  list->alloc_len);
3141                         break;
3142                 }
3143
3144                 sbuf_finish(sb);
3145
3146                 retval = copyout(sbuf_data(sb), list->lun_xml,
3147                                  sbuf_len(sb) + 1);
3148
3149                 list->fill_len = sbuf_len(sb) + 1;
3150                 list->status = CTL_LUN_LIST_OK;
3151                 sbuf_delete(sb);
3152                 break;
3153         }
3154         case CTL_ISCSI: {
3155                 struct ctl_iscsi *ci;
3156                 struct ctl_frontend *fe;
3157
3158                 ci = (struct ctl_iscsi *)addr;
3159
3160                 fe = ctl_frontend_find("iscsi");
3161                 if (fe == NULL) {
3162                         ci->status = CTL_ISCSI_ERROR;
3163                         snprintf(ci->error_str, sizeof(ci->error_str),
3164                             "Frontend \"iscsi\" not found.");
3165                         break;
3166                 }
3167
3168                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3169                 break;
3170         }
3171         case CTL_PORT_REQ: {
3172                 struct ctl_req *req;
3173                 struct ctl_frontend *fe;
3174
3175                 req = (struct ctl_req *)addr;
3176
3177                 fe = ctl_frontend_find(req->driver);
3178                 if (fe == NULL) {
3179                         req->status = CTL_LUN_ERROR;
3180                         snprintf(req->error_str, sizeof(req->error_str),
3181                             "Frontend \"%s\" not found.", req->driver);
3182                         break;
3183                 }
3184                 if (req->num_args > 0) {
3185                         req->kern_args = ctl_copyin_args(req->num_args,
3186                             req->args, req->error_str, sizeof(req->error_str));
3187                         if (req->kern_args == NULL) {
3188                                 req->status = CTL_LUN_ERROR;
3189                                 break;
3190                         }
3191                 }
3192
3193                 if (fe->ioctl)
3194                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3195                 else
3196                         retval = ENODEV;
3197
3198                 if (req->num_args > 0) {
3199                         ctl_copyout_args(req->num_args, req->kern_args);
3200                         ctl_free_args(req->num_args, req->kern_args);
3201                 }
3202                 break;
3203         }
3204         case CTL_PORT_LIST: {
3205                 struct sbuf *sb;
3206                 struct ctl_port *port;
3207                 struct ctl_lun_list *list;
3208                 struct ctl_option *opt;
3209                 int j;
3210                 uint32_t plun;
3211
3212                 list = (struct ctl_lun_list *)addr;
3213
3214                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3215                 if (sb == NULL) {
3216                         list->status = CTL_LUN_LIST_ERROR;
3217                         snprintf(list->error_str, sizeof(list->error_str),
3218                                  "Unable to allocate %d bytes for LUN list",
3219                                  list->alloc_len);
3220                         break;
3221                 }
3222
3223                 sbuf_printf(sb, "<ctlportlist>\n");
3224
3225                 mtx_lock(&softc->ctl_lock);
3226                 STAILQ_FOREACH(port, &softc->port_list, links) {
3227                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3228                                              (uintmax_t)port->targ_port);
3229
3230                         /*
3231                          * Bail out as soon as we see that we've overfilled
3232                          * the buffer.
3233                          */
3234                         if (retval != 0)
3235                                 break;
3236
3237                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3238                             "</frontend_type>\n", port->frontend->name);
3239                         if (retval != 0)
3240                                 break;
3241
3242                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3243                                              port->port_type);
3244                         if (retval != 0)
3245                                 break;
3246
3247                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3248                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3249                         if (retval != 0)
3250                                 break;
3251
3252                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3253                             port->port_name);
3254                         if (retval != 0)
3255                                 break;
3256
3257                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3258                             port->physical_port);
3259                         if (retval != 0)
3260                                 break;
3261
3262                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3263                             port->virtual_port);
3264                         if (retval != 0)
3265                                 break;
3266
3267                         if (port->target_devid != NULL) {
3268                                 sbuf_printf(sb, "\t<target>");
3269                                 ctl_id_sbuf(port->target_devid, sb);
3270                                 sbuf_printf(sb, "</target>\n");
3271                         }
3272
3273                         if (port->port_devid != NULL) {
3274                                 sbuf_printf(sb, "\t<port>");
3275                                 ctl_id_sbuf(port->port_devid, sb);
3276                                 sbuf_printf(sb, "</port>\n");
3277                         }
3278
3279                         if (port->port_info != NULL) {
3280                                 retval = port->port_info(port->onoff_arg, sb);
3281                                 if (retval != 0)
3282                                         break;
3283                         }
3284                         STAILQ_FOREACH(opt, &port->options, links) {
3285                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3286                                     opt->name, opt->value, opt->name);
3287                                 if (retval != 0)
3288                                         break;
3289                         }
3290
3291                         if (port->lun_map != NULL) {
3292                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3293                                 for (j = 0; j < port->lun_map_size; j++) {
3294                                         plun = ctl_lun_map_from_port(port, j);
3295                                         if (plun == UINT32_MAX)
3296                                                 continue;
3297                                         sbuf_printf(sb,
3298                                             "\t<lun id=\"%u\">%u</lun>\n",
3299                                             j, plun);
3300                                 }
3301                         }
3302
3303                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3304                                 if (port->wwpn_iid[j].in_use == 0 ||
3305                                     (port->wwpn_iid[j].wwpn == 0 &&
3306                                      port->wwpn_iid[j].name == NULL))
3307                                         continue;
3308
3309                                 if (port->wwpn_iid[j].name != NULL)
3310                                         retval = sbuf_printf(sb,
3311                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3312                                             j, port->wwpn_iid[j].name);
3313                                 else
3314                                         retval = sbuf_printf(sb,
3315                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3316                                             j, port->wwpn_iid[j].wwpn);
3317                                 if (retval != 0)
3318                                         break;
3319                         }
3320                         if (retval != 0)
3321                                 break;
3322
3323                         retval = sbuf_printf(sb, "</targ_port>\n");
3324                         if (retval != 0)
3325                                 break;
3326                 }
3327                 mtx_unlock(&softc->ctl_lock);
3328
3329                 if ((retval != 0)
3330                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3331                         retval = 0;
3332                         sbuf_delete(sb);
3333                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3334                         snprintf(list->error_str, sizeof(list->error_str),
3335                                  "Out of space, %d bytes is too small",
3336                                  list->alloc_len);
3337                         break;
3338                 }
3339
3340                 sbuf_finish(sb);
3341
3342                 retval = copyout(sbuf_data(sb), list->lun_xml,
3343                                  sbuf_len(sb) + 1);
3344
3345                 list->fill_len = sbuf_len(sb) + 1;
3346                 list->status = CTL_LUN_LIST_OK;
3347                 sbuf_delete(sb);
3348                 break;
3349         }
3350         case CTL_LUN_MAP: {
3351                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3352                 struct ctl_port *port;
3353
3354                 mtx_lock(&softc->ctl_lock);
3355                 if (lm->port < softc->port_min ||
3356                     lm->port >= softc->port_max ||
3357                     (port = softc->ctl_ports[lm->port]) == NULL) {
3358                         mtx_unlock(&softc->ctl_lock);
3359                         return (ENXIO);
3360                 }
3361                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3362                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3363                                 if (ctl_lun_map_to_port(port, lun->lun) ==
3364                                     UINT32_MAX)
3365                                         continue;
3366                                 mtx_lock(&lun->lun_lock);
3367                                 ctl_est_ua_port(lun, lm->port, -1,
3368                                     CTL_UA_LUN_CHANGE);
3369                                 mtx_unlock(&lun->lun_lock);
3370                         }
3371                 }
3372                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3373                 if (lm->plun != UINT32_MAX) {
3374                         if (lm->lun == UINT32_MAX)
3375                                 retval = ctl_lun_map_unset(port, lm->plun);
3376                         else if (lm->lun < CTL_MAX_LUNS &&
3377                             softc->ctl_luns[lm->lun] != NULL)
3378                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3379                         else
3380                                 return (ENXIO);
3381                 } else {
3382                         if (lm->lun == UINT32_MAX)
3383                                 retval = ctl_lun_map_deinit(port);
3384                         else
3385                                 retval = ctl_lun_map_init(port);
3386                 }
3387                 if (port->status & CTL_PORT_STATUS_ONLINE)
3388                         ctl_isc_announce_port(port);
3389                 break;
3390         }
3391         default: {
3392                 /* XXX KDM should we fix this? */
3393 #if 0
3394                 struct ctl_backend_driver *backend;
3395                 unsigned int type;
3396                 int found;
3397
3398                 found = 0;
3399
3400                 /*
3401                  * We encode the backend type as the ioctl type for backend
3402                  * ioctls.  So parse it out here, and then search for a
3403                  * backend of this type.
3404                  */
3405                 type = _IOC_TYPE(cmd);
3406
3407                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3408                         if (backend->type == type) {
3409                                 found = 1;
3410                                 break;
3411                         }
3412                 }
3413                 if (found == 0) {
3414                         printf("ctl: unknown ioctl command %#lx or backend "
3415                                "%d\n", cmd, type);
3416                         retval = EINVAL;
3417                         break;
3418                 }
3419                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3420 #endif
3421                 retval = ENOTTY;
3422                 break;
3423         }
3424         }
3425         return (retval);
3426 }
3427
3428 uint32_t
3429 ctl_get_initindex(struct ctl_nexus *nexus)
3430 {
3431         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3432 }
3433
3434 int
3435 ctl_lun_map_init(struct ctl_port *port)
3436 {
3437         struct ctl_softc *softc = port->ctl_softc;
3438         struct ctl_lun *lun;
3439         int size = ctl_lun_map_size;
3440         uint32_t i;
3441
3442         if (port->lun_map == NULL || port->lun_map_size < size) {
3443                 port->lun_map_size = 0;
3444                 free(port->lun_map, M_CTL);
3445                 port->lun_map = malloc(size * sizeof(uint32_t),
3446                     M_CTL, M_NOWAIT);
3447         }
3448         if (port->lun_map == NULL)
3449                 return (ENOMEM);
3450         for (i = 0; i < size; i++)
3451                 port->lun_map[i] = UINT32_MAX;
3452         port->lun_map_size = size;
3453         if (port->status & CTL_PORT_STATUS_ONLINE) {
3454                 if (port->lun_disable != NULL) {
3455                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3456                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3457                 }
3458                 ctl_isc_announce_port(port);
3459         }
3460         return (0);
3461 }
3462
3463 int
3464 ctl_lun_map_deinit(struct ctl_port *port)
3465 {
3466         struct ctl_softc *softc = port->ctl_softc;
3467         struct ctl_lun *lun;
3468
3469         if (port->lun_map == NULL)
3470                 return (0);
3471         port->lun_map_size = 0;
3472         free(port->lun_map, M_CTL);
3473         port->lun_map = NULL;
3474         if (port->status & CTL_PORT_STATUS_ONLINE) {
3475                 if (port->lun_enable != NULL) {
3476                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3477                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3478                 }
3479                 ctl_isc_announce_port(port);
3480         }
3481         return (0);
3482 }
3483
3484 int
3485 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3486 {
3487         int status;
3488         uint32_t old;
3489
3490         if (port->lun_map == NULL) {
3491                 status = ctl_lun_map_init(port);
3492                 if (status != 0)
3493                         return (status);
3494         }
3495         if (plun >= port->lun_map_size)
3496                 return (EINVAL);
3497         old = port->lun_map[plun];
3498         port->lun_map[plun] = glun;
3499         if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3500                 if (port->lun_enable != NULL)
3501                         port->lun_enable(port->targ_lun_arg, plun);
3502                 ctl_isc_announce_port(port);
3503         }
3504         return (0);
3505 }
3506
3507 int
3508 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3509 {
3510         uint32_t old;
3511
3512         if (port->lun_map == NULL || plun >= port->lun_map_size)
3513                 return (0);
3514         old = port->lun_map[plun];
3515         port->lun_map[plun] = UINT32_MAX;
3516         if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3517                 if (port->lun_disable != NULL)
3518                         port->lun_disable(port->targ_lun_arg, plun);
3519                 ctl_isc_announce_port(port);
3520         }
3521         return (0);
3522 }
3523
3524 uint32_t
3525 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3526 {
3527
3528         if (port == NULL)
3529                 return (UINT32_MAX);
3530         if (port->lun_map == NULL)
3531                 return (lun_id);
3532         if (lun_id > port->lun_map_size)
3533                 return (UINT32_MAX);
3534         return (port->lun_map[lun_id]);
3535 }
3536
3537 uint32_t
3538 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3539 {
3540         uint32_t i;
3541
3542         if (port == NULL)
3543                 return (UINT32_MAX);
3544         if (port->lun_map == NULL)
3545                 return (lun_id);
3546         for (i = 0; i < port->lun_map_size; i++) {
3547                 if (port->lun_map[i] == lun_id)
3548                         return (i);
3549         }
3550         return (UINT32_MAX);
3551 }
3552
3553 uint32_t
3554 ctl_decode_lun(uint64_t encoded)
3555 {
3556         uint8_t lun[8];
3557         uint32_t result = 0xffffffff;
3558
3559         be64enc(lun, encoded);
3560         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3561         case RPL_LUNDATA_ATYP_PERIPH:
3562                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3563                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3564                         result = lun[1];
3565                 break;
3566         case RPL_LUNDATA_ATYP_FLAT:
3567                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3568                     lun[6] == 0 && lun[7] == 0)
3569                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3570                 break;
3571         case RPL_LUNDATA_ATYP_EXTLUN:
3572                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3573                 case 0x02:
3574                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3575                         case 0x00:
3576                                 result = lun[1];
3577                                 break;
3578                         case 0x10:
3579                                 result = (lun[1] << 16) + (lun[2] << 8) +
3580                                     lun[3];
3581                                 break;
3582                         case 0x20:
3583                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3584                                         result = (lun[2] << 24) +
3585                                             (lun[3] << 16) + (lun[4] << 8) +
3586                                             lun[5];
3587                                 break;
3588                         }
3589                         break;
3590                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3591                         result = 0xffffffff;
3592                         break;
3593                 }
3594                 break;
3595         }
3596         return (result);
3597 }
3598
3599 uint64_t
3600 ctl_encode_lun(uint32_t decoded)
3601 {
3602         uint64_t l = decoded;
3603
3604         if (l <= 0xff)
3605                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3606         if (l <= 0x3fff)
3607                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3608         if (l <= 0xffffff)
3609                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3610                     (l << 32));
3611         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3612 }
3613
3614 int
3615 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3616 {
3617         int i;
3618
3619         for (i = first; i < last; i++) {
3620                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3621                         return (i);
3622         }
3623         return (-1);
3624 }
3625
3626 int
3627 ctl_set_mask(uint32_t *mask, uint32_t bit)
3628 {
3629         uint32_t chunk, piece;
3630
3631         chunk = bit >> 5;
3632         piece = bit % (sizeof(uint32_t) * 8);
3633
3634         if ((mask[chunk] & (1 << piece)) != 0)
3635                 return (-1);
3636         else
3637                 mask[chunk] |= (1 << piece);
3638
3639         return (0);
3640 }
3641
3642 int
3643 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3644 {
3645         uint32_t chunk, piece;
3646
3647         chunk = bit >> 5;
3648         piece = bit % (sizeof(uint32_t) * 8);
3649
3650         if ((mask[chunk] & (1 << piece)) == 0)
3651                 return (-1);
3652         else
3653                 mask[chunk] &= ~(1 << piece);
3654
3655         return (0);
3656 }
3657
3658 int
3659 ctl_is_set(uint32_t *mask, uint32_t bit)
3660 {
3661         uint32_t chunk, piece;
3662
3663         chunk = bit >> 5;
3664         piece = bit % (sizeof(uint32_t) * 8);
3665
3666         if ((mask[chunk] & (1 << piece)) == 0)
3667                 return (0);
3668         else
3669                 return (1);
3670 }
3671
3672 static uint64_t
3673 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3674 {
3675         uint64_t *t;
3676
3677         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3678         if (t == NULL)
3679                 return (0);
3680         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3681 }
3682
3683 static void
3684 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3685 {
3686         uint64_t *t;
3687
3688         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3689         if (t == NULL)
3690                 return;
3691         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3692 }
3693
3694 static void
3695 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3696 {
3697         uint64_t *p;
3698         u_int i;
3699
3700         i = residx/CTL_MAX_INIT_PER_PORT;
3701         if (lun->pr_keys[i] != NULL)
3702                 return;
3703         mtx_unlock(&lun->lun_lock);
3704         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3705             M_WAITOK | M_ZERO);
3706         mtx_lock(&lun->lun_lock);
3707         if (lun->pr_keys[i] == NULL)
3708                 lun->pr_keys[i] = p;
3709         else
3710                 free(p, M_CTL);
3711 }
3712
3713 static void
3714 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3715 {
3716         uint64_t *t;
3717
3718         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3719         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3720         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3721 }
3722
3723 /*
3724  * ctl_softc, pool_name, total_ctl_io are passed in.
3725  * npool is passed out.
3726  */
3727 int
3728 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3729                 uint32_t total_ctl_io, void **npool)
3730 {
3731         struct ctl_io_pool *pool;
3732
3733         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3734                                             M_NOWAIT | M_ZERO);
3735         if (pool == NULL)
3736                 return (ENOMEM);
3737
3738         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3739         pool->ctl_softc = ctl_softc;
3740 #ifdef IO_POOLS
3741         pool->zone = uma_zsecond_create(pool->name, NULL,
3742             NULL, NULL, NULL, ctl_softc->io_zone);
3743         /* uma_prealloc(pool->zone, total_ctl_io); */
3744 #else
3745         pool->zone = ctl_softc->io_zone;
3746 #endif
3747
3748         *npool = pool;
3749         return (0);
3750 }
3751
3752 void
3753 ctl_pool_free(struct ctl_io_pool *pool)
3754 {
3755
3756         if (pool == NULL)
3757                 return;
3758
3759 #ifdef IO_POOLS
3760         uma_zdestroy(pool->zone);
3761 #endif
3762         free(pool, M_CTL);
3763 }
3764
3765 union ctl_io *
3766 ctl_alloc_io(void *pool_ref)
3767 {
3768         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3769         union ctl_io *io;
3770
3771         io = uma_zalloc(pool->zone, M_WAITOK);
3772         if (io != NULL) {
3773                 io->io_hdr.pool = pool_ref;
3774                 CTL_SOFTC(io) = pool->ctl_softc;
3775         }
3776         return (io);
3777 }
3778
3779 union ctl_io *
3780 ctl_alloc_io_nowait(void *pool_ref)
3781 {
3782         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3783         union ctl_io *io;
3784
3785         io = uma_zalloc(pool->zone, M_NOWAIT);
3786         if (io != NULL) {
3787                 io->io_hdr.pool = pool_ref;
3788                 CTL_SOFTC(io) = pool->ctl_softc;
3789         }
3790         return (io);
3791 }
3792
3793 void
3794 ctl_free_io(union ctl_io *io)
3795 {
3796         struct ctl_io_pool *pool;
3797
3798         if (io == NULL)
3799                 return;
3800
3801         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3802         uma_zfree(pool->zone, io);
3803 }
3804
3805 void
3806 ctl_zero_io(union ctl_io *io)
3807 {
3808         struct ctl_io_pool *pool;
3809
3810         if (io == NULL)
3811                 return;
3812
3813         /*
3814          * May need to preserve linked list pointers at some point too.
3815          */
3816         pool = io->io_hdr.pool;
3817         memset(io, 0, sizeof(*io));
3818         io->io_hdr.pool = pool;
3819         CTL_SOFTC(io) = pool->ctl_softc;
3820 }
3821
3822 int
3823 ctl_expand_number(const char *buf, uint64_t *num)
3824 {
3825         char *endptr;
3826         uint64_t number;
3827         unsigned shift;
3828
3829         number = strtoq(buf, &endptr, 0);
3830
3831         switch (tolower((unsigned char)*endptr)) {
3832         case 'e':
3833                 shift = 60;
3834                 break;
3835         case 'p':
3836                 shift = 50;
3837                 break;
3838         case 't':
3839                 shift = 40;
3840                 break;
3841         case 'g':
3842                 shift = 30;
3843                 break;
3844         case 'm':
3845                 shift = 20;
3846                 break;
3847         case 'k':
3848                 shift = 10;
3849                 break;
3850         case 'b':
3851         case '\0': /* No unit. */
3852                 *num = number;
3853                 return (0);
3854         default:
3855                 /* Unrecognized unit. */
3856                 return (-1);
3857         }
3858
3859         if ((number << shift) >> shift != number) {
3860                 /* Overflow */
3861                 return (-1);
3862         }
3863         *num = number << shift;
3864         return (0);
3865 }
3866
3867
3868 /*
3869  * This routine could be used in the future to load default and/or saved
3870  * mode page parameters for a particuar lun.
3871  */
3872 static int
3873 ctl_init_page_index(struct ctl_lun *lun)
3874 {
3875         int i, page_code;
3876         struct ctl_page_index *page_index;
3877         const char *value;
3878         uint64_t ival;
3879
3880         memcpy(&lun->mode_pages.index, page_index_template,
3881                sizeof(page_index_template));
3882
3883         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3884
3885                 page_index = &lun->mode_pages.index[i];
3886                 if (lun->be_lun->lun_type == T_DIRECT &&
3887                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3888                         continue;
3889                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3890                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3891                         continue;
3892                 if (lun->be_lun->lun_type == T_CDROM &&
3893                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3894                         continue;
3895
3896                 page_code = page_index->page_code & SMPH_PC_MASK;
3897                 switch (page_code) {
3898                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3899                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3900                             ("subpage %#x for page %#x is incorrect!",
3901                             page_index->subpage, page_code));
3902                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3903                                &rw_er_page_default,
3904                                sizeof(rw_er_page_default));
3905                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3906                                &rw_er_page_changeable,
3907                                sizeof(rw_er_page_changeable));
3908                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3909                                &rw_er_page_default,
3910                                sizeof(rw_er_page_default));
3911                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3912                                &rw_er_page_default,
3913                                sizeof(rw_er_page_default));
3914                         page_index->page_data =
3915                                 (uint8_t *)lun->mode_pages.rw_er_page;
3916                         break;
3917                 }
3918                 case SMS_FORMAT_DEVICE_PAGE: {
3919                         struct scsi_format_page *format_page;
3920
3921                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3922                             ("subpage %#x for page %#x is incorrect!",
3923                             page_index->subpage, page_code));
3924
3925                         /*
3926                          * Sectors per track are set above.  Bytes per
3927                          * sector need to be set here on a per-LUN basis.
3928                          */
3929                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3930                                &format_page_default,
3931                                sizeof(format_page_default));
3932                         memcpy(&lun->mode_pages.format_page[
3933                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3934                                sizeof(format_page_changeable));
3935                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3936                                &format_page_default,
3937                                sizeof(format_page_default));
3938                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3939                                &format_page_default,
3940                                sizeof(format_page_default));
3941
3942                         format_page = &lun->mode_pages.format_page[
3943                                 CTL_PAGE_CURRENT];
3944                         scsi_ulto2b(lun->be_lun->blocksize,
3945                                     format_page->bytes_per_sector);
3946
3947                         format_page = &lun->mode_pages.format_page[
3948                                 CTL_PAGE_DEFAULT];
3949                         scsi_ulto2b(lun->be_lun->blocksize,
3950                                     format_page->bytes_per_sector);
3951
3952                         format_page = &lun->mode_pages.format_page[
3953                                 CTL_PAGE_SAVED];
3954                         scsi_ulto2b(lun->be_lun->blocksize,
3955                                     format_page->bytes_per_sector);
3956
3957                         page_index->page_data =
3958                                 (uint8_t *)lun->mode_pages.format_page;
3959                         break;
3960                 }
3961                 case SMS_RIGID_DISK_PAGE: {
3962                         struct scsi_rigid_disk_page *rigid_disk_page;
3963                         uint32_t sectors_per_cylinder;
3964                         uint64_t cylinders;
3965 #ifndef __XSCALE__
3966                         int shift;
3967 #endif /* !__XSCALE__ */
3968
3969                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3970                             ("subpage %#x for page %#x is incorrect!",
3971                             page_index->subpage, page_code));
3972
3973                         /*
3974                          * Rotation rate and sectors per track are set
3975                          * above.  We calculate the cylinders here based on
3976                          * capacity.  Due to the number of heads and
3977                          * sectors per track we're using, smaller arrays
3978                          * may turn out to have 0 cylinders.  Linux and
3979                          * FreeBSD don't pay attention to these mode pages
3980                          * to figure out capacity, but Solaris does.  It
3981                          * seems to deal with 0 cylinders just fine, and
3982                          * works out a fake geometry based on the capacity.
3983                          */
3984                         memcpy(&lun->mode_pages.rigid_disk_page[
3985                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3986                                sizeof(rigid_disk_page_default));
3987                         memcpy(&lun->mode_pages.rigid_disk_page[
3988                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3989                                sizeof(rigid_disk_page_changeable));
3990
3991                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3992                                 CTL_DEFAULT_HEADS;
3993
3994                         /*
3995                          * The divide method here will be more accurate,
3996                          * probably, but results in floating point being
3997                          * used in the kernel on i386 (__udivdi3()).  On the
3998                          * XScale, though, __udivdi3() is implemented in
3999                          * software.
4000                          *
4001                          * The shift method for cylinder calculation is
4002                          * accurate if sectors_per_cylinder is a power of
4003                          * 2.  Otherwise it might be slightly off -- you
4004                          * might have a bit of a truncation problem.
4005                          */
4006 #ifdef  __XSCALE__
4007                         cylinders = (lun->be_lun->maxlba + 1) /
4008                                 sectors_per_cylinder;
4009 #else
4010                         for (shift = 31; shift > 0; shift--) {
4011                                 if (sectors_per_cylinder & (1 << shift))
4012                                         break;
4013                         }
4014                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4015 #endif
4016
4017                         /*
4018                          * We've basically got 3 bytes, or 24 bits for the
4019                          * cylinder size in the mode page.  If we're over,
4020                          * just round down to 2^24.
4021                          */
4022                         if (cylinders > 0xffffff)
4023                                 cylinders = 0xffffff;
4024
4025                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4026                                 CTL_PAGE_DEFAULT];
4027                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4028
4029                         if ((value = ctl_get_opt(&lun->be_lun->options,
4030                             "rpm")) != NULL) {
4031                                 scsi_ulto2b(strtol(value, NULL, 0),
4032                                      rigid_disk_page->rotation_rate);
4033                         }
4034
4035                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4036                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4037                                sizeof(rigid_disk_page_default));
4038                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4039                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4040                                sizeof(rigid_disk_page_default));
4041
4042                         page_index->page_data =
4043                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4044                         break;
4045                 }
4046                 case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4047                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4048                             ("subpage %#x for page %#x is incorrect!",
4049                             page_index->subpage, page_code));
4050                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4051                                &verify_er_page_default,
4052                                sizeof(verify_er_page_default));
4053                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4054                                &verify_er_page_changeable,
4055                                sizeof(verify_er_page_changeable));
4056                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4057                                &verify_er_page_default,
4058                                sizeof(verify_er_page_default));
4059                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4060                                &verify_er_page_default,
4061                                sizeof(verify_er_page_default));
4062                         page_index->page_data =
4063                                 (uint8_t *)lun->mode_pages.verify_er_page;
4064                         break;
4065                 }
4066                 case SMS_CACHING_PAGE: {
4067                         struct scsi_caching_page *caching_page;
4068
4069                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4070                             ("subpage %#x for page %#x is incorrect!",
4071                             page_index->subpage, page_code));
4072                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4073                                &caching_page_default,
4074                                sizeof(caching_page_default));
4075                         memcpy(&lun->mode_pages.caching_page[
4076                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4077                                sizeof(caching_page_changeable));
4078                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4079                                &caching_page_default,
4080                                sizeof(caching_page_default));
4081                         caching_page = &lun->mode_pages.caching_page[
4082                             CTL_PAGE_SAVED];
4083                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4084                         if (value != NULL && strcmp(value, "off") == 0)
4085                                 caching_page->flags1 &= ~SCP_WCE;
4086                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4087                         if (value != NULL && strcmp(value, "off") == 0)
4088                                 caching_page->flags1 |= SCP_RCD;
4089                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4090                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4091                                sizeof(caching_page_default));
4092                         page_index->page_data =
4093                                 (uint8_t *)lun->mode_pages.caching_page;
4094                         break;
4095                 }
4096                 case SMS_CONTROL_MODE_PAGE: {
4097                         switch (page_index->subpage) {
4098                         case SMS_SUBPAGE_PAGE_0: {
4099                                 struct scsi_control_page *control_page;
4100
4101                                 memcpy(&lun->mode_pages.control_page[
4102                                     CTL_PAGE_DEFAULT],
4103                                        &control_page_default,
4104                                        sizeof(control_page_default));
4105                                 memcpy(&lun->mode_pages.control_page[
4106                                     CTL_PAGE_CHANGEABLE],
4107                                        &control_page_changeable,
4108                                        sizeof(control_page_changeable));
4109                                 memcpy(&lun->mode_pages.control_page[
4110                                     CTL_PAGE_SAVED],
4111                                        &control_page_default,
4112                                        sizeof(control_page_default));
4113                                 control_page = &lun->mode_pages.control_page[
4114                                     CTL_PAGE_SAVED];
4115                                 value = ctl_get_opt(&lun->be_lun->options,
4116                                     "reordering");
4117                                 if (value != NULL &&
4118                                     strcmp(value, "unrestricted") == 0) {
4119                                         control_page->queue_flags &=
4120                                             ~SCP_QUEUE_ALG_MASK;
4121                                         control_page->queue_flags |=
4122                                             SCP_QUEUE_ALG_UNRESTRICTED;
4123                                 }
4124                                 memcpy(&lun->mode_pages.control_page[
4125                                     CTL_PAGE_CURRENT],
4126                                        &lun->mode_pages.control_page[
4127                                     CTL_PAGE_SAVED],
4128                                        sizeof(control_page_default));
4129                                 page_index->page_data =
4130                                     (uint8_t *)lun->mode_pages.control_page;
4131                                 break;
4132                         }
4133                         case 0x01:
4134                                 memcpy(&lun->mode_pages.control_ext_page[
4135                                     CTL_PAGE_DEFAULT],
4136                                        &control_ext_page_default,
4137                                        sizeof(control_ext_page_default));
4138                                 memcpy(&lun->mode_pages.control_ext_page[
4139                                     CTL_PAGE_CHANGEABLE],
4140                                        &control_ext_page_changeable,
4141                                        sizeof(control_ext_page_changeable));
4142                                 memcpy(&lun->mode_pages.control_ext_page[
4143                                     CTL_PAGE_SAVED],
4144                                        &control_ext_page_default,
4145                                        sizeof(control_ext_page_default));
4146                                 memcpy(&lun->mode_pages.control_ext_page[
4147                                     CTL_PAGE_CURRENT],
4148                                        &lun->mode_pages.control_ext_page[
4149                                     CTL_PAGE_SAVED],
4150                                        sizeof(control_ext_page_default));
4151                                 page_index->page_data =
4152                                     (uint8_t *)lun->mode_pages.control_ext_page;
4153                                 break;
4154                         default:
4155                                 panic("subpage %#x for page %#x is incorrect!",
4156                                       page_index->subpage, page_code);
4157                         }
4158                         break;
4159                 }
4160                 case SMS_INFO_EXCEPTIONS_PAGE: {
4161                         switch (page_index->subpage) {
4162                         case SMS_SUBPAGE_PAGE_0:
4163                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4164                                        &ie_page_default,
4165                                        sizeof(ie_page_default));
4166                                 memcpy(&lun->mode_pages.ie_page[
4167                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4168                                        sizeof(ie_page_changeable));
4169                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4170                                        &ie_page_default,
4171                                        sizeof(ie_page_default));
4172                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4173                                        &ie_page_default,
4174                                        sizeof(ie_page_default));
4175                                 page_index->page_data =
4176                                         (uint8_t *)lun->mode_pages.ie_page;
4177                                 break;
4178                         case 0x02: {
4179                                 struct ctl_logical_block_provisioning_page *page;
4180
4181                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4182                                        &lbp_page_default,
4183                                        sizeof(lbp_page_default));
4184                                 memcpy(&lun->mode_pages.lbp_page[
4185                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4186                                        sizeof(lbp_page_changeable));
4187                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4188                                        &lbp_page_default,
4189                                        sizeof(lbp_page_default));
4190                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4191                                 value = ctl_get_opt(&lun->be_lun->options,
4192                                     "avail-threshold");
4193                                 if (value != NULL &&
4194                                     ctl_expand_number(value, &ival) == 0) {
4195                                         page->descr[0].flags |= SLBPPD_ENABLED |
4196                                             SLBPPD_ARMING_DEC;
4197                                         if (lun->be_lun->blocksize)
4198                                                 ival /= lun->be_lun->blocksize;
4199                                         else
4200                                                 ival /= 512;
4201                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4202                                             page->descr[0].count);
4203                                 }
4204                                 value = ctl_get_opt(&lun->be_lun->options,
4205                                     "used-threshold");
4206                                 if (value != NULL &&
4207                                     ctl_expand_number(value, &ival) == 0) {
4208                                         page->descr[1].flags |= SLBPPD_ENABLED |
4209                                             SLBPPD_ARMING_INC;
4210                                         if (lun->be_lun->blocksize)
4211                                                 ival /= lun->be_lun->blocksize;
4212                                         else
4213                                                 ival /= 512;
4214                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4215                                             page->descr[1].count);
4216                                 }
4217                                 value = ctl_get_opt(&lun->be_lun->options,
4218                                     "pool-avail-threshold");
4219                                 if (value != NULL &&
4220                                     ctl_expand_number(value, &ival) == 0) {
4221                                         page->descr[2].flags |= SLBPPD_ENABLED |
4222                                             SLBPPD_ARMING_DEC;
4223                                         if (lun->be_lun->blocksize)
4224                                                 ival /= lun->be_lun->blocksize;
4225                                         else
4226                                                 ival /= 512;
4227                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4228                                             page->descr[2].count);
4229                                 }
4230                                 value = ctl_get_opt(&lun->be_lun->options,
4231                                     "pool-used-threshold");
4232                                 if (value != NULL &&
4233                                     ctl_expand_number(value, &ival) == 0) {
4234                                         page->descr[3].flags |= SLBPPD_ENABLED |
4235                                             SLBPPD_ARMING_INC;
4236                                         if (lun->be_lun->blocksize)
4237                                                 ival /= lun->be_lun->blocksize;
4238                                         else
4239                                                 ival /= 512;
4240                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4241                                             page->descr[3].count);
4242                                 }
4243                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4244                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4245                                        sizeof(lbp_page_default));
4246                                 page_index->page_data =
4247                                         (uint8_t *)lun->mode_pages.lbp_page;
4248                                 break;
4249                         }
4250                         default:
4251                                 panic("subpage %#x for page %#x is incorrect!",
4252                                       page_index->subpage, page_code);
4253                         }
4254                         break;
4255                 }
4256                 case SMS_CDDVD_CAPS_PAGE:{
4257                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4258                             ("subpage %#x for page %#x is incorrect!",
4259                             page_index->subpage, page_code));
4260                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4261                                &cddvd_page_default,
4262                                sizeof(cddvd_page_default));
4263                         memcpy(&lun->mode_pages.cddvd_page[
4264                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4265                                sizeof(cddvd_page_changeable));
4266                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4267                                &cddvd_page_default,
4268                                sizeof(cddvd_page_default));
4269                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4270                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4271                                sizeof(cddvd_page_default));
4272                         page_index->page_data =
4273                                 (uint8_t *)lun->mode_pages.cddvd_page;
4274                         break;
4275                 }
4276                 default:
4277                         panic("invalid page code value %#x", page_code);
4278                 }
4279         }
4280
4281         return (CTL_RETVAL_COMPLETE);
4282 }
4283
4284 static int
4285 ctl_init_log_page_index(struct ctl_lun *lun)
4286 {
4287         struct ctl_page_index *page_index;
4288         int i, j, k, prev;
4289
4290         memcpy(&lun->log_pages.index, log_page_index_template,
4291                sizeof(log_page_index_template));
4292
4293         prev = -1;
4294         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4295
4296                 page_index = &lun->log_pages.index[i];
4297                 if (lun->be_lun->lun_type == T_DIRECT &&
4298                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4299                         continue;
4300                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4301                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4302                         continue;
4303                 if (lun->be_lun->lun_type == T_CDROM &&
4304                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4305                         continue;
4306
4307                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4308                     lun->backend->lun_attr == NULL)
4309                         continue;
4310
4311                 if (page_index->page_code != prev) {
4312                         lun->log_pages.pages_page[j] = page_index->page_code;
4313                         prev = page_index->page_code;
4314                         j++;
4315                 }
4316                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4317                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4318                 k++;
4319         }
4320         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4321         lun->log_pages.index[0].page_len = j;
4322         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4323         lun->log_pages.index[1].page_len = k * 2;
4324         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4325         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4326         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4327         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4328         lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4329         lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4330
4331         return (CTL_RETVAL_COMPLETE);
4332 }
4333
4334 static int
4335 hex2bin(const char *str, uint8_t *buf, int buf_size)
4336 {
4337         int i;
4338         u_char c;
4339
4340         memset(buf, 0, buf_size);
4341         while (isspace(str[0]))
4342                 str++;
4343         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4344                 str += 2;
4345         buf_size *= 2;
4346         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4347                 while (str[i] == '-')   /* Skip dashes in UUIDs. */
4348                         str++;
4349                 c = str[i];
4350                 if (isdigit(c))
4351                         c -= '0';
4352                 else if (isalpha(c))
4353                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4354                 else
4355                         break;
4356                 if (c >= 16)
4357                         break;
4358                 if ((i & 1) == 0)
4359                         buf[i / 2] |= (c << 4);
4360                 else
4361                         buf[i / 2] |= c;
4362         }
4363         return ((i + 1) / 2);
4364 }
4365
4366 /*
4367  * LUN allocation.
4368  *
4369  * Requirements:
4370  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4371  *   wants us to allocate the LUN and he can block.
4372  * - ctl_softc is always set
4373  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4374  *
4375  * Returns 0 for success, non-zero (errno) for failure.
4376  */
4377 static int
4378 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4379               struct ctl_be_lun *const be_lun)
4380 {
4381         struct ctl_lun *nlun, *lun;
4382         struct scsi_vpd_id_descriptor *desc;
4383         struct scsi_vpd_id_t10 *t10id;
4384         const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4385         int lun_number, i, lun_malloced;
4386         int devidlen, idlen1, idlen2 = 0, len;
4387
4388         if (be_lun == NULL)
4389                 return (EINVAL);
4390
4391         /*
4392          * We currently only support Direct Access or Processor LUN types.
4393          */
4394         switch (be_lun->lun_type) {
4395         case T_DIRECT:
4396         case T_PROCESSOR:
4397         case T_CDROM:
4398                 break;
4399         case T_SEQUENTIAL:
4400         case T_CHANGER:
4401         default:
4402                 be_lun->lun_config_status(be_lun->be_lun,
4403                                           CTL_LUN_CONFIG_FAILURE);
4404                 break;
4405         }
4406         if (ctl_lun == NULL) {
4407                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4408                 lun_malloced = 1;
4409         } else {
4410                 lun_malloced = 0;
4411                 lun = ctl_lun;
4412         }
4413
4414         memset(lun, 0, sizeof(*lun));
4415         if (lun_malloced)
4416                 lun->flags = CTL_LUN_MALLOCED;
4417
4418         /* Generate LUN ID. */
4419         devidlen = max(CTL_DEVID_MIN_LEN,
4420             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4421         idlen1 = sizeof(*t10id) + devidlen;
4422         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4423         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4424         if (scsiname != NULL) {
4425                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4426                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4427         }
4428         eui = ctl_get_opt(&be_lun->options, "eui");
4429         if (eui != NULL) {
4430                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4431         }
4432         naa = ctl_get_opt(&be_lun->options, "naa");
4433         if (naa != NULL) {
4434                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4435         }
4436         uuid = ctl_get_opt(&be_lun->options, "uuid");
4437         if (uuid != NULL) {
4438                 len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4439         }
4440         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4441             M_CTL, M_WAITOK | M_ZERO);
4442         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4443         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4444         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4445         desc->length = idlen1;
4446         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4447         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4448         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4449                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4450         } else {
4451                 strncpy(t10id->vendor, vendor,
4452                     min(sizeof(t10id->vendor), strlen(vendor)));
4453         }
4454         strncpy((char *)t10id->vendor_spec_id,
4455             (char *)be_lun->device_id, devidlen);
4456         if (scsiname != NULL) {
4457                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4458                     desc->length);
4459                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4460                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4461                     SVPD_ID_TYPE_SCSI_NAME;
4462                 desc->length = idlen2;
4463                 strlcpy(desc->identifier, scsiname, idlen2);
4464         }
4465         if (eui != NULL) {
4466                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4467                     desc->length);
4468                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4469                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4470                     SVPD_ID_TYPE_EUI64;
4471                 desc->length = hex2bin(eui, desc->identifier, 16);
4472                 desc->length = desc->length > 12 ? 16 :
4473                     (desc->length > 8 ? 12 : 8);
4474                 len -= 16 - desc->length;
4475         }
4476         if (naa != NULL) {
4477                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4478                     desc->length);
4479                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4480                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4481                     SVPD_ID_TYPE_NAA;
4482                 desc->length = hex2bin(naa, desc->identifier, 16);
4483                 desc->length = desc->length > 8 ? 16 : 8;
4484                 len -= 16 - desc->length;
4485         }
4486         if (uuid != NULL) {
4487                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4488                     desc->length);
4489                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4490                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4491                     SVPD_ID_TYPE_UUID;
4492                 desc->identifier[0] = 0x10;
4493                 hex2bin(uuid, &desc->identifier[2], 16);
4494                 desc->length = 18;
4495         }
4496         lun->lun_devid->len = len;
4497
4498         mtx_lock(&ctl_softc->ctl_lock);
4499         /*
4500          * See if the caller requested a particular LUN number.  If so, see
4501          * if it is available.  Otherwise, allocate the first available LUN.
4502          */
4503         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4504                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4505                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4506                         mtx_unlock(&ctl_softc->ctl_lock);
4507                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4508                                 printf("ctl: requested LUN ID %d is higher "
4509                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4510                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4511                         } else {
4512                                 /*
4513                                  * XXX KDM return an error, or just assign
4514                                  * another LUN ID in this case??
4515                                  */
4516                                 printf("ctl: requested LUN ID %d is already "
4517                                        "in use\n", be_lun->req_lun_id);
4518                         }
4519                         if (lun->flags & CTL_LUN_MALLOCED)
4520                                 free(lun, M_CTL);
4521                         be_lun->lun_config_status(be_lun->be_lun,
4522                                                   CTL_LUN_CONFIG_FAILURE);
4523                         return (ENOSPC);
4524                 }
4525                 lun_number = be_lun->req_lun_id;
4526         } else {
4527                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4528                 if (lun_number == -1) {
4529                         mtx_unlock(&ctl_softc->ctl_lock);
4530                         printf("ctl: can't allocate LUN, out of LUNs\n");
4531                         if (lun->flags & CTL_LUN_MALLOCED)
4532                                 free(lun, M_CTL);
4533                         be_lun->lun_config_status(be_lun->be_lun,
4534                                                   CTL_LUN_CONFIG_FAILURE);
4535                         return (ENOSPC);
4536                 }
4537         }
4538         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4539
4540         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4541         lun->lun = lun_number;
4542         lun->be_lun = be_lun;
4543         /*
4544          * The processor LUN is always enabled.  Disk LUNs come on line
4545          * disabled, and must be enabled by the backend.
4546          */
4547         lun->flags |= CTL_LUN_DISABLED;
4548         lun->backend = be_lun->be;
4549         be_lun->ctl_lun = lun;
4550         be_lun->lun_id = lun_number;
4551         atomic_add_int(&be_lun->be->num_luns, 1);
4552         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4553                 lun->flags |= CTL_LUN_EJECTED;
4554         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4555                 lun->flags |= CTL_LUN_NO_MEDIA;
4556         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4557                 lun->flags |= CTL_LUN_STOPPED;
4558
4559         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4560                 lun->flags |= CTL_LUN_PRIMARY_SC;
4561
4562         value = ctl_get_opt(&be_lun->options, "removable");
4563         if (value != NULL) {
4564                 if (strcmp(value, "on") == 0)
4565                         lun->flags |= CTL_LUN_REMOVABLE;
4566         } else if (be_lun->lun_type == T_CDROM)
4567                 lun->flags |= CTL_LUN_REMOVABLE;
4568
4569         lun->ctl_softc = ctl_softc;
4570 #ifdef CTL_TIME_IO
4571         lun->last_busy = getsbinuptime();
4572 #endif
4573         TAILQ_INIT(&lun->ooa_queue);
4574         TAILQ_INIT(&lun->blocked_queue);
4575         STAILQ_INIT(&lun->error_list);
4576         lun->ie_reported = 1;
4577         callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4578         ctl_tpc_lun_init(lun);
4579         if (lun->flags & CTL_LUN_REMOVABLE) {
4580                 lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4581                     M_CTL, M_WAITOK);
4582         }
4583
4584         /*
4585          * Initialize the mode and log page index.
4586          */
4587         ctl_init_page_index(lun);
4588         ctl_init_log_page_index(lun);
4589
4590         /*
4591          * Now, before we insert this lun on the lun list, set the lun
4592          * inventory changed UA for all other luns.
4593          */
4594         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4595                 mtx_lock(&nlun->lun_lock);
4596                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4597                 mtx_unlock(&nlun->lun_lock);
4598         }
4599
4600         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4601
4602         ctl_softc->ctl_luns[lun_number] = lun;
4603
4604         ctl_softc->num_luns++;
4605
4606         /* Setup statistics gathering */
4607         lun->stats.device_type = be_lun->lun_type;
4608         lun->stats.lun_number = lun_number;
4609         lun->stats.blocksize = be_lun->blocksize;
4610         if (be_lun->blocksize == 0)
4611                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4612         for (i = 0;i < CTL_MAX_PORTS;i++)
4613                 lun->stats.ports[i].targ_port = i;
4614
4615         mtx_unlock(&ctl_softc->ctl_lock);
4616
4617         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4618         return (0);
4619 }
4620
4621 /*
4622  * Delete a LUN.
4623  * Assumptions:
4624  * - LUN has already been marked invalid and any pending I/O has been taken
4625  *   care of.
4626  */
4627 static int
4628 ctl_free_lun(struct ctl_lun *lun)
4629 {
4630         struct ctl_softc *softc = lun->ctl_softc;
4631         struct ctl_lun *nlun;
4632         int i;
4633
4634         mtx_assert(&softc->ctl_lock, MA_OWNED);
4635
4636         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4637
4638         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4639
4640         softc->ctl_luns[lun->lun] = NULL;
4641
4642         if (!TAILQ_EMPTY(&lun->ooa_queue))
4643                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4644
4645         softc->num_luns--;
4646
4647         /*
4648          * Tell the backend to free resources, if this LUN has a backend.
4649          */
4650         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4651         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4652
4653         lun->ie_reportcnt = UINT32_MAX;
4654         callout_drain(&lun->ie_callout);
4655
4656         ctl_tpc_lun_shutdown(lun);
4657         mtx_destroy(&lun->lun_lock);
4658         free(lun->lun_devid, M_CTL);
4659         for (i = 0; i < CTL_MAX_PORTS; i++)
4660                 free(lun->pending_ua[i], M_CTL);
4661         for (i = 0; i < CTL_MAX_PORTS; i++)
4662                 free(lun->pr_keys[i], M_CTL);
4663         free(lun->write_buffer, M_CTL);
4664         free(lun->prevent, M_CTL);
4665         if (lun->flags & CTL_LUN_MALLOCED)
4666                 free(lun, M_CTL);
4667
4668         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4669                 mtx_lock(&nlun->lun_lock);
4670                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4671                 mtx_unlock(&nlun->lun_lock);
4672         }
4673
4674         return (0);
4675 }
4676
4677 static void
4678 ctl_create_lun(struct ctl_be_lun *be_lun)
4679 {
4680
4681         /*
4682          * ctl_alloc_lun() should handle all potential failure cases.
4683          */
4684         ctl_alloc_lun(control_softc, NULL, be_lun);
4685 }
4686
4687 int
4688 ctl_add_lun(struct ctl_be_lun *be_lun)
4689 {
4690         struct ctl_softc *softc = control_softc;
4691
4692         mtx_lock(&softc->ctl_lock);
4693         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4694         mtx_unlock(&softc->ctl_lock);
4695         wakeup(&softc->pending_lun_queue);
4696
4697         return (0);
4698 }
4699
4700 int
4701 ctl_enable_lun(struct ctl_be_lun *be_lun)
4702 {
4703         struct ctl_softc *softc;
4704         struct ctl_port *port, *nport;
4705         struct ctl_lun *lun;
4706         int retval;
4707
4708         lun = (struct ctl_lun *)be_lun->ctl_lun;
4709         softc = lun->ctl_softc;
4710
4711         mtx_lock(&softc->ctl_lock);
4712         mtx_lock(&lun->lun_lock);
4713         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4714                 /*
4715                  * eh?  Why did we get called if the LUN is already
4716                  * enabled?
4717                  */
4718                 mtx_unlock(&lun->lun_lock);
4719                 mtx_unlock(&softc->ctl_lock);
4720                 return (0);
4721         }
4722         lun->flags &= ~CTL_LUN_DISABLED;
4723         mtx_unlock(&lun->lun_lock);
4724
4725         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4726                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4727                     port->lun_map != NULL || port->lun_enable == NULL)
4728                         continue;
4729
4730                 /*
4731                  * Drop the lock while we call the FETD's enable routine.
4732                  * This can lead to a callback into CTL (at least in the
4733                  * case of the internal initiator frontend.
4734                  */
4735                 mtx_unlock(&softc->ctl_lock);
4736                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4737                 mtx_lock(&softc->ctl_lock);
4738                 if (retval != 0) {
4739                         printf("%s: FETD %s port %d returned error "
4740                                "%d for lun_enable on lun %jd\n",
4741                                __func__, port->port_name, port->targ_port,
4742                                retval, (intmax_t)lun->lun);
4743                 }
4744         }
4745
4746         mtx_unlock(&softc->ctl_lock);
4747         ctl_isc_announce_lun(lun);
4748
4749         return (0);
4750 }
4751
4752 int
4753 ctl_disable_lun(struct ctl_be_lun *be_lun)
4754 {
4755         struct ctl_softc *softc;
4756         struct ctl_port *port;
4757         struct ctl_lun *lun;
4758         int retval;
4759
4760         lun = (struct ctl_lun *)be_lun->ctl_lun;
4761         softc = lun->ctl_softc;
4762
4763         mtx_lock(&softc->ctl_lock);
4764         mtx_lock(&lun->lun_lock);
4765         if (lun->flags & CTL_LUN_DISABLED) {
4766                 mtx_unlock(&lun->lun_lock);
4767                 mtx_unlock(&softc->ctl_lock);
4768                 return (0);
4769         }
4770         lun->flags |= CTL_LUN_DISABLED;
4771         mtx_unlock(&lun->lun_lock);
4772
4773         STAILQ_FOREACH(port, &softc->port_list, links) {
4774                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4775                     port->lun_map != NULL || port->lun_disable == NULL)
4776                         continue;
4777
4778                 /*
4779                  * Drop the lock before we call the frontend's disable
4780                  * routine, to avoid lock order reversals.
4781                  *
4782                  * XXX KDM what happens if the frontend list changes while
4783                  * we're traversing it?  It's unlikely, but should be handled.
4784                  */
4785                 mtx_unlock(&softc->ctl_lock);
4786                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4787                 mtx_lock(&softc->ctl_lock);
4788                 if (retval != 0) {
4789                         printf("%s: FETD %s port %d returned error "
4790                                "%d for lun_disable on lun %jd\n",
4791                                __func__, port->port_name, port->targ_port,
4792                                retval, (intmax_t)lun->lun);
4793                 }
4794         }
4795
4796         mtx_unlock(&softc->ctl_lock);
4797         ctl_isc_announce_lun(lun);
4798
4799         return (0);
4800 }
4801
4802 int
4803 ctl_start_lun(struct ctl_be_lun *be_lun)
4804 {
4805         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4806
4807         mtx_lock(&lun->lun_lock);
4808         lun->flags &= ~CTL_LUN_STOPPED;
4809         mtx_unlock(&lun->lun_lock);
4810         return (0);
4811 }
4812
4813 int
4814 ctl_stop_lun(struct ctl_be_lun *be_lun)
4815 {
4816         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4817
4818         mtx_lock(&lun->lun_lock);
4819         lun->flags |= CTL_LUN_STOPPED;
4820         mtx_unlock(&lun->lun_lock);
4821         return (0);
4822 }
4823
4824 int
4825 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4826 {
4827         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4828
4829         mtx_lock(&lun->lun_lock);
4830         lun->flags |= CTL_LUN_NO_MEDIA;
4831         mtx_unlock(&lun->lun_lock);
4832         return (0);
4833 }
4834
4835 int
4836 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4837 {
4838         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4839         union ctl_ha_msg msg;
4840
4841         mtx_lock(&lun->lun_lock);
4842         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4843         if (lun->flags & CTL_LUN_REMOVABLE)
4844                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4845         mtx_unlock(&lun->lun_lock);
4846         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4847             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4848                 bzero(&msg.ua, sizeof(msg.ua));
4849                 msg.hdr.msg_type = CTL_MSG_UA;
4850                 msg.hdr.nexus.initid = -1;
4851                 msg.hdr.nexus.targ_port = -1;
4852                 msg.hdr.nexus.targ_lun = lun->lun;
4853                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4854                 msg.ua.ua_all = 1;
4855                 msg.ua.ua_set = 1;
4856                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4857                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4858                     M_WAITOK);
4859         }
4860         return (0);
4861 }
4862
4863 int
4864 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4865 {
4866         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4867
4868         mtx_lock(&lun->lun_lock);
4869         lun->flags |= CTL_LUN_EJECTED;
4870         mtx_unlock(&lun->lun_lock);
4871         return (0);
4872 }
4873
4874 int
4875 ctl_lun_primary(struct ctl_be_lun *be_lun)
4876 {
4877         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4878
4879         mtx_lock(&lun->lun_lock);
4880         lun->flags |= CTL_LUN_PRIMARY_SC;
4881         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4882         mtx_unlock(&lun->lun_lock);
4883         ctl_isc_announce_lun(lun);
4884         return (0);
4885 }
4886
4887 int
4888 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4889 {
4890         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4891
4892         mtx_lock(&lun->lun_lock);
4893         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4894         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4895         mtx_unlock(&lun->lun_lock);
4896         ctl_isc_announce_lun(lun);
4897         return (0);
4898 }
4899
4900 int
4901 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4902 {
4903         struct ctl_softc *softc;
4904         struct ctl_lun *lun;
4905
4906         lun = (struct ctl_lun *)be_lun->ctl_lun;
4907         softc = lun->ctl_softc;
4908
4909         mtx_lock(&lun->lun_lock);
4910
4911         /*
4912          * The LUN needs to be disabled before it can be marked invalid.
4913          */
4914         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4915                 mtx_unlock(&lun->lun_lock);
4916                 return (-1);
4917         }
4918         /*
4919          * Mark the LUN invalid.
4920          */
4921         lun->flags |= CTL_LUN_INVALID;
4922
4923         /*
4924          * If there is nothing in the OOA queue, go ahead and free the LUN.
4925          * If we have something in the OOA queue, we'll free it when the
4926          * last I/O completes.
4927          */
4928         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4929                 mtx_unlock(&lun->lun_lock);
4930                 mtx_lock(&softc->ctl_lock);
4931                 ctl_free_lun(lun);
4932                 mtx_unlock(&softc->ctl_lock);
4933         } else
4934                 mtx_unlock(&lun->lun_lock);
4935
4936         return (0);
4937 }
4938
4939 void
4940 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4941 {
4942         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4943         union ctl_ha_msg msg;
4944
4945         mtx_lock(&lun->lun_lock);
4946         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4947         mtx_unlock(&lun->lun_lock);
4948         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4949                 /* Send msg to other side. */
4950                 bzero(&msg.ua, sizeof(msg.ua));
4951                 msg.hdr.msg_type = CTL_MSG_UA;
4952                 msg.hdr.nexus.initid = -1;
4953                 msg.hdr.nexus.targ_port = -1;
4954                 msg.hdr.nexus.targ_lun = lun->lun;
4955                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4956                 msg.ua.ua_all = 1;
4957                 msg.ua.ua_set = 1;
4958                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4959                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4960                     M_WAITOK);
4961         }
4962 }
4963
4964 /*
4965  * Backend "memory move is complete" callback for requests that never
4966  * make it down to say RAIDCore's configuration code.
4967  */
4968 int
4969 ctl_config_move_done(union ctl_io *io)
4970 {
4971         int retval;
4972
4973         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4974         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4975             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4976
4977         if ((io->io_hdr.port_status != 0) &&
4978             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4979              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4980                 /*
4981                  * For hardware error sense keys, the sense key
4982                  * specific value is defined to be a retry count,
4983                  * but we use it to pass back an internal FETD
4984                  * error code.  XXX KDM  Hopefully the FETD is only
4985                  * using 16 bits for an error code, since that's
4986                  * all the space we have in the sks field.
4987                  */
4988                 ctl_set_internal_failure(&io->scsiio,
4989                                          /*sks_valid*/ 1,
4990                                          /*retry_count*/
4991                                          io->io_hdr.port_status);
4992         }
4993
4994         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4995                 ctl_data_print(io);
4996         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4997             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4998              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4999             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5000                 /*
5001                  * XXX KDM just assuming a single pointer here, and not a
5002                  * S/G list.  If we start using S/G lists for config data,
5003                  * we'll need to know how to clean them up here as well.
5004                  */
5005                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5006                         free(io->scsiio.kern_data_ptr, M_CTL);
5007                 ctl_done(io);
5008                 retval = CTL_RETVAL_COMPLETE;
5009         } else {
5010                 /*
5011                  * XXX KDM now we need to continue data movement.  Some
5012                  * options:
5013                  * - call ctl_scsiio() again?  We don't do this for data
5014                  *   writes, because for those at least we know ahead of
5015                  *   time where the write will go and how long it is.  For
5016                  *   config writes, though, that information is largely
5017                  *   contained within the write itself, thus we need to
5018                  *   parse out the data again.
5019                  *
5020                  * - Call some other function once the data is in?
5021                  */
5022
5023                 /*
5024                  * XXX KDM call ctl_scsiio() again for now, and check flag
5025                  * bits to see whether we're allocated or not.
5026                  */
5027                 retval = ctl_scsiio(&io->scsiio);
5028         }
5029         return (retval);
5030 }
5031
5032 /*
5033  * This gets called by a backend driver when it is done with a
5034  * data_submit method.
5035  */
5036 void
5037 ctl_data_submit_done(union ctl_io *io)
5038 {
5039         /*
5040          * If the IO_CONT flag is set, we need to call the supplied
5041          * function to continue processing the I/O, instead of completing
5042          * the I/O just yet.
5043          *
5044          * If there is an error, though, we don't want to keep processing.
5045          * Instead, just send status back to the initiator.
5046          */
5047         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5048             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5049             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5050              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5051                 io->scsiio.io_cont(io);
5052                 return;
5053         }
5054         ctl_done(io);
5055 }
5056
5057 /*
5058  * This gets called by a backend driver when it is done with a
5059  * configuration write.
5060  */
5061 void
5062 ctl_config_write_done(union ctl_io *io)
5063 {
5064         uint8_t *buf;
5065
5066         /*
5067          * If the IO_CONT flag is set, we need to call the supplied
5068          * function to continue processing the I/O, instead of completing
5069          * the I/O just yet.
5070          *
5071          * If there is an error, though, we don't want to keep processing.
5072          * Instead, just send status back to the initiator.
5073          */
5074         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5075             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5076             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5077              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5078                 io->scsiio.io_cont(io);
5079                 return;
5080         }
5081         /*
5082          * Since a configuration write can be done for commands that actually
5083          * have data allocated, like write buffer, and commands that have
5084          * no data, like start/stop unit, we need to check here.
5085          */
5086         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5087                 buf = io->scsiio.kern_data_ptr;
5088         else
5089                 buf = NULL;
5090         ctl_done(io);
5091         if (buf)
5092                 free(buf, M_CTL);
5093 }
5094
5095 void
5096 ctl_config_read_done(union ctl_io *io)
5097 {
5098         uint8_t *buf;
5099
5100         /*
5101          * If there is some error -- we are done, skip data transfer.
5102          */
5103         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5104             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5105              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5106                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5107                         buf = io->scsiio.kern_data_ptr;
5108                 else
5109                         buf = NULL;
5110                 ctl_done(io);
5111                 if (buf)
5112                         free(buf, M_CTL);
5113                 return;
5114         }
5115
5116         /*
5117          * If the IO_CONT flag is set, we need to call the supplied
5118          * function to continue processing the I/O, instead of completing
5119          * the I/O just yet.
5120          */
5121         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5122                 io->scsiio.io_cont(io);
5123                 return;
5124         }
5125
5126         ctl_datamove(io);
5127 }
5128
5129 /*
5130  * SCSI release command.
5131  */
5132 int
5133 ctl_scsi_release(struct ctl_scsiio *ctsio)
5134 {
5135         struct ctl_lun *lun = CTL_LUN(ctsio);
5136         uint32_t residx;
5137
5138         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5139
5140         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5141
5142         /*
5143          * XXX KDM right now, we only support LUN reservation.  We don't
5144          * support 3rd party reservations, or extent reservations, which
5145          * might actually need the parameter list.  If we've gotten this
5146          * far, we've got a LUN reservation.  Anything else got kicked out
5147          * above.  So, according to SPC, ignore the length.
5148          */
5149
5150         mtx_lock(&lun->lun_lock);
5151
5152         /*
5153          * According to SPC, it is not an error for an intiator to attempt
5154          * to release a reservation on a LUN that isn't reserved, or that
5155          * is reserved by another initiator.  The reservation can only be
5156          * released, though, by the initiator who made it or by one of
5157          * several reset type events.
5158          */
5159         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5160                         lun->flags &= ~CTL_LUN_RESERVED;
5161
5162         mtx_unlock(&lun->lun_lock);
5163
5164         ctl_set_success(ctsio);
5165         ctl_done((union ctl_io *)ctsio);
5166         return (CTL_RETVAL_COMPLETE);
5167 }
5168
5169 int
5170 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5171 {
5172         struct ctl_lun *lun = CTL_LUN(ctsio);
5173         uint32_t residx;
5174
5175         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5176
5177         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5178
5179         /*
5180          * XXX KDM right now, we only support LUN reservation.  We don't
5181          * support 3rd party reservations, or extent reservations, which
5182          * might actually need the parameter list.  If we've gotten this
5183          * far, we've got a LUN reservation.  Anything else got kicked out
5184          * above.  So, according to SPC, ignore the length.
5185          */
5186
5187         mtx_lock(&lun->lun_lock);
5188         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5189                 ctl_set_reservation_conflict(ctsio);
5190                 goto bailout;
5191         }
5192
5193         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5194         if (lun->flags & CTL_LUN_PR_RESERVED) {
5195                 ctl_set_success(ctsio);
5196                 goto bailout;
5197         }
5198
5199         lun->flags |= CTL_LUN_RESERVED;
5200         lun->res_idx = residx;
5201         ctl_set_success(ctsio);
5202
5203 bailout:
5204         mtx_unlock(&lun->lun_lock);
5205         ctl_done((union ctl_io *)ctsio);
5206         return (CTL_RETVAL_COMPLETE);
5207 }
5208
5209 int
5210 ctl_start_stop(struct ctl_scsiio *ctsio)
5211 {
5212         struct ctl_lun *lun = CTL_LUN(ctsio);
5213         struct scsi_start_stop_unit *cdb;
5214         int retval;
5215
5216         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5217
5218         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5219
5220         if ((cdb->how & SSS_PC_MASK) == 0) {
5221                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5222                     (cdb->how & SSS_START) == 0) {
5223                         uint32_t residx;
5224
5225                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5226                         if (ctl_get_prkey(lun, residx) == 0 ||
5227                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5228
5229                                 ctl_set_reservation_conflict(ctsio);
5230                                 ctl_done((union ctl_io *)ctsio);
5231                                 return (CTL_RETVAL_COMPLETE);
5232                         }
5233                 }
5234
5235                 if ((cdb->how & SSS_LOEJ) &&
5236                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5237                         ctl_set_invalid_field(ctsio,
5238                                               /*sks_valid*/ 1,
5239                                               /*command*/ 1,
5240                                               /*field*/ 4,
5241                                               /*bit_valid*/ 1,
5242                                               /*bit*/ 1);
5243                         ctl_done((union ctl_io *)ctsio);
5244                         return (CTL_RETVAL_COMPLETE);
5245                 }
5246
5247                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5248                     lun->prevent_count > 0) {
5249                         /* "Medium removal prevented" */
5250                         ctl_set_sense(ctsio, /*current_error*/ 1,
5251                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5252                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5253                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5254                         ctl_done((union ctl_io *)ctsio);
5255                         return (CTL_RETVAL_COMPLETE);
5256                 }
5257         }
5258
5259         retval = lun->backend->config_write((union ctl_io *)ctsio);
5260         return (retval);
5261 }
5262
5263 int
5264 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5265 {
5266         struct ctl_lun *lun = CTL_LUN(ctsio);
5267         struct scsi_prevent *cdb;
5268         int retval;
5269         uint32_t initidx;
5270
5271         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5272
5273         cdb = (struct scsi_prevent *)ctsio->cdb;
5274
5275         if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5276                 ctl_set_invalid_opcode(ctsio);
5277                 ctl_done((union ctl_io *)ctsio);
5278                 return (CTL_RETVAL_COMPLETE);
5279         }
5280
5281         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5282         mtx_lock(&lun->lun_lock);
5283         if ((cdb->how & PR_PREVENT) &&
5284             ctl_is_set(lun->prevent, initidx) == 0) {
5285                 ctl_set_mask(lun->prevent, initidx);
5286                 lun->prevent_count++;
5287         } else if ((cdb->how & PR_PREVENT) == 0 &&
5288             ctl_is_set(lun->prevent, initidx)) {
5289                 ctl_clear_mask(lun->prevent, initidx);
5290                 lun->prevent_count--;
5291         }
5292         mtx_unlock(&lun->lun_lock);
5293         retval = lun->backend->config_write((union ctl_io *)ctsio);
5294         return (retval);
5295 }
5296
5297 /*
5298  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5299  * we don't really do anything with the LBA and length fields if the user
5300  * passes them in.  Instead we'll just flush out the cache for the entire
5301  * LUN.
5302  */
5303 int
5304 ctl_sync_cache(struct ctl_scsiio *ctsio)
5305 {
5306         struct ctl_lun *lun = CTL_LUN(ctsio);
5307         struct ctl_lba_len_flags *lbalen;
5308         uint64_t starting_lba;
5309         uint32_t block_count;
5310         int retval;
5311         uint8_t byte2;
5312
5313         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5314
5315         retval = 0;
5316
5317         switch (ctsio->cdb[0]) {
5318         case SYNCHRONIZE_CACHE: {
5319                 struct scsi_sync_cache *cdb;
5320                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5321
5322                 starting_lba = scsi_4btoul(cdb->begin_lba);
5323                 block_count = scsi_2btoul(cdb->lb_count);
5324                 byte2 = cdb->byte2;
5325                 break;
5326         }
5327         case SYNCHRONIZE_CACHE_16: {
5328                 struct scsi_sync_cache_16 *cdb;
5329                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5330
5331                 starting_lba = scsi_8btou64(cdb->begin_lba);
5332                 block_count = scsi_4btoul(cdb->lb_count);
5333                 byte2 = cdb->byte2;
5334                 break;
5335         }
5336         default:
5337                 ctl_set_invalid_opcode(ctsio);
5338                 ctl_done((union ctl_io *)ctsio);
5339                 goto bailout;
5340                 break; /* NOTREACHED */
5341         }
5342
5343         /*
5344          * We check the LBA and length, but don't do anything with them.
5345          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5346          * get flushed.  This check will just help satisfy anyone who wants
5347          * to see an error for an out of range LBA.
5348          */
5349         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5350                 ctl_set_lba_out_of_range(ctsio,
5351                     MAX(starting_lba, lun->be_lun->maxlba + 1));
5352                 ctl_done((union ctl_io *)ctsio);
5353                 goto bailout;
5354         }
5355
5356         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5357         lbalen->lba = starting_lba;
5358         lbalen->len = block_count;
5359         lbalen->flags = byte2;
5360         retval = lun->backend->config_write((union ctl_io *)ctsio);
5361
5362 bailout:
5363         return (retval);
5364 }
5365
5366 int
5367 ctl_format(struct ctl_scsiio *ctsio)
5368 {
5369         struct scsi_format *cdb;
5370         int length, defect_list_len;
5371
5372         CTL_DEBUG_PRINT(("ctl_format\n"));
5373
5374         cdb = (struct scsi_format *)ctsio->cdb;
5375
5376         length = 0;
5377         if (cdb->byte2 & SF_FMTDATA) {
5378                 if (cdb->byte2 & SF_LONGLIST)
5379                         length = sizeof(struct scsi_format_header_long);
5380                 else
5381                         length = sizeof(struct scsi_format_header_short);
5382         }
5383
5384         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5385          && (length > 0)) {
5386                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5387                 ctsio->kern_data_len = length;
5388                 ctsio->kern_total_len = length;
5389                 ctsio->kern_data_resid = 0;
5390                 ctsio->kern_rel_offset = 0;
5391                 ctsio->kern_sg_entries = 0;
5392                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5393                 ctsio->be_move_done = ctl_config_move_done;
5394                 ctl_datamove((union ctl_io *)ctsio);
5395
5396                 return (CTL_RETVAL_COMPLETE);
5397         }
5398
5399         defect_list_len = 0;
5400
5401         if (cdb->byte2 & SF_FMTDATA) {
5402                 if (cdb->byte2 & SF_LONGLIST) {
5403                         struct scsi_format_header_long *header;
5404
5405                         header = (struct scsi_format_header_long *)
5406                                 ctsio->kern_data_ptr;
5407
5408                         defect_list_len = scsi_4btoul(header->defect_list_len);
5409                         if (defect_list_len != 0) {
5410                                 ctl_set_invalid_field(ctsio,
5411                                                       /*sks_valid*/ 1,
5412                                                       /*command*/ 0,
5413                                                       /*field*/ 2,
5414                                                       /*bit_valid*/ 0,
5415                                                       /*bit*/ 0);
5416                                 goto bailout;
5417                         }
5418                 } else {
5419                         struct scsi_format_header_short *header;
5420
5421                         header = (struct scsi_format_header_short *)
5422                                 ctsio->kern_data_ptr;
5423
5424                         defect_list_len = scsi_2btoul(header->defect_list_len);
5425                         if (defect_list_len != 0) {
5426                                 ctl_set_invalid_field(ctsio,
5427                                                       /*sks_valid*/ 1,
5428                                                       /*command*/ 0,
5429                                                       /*field*/ 2,
5430                                                       /*bit_valid*/ 0,
5431                                                       /*bit*/ 0);
5432                                 goto bailout;
5433                         }
5434                 }
5435         }
5436
5437         ctl_set_success(ctsio);
5438 bailout:
5439
5440         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5441                 free(ctsio->kern_data_ptr, M_CTL);
5442                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5443         }
5444
5445         ctl_done((union ctl_io *)ctsio);
5446         return (CTL_RETVAL_COMPLETE);
5447 }
5448
5449 int
5450 ctl_read_buffer(struct ctl_scsiio *ctsio)
5451 {
5452         struct ctl_lun *lun = CTL_LUN(ctsio);
5453         uint64_t buffer_offset;
5454         uint32_t len;
5455         uint8_t byte2;
5456         static uint8_t descr[4];
5457         static uint8_t echo_descr[4] = { 0 };
5458
5459         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5460
5461         switch (ctsio->cdb[0]) {
5462         case READ_BUFFER: {
5463                 struct scsi_read_buffer *cdb;
5464
5465                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5466                 buffer_offset = scsi_3btoul(cdb->offset);
5467                 len = scsi_3btoul(cdb->length);
5468                 byte2 = cdb->byte2;
5469                 break;
5470         }
5471         case READ_BUFFER_16: {
5472                 struct scsi_read_buffer_16 *cdb;
5473
5474                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5475                 buffer_offset = scsi_8btou64(cdb->offset);
5476                 len = scsi_4btoul(cdb->length);
5477                 byte2 = cdb->byte2;
5478                 break;
5479         }
5480         default: /* This shouldn't happen. */
5481                 ctl_set_invalid_opcode(ctsio);
5482                 ctl_done((union ctl_io *)ctsio);
5483                 return (CTL_RETVAL_COMPLETE);
5484         }
5485
5486         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5487             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5488                 ctl_set_invalid_field(ctsio,
5489                                       /*sks_valid*/ 1,
5490                                       /*command*/ 1,
5491                                       /*field*/ 6,
5492                                       /*bit_valid*/ 0,
5493                                       /*bit*/ 0);
5494                 ctl_done((union ctl_io *)ctsio);
5495                 return (CTL_RETVAL_COMPLETE);
5496         }
5497
5498         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5499                 descr[0] = 0;
5500                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5501                 ctsio->kern_data_ptr = descr;
5502                 len = min(len, sizeof(descr));
5503         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5504                 ctsio->kern_data_ptr = echo_descr;
5505                 len = min(len, sizeof(echo_descr));
5506         } else {
5507                 if (lun->write_buffer == NULL) {
5508                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5509                             M_CTL, M_WAITOK);
5510                 }
5511                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5512         }
5513         ctsio->kern_data_len = len;
5514         ctsio->kern_total_len = len;
5515         ctsio->kern_data_resid = 0;
5516         ctsio->kern_rel_offset = 0;
5517         ctsio->kern_sg_entries = 0;
5518         ctl_set_success(ctsio);
5519         ctsio->be_move_done = ctl_config_move_done;
5520         ctl_datamove((union ctl_io *)ctsio);
5521         return (CTL_RETVAL_COMPLETE);
5522 }
5523
5524 int
5525 ctl_write_buffer(struct ctl_scsiio *ctsio)
5526 {
5527         struct ctl_lun *lun = CTL_LUN(ctsio);
5528         struct scsi_write_buffer *cdb;
5529         int buffer_offset, len;
5530
5531         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5532
5533         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5534
5535         len = scsi_3btoul(cdb->length);
5536         buffer_offset = scsi_3btoul(cdb->offset);
5537
5538         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5539                 ctl_set_invalid_field(ctsio,
5540                                       /*sks_valid*/ 1,
5541                                       /*command*/ 1,
5542                                       /*field*/ 6,
5543                                       /*bit_valid*/ 0,
5544                                       /*bit*/ 0);
5545                 ctl_done((union ctl_io *)ctsio);
5546                 return (CTL_RETVAL_COMPLETE);
5547         }
5548
5549         /*
5550          * If we've got a kernel request that hasn't been malloced yet,
5551          * malloc it and tell the caller the data buffer is here.
5552          */
5553         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5554                 if (lun->write_buffer == NULL) {
5555                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5556                             M_CTL, M_WAITOK);
5557                 }
5558                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5559                 ctsio->kern_data_len = len;
5560                 ctsio->kern_total_len = len;
5561                 ctsio->kern_data_resid = 0;
5562                 ctsio->kern_rel_offset = 0;
5563                 ctsio->kern_sg_entries = 0;
5564                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5565                 ctsio->be_move_done = ctl_config_move_done;
5566                 ctl_datamove((union ctl_io *)ctsio);
5567
5568                 return (CTL_RETVAL_COMPLETE);
5569         }
5570
5571         ctl_set_success(ctsio);
5572         ctl_done((union ctl_io *)ctsio);
5573         return (CTL_RETVAL_COMPLETE);
5574 }
5575
5576 int
5577 ctl_write_same(struct ctl_scsiio *ctsio)
5578 {
5579         struct ctl_lun *lun = CTL_LUN(ctsio);
5580         struct ctl_lba_len_flags *lbalen;
5581         uint64_t lba;
5582         uint32_t num_blocks;
5583         int len, retval;
5584         uint8_t byte2;
5585
5586         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5587
5588         switch (ctsio->cdb[0]) {
5589         case WRITE_SAME_10: {
5590                 struct scsi_write_same_10 *cdb;
5591
5592                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5593
5594                 lba = scsi_4btoul(cdb->addr);
5595                 num_blocks = scsi_2btoul(cdb->length);
5596                 byte2 = cdb->byte2;
5597                 break;
5598         }
5599         case WRITE_SAME_16: {
5600                 struct scsi_write_same_16 *cdb;
5601
5602                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5603
5604                 lba = scsi_8btou64(cdb->addr);
5605                 num_blocks = scsi_4btoul(cdb->length);
5606                 byte2 = cdb->byte2;
5607                 break;
5608         }
5609         default:
5610                 /*
5611                  * We got a command we don't support.  This shouldn't
5612                  * happen, commands should be filtered out above us.
5613                  */
5614                 ctl_set_invalid_opcode(ctsio);
5615                 ctl_done((union ctl_io *)ctsio);
5616
5617                 return (CTL_RETVAL_COMPLETE);
5618                 break; /* NOTREACHED */
5619         }
5620
5621         /* ANCHOR flag can be used only together with UNMAP */
5622         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5623                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5624                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5625                 ctl_done((union ctl_io *)ctsio);
5626                 return (CTL_RETVAL_COMPLETE);
5627         }
5628
5629         /*
5630          * The first check is to make sure we're in bounds, the second
5631          * check is to catch wrap-around problems.  If the lba + num blocks
5632          * is less than the lba, then we've wrapped around and the block
5633          * range is invalid anyway.
5634          */
5635         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5636          || ((lba + num_blocks) < lba)) {
5637                 ctl_set_lba_out_of_range(ctsio,
5638                     MAX(lba, lun->be_lun->maxlba + 1));
5639                 ctl_done((union ctl_io *)ctsio);
5640                 return (CTL_RETVAL_COMPLETE);
5641         }
5642
5643         /* Zero number of blocks means "to the last logical block" */
5644         if (num_blocks == 0) {
5645                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5646                         ctl_set_invalid_field(ctsio,
5647                                               /*sks_valid*/ 0,
5648                                               /*command*/ 1,
5649                                               /*field*/ 0,
5650                                               /*bit_valid*/ 0,
5651                                               /*bit*/ 0);
5652                         ctl_done((union ctl_io *)ctsio);
5653                         return (CTL_RETVAL_COMPLETE);
5654                 }
5655                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5656         }
5657
5658         len = lun->be_lun->blocksize;
5659
5660         /*
5661          * If we've got a kernel request that hasn't been malloced yet,
5662          * malloc it and tell the caller the data buffer is here.
5663          */
5664         if ((byte2 & SWS_NDOB) == 0 &&
5665             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5666                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5667                 ctsio->kern_data_len = len;
5668                 ctsio->kern_total_len = len;
5669                 ctsio->kern_data_resid = 0;
5670                 ctsio->kern_rel_offset = 0;
5671                 ctsio->kern_sg_entries = 0;
5672                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5673                 ctsio->be_move_done = ctl_config_move_done;
5674                 ctl_datamove((union ctl_io *)ctsio);
5675
5676                 return (CTL_RETVAL_COMPLETE);
5677         }
5678
5679         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5680         lbalen->lba = lba;
5681         lbalen->len = num_blocks;
5682         lbalen->flags = byte2;
5683         retval = lun->backend->config_write((union ctl_io *)ctsio);
5684
5685         return (retval);
5686 }
5687
5688 int
5689 ctl_unmap(struct ctl_scsiio *ctsio)
5690 {
5691         struct ctl_lun *lun = CTL_LUN(ctsio);
5692         struct scsi_unmap *cdb;
5693         struct ctl_ptr_len_flags *ptrlen;
5694         struct scsi_unmap_header *hdr;
5695         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5696         uint64_t lba;
5697         uint32_t num_blocks;
5698         int len, retval;
5699         uint8_t byte2;
5700
5701         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5702
5703         cdb = (struct scsi_unmap *)ctsio->cdb;
5704         len = scsi_2btoul(cdb->length);
5705         byte2 = cdb->byte2;
5706
5707         /*
5708          * If we've got a kernel request that hasn't been malloced yet,
5709          * malloc it and tell the caller the data buffer is here.
5710          */
5711         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5712                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5713                 ctsio->kern_data_len = len;
5714                 ctsio->kern_total_len = len;
5715                 ctsio->kern_data_resid = 0;
5716                 ctsio->kern_rel_offset = 0;
5717                 ctsio->kern_sg_entries = 0;
5718                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5719                 ctsio->be_move_done = ctl_config_move_done;
5720                 ctl_datamove((union ctl_io *)ctsio);
5721
5722                 return (CTL_RETVAL_COMPLETE);
5723         }
5724
5725         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5726         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5727         if (len < sizeof (*hdr) ||
5728             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5729             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5730             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5731                 ctl_set_invalid_field(ctsio,
5732                                       /*sks_valid*/ 0,
5733                                       /*command*/ 0,
5734                                       /*field*/ 0,
5735                                       /*bit_valid*/ 0,
5736                                       /*bit*/ 0);
5737                 goto done;
5738         }
5739         len = scsi_2btoul(hdr->desc_length);
5740         buf = (struct scsi_unmap_desc *)(hdr + 1);
5741         end = buf + len / sizeof(*buf);
5742
5743         endnz = buf;
5744         for (range = buf; range < end; range++) {
5745                 lba = scsi_8btou64(range->lba);
5746                 num_blocks = scsi_4btoul(range->length);
5747                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5748                  || ((lba + num_blocks) < lba)) {
5749                         ctl_set_lba_out_of_range(ctsio,
5750                             MAX(lba, lun->be_lun->maxlba + 1));
5751                         ctl_done((union ctl_io *)ctsio);
5752                         return (CTL_RETVAL_COMPLETE);
5753                 }
5754                 if (num_blocks != 0)
5755                         endnz = range + 1;
5756         }
5757
5758         /*
5759          * Block backend can not handle zero last range.
5760          * Filter it out and return if there is nothing left.
5761          */
5762         len = (uint8_t *)endnz - (uint8_t *)buf;
5763         if (len == 0) {
5764                 ctl_set_success(ctsio);
5765                 goto done;
5766         }
5767
5768         mtx_lock(&lun->lun_lock);
5769         ptrlen = (struct ctl_ptr_len_flags *)
5770             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5771         ptrlen->ptr = (void *)buf;
5772         ptrlen->len = len;
5773         ptrlen->flags = byte2;
5774         ctl_check_blocked(lun);
5775         mtx_unlock(&lun->lun_lock);
5776
5777         retval = lun->backend->config_write((union ctl_io *)ctsio);
5778         return (retval);
5779
5780 done:
5781         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5782                 free(ctsio->kern_data_ptr, M_CTL);
5783                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5784         }
5785         ctl_done((union ctl_io *)ctsio);
5786         return (CTL_RETVAL_COMPLETE);
5787 }
5788
5789 int
5790 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5791                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5792 {
5793         struct ctl_lun *lun = CTL_LUN(ctsio);
5794         uint8_t *current_cp;
5795         int set_ua;
5796         uint32_t initidx;
5797
5798         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5799         set_ua = 0;
5800
5801         current_cp = (page_index->page_data + (page_index->page_len *
5802             CTL_PAGE_CURRENT));
5803
5804         mtx_lock(&lun->lun_lock);
5805         if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5806                 memcpy(current_cp, page_ptr, page_index->page_len);
5807                 set_ua = 1;
5808         }
5809         if (set_ua != 0)
5810                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5811         mtx_unlock(&lun->lun_lock);
5812         if (set_ua) {
5813                 ctl_isc_announce_mode(lun,
5814                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5815                     page_index->page_code, page_index->subpage);
5816         }
5817         return (CTL_RETVAL_COMPLETE);
5818 }
5819
5820 static void
5821 ctl_ie_timer(void *arg)
5822 {
5823         struct ctl_lun *lun = arg;
5824         uint64_t t;
5825
5826         if (lun->ie_asc == 0)
5827                 return;
5828
5829         if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5830                 ctl_est_ua_all(lun, -1, CTL_UA_IE);
5831         else
5832                 lun->ie_reported = 0;
5833
5834         if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5835                 lun->ie_reportcnt++;
5836                 t = scsi_4btoul(lun->MODE_IE.interval_timer);
5837                 if (t == 0 || t == UINT32_MAX)
5838                         t = 3000;  /* 5 min */
5839                 callout_schedule(&lun->ie_callout, t * hz / 10);
5840         }
5841 }
5842
5843 int
5844 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5845                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5846 {
5847         struct ctl_lun *lun = CTL_LUN(ctsio);
5848         struct scsi_info_exceptions_page *pg;
5849         uint64_t t;
5850
5851         (void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5852
5853         pg = (struct scsi_info_exceptions_page *)page_ptr;
5854         mtx_lock(&lun->lun_lock);
5855         if (pg->info_flags & SIEP_FLAGS_TEST) {
5856                 lun->ie_asc = 0x5d;
5857                 lun->ie_ascq = 0xff;
5858                 if (pg->mrie == SIEP_MRIE_UA) {
5859                         ctl_est_ua_all(lun, -1, CTL_UA_IE);
5860                         lun->ie_reported = 1;
5861                 } else {
5862                         ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5863                         lun->ie_reported = -1;
5864                 }
5865                 lun->ie_reportcnt = 1;
5866                 if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5867                         lun->ie_reportcnt++;
5868                         t = scsi_4btoul(pg->interval_timer);
5869                         if (t == 0 || t == UINT32_MAX)
5870                                 t = 3000;  /* 5 min */
5871                         callout_reset(&lun->ie_callout, t * hz / 10,
5872                             ctl_ie_timer, lun);
5873                 }
5874         } else {
5875                 lun->ie_asc = 0;
5876                 lun->ie_ascq = 0;
5877                 lun->ie_reported = 1;
5878                 ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5879                 lun->ie_reportcnt = UINT32_MAX;
5880                 callout_stop(&lun->ie_callout);
5881         }
5882         mtx_unlock(&lun->lun_lock);
5883         return (CTL_RETVAL_COMPLETE);
5884 }
5885
5886 static int
5887 ctl_do_mode_select(union ctl_io *io)
5888 {
5889         struct ctl_lun *lun = CTL_LUN(io);
5890         struct scsi_mode_page_header *page_header;
5891         struct ctl_page_index *page_index;
5892         struct ctl_scsiio *ctsio;
5893         int page_len, page_len_offset, page_len_size;
5894         union ctl_modepage_info *modepage_info;
5895         uint16_t *len_left, *len_used;
5896         int retval, i;
5897
5898         ctsio = &io->scsiio;
5899         page_index = NULL;
5900         page_len = 0;
5901
5902         modepage_info = (union ctl_modepage_info *)
5903                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5904         len_left = &modepage_info->header.len_left;
5905         len_used = &modepage_info->header.len_used;
5906
5907 do_next_page:
5908
5909         page_header = (struct scsi_mode_page_header *)
5910                 (ctsio->kern_data_ptr + *len_used);
5911
5912         if (*len_left == 0) {
5913                 free(ctsio->kern_data_ptr, M_CTL);
5914                 ctl_set_success(ctsio);
5915                 ctl_done((union ctl_io *)ctsio);
5916                 return (CTL_RETVAL_COMPLETE);
5917         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5918
5919                 free(ctsio->kern_data_ptr, M_CTL);
5920                 ctl_set_param_len_error(ctsio);
5921                 ctl_done((union ctl_io *)ctsio);
5922                 return (CTL_RETVAL_COMPLETE);
5923
5924         } else if ((page_header->page_code & SMPH_SPF)
5925                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5926
5927                 free(ctsio->kern_data_ptr, M_CTL);
5928                 ctl_set_param_len_error(ctsio);
5929                 ctl_done((union ctl_io *)ctsio);
5930                 return (CTL_RETVAL_COMPLETE);
5931         }
5932
5933
5934         /*
5935          * XXX KDM should we do something with the block descriptor?
5936          */
5937         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5938                 page_index = &lun->mode_pages.index[i];
5939                 if (lun->be_lun->lun_type == T_DIRECT &&
5940                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5941                         continue;
5942                 if (lun->be_lun->lun_type == T_PROCESSOR &&
5943                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5944                         continue;
5945                 if (lun->be_lun->lun_type == T_CDROM &&
5946                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5947                         continue;
5948
5949                 if ((page_index->page_code & SMPH_PC_MASK) !=
5950                     (page_header->page_code & SMPH_PC_MASK))
5951                         continue;
5952
5953                 /*
5954                  * If neither page has a subpage code, then we've got a
5955                  * match.
5956                  */
5957                 if (((page_index->page_code & SMPH_SPF) == 0)
5958                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5959                         page_len = page_header->page_length;
5960                         break;
5961                 }
5962
5963                 /*
5964                  * If both pages have subpages, then the subpage numbers
5965                  * have to match.
5966                  */
5967                 if ((page_index->page_code & SMPH_SPF)
5968                   && (page_header->page_code & SMPH_SPF)) {
5969                         struct scsi_mode_page_header_sp *sph;
5970
5971                         sph = (struct scsi_mode_page_header_sp *)page_header;
5972                         if (page_index->subpage == sph->subpage) {
5973                                 page_len = scsi_2btoul(sph->page_length);
5974                                 break;
5975                         }
5976                 }
5977         }
5978
5979         /*
5980          * If we couldn't find the page, or if we don't have a mode select
5981          * handler for it, send back an error to the user.
5982          */
5983         if ((i >= CTL_NUM_MODE_PAGES)
5984          || (page_index->select_handler == NULL)) {
5985                 ctl_set_invalid_field(ctsio,
5986                                       /*sks_valid*/ 1,
5987                                       /*command*/ 0,
5988                                       /*field*/ *len_used,
5989                                       /*bit_valid*/ 0,
5990                                       /*bit*/ 0);
5991                 free(ctsio->kern_data_ptr, M_CTL);
5992                 ctl_done((union ctl_io *)ctsio);
5993                 return (CTL_RETVAL_COMPLETE);
5994         }
5995
5996         if (page_index->page_code & SMPH_SPF) {
5997                 page_len_offset = 2;
5998                 page_len_size = 2;
5999         } else {
6000                 page_len_size = 1;
6001                 page_len_offset = 1;
6002         }
6003
6004         /*
6005          * If the length the initiator gives us isn't the one we specify in
6006          * the mode page header, or if they didn't specify enough data in
6007          * the CDB to avoid truncating this page, kick out the request.
6008          */
6009         if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6010                 ctl_set_invalid_field(ctsio,
6011                                       /*sks_valid*/ 1,
6012                                       /*command*/ 0,
6013                                       /*field*/ *len_used + page_len_offset,
6014                                       /*bit_valid*/ 0,
6015                                       /*bit*/ 0);
6016                 free(ctsio->kern_data_ptr, M_CTL);
6017                 ctl_done((union ctl_io *)ctsio);
6018                 return (CTL_RETVAL_COMPLETE);
6019         }
6020         if (*len_left < page_index->page_len) {
6021                 free(ctsio->kern_data_ptr, M_CTL);
6022                 ctl_set_param_len_error(ctsio);
6023                 ctl_done((union ctl_io *)ctsio);
6024                 return (CTL_RETVAL_COMPLETE);
6025         }
6026
6027         /*
6028          * Run through the mode page, checking to make sure that the bits
6029          * the user changed are actually legal for him to change.
6030          */
6031         for (i = 0; i < page_index->page_len; i++) {
6032                 uint8_t *user_byte, *change_mask, *current_byte;
6033                 int bad_bit;
6034                 int j;
6035
6036                 user_byte = (uint8_t *)page_header + i;
6037                 change_mask = page_index->page_data +
6038                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6039                 current_byte = page_index->page_data +
6040                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6041
6042                 /*
6043                  * Check to see whether the user set any bits in this byte
6044                  * that he is not allowed to set.
6045                  */
6046                 if ((*user_byte & ~(*change_mask)) ==
6047                     (*current_byte & ~(*change_mask)))
6048                         continue;
6049
6050                 /*
6051                  * Go through bit by bit to determine which one is illegal.
6052                  */
6053                 bad_bit = 0;
6054                 for (j = 7; j >= 0; j--) {
6055                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6056                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6057                                 bad_bit = i;
6058                                 break;
6059                         }
6060                 }
6061                 ctl_set_invalid_field(ctsio,
6062                                       /*sks_valid*/ 1,
6063                                       /*command*/ 0,
6064                                       /*field*/ *len_used + i,
6065                                       /*bit_valid*/ 1,
6066                                       /*bit*/ bad_bit);
6067                 free(ctsio->kern_data_ptr, M_CTL);
6068                 ctl_done((union ctl_io *)ctsio);
6069                 return (CTL_RETVAL_COMPLETE);
6070         }
6071
6072         /*
6073          * Decrement these before we call the page handler, since we may
6074          * end up getting called back one way or another before the handler
6075          * returns to this context.
6076          */
6077         *len_left -= page_index->page_len;
6078         *len_used += page_index->page_len;
6079
6080         retval = page_index->select_handler(ctsio, page_index,
6081                                             (uint8_t *)page_header);
6082
6083         /*
6084          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6085          * wait until this queued command completes to finish processing
6086          * the mode page.  If it returns anything other than
6087          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6088          * already set the sense information, freed the data pointer, and
6089          * completed the io for us.
6090          */
6091         if (retval != CTL_RETVAL_COMPLETE)
6092                 goto bailout_no_done;
6093
6094         /*
6095          * If the initiator sent us more than one page, parse the next one.
6096          */
6097         if (*len_left > 0)
6098                 goto do_next_page;
6099
6100         ctl_set_success(ctsio);
6101         free(ctsio->kern_data_ptr, M_CTL);
6102         ctl_done((union ctl_io *)ctsio);
6103
6104 bailout_no_done:
6105
6106         return (CTL_RETVAL_COMPLETE);
6107
6108 }
6109
6110 int
6111 ctl_mode_select(struct ctl_scsiio *ctsio)
6112 {
6113         struct ctl_lun *lun = CTL_LUN(ctsio);
6114         union ctl_modepage_info *modepage_info;
6115         int bd_len, i, header_size, param_len, pf, rtd, sp;
6116         uint32_t initidx;
6117
6118         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6119         switch (ctsio->cdb[0]) {
6120         case MODE_SELECT_6: {
6121                 struct scsi_mode_select_6 *cdb;
6122
6123                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6124
6125                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6126                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6127                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6128                 param_len = cdb->length;
6129                 header_size = sizeof(struct scsi_mode_header_6);
6130                 break;
6131         }
6132         case MODE_SELECT_10: {
6133                 struct scsi_mode_select_10 *cdb;
6134
6135                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6136
6137                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6138                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6139                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6140                 param_len = scsi_2btoul(cdb->length);
6141                 header_size = sizeof(struct scsi_mode_header_10);
6142                 break;
6143         }
6144         default:
6145                 ctl_set_invalid_opcode(ctsio);
6146                 ctl_done((union ctl_io *)ctsio);
6147                 return (CTL_RETVAL_COMPLETE);
6148         }
6149
6150         if (rtd) {
6151                 if (param_len != 0) {
6152                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6153                             /*command*/ 1, /*field*/ 0,
6154                             /*bit_valid*/ 0, /*bit*/ 0);
6155                         ctl_done((union ctl_io *)ctsio);
6156                         return (CTL_RETVAL_COMPLETE);
6157                 }
6158
6159                 /* Revert to defaults. */
6160                 ctl_init_page_index(lun);
6161                 mtx_lock(&lun->lun_lock);
6162                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6163                 mtx_unlock(&lun->lun_lock);
6164                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6165                         ctl_isc_announce_mode(lun, -1,
6166                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6167                             lun->mode_pages.index[i].subpage);
6168                 }
6169                 ctl_set_success(ctsio);
6170                 ctl_done((union ctl_io *)ctsio);
6171                 return (CTL_RETVAL_COMPLETE);
6172         }
6173
6174         /*
6175          * From SPC-3:
6176          * "A parameter list length of zero indicates that the Data-Out Buffer
6177          * shall be empty. This condition shall not be considered as an error."
6178          */
6179         if (param_len == 0) {
6180                 ctl_set_success(ctsio);
6181                 ctl_done((union ctl_io *)ctsio);
6182                 return (CTL_RETVAL_COMPLETE);
6183         }
6184
6185         /*
6186          * Since we'll hit this the first time through, prior to
6187          * allocation, we don't need to free a data buffer here.
6188          */
6189         if (param_len < header_size) {
6190                 ctl_set_param_len_error(ctsio);
6191                 ctl_done((union ctl_io *)ctsio);
6192                 return (CTL_RETVAL_COMPLETE);
6193         }
6194
6195         /*
6196          * Allocate the data buffer and grab the user's data.  In theory,
6197          * we shouldn't have to sanity check the parameter list length here
6198          * because the maximum size is 64K.  We should be able to malloc
6199          * that much without too many problems.
6200          */
6201         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6202                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6203                 ctsio->kern_data_len = param_len;
6204                 ctsio->kern_total_len = param_len;
6205                 ctsio->kern_data_resid = 0;
6206                 ctsio->kern_rel_offset = 0;
6207                 ctsio->kern_sg_entries = 0;
6208                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6209                 ctsio->be_move_done = ctl_config_move_done;
6210                 ctl_datamove((union ctl_io *)ctsio);
6211
6212                 return (CTL_RETVAL_COMPLETE);
6213         }
6214
6215         switch (ctsio->cdb[0]) {
6216         case MODE_SELECT_6: {
6217                 struct scsi_mode_header_6 *mh6;
6218
6219                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6220                 bd_len = mh6->blk_desc_len;
6221                 break;
6222         }
6223         case MODE_SELECT_10: {
6224                 struct scsi_mode_header_10 *mh10;
6225
6226                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6227                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6228                 break;
6229         }
6230         default:
6231                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6232         }
6233
6234         if (param_len < (header_size + bd_len)) {
6235                 free(ctsio->kern_data_ptr, M_CTL);
6236                 ctl_set_param_len_error(ctsio);
6237                 ctl_done((union ctl_io *)ctsio);
6238                 return (CTL_RETVAL_COMPLETE);
6239         }
6240
6241         /*
6242          * Set the IO_CONT flag, so that if this I/O gets passed to
6243          * ctl_config_write_done(), it'll get passed back to
6244          * ctl_do_mode_select() for further processing, or completion if
6245          * we're all done.
6246          */
6247         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6248         ctsio->io_cont = ctl_do_mode_select;
6249
6250         modepage_info = (union ctl_modepage_info *)
6251                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6252         memset(modepage_info, 0, sizeof(*modepage_info));
6253         modepage_info->header.len_left = param_len - header_size - bd_len;
6254         modepage_info->header.len_used = header_size + bd_len;
6255
6256         return (ctl_do_mode_select((union ctl_io *)ctsio));
6257 }
6258
6259 int
6260 ctl_mode_sense(struct ctl_scsiio *ctsio)
6261 {
6262         struct ctl_lun *lun = CTL_LUN(ctsio);
6263         int pc, page_code, dbd, llba, subpage;
6264         int alloc_len, page_len, header_len, total_len;
6265         struct scsi_mode_block_descr *block_desc;
6266         struct ctl_page_index *page_index;
6267
6268         dbd = 0;
6269         llba = 0;
6270         block_desc = NULL;
6271
6272         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6273
6274         switch (ctsio->cdb[0]) {
6275         case MODE_SENSE_6: {
6276                 struct scsi_mode_sense_6 *cdb;
6277
6278                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6279
6280                 header_len = sizeof(struct scsi_mode_hdr_6);
6281                 if (cdb->byte2 & SMS_DBD)
6282                         dbd = 1;
6283                 else
6284                         header_len += sizeof(struct scsi_mode_block_descr);
6285
6286                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6287                 page_code = cdb->page & SMS_PAGE_CODE;
6288                 subpage = cdb->subpage;
6289                 alloc_len = cdb->length;
6290                 break;
6291         }
6292         case MODE_SENSE_10: {
6293                 struct scsi_mode_sense_10 *cdb;
6294
6295                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6296
6297                 header_len = sizeof(struct scsi_mode_hdr_10);
6298
6299                 if (cdb->byte2 & SMS_DBD)
6300                         dbd = 1;
6301                 else
6302                         header_len += sizeof(struct scsi_mode_block_descr);
6303                 if (cdb->byte2 & SMS10_LLBAA)
6304                         llba = 1;
6305                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6306                 page_code = cdb->page & SMS_PAGE_CODE;
6307                 subpage = cdb->subpage;
6308                 alloc_len = scsi_2btoul(cdb->length);
6309                 break;
6310         }
6311         default:
6312                 ctl_set_invalid_opcode(ctsio);
6313                 ctl_done((union ctl_io *)ctsio);
6314                 return (CTL_RETVAL_COMPLETE);
6315                 break; /* NOTREACHED */
6316         }
6317
6318         /*
6319          * We have to make a first pass through to calculate the size of
6320          * the pages that match the user's query.  Then we allocate enough
6321          * memory to hold it, and actually copy the data into the buffer.
6322          */
6323         switch (page_code) {
6324         case SMS_ALL_PAGES_PAGE: {
6325                 u_int i;
6326
6327                 page_len = 0;
6328
6329                 /*
6330                  * At the moment, values other than 0 and 0xff here are
6331                  * reserved according to SPC-3.
6332                  */
6333                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6334                  && (subpage != SMS_SUBPAGE_ALL)) {
6335                         ctl_set_invalid_field(ctsio,
6336                                               /*sks_valid*/ 1,
6337                                               /*command*/ 1,
6338                                               /*field*/ 3,
6339                                               /*bit_valid*/ 0,
6340                                               /*bit*/ 0);
6341                         ctl_done((union ctl_io *)ctsio);
6342                         return (CTL_RETVAL_COMPLETE);
6343                 }
6344
6345                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6346                         page_index = &lun->mode_pages.index[i];
6347
6348                         /* Make sure the page is supported for this dev type */
6349                         if (lun->be_lun->lun_type == T_DIRECT &&
6350                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6351                                 continue;
6352                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6353                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6354                                 continue;
6355                         if (lun->be_lun->lun_type == T_CDROM &&
6356                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6357                                 continue;
6358
6359                         /*
6360                          * We don't use this subpage if the user didn't
6361                          * request all subpages.
6362                          */
6363                         if ((page_index->subpage != 0)
6364                          && (subpage == SMS_SUBPAGE_PAGE_0))
6365                                 continue;
6366
6367 #if 0
6368                         printf("found page %#x len %d\n",
6369                                page_index->page_code & SMPH_PC_MASK,
6370                                page_index->page_len);
6371 #endif
6372                         page_len += page_index->page_len;
6373                 }
6374                 break;
6375         }
6376         default: {
6377                 u_int i;
6378
6379                 page_len = 0;
6380
6381                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6382                         page_index = &lun->mode_pages.index[i];
6383
6384                         /* Make sure the page is supported for this dev type */
6385                         if (lun->be_lun->lun_type == T_DIRECT &&
6386                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6387                                 continue;
6388                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6389                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6390                                 continue;
6391                         if (lun->be_lun->lun_type == T_CDROM &&
6392                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6393                                 continue;
6394
6395                         /* Look for the right page code */
6396                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6397                                 continue;
6398
6399                         /* Look for the right subpage or the subpage wildcard*/
6400                         if ((page_index->subpage != subpage)
6401                          && (subpage != SMS_SUBPAGE_ALL))
6402                                 continue;
6403
6404 #if 0
6405                         printf("found page %#x len %d\n",
6406                                page_index->page_code & SMPH_PC_MASK,
6407                                page_index->page_len);
6408 #endif
6409
6410                         page_len += page_index->page_len;
6411                 }
6412
6413                 if (page_len == 0) {
6414                         ctl_set_invalid_field(ctsio,
6415                                               /*sks_valid*/ 1,
6416                                               /*command*/ 1,
6417                                               /*field*/ 2,
6418                                               /*bit_valid*/ 1,
6419                                               /*bit*/ 5);
6420                         ctl_done((union ctl_io *)ctsio);
6421                         return (CTL_RETVAL_COMPLETE);
6422                 }
6423                 break;
6424         }
6425         }
6426
6427         total_len = header_len + page_len;
6428 #if 0
6429         printf("header_len = %d, page_len = %d, total_len = %d\n",
6430                header_len, page_len, total_len);
6431 #endif
6432
6433         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6434         ctsio->kern_sg_entries = 0;
6435         ctsio->kern_data_resid = 0;
6436         ctsio->kern_rel_offset = 0;
6437         if (total_len < alloc_len) {
6438                 ctsio->residual = alloc_len - total_len;
6439                 ctsio->kern_data_len = total_len;
6440                 ctsio->kern_total_len = total_len;
6441         } else {
6442                 ctsio->residual = 0;
6443                 ctsio->kern_data_len = alloc_len;
6444                 ctsio->kern_total_len = alloc_len;
6445         }
6446
6447         switch (ctsio->cdb[0]) {
6448         case MODE_SENSE_6: {
6449                 struct scsi_mode_hdr_6 *header;
6450
6451                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6452
6453                 header->datalen = MIN(total_len - 1, 254);
6454                 if (lun->be_lun->lun_type == T_DIRECT) {
6455                         header->dev_specific = 0x10; /* DPOFUA */
6456                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6457                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6458                                 header->dev_specific |= 0x80; /* WP */
6459                 }
6460                 if (dbd)
6461                         header->block_descr_len = 0;
6462                 else
6463                         header->block_descr_len =
6464                                 sizeof(struct scsi_mode_block_descr);
6465                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6466                 break;
6467         }
6468         case MODE_SENSE_10: {
6469                 struct scsi_mode_hdr_10 *header;
6470                 int datalen;
6471
6472                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6473
6474                 datalen = MIN(total_len - 2, 65533);
6475                 scsi_ulto2b(datalen, header->datalen);
6476                 if (lun->be_lun->lun_type == T_DIRECT) {
6477                         header->dev_specific = 0x10; /* DPOFUA */
6478                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6479                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6480                                 header->dev_specific |= 0x80; /* WP */
6481                 }
6482                 if (dbd)
6483                         scsi_ulto2b(0, header->block_descr_len);
6484                 else
6485                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6486                                     header->block_descr_len);
6487                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6488                 break;
6489         }
6490         default:
6491                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6492         }
6493
6494         /*
6495          * If we've got a disk, use its blocksize in the block
6496          * descriptor.  Otherwise, just set it to 0.
6497          */
6498         if (dbd == 0) {
6499                 if (lun->be_lun->lun_type == T_DIRECT)
6500                         scsi_ulto3b(lun->be_lun->blocksize,
6501                                     block_desc->block_len);
6502                 else
6503                         scsi_ulto3b(0, block_desc->block_len);
6504         }
6505
6506         switch (page_code) {
6507         case SMS_ALL_PAGES_PAGE: {
6508                 int i, data_used;
6509
6510                 data_used = header_len;
6511                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6512                         struct ctl_page_index *page_index;
6513
6514                         page_index = &lun->mode_pages.index[i];
6515                         if (lun->be_lun->lun_type == T_DIRECT &&
6516                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6517                                 continue;
6518                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6519                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6520                                 continue;
6521                         if (lun->be_lun->lun_type == T_CDROM &&
6522                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6523                                 continue;
6524
6525                         /*
6526                          * We don't use this subpage if the user didn't
6527                          * request all subpages.  We already checked (above)
6528                          * to make sure the user only specified a subpage
6529                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6530                          */
6531                         if ((page_index->subpage != 0)
6532                          && (subpage == SMS_SUBPAGE_PAGE_0))
6533                                 continue;
6534
6535                         /*
6536                          * Call the handler, if it exists, to update the
6537                          * page to the latest values.
6538                          */
6539                         if (page_index->sense_handler != NULL)
6540                                 page_index->sense_handler(ctsio, page_index,pc);
6541
6542                         memcpy(ctsio->kern_data_ptr + data_used,
6543                                page_index->page_data +
6544                                (page_index->page_len * pc),
6545                                page_index->page_len);
6546                         data_used += page_index->page_len;
6547                 }
6548                 break;
6549         }
6550         default: {
6551                 int i, data_used;
6552
6553                 data_used = header_len;
6554
6555                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6556                         struct ctl_page_index *page_index;
6557
6558                         page_index = &lun->mode_pages.index[i];
6559
6560                         /* Look for the right page code */
6561                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6562                                 continue;
6563
6564                         /* Look for the right subpage or the subpage wildcard*/
6565                         if ((page_index->subpage != subpage)
6566                          && (subpage != SMS_SUBPAGE_ALL))
6567                                 continue;
6568
6569                         /* Make sure the page is supported for this dev type */
6570                         if (lun->be_lun->lun_type == T_DIRECT &&
6571                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6572                                 continue;
6573                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6574                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6575                                 continue;
6576                         if (lun->be_lun->lun_type == T_CDROM &&
6577                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6578                                 continue;
6579
6580                         /*
6581                          * Call the handler, if it exists, to update the
6582                          * page to the latest values.
6583                          */
6584                         if (page_index->sense_handler != NULL)
6585                                 page_index->sense_handler(ctsio, page_index,pc);
6586
6587                         memcpy(ctsio->kern_data_ptr + data_used,
6588                                page_index->page_data +
6589                                (page_index->page_len * pc),
6590                                page_index->page_len);
6591                         data_used += page_index->page_len;
6592                 }
6593                 break;
6594         }
6595         }
6596
6597         ctl_set_success(ctsio);
6598         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6599         ctsio->be_move_done = ctl_config_move_done;
6600         ctl_datamove((union ctl_io *)ctsio);
6601         return (CTL_RETVAL_COMPLETE);
6602 }
6603
6604 int
6605 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6606                                struct ctl_page_index *page_index,
6607                                int pc)
6608 {
6609         struct ctl_lun *lun = CTL_LUN(ctsio);
6610         struct scsi_log_param_header *phdr;
6611         uint8_t *data;
6612         uint64_t val;
6613
6614         data = page_index->page_data;
6615
6616         if (lun->backend->lun_attr != NULL &&
6617             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6618              != UINT64_MAX) {
6619                 phdr = (struct scsi_log_param_header *)data;
6620                 scsi_ulto2b(0x0001, phdr->param_code);
6621                 phdr->param_control = SLP_LBIN | SLP_LP;
6622                 phdr->param_len = 8;
6623                 data = (uint8_t *)(phdr + 1);
6624                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6625                 data[4] = 0x02; /* per-pool */
6626                 data += phdr->param_len;
6627         }
6628
6629         if (lun->backend->lun_attr != NULL &&
6630             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6631              != UINT64_MAX) {
6632                 phdr = (struct scsi_log_param_header *)data;
6633                 scsi_ulto2b(0x0002, phdr->param_code);
6634                 phdr->param_control = SLP_LBIN | SLP_LP;
6635                 phdr->param_len = 8;
6636                 data = (uint8_t *)(phdr + 1);
6637                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6638                 data[4] = 0x01; /* per-LUN */
6639                 data += phdr->param_len;
6640         }
6641
6642         if (lun->backend->lun_attr != NULL &&
6643             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6644              != UINT64_MAX) {
6645                 phdr = (struct scsi_log_param_header *)data;
6646                 scsi_ulto2b(0x00f1, phdr->param_code);
6647                 phdr->param_control = SLP_LBIN | SLP_LP;
6648                 phdr->param_len = 8;
6649                 data = (uint8_t *)(phdr + 1);
6650                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6651                 data[4] = 0x02; /* per-pool */
6652                 data += phdr->param_len;
6653         }
6654
6655         if (lun->backend->lun_attr != NULL &&
6656             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6657              != UINT64_MAX) {
6658                 phdr = (struct scsi_log_param_header *)data;
6659                 scsi_ulto2b(0x00f2, phdr->param_code);
6660                 phdr->param_control = SLP_LBIN | SLP_LP;
6661                 phdr->param_len = 8;
6662                 data = (uint8_t *)(phdr + 1);
6663                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6664                 data[4] = 0x02; /* per-pool */
6665                 data += phdr->param_len;
6666         }
6667
6668         page_index->page_len = data - page_index->page_data;
6669         return (0);
6670 }
6671
6672 int
6673 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6674                                struct ctl_page_index *page_index,
6675                                int pc)
6676 {
6677         struct ctl_lun *lun = CTL_LUN(ctsio);
6678         struct stat_page *data;
6679         uint64_t rn, wn, rb, wb;
6680         struct bintime rt, wt;
6681         int i;
6682
6683         data = (struct stat_page *)page_index->page_data;
6684
6685         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6686         data->sap.hdr.param_control = SLP_LBIN;
6687         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6688             sizeof(struct scsi_log_param_header);
6689         rn = wn = rb = wb = 0;
6690         bintime_clear(&rt);
6691         bintime_clear(&wt);
6692         for (i = 0; i < CTL_MAX_PORTS; i++) {
6693                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6694                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6695                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6696                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6697                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6698                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6699         }
6700         scsi_u64to8b(rn, data->sap.read_num);
6701         scsi_u64to8b(wn, data->sap.write_num);
6702         if (lun->stats.blocksize > 0) {
6703                 scsi_u64to8b(wb / lun->stats.blocksize,
6704                     data->sap.recvieved_lba);
6705                 scsi_u64to8b(rb / lun->stats.blocksize,
6706                     data->sap.transmitted_lba);
6707         }
6708         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6709             data->sap.read_int);
6710         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6711             data->sap.write_int);
6712         scsi_u64to8b(0, data->sap.weighted_num);
6713         scsi_u64to8b(0, data->sap.weighted_int);
6714         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6715         data->it.hdr.param_control = SLP_LBIN;
6716         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6717             sizeof(struct scsi_log_param_header);
6718 #ifdef CTL_TIME_IO
6719         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6720 #endif
6721         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6722         data->it.hdr.param_control = SLP_LBIN;
6723         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6724             sizeof(struct scsi_log_param_header);
6725         scsi_ulto4b(3, data->ti.exponent);
6726         scsi_ulto4b(1, data->ti.integer);
6727         return (0);
6728 }
6729
6730 int
6731 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6732                                struct ctl_page_index *page_index,
6733                                int pc)
6734 {
6735         struct ctl_lun *lun = CTL_LUN(ctsio);
6736         struct scsi_log_informational_exceptions *data;
6737
6738         data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6739
6740         scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6741         data->hdr.param_control = SLP_LBIN;
6742         data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6743             sizeof(struct scsi_log_param_header);
6744         data->ie_asc = lun->ie_asc;
6745         data->ie_ascq = lun->ie_ascq;
6746         data->temperature = 0xff;
6747         return (0);
6748 }
6749
6750 int
6751 ctl_log_sense(struct ctl_scsiio *ctsio)
6752 {
6753         struct ctl_lun *lun = CTL_LUN(ctsio);
6754         int i, pc, page_code, subpage;
6755         int alloc_len, total_len;
6756         struct ctl_page_index *page_index;
6757         struct scsi_log_sense *cdb;
6758         struct scsi_log_header *header;
6759
6760         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6761
6762         cdb = (struct scsi_log_sense *)ctsio->cdb;
6763         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6764         page_code = cdb->page & SLS_PAGE_CODE;
6765         subpage = cdb->subpage;
6766         alloc_len = scsi_2btoul(cdb->length);
6767
6768         page_index = NULL;
6769         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6770                 page_index = &lun->log_pages.index[i];
6771
6772                 /* Look for the right page code */
6773                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6774                         continue;
6775
6776                 /* Look for the right subpage or the subpage wildcard*/
6777                 if (page_index->subpage != subpage)
6778                         continue;
6779
6780                 break;
6781         }
6782         if (i >= CTL_NUM_LOG_PAGES) {
6783                 ctl_set_invalid_field(ctsio,
6784                                       /*sks_valid*/ 1,
6785                                       /*command*/ 1,
6786                                       /*field*/ 2,
6787                                       /*bit_valid*/ 0,
6788                                       /*bit*/ 0);
6789                 ctl_done((union ctl_io *)ctsio);
6790                 return (CTL_RETVAL_COMPLETE);
6791         }
6792
6793         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6794
6795         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6796         ctsio->kern_sg_entries = 0;
6797         ctsio->kern_data_resid = 0;
6798         ctsio->kern_rel_offset = 0;
6799         if (total_len < alloc_len) {
6800                 ctsio->residual = alloc_len - total_len;
6801                 ctsio->kern_data_len = total_len;
6802                 ctsio->kern_total_len = total_len;
6803         } else {
6804                 ctsio->residual = 0;
6805                 ctsio->kern_data_len = alloc_len;
6806                 ctsio->kern_total_len = alloc_len;
6807         }
6808
6809         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6810         header->page = page_index->page_code;
6811         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6812                 header->page |= SL_DS;
6813         if (page_index->subpage) {
6814                 header->page |= SL_SPF;
6815                 header->subpage = page_index->subpage;
6816         }
6817         scsi_ulto2b(page_index->page_len, header->datalen);
6818
6819         /*
6820          * Call the handler, if it exists, to update the
6821          * page to the latest values.
6822          */
6823         if (page_index->sense_handler != NULL)
6824                 page_index->sense_handler(ctsio, page_index, pc);
6825
6826         memcpy(header + 1, page_index->page_data, page_index->page_len);
6827
6828         ctl_set_success(ctsio);
6829         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6830         ctsio->be_move_done = ctl_config_move_done;
6831         ctl_datamove((union ctl_io *)ctsio);
6832         return (CTL_RETVAL_COMPLETE);
6833 }
6834
6835 int
6836 ctl_read_capacity(struct ctl_scsiio *ctsio)
6837 {
6838         struct ctl_lun *lun = CTL_LUN(ctsio);
6839         struct scsi_read_capacity *cdb;
6840         struct scsi_read_capacity_data *data;
6841         uint32_t lba;
6842
6843         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6844
6845         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6846
6847         lba = scsi_4btoul(cdb->addr);
6848         if (((cdb->pmi & SRC_PMI) == 0)
6849          && (lba != 0)) {
6850                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6851                                       /*sks_valid*/ 1,
6852                                       /*command*/ 1,
6853                                       /*field*/ 2,
6854                                       /*bit_valid*/ 0,
6855                                       /*bit*/ 0);
6856                 ctl_done((union ctl_io *)ctsio);
6857                 return (CTL_RETVAL_COMPLETE);
6858         }
6859
6860         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6861         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6862         ctsio->residual = 0;
6863         ctsio->kern_data_len = sizeof(*data);
6864         ctsio->kern_total_len = sizeof(*data);
6865         ctsio->kern_data_resid = 0;
6866         ctsio->kern_rel_offset = 0;
6867         ctsio->kern_sg_entries = 0;
6868
6869         /*
6870          * If the maximum LBA is greater than 0xfffffffe, the user must
6871          * issue a SERVICE ACTION IN (16) command, with the read capacity
6872          * serivce action set.
6873          */
6874         if (lun->be_lun->maxlba > 0xfffffffe)
6875                 scsi_ulto4b(0xffffffff, data->addr);
6876         else
6877                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6878
6879         /*
6880          * XXX KDM this may not be 512 bytes...
6881          */
6882         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6883
6884         ctl_set_success(ctsio);
6885         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6886         ctsio->be_move_done = ctl_config_move_done;
6887         ctl_datamove((union ctl_io *)ctsio);
6888         return (CTL_RETVAL_COMPLETE);
6889 }
6890
6891 int
6892 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6893 {
6894         struct ctl_lun *lun = CTL_LUN(ctsio);
6895         struct scsi_read_capacity_16 *cdb;
6896         struct scsi_read_capacity_data_long *data;
6897         uint64_t lba;
6898         uint32_t alloc_len;
6899
6900         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6901
6902         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6903
6904         alloc_len = scsi_4btoul(cdb->alloc_len);
6905         lba = scsi_8btou64(cdb->addr);
6906
6907         if ((cdb->reladr & SRC16_PMI)
6908          && (lba != 0)) {
6909                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6910                                       /*sks_valid*/ 1,
6911                                       /*command*/ 1,
6912                                       /*field*/ 2,
6913                                       /*bit_valid*/ 0,
6914                                       /*bit*/ 0);
6915                 ctl_done((union ctl_io *)ctsio);
6916                 return (CTL_RETVAL_COMPLETE);
6917         }
6918
6919         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6920         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6921
6922         if (sizeof(*data) < alloc_len) {
6923                 ctsio->residual = alloc_len - sizeof(*data);
6924                 ctsio->kern_data_len = sizeof(*data);
6925                 ctsio->kern_total_len = sizeof(*data);
6926         } else {
6927                 ctsio->residual = 0;
6928                 ctsio->kern_data_len = alloc_len;
6929                 ctsio->kern_total_len = alloc_len;
6930         }
6931         ctsio->kern_data_resid = 0;
6932         ctsio->kern_rel_offset = 0;
6933         ctsio->kern_sg_entries = 0;
6934
6935         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6936         /* XXX KDM this may not be 512 bytes... */
6937         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6938         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6939         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6940         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6941                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6942
6943         ctl_set_success(ctsio);
6944         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6945         ctsio->be_move_done = ctl_config_move_done;
6946         ctl_datamove((union ctl_io *)ctsio);
6947         return (CTL_RETVAL_COMPLETE);
6948 }
6949
6950 int
6951 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6952 {
6953         struct ctl_lun *lun = CTL_LUN(ctsio);
6954         struct scsi_get_lba_status *cdb;
6955         struct scsi_get_lba_status_data *data;
6956         struct ctl_lba_len_flags *lbalen;
6957         uint64_t lba;
6958         uint32_t alloc_len, total_len;
6959         int retval;
6960
6961         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6962
6963         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6964         lba = scsi_8btou64(cdb->addr);
6965         alloc_len = scsi_4btoul(cdb->alloc_len);
6966
6967         if (lba > lun->be_lun->maxlba) {
6968                 ctl_set_lba_out_of_range(ctsio, lba);
6969                 ctl_done((union ctl_io *)ctsio);
6970                 return (CTL_RETVAL_COMPLETE);
6971         }
6972
6973         total_len = sizeof(*data) + sizeof(data->descr[0]);
6974         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6975         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6976
6977         if (total_len < alloc_len) {
6978                 ctsio->residual = alloc_len - total_len;
6979                 ctsio->kern_data_len = total_len;
6980                 ctsio->kern_total_len = total_len;
6981         } else {
6982                 ctsio->residual = 0;
6983                 ctsio->kern_data_len = alloc_len;
6984                 ctsio->kern_total_len = alloc_len;
6985         }
6986         ctsio->kern_data_resid = 0;
6987         ctsio->kern_rel_offset = 0;
6988         ctsio->kern_sg_entries = 0;
6989
6990         /* Fill dummy data in case backend can't tell anything. */
6991         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6992         scsi_u64to8b(lba, data->descr[0].addr);
6993         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6994             data->descr[0].length);
6995         data->descr[0].status = 0; /* Mapped or unknown. */
6996
6997         ctl_set_success(ctsio);
6998         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6999         ctsio->be_move_done = ctl_config_move_done;
7000
7001         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7002         lbalen->lba = lba;
7003         lbalen->len = total_len;
7004         lbalen->flags = 0;
7005         retval = lun->backend->config_read((union ctl_io *)ctsio);
7006         return (CTL_RETVAL_COMPLETE);
7007 }
7008
7009 int
7010 ctl_read_defect(struct ctl_scsiio *ctsio)
7011 {
7012         struct scsi_read_defect_data_10 *ccb10;
7013         struct scsi_read_defect_data_12 *ccb12;
7014         struct scsi_read_defect_data_hdr_10 *data10;
7015         struct scsi_read_defect_data_hdr_12 *data12;
7016         uint32_t alloc_len, data_len;
7017         uint8_t format;
7018
7019         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7020
7021         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7022                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7023                 format = ccb10->format;
7024                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7025                 data_len = sizeof(*data10);
7026         } else {
7027                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7028                 format = ccb12->format;
7029                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7030                 data_len = sizeof(*data12);
7031         }
7032         if (alloc_len == 0) {
7033                 ctl_set_success(ctsio);
7034                 ctl_done((union ctl_io *)ctsio);
7035                 return (CTL_RETVAL_COMPLETE);
7036         }
7037
7038         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7039         if (data_len < alloc_len) {
7040                 ctsio->residual = alloc_len - data_len;
7041                 ctsio->kern_data_len = data_len;
7042                 ctsio->kern_total_len = data_len;
7043         } else {
7044                 ctsio->residual = 0;
7045                 ctsio->kern_data_len = alloc_len;
7046                 ctsio->kern_total_len = alloc_len;
7047         }
7048         ctsio->kern_data_resid = 0;
7049         ctsio->kern_rel_offset = 0;
7050         ctsio->kern_sg_entries = 0;
7051
7052         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7053                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7054                     ctsio->kern_data_ptr;
7055                 data10->format = format;
7056                 scsi_ulto2b(0, data10->length);
7057         } else {
7058                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7059                     ctsio->kern_data_ptr;
7060                 data12->format = format;
7061                 scsi_ulto2b(0, data12->generation);
7062                 scsi_ulto4b(0, data12->length);
7063         }
7064
7065         ctl_set_success(ctsio);
7066         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7067         ctsio->be_move_done = ctl_config_move_done;
7068         ctl_datamove((union ctl_io *)ctsio);
7069         return (CTL_RETVAL_COMPLETE);
7070 }
7071
7072 int
7073 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7074 {
7075         struct ctl_softc *softc = CTL_SOFTC(ctsio);
7076         struct ctl_lun *lun = CTL_LUN(ctsio);
7077         struct scsi_maintenance_in *cdb;
7078         int retval;
7079         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7080         int num_ha_groups, num_target_ports, shared_group;
7081         struct ctl_port *port;
7082         struct scsi_target_group_data *rtg_ptr;
7083         struct scsi_target_group_data_extended *rtg_ext_ptr;
7084         struct scsi_target_port_group_descriptor *tpg_desc;
7085
7086         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7087
7088         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7089         retval = CTL_RETVAL_COMPLETE;
7090
7091         switch (cdb->byte2 & STG_PDF_MASK) {
7092         case STG_PDF_LENGTH:
7093                 ext = 0;
7094                 break;
7095         case STG_PDF_EXTENDED:
7096                 ext = 1;
7097                 break;
7098         default:
7099                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7100                                       /*sks_valid*/ 1,
7101                                       /*command*/ 1,
7102                                       /*field*/ 2,
7103                                       /*bit_valid*/ 1,
7104                                       /*bit*/ 5);
7105                 ctl_done((union ctl_io *)ctsio);
7106                 return(retval);
7107         }
7108
7109         num_target_ports = 0;
7110         shared_group = (softc->is_single != 0);
7111         mtx_lock(&softc->ctl_lock);
7112         STAILQ_FOREACH(port, &softc->port_list, links) {
7113                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7114                         continue;
7115                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7116                         continue;
7117                 num_target_ports++;
7118                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7119                         shared_group = 1;
7120         }
7121         mtx_unlock(&softc->ctl_lock);
7122         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7123
7124         if (ext)
7125                 total_len = sizeof(struct scsi_target_group_data_extended);
7126         else
7127                 total_len = sizeof(struct scsi_target_group_data);
7128         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7129                 (shared_group + num_ha_groups) +
7130             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7131
7132         alloc_len = scsi_4btoul(cdb->length);
7133
7134         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7135
7136         ctsio->kern_sg_entries = 0;
7137
7138         if (total_len < alloc_len) {
7139                 ctsio->residual = alloc_len - total_len;
7140                 ctsio->kern_data_len = total_len;
7141                 ctsio->kern_total_len = total_len;
7142         } else {
7143                 ctsio->residual = 0;
7144                 ctsio->kern_data_len = alloc_len;
7145                 ctsio->kern_total_len = alloc_len;
7146         }
7147         ctsio->kern_data_resid = 0;
7148         ctsio->kern_rel_offset = 0;
7149
7150         if (ext) {
7151                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7152                     ctsio->kern_data_ptr;
7153                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7154                 rtg_ext_ptr->format_type = 0x10;
7155                 rtg_ext_ptr->implicit_transition_time = 0;
7156                 tpg_desc = &rtg_ext_ptr->groups[0];
7157         } else {
7158                 rtg_ptr = (struct scsi_target_group_data *)
7159                     ctsio->kern_data_ptr;
7160                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7161                 tpg_desc = &rtg_ptr->groups[0];
7162         }
7163
7164         mtx_lock(&softc->ctl_lock);
7165         pg = softc->port_min / softc->port_cnt;
7166         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7167                 /* Some shelf is known to be primary. */
7168                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7169                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7170                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7171                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7172                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7173                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7174                 else
7175                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7176                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7177                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7178                 } else {
7179                         ts = os;
7180                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7181                 }
7182         } else {
7183                 /* No known primary shelf. */
7184                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7185                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7186                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7187                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7188                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7189                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7190                 } else {
7191                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7192                 }
7193         }
7194         if (shared_group) {
7195                 tpg_desc->pref_state = ts;
7196                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7197                     TPG_U_SUP | TPG_T_SUP;
7198                 scsi_ulto2b(1, tpg_desc->target_port_group);
7199                 tpg_desc->status = TPG_IMPLICIT;
7200                 pc = 0;
7201                 STAILQ_FOREACH(port, &softc->port_list, links) {
7202                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7203                                 continue;
7204                         if (!softc->is_single &&
7205                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7206                                 continue;
7207                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7208                                 continue;
7209                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7210                             relative_target_port_identifier);
7211                         pc++;
7212                 }
7213                 tpg_desc->target_port_count = pc;
7214                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7215                     &tpg_desc->descriptors[pc];
7216         }
7217         for (g = 0; g < num_ha_groups; g++) {
7218                 tpg_desc->pref_state = (g == pg) ? ts : os;
7219                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7220                     TPG_U_SUP | TPG_T_SUP;
7221                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7222                 tpg_desc->status = TPG_IMPLICIT;
7223                 pc = 0;
7224                 STAILQ_FOREACH(port, &softc->port_list, links) {
7225                         if (port->targ_port < g * softc->port_cnt ||
7226                             port->targ_port >= (g + 1) * softc->port_cnt)
7227                                 continue;
7228                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7229                                 continue;
7230                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7231                                 continue;
7232                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7233                                 continue;
7234                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7235                             relative_target_port_identifier);
7236                         pc++;
7237                 }
7238                 tpg_desc->target_port_count = pc;
7239                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7240                     &tpg_desc->descriptors[pc];
7241         }
7242         mtx_unlock(&softc->ctl_lock);
7243
7244         ctl_set_success(ctsio);
7245         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7246         ctsio->be_move_done = ctl_config_move_done;
7247         ctl_datamove((union ctl_io *)ctsio);
7248         return(retval);
7249 }
7250
7251 int
7252 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7253 {
7254         struct ctl_lun *lun = CTL_LUN(ctsio);
7255         struct scsi_report_supported_opcodes *cdb;
7256         const struct ctl_cmd_entry *entry, *sentry;
7257         struct scsi_report_supported_opcodes_all *all;
7258         struct scsi_report_supported_opcodes_descr *descr;
7259         struct scsi_report_supported_opcodes_one *one;
7260         int retval;
7261         int alloc_len, total_len;
7262         int opcode, service_action, i, j, num;
7263
7264         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7265
7266         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7267         retval = CTL_RETVAL_COMPLETE;
7268
7269         opcode = cdb->requested_opcode;
7270         service_action = scsi_2btoul(cdb->requested_service_action);
7271         switch (cdb->options & RSO_OPTIONS_MASK) {
7272         case RSO_OPTIONS_ALL:
7273                 num = 0;
7274                 for (i = 0; i < 256; i++) {
7275                         entry = &ctl_cmd_table[i];
7276                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7277                                 for (j = 0; j < 32; j++) {
7278                                         sentry = &((const struct ctl_cmd_entry *)
7279                                             entry->execute)[j];
7280                                         if (ctl_cmd_applicable(
7281                                             lun->be_lun->lun_type, sentry))
7282                                                 num++;
7283                                 }
7284                         } else {
7285                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7286                                     entry))
7287                                         num++;
7288                         }
7289                 }
7290                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7291                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7292                 break;
7293         case RSO_OPTIONS_OC:
7294                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7295                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7296                                               /*sks_valid*/ 1,
7297                                               /*command*/ 1,
7298                                               /*field*/ 2,
7299                                               /*bit_valid*/ 1,
7300                                               /*bit*/ 2);
7301                         ctl_done((union ctl_io *)ctsio);
7302                         return (CTL_RETVAL_COMPLETE);
7303                 }
7304                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7305                 break;
7306         case RSO_OPTIONS_OC_SA:
7307                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7308                     service_action >= 32) {
7309                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7310                                               /*sks_valid*/ 1,
7311                                               /*command*/ 1,
7312                                               /*field*/ 2,
7313                                               /*bit_valid*/ 1,
7314                                               /*bit*/ 2);
7315                         ctl_done((union ctl_io *)ctsio);
7316                         return (CTL_RETVAL_COMPLETE);
7317                 }
7318                 /* FALLTHROUGH */
7319         case RSO_OPTIONS_OC_ASA:
7320                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7321                 break;
7322         default:
7323                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7324                                       /*sks_valid*/ 1,
7325                                       /*command*/ 1,
7326                                       /*field*/ 2,
7327                                       /*bit_valid*/ 1,
7328                                       /*bit*/ 2);
7329                 ctl_done((union ctl_io *)ctsio);
7330                 return (CTL_RETVAL_COMPLETE);
7331         }
7332
7333         alloc_len = scsi_4btoul(cdb->length);
7334
7335         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7336
7337         ctsio->kern_sg_entries = 0;
7338
7339         if (total_len < alloc_len) {
7340                 ctsio->residual = alloc_len - total_len;
7341                 ctsio->kern_data_len = total_len;
7342                 ctsio->kern_total_len = total_len;
7343         } else {
7344                 ctsio->residual = 0;
7345                 ctsio->kern_data_len = alloc_len;
7346                 ctsio->kern_total_len = alloc_len;
7347         }
7348         ctsio->kern_data_resid = 0;
7349         ctsio->kern_rel_offset = 0;
7350
7351         switch (cdb->options & RSO_OPTIONS_MASK) {
7352         case RSO_OPTIONS_ALL:
7353                 all = (struct scsi_report_supported_opcodes_all *)
7354                     ctsio->kern_data_ptr;
7355                 num = 0;
7356                 for (i = 0; i < 256; i++) {
7357                         entry = &ctl_cmd_table[i];
7358                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7359                                 for (j = 0; j < 32; j++) {
7360                                         sentry = &((const struct ctl_cmd_entry *)
7361                                             entry->execute)[j];
7362                                         if (!ctl_cmd_applicable(
7363                                             lun->be_lun->lun_type, sentry))
7364                                                 continue;
7365                                         descr = &all->descr[num++];
7366                                         descr->opcode = i;
7367                                         scsi_ulto2b(j, descr->service_action);
7368                                         descr->flags = RSO_SERVACTV;
7369                                         scsi_ulto2b(sentry->length,
7370                                             descr->cdb_length);
7371                                 }
7372                         } else {
7373                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7374                                     entry))
7375                                         continue;
7376                                 descr = &all->descr[num++];
7377                                 descr->opcode = i;
7378                                 scsi_ulto2b(0, descr->service_action);
7379                                 descr->flags = 0;
7380                                 scsi_ulto2b(entry->length, descr->cdb_length);
7381                         }
7382                 }
7383                 scsi_ulto4b(
7384                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7385                     all->length);
7386                 break;
7387         case RSO_OPTIONS_OC:
7388                 one = (struct scsi_report_supported_opcodes_one *)
7389                     ctsio->kern_data_ptr;
7390                 entry = &ctl_cmd_table[opcode];
7391                 goto fill_one;
7392         case RSO_OPTIONS_OC_SA:
7393                 one = (struct scsi_report_supported_opcodes_one *)
7394                     ctsio->kern_data_ptr;
7395                 entry = &ctl_cmd_table[opcode];
7396                 entry = &((const struct ctl_cmd_entry *)
7397                     entry->execute)[service_action];
7398 fill_one:
7399                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7400                         one->support = 3;
7401                         scsi_ulto2b(entry->length, one->cdb_length);
7402                         one->cdb_usage[0] = opcode;
7403                         memcpy(&one->cdb_usage[1], entry->usage,
7404                             entry->length - 1);
7405                 } else
7406                         one->support = 1;
7407                 break;
7408         case RSO_OPTIONS_OC_ASA:
7409                 one = (struct scsi_report_supported_opcodes_one *)
7410                     ctsio->kern_data_ptr;
7411                 entry = &ctl_cmd_table[opcode];
7412                 if (entry->flags & CTL_CMD_FLAG_SA5) {
7413                         entry = &((const struct ctl_cmd_entry *)
7414                             entry->execute)[service_action];
7415                 } else if (service_action != 0) {
7416                         one->support = 1;
7417                         break;
7418                 }
7419                 goto fill_one;
7420         }
7421
7422         ctl_set_success(ctsio);
7423         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7424         ctsio->be_move_done = ctl_config_move_done;
7425         ctl_datamove((union ctl_io *)ctsio);
7426         return(retval);
7427 }
7428
7429 int
7430 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7431 {
7432         struct scsi_report_supported_tmf *cdb;
7433         struct scsi_report_supported_tmf_ext_data *data;
7434         int retval;
7435         int alloc_len, total_len;
7436
7437         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7438
7439         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7440
7441         retval = CTL_RETVAL_COMPLETE;
7442
7443         if (cdb->options & RST_REPD)
7444                 total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7445         else
7446                 total_len = sizeof(struct scsi_report_supported_tmf_data);
7447         alloc_len = scsi_4btoul(cdb->length);
7448
7449         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7450
7451         ctsio->kern_sg_entries = 0;
7452
7453         if (total_len < alloc_len) {
7454                 ctsio->residual = alloc_len - total_len;
7455                 ctsio->kern_data_len = total_len;
7456                 ctsio->kern_total_len = total_len;
7457         } else {
7458                 ctsio->residual = 0;
7459                 ctsio->kern_data_len = alloc_len;
7460                 ctsio->kern_total_len = alloc_len;
7461         }
7462         ctsio->kern_data_resid = 0;
7463         ctsio->kern_rel_offset = 0;
7464
7465         data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7466         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7467             RST_TRS;
7468         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7469         data->length = total_len - 4;
7470
7471         ctl_set_success(ctsio);
7472         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7473         ctsio->be_move_done = ctl_config_move_done;
7474         ctl_datamove((union ctl_io *)ctsio);
7475         return (retval);
7476 }
7477
7478 int
7479 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7480 {
7481         struct scsi_report_timestamp *cdb;
7482         struct scsi_report_timestamp_data *data;
7483         struct timeval tv;
7484         int64_t timestamp;
7485         int retval;
7486         int alloc_len, total_len;
7487
7488         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7489
7490         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7491
7492         retval = CTL_RETVAL_COMPLETE;
7493
7494         total_len = sizeof(struct scsi_report_timestamp_data);
7495         alloc_len = scsi_4btoul(cdb->length);
7496
7497         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7498
7499         ctsio->kern_sg_entries = 0;
7500
7501         if (total_len < alloc_len) {
7502                 ctsio->residual = alloc_len - total_len;
7503                 ctsio->kern_data_len = total_len;
7504                 ctsio->kern_total_len = total_len;
7505         } else {
7506                 ctsio->residual = 0;
7507                 ctsio->kern_data_len = alloc_len;
7508                 ctsio->kern_total_len = alloc_len;
7509         }
7510         ctsio->kern_data_resid = 0;
7511         ctsio->kern_rel_offset = 0;
7512
7513         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7514         scsi_ulto2b(sizeof(*data) - 2, data->length);
7515         data->origin = RTS_ORIG_OUTSIDE;
7516         getmicrotime(&tv);
7517         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7518         scsi_ulto4b(timestamp >> 16, data->timestamp);
7519         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7520
7521         ctl_set_success(ctsio);
7522         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7523         ctsio->be_move_done = ctl_config_move_done;
7524         ctl_datamove((union ctl_io *)ctsio);
7525         return (retval);
7526 }
7527
7528 int
7529 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7530 {
7531         struct ctl_softc *softc = CTL_SOFTC(ctsio);
7532         struct ctl_lun *lun = CTL_LUN(ctsio);
7533         struct scsi_per_res_in *cdb;
7534         int alloc_len, total_len = 0;
7535         /* struct scsi_per_res_in_rsrv in_data; */
7536         uint64_t key;
7537
7538         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7539
7540         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7541
7542         alloc_len = scsi_2btoul(cdb->length);
7543
7544 retry:
7545         mtx_lock(&lun->lun_lock);
7546         switch (cdb->action) {
7547         case SPRI_RK: /* read keys */
7548                 total_len = sizeof(struct scsi_per_res_in_keys) +
7549                         lun->pr_key_count *
7550                         sizeof(struct scsi_per_res_key);
7551                 break;
7552         case SPRI_RR: /* read reservation */
7553                 if (lun->flags & CTL_LUN_PR_RESERVED)
7554                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7555                 else
7556                         total_len = sizeof(struct scsi_per_res_in_header);
7557                 break;
7558         case SPRI_RC: /* report capabilities */
7559                 total_len = sizeof(struct scsi_per_res_cap);
7560                 break;
7561         case SPRI_RS: /* read full status */
7562                 total_len = sizeof(struct scsi_per_res_in_header) +
7563                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7564                     lun->pr_key_count;
7565                 break;
7566         default:
7567                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7568         }
7569         mtx_unlock(&lun->lun_lock);
7570
7571         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7572
7573         if (total_len < alloc_len) {
7574                 ctsio->residual = alloc_len - total_len;
7575                 ctsio->kern_data_len = total_len;
7576                 ctsio->kern_total_len = total_len;
7577         } else {
7578                 ctsio->residual = 0;
7579                 ctsio->kern_data_len = alloc_len;
7580                 ctsio->kern_total_len = alloc_len;
7581         }
7582
7583         ctsio->kern_data_resid = 0;
7584         ctsio->kern_rel_offset = 0;
7585         ctsio->kern_sg_entries = 0;
7586
7587         mtx_lock(&lun->lun_lock);
7588         switch (cdb->action) {
7589         case SPRI_RK: { // read keys
7590         struct scsi_per_res_in_keys *res_keys;
7591                 int i, key_count;
7592
7593                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7594
7595                 /*
7596                  * We had to drop the lock to allocate our buffer, which
7597                  * leaves time for someone to come in with another
7598                  * persistent reservation.  (That is unlikely, though,
7599                  * since this should be the only persistent reservation
7600                  * command active right now.)
7601                  */
7602                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7603                     (lun->pr_key_count *
7604                      sizeof(struct scsi_per_res_key)))){
7605                         mtx_unlock(&lun->lun_lock);
7606                         free(ctsio->kern_data_ptr, M_CTL);
7607                         printf("%s: reservation length changed, retrying\n",
7608                                __func__);
7609                         goto retry;
7610                 }
7611
7612                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7613
7614                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7615                              lun->pr_key_count, res_keys->header.length);
7616
7617                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7618                         if ((key = ctl_get_prkey(lun, i)) == 0)
7619                                 continue;
7620
7621                         /*
7622                          * We used lun->pr_key_count to calculate the
7623                          * size to allocate.  If it turns out the number of
7624                          * initiators with the registered flag set is
7625                          * larger than that (i.e. they haven't been kept in
7626                          * sync), we've got a problem.
7627                          */
7628                         if (key_count >= lun->pr_key_count) {
7629                                 key_count++;
7630                                 continue;
7631                         }
7632                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7633                         key_count++;
7634                 }
7635                 break;
7636         }
7637         case SPRI_RR: { // read reservation
7638                 struct scsi_per_res_in_rsrv *res;
7639                 int tmp_len, header_only;
7640
7641                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7642
7643                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7644
7645                 if (lun->flags & CTL_LUN_PR_RESERVED)
7646                 {
7647                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7648                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7649                                     res->header.length);
7650                         header_only = 0;
7651                 } else {
7652                         tmp_len = sizeof(struct scsi_per_res_in_header);
7653                         scsi_ulto4b(0, res->header.length);
7654                         header_only = 1;
7655                 }
7656
7657                 /*
7658                  * We had to drop the lock to allocate our buffer, which
7659                  * leaves time for someone to come in with another
7660                  * persistent reservation.  (That is unlikely, though,
7661                  * since this should be the only persistent reservation
7662                  * command active right now.)
7663                  */
7664                 if (tmp_len != total_len) {
7665                         mtx_unlock(&lun->lun_lock);
7666                         free(ctsio->kern_data_ptr, M_CTL);
7667                         printf("%s: reservation status changed, retrying\n",
7668                                __func__);
7669                         goto retry;
7670                 }
7671
7672                 /*
7673                  * No reservation held, so we're done.
7674                  */
7675                 if (header_only != 0)
7676                         break;
7677
7678                 /*
7679                  * If the registration is an All Registrants type, the key
7680                  * is 0, since it doesn't really matter.
7681                  */
7682                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7683                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7684                             res->data.reservation);
7685                 }
7686                 res->data.scopetype = lun->pr_res_type;
7687                 break;
7688         }
7689         case SPRI_RC:     //report capabilities
7690         {
7691                 struct scsi_per_res_cap *res_cap;
7692                 uint16_t type_mask;
7693
7694                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7695                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7696                 res_cap->flags1 = SPRI_CRH;
7697                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7698                 type_mask = SPRI_TM_WR_EX_AR |
7699                             SPRI_TM_EX_AC_RO |
7700                             SPRI_TM_WR_EX_RO |
7701                             SPRI_TM_EX_AC |
7702                             SPRI_TM_WR_EX |
7703                             SPRI_TM_EX_AC_AR;
7704                 scsi_ulto2b(type_mask, res_cap->type_mask);
7705                 break;
7706         }
7707         case SPRI_RS: { // read full status
7708                 struct scsi_per_res_in_full *res_status;
7709                 struct scsi_per_res_in_full_desc *res_desc;
7710                 struct ctl_port *port;
7711                 int i, len;
7712
7713                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7714
7715                 /*
7716                  * We had to drop the lock to allocate our buffer, which
7717                  * leaves time for someone to come in with another
7718                  * persistent reservation.  (That is unlikely, though,
7719                  * since this should be the only persistent reservation
7720                  * command active right now.)
7721                  */
7722                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7723                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7724                      lun->pr_key_count)){
7725                         mtx_unlock(&lun->lun_lock);
7726                         free(ctsio->kern_data_ptr, M_CTL);
7727                         printf("%s: reservation length changed, retrying\n",
7728                                __func__);
7729                         goto retry;
7730                 }
7731
7732                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7733
7734                 res_desc = &res_status->desc[0];
7735                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7736                         if ((key = ctl_get_prkey(lun, i)) == 0)
7737                                 continue;
7738
7739                         scsi_u64to8b(key, res_desc->res_key.key);
7740                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7741                             (lun->pr_res_idx == i ||
7742                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7743                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7744                                 res_desc->scopetype = lun->pr_res_type;
7745                         }
7746                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7747                             res_desc->rel_trgt_port_id);
7748                         len = 0;
7749                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7750                         if (port != NULL)
7751                                 len = ctl_create_iid(port,
7752                                     i % CTL_MAX_INIT_PER_PORT,
7753                                     res_desc->transport_id);
7754                         scsi_ulto4b(len, res_desc->additional_length);
7755                         res_desc = (struct scsi_per_res_in_full_desc *)
7756                             &res_desc->transport_id[len];
7757                 }
7758                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7759                     res_status->header.length);
7760                 break;
7761         }
7762         default:
7763                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7764         }
7765         mtx_unlock(&lun->lun_lock);
7766
7767         ctl_set_success(ctsio);
7768         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7769         ctsio->be_move_done = ctl_config_move_done;
7770         ctl_datamove((union ctl_io *)ctsio);
7771         return (CTL_RETVAL_COMPLETE);
7772 }
7773
7774 /*
7775  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7776  * it should return.
7777  */
7778 static int
7779 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7780                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7781                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7782                 struct scsi_per_res_out_parms* param)
7783 {
7784         union ctl_ha_msg persis_io;
7785         int i;
7786
7787         mtx_lock(&lun->lun_lock);
7788         if (sa_res_key == 0) {
7789                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7790                         /* validate scope and type */
7791                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7792                              SPR_LU_SCOPE) {
7793                                 mtx_unlock(&lun->lun_lock);
7794                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7795                                                       /*sks_valid*/ 1,
7796                                                       /*command*/ 1,
7797                                                       /*field*/ 2,
7798                                                       /*bit_valid*/ 1,
7799                                                       /*bit*/ 4);
7800                                 ctl_done((union ctl_io *)ctsio);
7801                                 return (1);
7802                         }
7803
7804                         if (type>8 || type==2 || type==4 || type==0) {
7805                                 mtx_unlock(&lun->lun_lock);
7806                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7807                                                       /*sks_valid*/ 1,
7808                                                       /*command*/ 1,
7809                                                       /*field*/ 2,
7810                                                       /*bit_valid*/ 1,
7811                                                       /*bit*/ 0);
7812                                 ctl_done((union ctl_io *)ctsio);
7813                                 return (1);
7814                         }
7815
7816                         /*
7817                          * Unregister everybody else and build UA for
7818                          * them
7819                          */
7820                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7821                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7822                                         continue;
7823
7824                                 ctl_clr_prkey(lun, i);
7825                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7826                         }
7827                         lun->pr_key_count = 1;
7828                         lun->pr_res_type = type;
7829                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7830                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7831                                 lun->pr_res_idx = residx;
7832                         lun->pr_generation++;
7833                         mtx_unlock(&lun->lun_lock);
7834
7835                         /* send msg to other side */
7836                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7837                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7838                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7839                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7840                         persis_io.pr.pr_info.res_type = type;
7841                         memcpy(persis_io.pr.pr_info.sa_res_key,
7842                                param->serv_act_res_key,
7843                                sizeof(param->serv_act_res_key));
7844                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7845                             sizeof(persis_io.pr), M_WAITOK);
7846                 } else {
7847                         /* not all registrants */
7848                         mtx_unlock(&lun->lun_lock);
7849                         free(ctsio->kern_data_ptr, M_CTL);
7850                         ctl_set_invalid_field(ctsio,
7851                                               /*sks_valid*/ 1,
7852                                               /*command*/ 0,
7853                                               /*field*/ 8,
7854                                               /*bit_valid*/ 0,
7855                                               /*bit*/ 0);
7856                         ctl_done((union ctl_io *)ctsio);
7857                         return (1);
7858                 }
7859         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7860                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7861                 int found = 0;
7862
7863                 if (res_key == sa_res_key) {
7864                         /* special case */
7865                         /*
7866                          * The spec implies this is not good but doesn't
7867                          * say what to do. There are two choices either
7868                          * generate a res conflict or check condition
7869                          * with illegal field in parameter data. Since
7870                          * that is what is done when the sa_res_key is
7871                          * zero I'll take that approach since this has
7872                          * to do with the sa_res_key.
7873                          */
7874                         mtx_unlock(&lun->lun_lock);
7875                         free(ctsio->kern_data_ptr, M_CTL);
7876                         ctl_set_invalid_field(ctsio,
7877                                               /*sks_valid*/ 1,
7878                                               /*command*/ 0,
7879                                               /*field*/ 8,
7880                                               /*bit_valid*/ 0,
7881                                               /*bit*/ 0);
7882                         ctl_done((union ctl_io *)ctsio);
7883                         return (1);
7884                 }
7885
7886                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7887                         if (ctl_get_prkey(lun, i) != sa_res_key)
7888                                 continue;
7889
7890                         found = 1;
7891                         ctl_clr_prkey(lun, i);
7892                         lun->pr_key_count--;
7893                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7894                 }
7895                 if (!found) {
7896                         mtx_unlock(&lun->lun_lock);
7897                         free(ctsio->kern_data_ptr, M_CTL);
7898                         ctl_set_reservation_conflict(ctsio);
7899                         ctl_done((union ctl_io *)ctsio);
7900                         return (CTL_RETVAL_COMPLETE);
7901                 }
7902                 lun->pr_generation++;
7903                 mtx_unlock(&lun->lun_lock);
7904
7905                 /* send msg to other side */
7906                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7907                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7908                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7909                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7910                 persis_io.pr.pr_info.res_type = type;
7911                 memcpy(persis_io.pr.pr_info.sa_res_key,
7912                        param->serv_act_res_key,
7913                        sizeof(param->serv_act_res_key));
7914                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7915                     sizeof(persis_io.pr), M_WAITOK);
7916         } else {
7917                 /* Reserved but not all registrants */
7918                 /* sa_res_key is res holder */
7919                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7920                         /* validate scope and type */
7921                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7922                              SPR_LU_SCOPE) {
7923                                 mtx_unlock(&lun->lun_lock);
7924                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7925                                                       /*sks_valid*/ 1,
7926                                                       /*command*/ 1,
7927                                                       /*field*/ 2,
7928                                                       /*bit_valid*/ 1,
7929                                                       /*bit*/ 4);
7930                                 ctl_done((union ctl_io *)ctsio);
7931                                 return (1);
7932                         }
7933
7934                         if (type>8 || type==2 || type==4 || type==0) {
7935                                 mtx_unlock(&lun->lun_lock);
7936                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7937                                                       /*sks_valid*/ 1,
7938                                                       /*command*/ 1,
7939                                                       /*field*/ 2,
7940                                                       /*bit_valid*/ 1,
7941                                                       /*bit*/ 0);
7942                                 ctl_done((union ctl_io *)ctsio);
7943                                 return (1);
7944                         }
7945
7946                         /*
7947                          * Do the following:
7948                          * if sa_res_key != res_key remove all
7949                          * registrants w/sa_res_key and generate UA
7950                          * for these registrants(Registrations
7951                          * Preempted) if it wasn't an exclusive
7952                          * reservation generate UA(Reservations
7953                          * Preempted) for all other registered nexuses
7954                          * if the type has changed. Establish the new
7955                          * reservation and holder. If res_key and
7956                          * sa_res_key are the same do the above
7957                          * except don't unregister the res holder.
7958                          */
7959
7960                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7961                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7962                                         continue;
7963
7964                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7965                                         ctl_clr_prkey(lun, i);
7966                                         lun->pr_key_count--;
7967                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7968                                 } else if (type != lun->pr_res_type &&
7969                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7970                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7971                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7972                                 }
7973                         }
7974                         lun->pr_res_type = type;
7975                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7976                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7977                                 lun->pr_res_idx = residx;
7978                         else
7979                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7980                         lun->pr_generation++;
7981                         mtx_unlock(&lun->lun_lock);
7982
7983                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7984                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7985                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7986                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7987                         persis_io.pr.pr_info.res_type = type;
7988                         memcpy(persis_io.pr.pr_info.sa_res_key,
7989                                param->serv_act_res_key,
7990                                sizeof(param->serv_act_res_key));
7991                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7992                             sizeof(persis_io.pr), M_WAITOK);
7993                 } else {
7994                         /*
7995                          * sa_res_key is not the res holder just
7996                          * remove registrants
7997                          */
7998                         int found=0;
7999
8000                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8001                                 if (sa_res_key != ctl_get_prkey(lun, i))
8002                                         continue;
8003
8004                                 found = 1;
8005                                 ctl_clr_prkey(lun, i);
8006                                 lun->pr_key_count--;
8007                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8008                         }
8009
8010                         if (!found) {
8011                                 mtx_unlock(&lun->lun_lock);
8012                                 free(ctsio->kern_data_ptr, M_CTL);
8013                                 ctl_set_reservation_conflict(ctsio);
8014                                 ctl_done((union ctl_io *)ctsio);
8015                                 return (1);
8016                         }
8017                         lun->pr_generation++;
8018                         mtx_unlock(&lun->lun_lock);
8019
8020                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8021                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8022                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8023                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8024                         persis_io.pr.pr_info.res_type = type;
8025                         memcpy(persis_io.pr.pr_info.sa_res_key,
8026                                param->serv_act_res_key,
8027                                sizeof(param->serv_act_res_key));
8028                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8029                             sizeof(persis_io.pr), M_WAITOK);
8030                 }
8031         }
8032         return (0);
8033 }
8034
8035 static void
8036 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8037 {
8038         uint64_t sa_res_key;
8039         int i;
8040
8041         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8042
8043         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8044          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8045          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8046                 if (sa_res_key == 0) {
8047                         /*
8048                          * Unregister everybody else and build UA for
8049                          * them
8050                          */
8051                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8052                                 if (i == msg->pr.pr_info.residx ||
8053                                     ctl_get_prkey(lun, i) == 0)
8054                                         continue;
8055
8056                                 ctl_clr_prkey(lun, i);
8057                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8058                         }
8059
8060                         lun->pr_key_count = 1;
8061                         lun->pr_res_type = msg->pr.pr_info.res_type;
8062                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8063                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8064                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8065                 } else {
8066                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8067                                 if (sa_res_key == ctl_get_prkey(lun, i))
8068                                         continue;
8069
8070                                 ctl_clr_prkey(lun, i);
8071                                 lun->pr_key_count--;
8072                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8073                         }
8074                 }
8075         } else {
8076                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8077                         if (i == msg->pr.pr_info.residx ||
8078                             ctl_get_prkey(lun, i) == 0)
8079                                 continue;
8080
8081                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8082                                 ctl_clr_prkey(lun, i);
8083                                 lun->pr_key_count--;
8084                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8085                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8086                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8087                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8088                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8089                         }
8090                 }
8091                 lun->pr_res_type = msg->pr.pr_info.res_type;
8092                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8093                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8094                         lun->pr_res_idx = msg->pr.pr_info.residx;
8095                 else
8096                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8097         }
8098         lun->pr_generation++;
8099
8100 }
8101
8102
8103 int
8104 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8105 {
8106         struct ctl_softc *softc = CTL_SOFTC(ctsio);
8107         struct ctl_lun *lun = CTL_LUN(ctsio);
8108         int retval;
8109         u_int32_t param_len;
8110         struct scsi_per_res_out *cdb;
8111         struct scsi_per_res_out_parms* param;
8112         uint32_t residx;
8113         uint64_t res_key, sa_res_key, key;
8114         uint8_t type;
8115         union ctl_ha_msg persis_io;
8116         int    i;
8117
8118         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8119
8120         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8121         retval = CTL_RETVAL_COMPLETE;
8122
8123         /*
8124          * We only support whole-LUN scope.  The scope & type are ignored for
8125          * register, register and ignore existing key and clear.
8126          * We sometimes ignore scope and type on preempts too!!
8127          * Verify reservation type here as well.
8128          */
8129         type = cdb->scope_type & SPR_TYPE_MASK;
8130         if ((cdb->action == SPRO_RESERVE)
8131          || (cdb->action == SPRO_RELEASE)) {
8132                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8133                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8134                                               /*sks_valid*/ 1,
8135                                               /*command*/ 1,
8136                                               /*field*/ 2,
8137                                               /*bit_valid*/ 1,
8138                                               /*bit*/ 4);
8139                         ctl_done((union ctl_io *)ctsio);
8140                         return (CTL_RETVAL_COMPLETE);
8141                 }
8142
8143                 if (type>8 || type==2 || type==4 || type==0) {
8144                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8145                                               /*sks_valid*/ 1,
8146                                               /*command*/ 1,
8147                                               /*field*/ 2,
8148                                               /*bit_valid*/ 1,
8149                                               /*bit*/ 0);
8150                         ctl_done((union ctl_io *)ctsio);
8151                         return (CTL_RETVAL_COMPLETE);
8152                 }
8153         }
8154
8155         param_len = scsi_4btoul(cdb->length);
8156
8157         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8158                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8159                 ctsio->kern_data_len = param_len;
8160                 ctsio->kern_total_len = param_len;
8161                 ctsio->kern_data_resid = 0;
8162                 ctsio->kern_rel_offset = 0;
8163                 ctsio->kern_sg_entries = 0;
8164                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8165                 ctsio->be_move_done = ctl_config_move_done;
8166                 ctl_datamove((union ctl_io *)ctsio);
8167
8168                 return (CTL_RETVAL_COMPLETE);
8169         }
8170
8171         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8172
8173         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8174         res_key = scsi_8btou64(param->res_key.key);
8175         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8176
8177         /*
8178          * Validate the reservation key here except for SPRO_REG_IGNO
8179          * This must be done for all other service actions
8180          */
8181         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8182                 mtx_lock(&lun->lun_lock);
8183                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8184                         if (res_key != key) {
8185                                 /*
8186                                  * The current key passed in doesn't match
8187                                  * the one the initiator previously
8188                                  * registered.
8189                                  */
8190                                 mtx_unlock(&lun->lun_lock);
8191                                 free(ctsio->kern_data_ptr, M_CTL);
8192                                 ctl_set_reservation_conflict(ctsio);
8193                                 ctl_done((union ctl_io *)ctsio);
8194                                 return (CTL_RETVAL_COMPLETE);
8195                         }
8196                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8197                         /*
8198                          * We are not registered
8199                          */
8200                         mtx_unlock(&lun->lun_lock);
8201                         free(ctsio->kern_data_ptr, M_CTL);
8202                         ctl_set_reservation_conflict(ctsio);
8203                         ctl_done((union ctl_io *)ctsio);
8204                         return (CTL_RETVAL_COMPLETE);
8205                 } else if (res_key != 0) {
8206                         /*
8207                          * We are not registered and trying to register but
8208                          * the register key isn't zero.
8209                          */
8210                         mtx_unlock(&lun->lun_lock);
8211                         free(ctsio->kern_data_ptr, M_CTL);
8212                         ctl_set_reservation_conflict(ctsio);
8213                         ctl_done((union ctl_io *)ctsio);
8214                         return (CTL_RETVAL_COMPLETE);
8215                 }
8216                 mtx_unlock(&lun->lun_lock);
8217         }
8218
8219         switch (cdb->action & SPRO_ACTION_MASK) {
8220         case SPRO_REGISTER:
8221         case SPRO_REG_IGNO: {
8222
8223 #if 0
8224                 printf("Registration received\n");
8225 #endif
8226
8227                 /*
8228                  * We don't support any of these options, as we report in
8229                  * the read capabilities request (see
8230                  * ctl_persistent_reserve_in(), above).
8231                  */
8232                 if ((param->flags & SPR_SPEC_I_PT)
8233                  || (param->flags & SPR_ALL_TG_PT)
8234                  || (param->flags & SPR_APTPL)) {
8235                         int bit_ptr;
8236
8237                         if (param->flags & SPR_APTPL)
8238                                 bit_ptr = 0;
8239                         else if (param->flags & SPR_ALL_TG_PT)
8240                                 bit_ptr = 2;
8241                         else /* SPR_SPEC_I_PT */
8242                                 bit_ptr = 3;
8243
8244                         free(ctsio->kern_data_ptr, M_CTL);
8245                         ctl_set_invalid_field(ctsio,
8246                                               /*sks_valid*/ 1,
8247                                               /*command*/ 0,
8248                                               /*field*/ 20,
8249                                               /*bit_valid*/ 1,
8250                                               /*bit*/ bit_ptr);
8251                         ctl_done((union ctl_io *)ctsio);
8252                         return (CTL_RETVAL_COMPLETE);
8253                 }
8254
8255                 mtx_lock(&lun->lun_lock);
8256
8257                 /*
8258                  * The initiator wants to clear the
8259                  * key/unregister.
8260                  */
8261                 if (sa_res_key == 0) {
8262                         if ((res_key == 0
8263                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8264                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8265                           && ctl_get_prkey(lun, residx) == 0)) {
8266                                 mtx_unlock(&lun->lun_lock);
8267                                 goto done;
8268                         }
8269
8270                         ctl_clr_prkey(lun, residx);
8271                         lun->pr_key_count--;
8272
8273                         if (residx == lun->pr_res_idx) {
8274                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8275                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8276
8277                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8278                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8279                                     lun->pr_key_count) {
8280                                         /*
8281                                          * If the reservation is a registrants
8282                                          * only type we need to generate a UA
8283                                          * for other registered inits.  The
8284                                          * sense code should be RESERVATIONS
8285                                          * RELEASED
8286                                          */
8287
8288                                         for (i = softc->init_min; i < softc->init_max; i++){
8289                                                 if (ctl_get_prkey(lun, i) == 0)
8290                                                         continue;
8291                                                 ctl_est_ua(lun, i,
8292                                                     CTL_UA_RES_RELEASE);
8293                                         }
8294                                 }
8295                                 lun->pr_res_type = 0;
8296                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8297                                 if (lun->pr_key_count==0) {
8298                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8299                                         lun->pr_res_type = 0;
8300                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8301                                 }
8302                         }
8303                         lun->pr_generation++;
8304                         mtx_unlock(&lun->lun_lock);
8305
8306                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8307                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8308                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8309                         persis_io.pr.pr_info.residx = residx;
8310                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8311                             sizeof(persis_io.pr), M_WAITOK);
8312                 } else /* sa_res_key != 0 */ {
8313
8314                         /*
8315                          * If we aren't registered currently then increment
8316                          * the key count and set the registered flag.
8317                          */
8318                         ctl_alloc_prkey(lun, residx);
8319                         if (ctl_get_prkey(lun, residx) == 0)
8320                                 lun->pr_key_count++;
8321                         ctl_set_prkey(lun, residx, sa_res_key);
8322                         lun->pr_generation++;
8323                         mtx_unlock(&lun->lun_lock);
8324
8325                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8326                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8327                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8328                         persis_io.pr.pr_info.residx = residx;
8329                         memcpy(persis_io.pr.pr_info.sa_res_key,
8330                                param->serv_act_res_key,
8331                                sizeof(param->serv_act_res_key));
8332                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8333                             sizeof(persis_io.pr), M_WAITOK);
8334                 }
8335
8336                 break;
8337         }
8338         case SPRO_RESERVE:
8339 #if 0
8340                 printf("Reserve executed type %d\n", type);
8341 #endif
8342                 mtx_lock(&lun->lun_lock);
8343                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8344                         /*
8345                          * if this isn't the reservation holder and it's
8346                          * not a "all registrants" type or if the type is
8347                          * different then we have a conflict
8348                          */
8349                         if ((lun->pr_res_idx != residx
8350                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8351                          || lun->pr_res_type != type) {
8352                                 mtx_unlock(&lun->lun_lock);
8353                                 free(ctsio->kern_data_ptr, M_CTL);
8354                                 ctl_set_reservation_conflict(ctsio);
8355                                 ctl_done((union ctl_io *)ctsio);
8356                                 return (CTL_RETVAL_COMPLETE);
8357                         }
8358                         mtx_unlock(&lun->lun_lock);
8359                 } else /* create a reservation */ {
8360                         /*
8361                          * If it's not an "all registrants" type record
8362                          * reservation holder
8363                          */
8364                         if (type != SPR_TYPE_WR_EX_AR
8365                          && type != SPR_TYPE_EX_AC_AR)
8366                                 lun->pr_res_idx = residx; /* Res holder */
8367                         else
8368                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8369
8370                         lun->flags |= CTL_LUN_PR_RESERVED;
8371                         lun->pr_res_type = type;
8372
8373                         mtx_unlock(&lun->lun_lock);
8374
8375                         /* send msg to other side */
8376                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8377                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8378                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8379                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8380                         persis_io.pr.pr_info.res_type = type;
8381                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8382                             sizeof(persis_io.pr), M_WAITOK);
8383                 }
8384                 break;
8385
8386         case SPRO_RELEASE:
8387                 mtx_lock(&lun->lun_lock);
8388                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8389                         /* No reservation exists return good status */
8390                         mtx_unlock(&lun->lun_lock);
8391                         goto done;
8392                 }
8393                 /*
8394                  * Is this nexus a reservation holder?
8395                  */
8396                 if (lun->pr_res_idx != residx
8397                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8398                         /*
8399                          * not a res holder return good status but
8400                          * do nothing
8401                          */
8402                         mtx_unlock(&lun->lun_lock);
8403                         goto done;
8404                 }
8405
8406                 if (lun->pr_res_type != type) {
8407                         mtx_unlock(&lun->lun_lock);
8408                         free(ctsio->kern_data_ptr, M_CTL);
8409                         ctl_set_illegal_pr_release(ctsio);
8410                         ctl_done((union ctl_io *)ctsio);
8411                         return (CTL_RETVAL_COMPLETE);
8412                 }
8413
8414                 /* okay to release */
8415                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8416                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8417                 lun->pr_res_type = 0;
8418
8419                 /*
8420                  * If this isn't an exclusive access reservation and NUAR
8421                  * is not set, generate UA for all other registrants.
8422                  */
8423                 if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8424                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8425                         for (i = softc->init_min; i < softc->init_max; i++) {
8426                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8427                                         continue;
8428                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8429                         }
8430                 }
8431                 mtx_unlock(&lun->lun_lock);
8432
8433                 /* Send msg to other side */
8434                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8435                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8436                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8437                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8438                      sizeof(persis_io.pr), M_WAITOK);
8439                 break;
8440
8441         case SPRO_CLEAR:
8442                 /* send msg to other side */
8443
8444                 mtx_lock(&lun->lun_lock);
8445                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8446                 lun->pr_res_type = 0;
8447                 lun->pr_key_count = 0;
8448                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8449
8450                 ctl_clr_prkey(lun, residx);
8451                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8452                         if (ctl_get_prkey(lun, i) != 0) {
8453                                 ctl_clr_prkey(lun, i);
8454                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8455                         }
8456                 lun->pr_generation++;
8457                 mtx_unlock(&lun->lun_lock);
8458
8459                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8460                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8461                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8462                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8463                      sizeof(persis_io.pr), M_WAITOK);
8464                 break;
8465
8466         case SPRO_PREEMPT:
8467         case SPRO_PRE_ABO: {
8468                 int nretval;
8469
8470                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8471                                           residx, ctsio, cdb, param);
8472                 if (nretval != 0)
8473                         return (CTL_RETVAL_COMPLETE);
8474                 break;
8475         }
8476         default:
8477                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8478         }
8479
8480 done:
8481         free(ctsio->kern_data_ptr, M_CTL);
8482         ctl_set_success(ctsio);
8483         ctl_done((union ctl_io *)ctsio);
8484
8485         return (retval);
8486 }
8487
8488 /*
8489  * This routine is for handling a message from the other SC pertaining to
8490  * persistent reserve out. All the error checking will have been done
8491  * so only perorming the action need be done here to keep the two
8492  * in sync.
8493  */
8494 static void
8495 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8496 {
8497         struct ctl_softc *softc = CTL_SOFTC(io);
8498         union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8499         struct ctl_lun *lun;
8500         int i;
8501         uint32_t residx, targ_lun;
8502
8503         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8504         mtx_lock(&softc->ctl_lock);
8505         if (targ_lun >= CTL_MAX_LUNS ||
8506             (lun = softc->ctl_luns[targ_lun]) == NULL) {
8507                 mtx_unlock(&softc->ctl_lock);
8508                 return;
8509         }
8510         mtx_lock(&lun->lun_lock);
8511         mtx_unlock(&softc->ctl_lock);
8512         if (lun->flags & CTL_LUN_DISABLED) {
8513                 mtx_unlock(&lun->lun_lock);
8514                 return;
8515         }
8516         residx = ctl_get_initindex(&msg->hdr.nexus);
8517         switch(msg->pr.pr_info.action) {
8518         case CTL_PR_REG_KEY:
8519                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8520                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8521                         lun->pr_key_count++;
8522                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8523                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8524                 lun->pr_generation++;
8525                 break;
8526
8527         case CTL_PR_UNREG_KEY:
8528                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8529                 lun->pr_key_count--;
8530
8531                 /* XXX Need to see if the reservation has been released */
8532                 /* if so do we need to generate UA? */
8533                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8534                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8535                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8536
8537                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8538                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8539                             lun->pr_key_count) {
8540                                 /*
8541                                  * If the reservation is a registrants
8542                                  * only type we need to generate a UA
8543                                  * for other registered inits.  The
8544                                  * sense code should be RESERVATIONS
8545                                  * RELEASED
8546                                  */
8547
8548                                 for (i = softc->init_min; i < softc->init_max; i++) {
8549                                         if (ctl_get_prkey(lun, i) == 0)
8550                                                 continue;
8551
8552                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8553                                 }
8554                         }
8555                         lun->pr_res_type = 0;
8556                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8557                         if (lun->pr_key_count==0) {
8558                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8559                                 lun->pr_res_type = 0;
8560                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8561                         }
8562                 }
8563                 lun->pr_generation++;
8564                 break;
8565
8566         case CTL_PR_RESERVE:
8567                 lun->flags |= CTL_LUN_PR_RESERVED;
8568                 lun->pr_res_type = msg->pr.pr_info.res_type;
8569                 lun->pr_res_idx = msg->pr.pr_info.residx;
8570
8571                 break;
8572
8573         case CTL_PR_RELEASE:
8574                 /*
8575                  * If this isn't an exclusive access reservation and NUAR
8576                  * is not set, generate UA for all other registrants.
8577                  */
8578                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8579                     lun->pr_res_type != SPR_TYPE_WR_EX &&
8580                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8581                         for (i = softc->init_min; i < softc->init_max; i++)
8582                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8583                                         continue;
8584                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8585                 }
8586
8587                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8588                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8589                 lun->pr_res_type = 0;
8590                 break;
8591
8592         case CTL_PR_PREEMPT:
8593                 ctl_pro_preempt_other(lun, msg);
8594                 break;
8595         case CTL_PR_CLEAR:
8596                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8597                 lun->pr_res_type = 0;
8598                 lun->pr_key_count = 0;
8599                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8600
8601                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8602                         if (ctl_get_prkey(lun, i) == 0)
8603                                 continue;
8604                         ctl_clr_prkey(lun, i);
8605                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8606                 }
8607                 lun->pr_generation++;
8608                 break;
8609         }
8610
8611         mtx_unlock(&lun->lun_lock);
8612 }
8613
8614 int
8615 ctl_read_write(struct ctl_scsiio *ctsio)
8616 {
8617         struct ctl_lun *lun = CTL_LUN(ctsio);
8618         struct ctl_lba_len_flags *lbalen;
8619         uint64_t lba;
8620         uint32_t num_blocks;
8621         int flags, retval;
8622         int isread;
8623
8624         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8625
8626         flags = 0;
8627         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8628               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8629         switch (ctsio->cdb[0]) {
8630         case READ_6:
8631         case WRITE_6: {
8632                 struct scsi_rw_6 *cdb;
8633
8634                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8635
8636                 lba = scsi_3btoul(cdb->addr);
8637                 /* only 5 bits are valid in the most significant address byte */
8638                 lba &= 0x1fffff;
8639                 num_blocks = cdb->length;
8640                 /*
8641                  * This is correct according to SBC-2.
8642                  */
8643                 if (num_blocks == 0)
8644                         num_blocks = 256;
8645                 break;
8646         }
8647         case READ_10:
8648         case WRITE_10: {
8649                 struct scsi_rw_10 *cdb;
8650
8651                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8652                 if (cdb->byte2 & SRW10_FUA)
8653                         flags |= CTL_LLF_FUA;
8654                 if (cdb->byte2 & SRW10_DPO)
8655                         flags |= CTL_LLF_DPO;
8656                 lba = scsi_4btoul(cdb->addr);
8657                 num_blocks = scsi_2btoul(cdb->length);
8658                 break;
8659         }
8660         case WRITE_VERIFY_10: {
8661                 struct scsi_write_verify_10 *cdb;
8662
8663                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8664                 flags |= CTL_LLF_FUA;
8665                 if (cdb->byte2 & SWV_DPO)
8666                         flags |= CTL_LLF_DPO;
8667                 lba = scsi_4btoul(cdb->addr);
8668                 num_blocks = scsi_2btoul(cdb->length);
8669                 break;
8670         }
8671         case READ_12:
8672         case WRITE_12: {
8673                 struct scsi_rw_12 *cdb;
8674
8675                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8676                 if (cdb->byte2 & SRW12_FUA)
8677                         flags |= CTL_LLF_FUA;
8678                 if (cdb->byte2 & SRW12_DPO)
8679                         flags |= CTL_LLF_DPO;
8680                 lba = scsi_4btoul(cdb->addr);
8681                 num_blocks = scsi_4btoul(cdb->length);
8682                 break;
8683         }
8684         case WRITE_VERIFY_12: {
8685                 struct scsi_write_verify_12 *cdb;
8686
8687                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8688                 flags |= CTL_LLF_FUA;
8689                 if (cdb->byte2 & SWV_DPO)
8690                         flags |= CTL_LLF_DPO;
8691                 lba = scsi_4btoul(cdb->addr);
8692                 num_blocks = scsi_4btoul(cdb->length);
8693                 break;
8694         }
8695         case READ_16:
8696         case WRITE_16: {
8697                 struct scsi_rw_16 *cdb;
8698
8699                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8700                 if (cdb->byte2 & SRW12_FUA)
8701                         flags |= CTL_LLF_FUA;
8702                 if (cdb->byte2 & SRW12_DPO)
8703                         flags |= CTL_LLF_DPO;
8704                 lba = scsi_8btou64(cdb->addr);
8705                 num_blocks = scsi_4btoul(cdb->length);
8706                 break;
8707         }
8708         case WRITE_ATOMIC_16: {
8709                 struct scsi_write_atomic_16 *cdb;
8710
8711                 if (lun->be_lun->atomicblock == 0) {
8712                         ctl_set_invalid_opcode(ctsio);
8713                         ctl_done((union ctl_io *)ctsio);
8714                         return (CTL_RETVAL_COMPLETE);
8715                 }
8716
8717                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8718                 if (cdb->byte2 & SRW12_FUA)
8719                         flags |= CTL_LLF_FUA;
8720                 if (cdb->byte2 & SRW12_DPO)
8721                         flags |= CTL_LLF_DPO;
8722                 lba = scsi_8btou64(cdb->addr);
8723                 num_blocks = scsi_2btoul(cdb->length);
8724                 if (num_blocks > lun->be_lun->atomicblock) {
8725                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8726                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8727                             /*bit*/ 0);
8728                         ctl_done((union ctl_io *)ctsio);
8729                         return (CTL_RETVAL_COMPLETE);
8730                 }
8731                 break;
8732         }
8733         case WRITE_VERIFY_16: {
8734                 struct scsi_write_verify_16 *cdb;
8735
8736                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8737                 flags |= CTL_LLF_FUA;
8738                 if (cdb->byte2 & SWV_DPO)
8739                         flags |= CTL_LLF_DPO;
8740                 lba = scsi_8btou64(cdb->addr);
8741                 num_blocks = scsi_4btoul(cdb->length);
8742                 break;
8743         }
8744         default:
8745                 /*
8746                  * We got a command we don't support.  This shouldn't
8747                  * happen, commands should be filtered out above us.
8748                  */
8749                 ctl_set_invalid_opcode(ctsio);
8750                 ctl_done((union ctl_io *)ctsio);
8751
8752                 return (CTL_RETVAL_COMPLETE);
8753                 break; /* NOTREACHED */
8754         }
8755
8756         /*
8757          * The first check is to make sure we're in bounds, the second
8758          * check is to catch wrap-around problems.  If the lba + num blocks
8759          * is less than the lba, then we've wrapped around and the block
8760          * range is invalid anyway.
8761          */
8762         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8763          || ((lba + num_blocks) < lba)) {
8764                 ctl_set_lba_out_of_range(ctsio,
8765                     MAX(lba, lun->be_lun->maxlba + 1));
8766                 ctl_done((union ctl_io *)ctsio);
8767                 return (CTL_RETVAL_COMPLETE);
8768         }
8769
8770         /*
8771          * According to SBC-3, a transfer length of 0 is not an error.
8772          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8773          * translates to 256 blocks for those commands.
8774          */
8775         if (num_blocks == 0) {
8776                 ctl_set_success(ctsio);
8777                 ctl_done((union ctl_io *)ctsio);
8778                 return (CTL_RETVAL_COMPLETE);
8779         }
8780
8781         /* Set FUA and/or DPO if caches are disabled. */
8782         if (isread) {
8783                 if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8784                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8785         } else {
8786                 if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8787                         flags |= CTL_LLF_FUA;
8788         }
8789
8790         lbalen = (struct ctl_lba_len_flags *)
8791             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8792         lbalen->lba = lba;
8793         lbalen->len = num_blocks;
8794         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8795
8796         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8797         ctsio->kern_rel_offset = 0;
8798
8799         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8800
8801         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8802         return (retval);
8803 }
8804
8805 static int
8806 ctl_cnw_cont(union ctl_io *io)
8807 {
8808         struct ctl_lun *lun = CTL_LUN(io);
8809         struct ctl_scsiio *ctsio;
8810         struct ctl_lba_len_flags *lbalen;
8811         int retval;
8812
8813         ctsio = &io->scsiio;
8814         ctsio->io_hdr.status = CTL_STATUS_NONE;
8815         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8816         lbalen = (struct ctl_lba_len_flags *)
8817             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8818         lbalen->flags &= ~CTL_LLF_COMPARE;
8819         lbalen->flags |= CTL_LLF_WRITE;
8820
8821         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8822         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8823         return (retval);
8824 }
8825
8826 int
8827 ctl_cnw(struct ctl_scsiio *ctsio)
8828 {
8829         struct ctl_lun *lun = CTL_LUN(ctsio);
8830         struct ctl_lba_len_flags *lbalen;
8831         uint64_t lba;
8832         uint32_t num_blocks;
8833         int flags, retval;
8834
8835         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8836
8837         flags = 0;
8838         switch (ctsio->cdb[0]) {
8839         case COMPARE_AND_WRITE: {
8840                 struct scsi_compare_and_write *cdb;
8841
8842                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8843                 if (cdb->byte2 & SRW10_FUA)
8844                         flags |= CTL_LLF_FUA;
8845                 if (cdb->byte2 & SRW10_DPO)
8846                         flags |= CTL_LLF_DPO;
8847                 lba = scsi_8btou64(cdb->addr);
8848                 num_blocks = cdb->length;
8849                 break;
8850         }
8851         default:
8852                 /*
8853                  * We got a command we don't support.  This shouldn't
8854                  * happen, commands should be filtered out above us.
8855                  */
8856                 ctl_set_invalid_opcode(ctsio);
8857                 ctl_done((union ctl_io *)ctsio);
8858
8859                 return (CTL_RETVAL_COMPLETE);
8860                 break; /* NOTREACHED */
8861         }
8862
8863         /*
8864          * The first check is to make sure we're in bounds, the second
8865          * check is to catch wrap-around problems.  If the lba + num blocks
8866          * is less than the lba, then we've wrapped around and the block
8867          * range is invalid anyway.
8868          */
8869         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8870          || ((lba + num_blocks) < lba)) {
8871                 ctl_set_lba_out_of_range(ctsio,
8872                     MAX(lba, lun->be_lun->maxlba + 1));
8873                 ctl_done((union ctl_io *)ctsio);
8874                 return (CTL_RETVAL_COMPLETE);
8875         }
8876
8877         /*
8878          * According to SBC-3, a transfer length of 0 is not an error.
8879          */
8880         if (num_blocks == 0) {
8881                 ctl_set_success(ctsio);
8882                 ctl_done((union ctl_io *)ctsio);
8883                 return (CTL_RETVAL_COMPLETE);
8884         }
8885
8886         /* Set FUA if write cache is disabled. */
8887         if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8888                 flags |= CTL_LLF_FUA;
8889
8890         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8891         ctsio->kern_rel_offset = 0;
8892
8893         /*
8894          * Set the IO_CONT flag, so that if this I/O gets passed to
8895          * ctl_data_submit_done(), it'll get passed back to
8896          * ctl_ctl_cnw_cont() for further processing.
8897          */
8898         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8899         ctsio->io_cont = ctl_cnw_cont;
8900
8901         lbalen = (struct ctl_lba_len_flags *)
8902             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8903         lbalen->lba = lba;
8904         lbalen->len = num_blocks;
8905         lbalen->flags = CTL_LLF_COMPARE | flags;
8906
8907         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8908         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8909         return (retval);
8910 }
8911
8912 int
8913 ctl_verify(struct ctl_scsiio *ctsio)
8914 {
8915         struct ctl_lun *lun = CTL_LUN(ctsio);
8916         struct ctl_lba_len_flags *lbalen;
8917         uint64_t lba;
8918         uint32_t num_blocks;
8919         int bytchk, flags;
8920         int retval;
8921
8922         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8923
8924         bytchk = 0;
8925         flags = CTL_LLF_FUA;
8926         switch (ctsio->cdb[0]) {
8927         case VERIFY_10: {
8928                 struct scsi_verify_10 *cdb;
8929
8930                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8931                 if (cdb->byte2 & SVFY_BYTCHK)
8932                         bytchk = 1;
8933                 if (cdb->byte2 & SVFY_DPO)
8934                         flags |= CTL_LLF_DPO;
8935                 lba = scsi_4btoul(cdb->addr);
8936                 num_blocks = scsi_2btoul(cdb->length);
8937                 break;
8938         }
8939         case VERIFY_12: {
8940                 struct scsi_verify_12 *cdb;
8941
8942                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8943                 if (cdb->byte2 & SVFY_BYTCHK)
8944                         bytchk = 1;
8945                 if (cdb->byte2 & SVFY_DPO)
8946                         flags |= CTL_LLF_DPO;
8947                 lba = scsi_4btoul(cdb->addr);
8948                 num_blocks = scsi_4btoul(cdb->length);
8949                 break;
8950         }
8951         case VERIFY_16: {
8952                 struct scsi_rw_16 *cdb;
8953
8954                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8955                 if (cdb->byte2 & SVFY_BYTCHK)
8956                         bytchk = 1;
8957                 if (cdb->byte2 & SVFY_DPO)
8958                         flags |= CTL_LLF_DPO;
8959                 lba = scsi_8btou64(cdb->addr);
8960                 num_blocks = scsi_4btoul(cdb->length);
8961                 break;
8962         }
8963         default:
8964                 /*
8965                  * We got a command we don't support.  This shouldn't
8966                  * happen, commands should be filtered out above us.
8967                  */
8968                 ctl_set_invalid_opcode(ctsio);
8969                 ctl_done((union ctl_io *)ctsio);
8970                 return (CTL_RETVAL_COMPLETE);
8971         }
8972
8973         /*
8974          * The first check is to make sure we're in bounds, the second
8975          * check is to catch wrap-around problems.  If the lba + num blocks
8976          * is less than the lba, then we've wrapped around and the block
8977          * range is invalid anyway.
8978          */
8979         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8980          || ((lba + num_blocks) < lba)) {
8981                 ctl_set_lba_out_of_range(ctsio,
8982                     MAX(lba, lun->be_lun->maxlba + 1));
8983                 ctl_done((union ctl_io *)ctsio);
8984                 return (CTL_RETVAL_COMPLETE);
8985         }
8986
8987         /*
8988          * According to SBC-3, a transfer length of 0 is not an error.
8989          */
8990         if (num_blocks == 0) {
8991                 ctl_set_success(ctsio);
8992                 ctl_done((union ctl_io *)ctsio);
8993                 return (CTL_RETVAL_COMPLETE);
8994         }
8995
8996         lbalen = (struct ctl_lba_len_flags *)
8997             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8998         lbalen->lba = lba;
8999         lbalen->len = num_blocks;
9000         if (bytchk) {
9001                 lbalen->flags = CTL_LLF_COMPARE | flags;
9002                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9003         } else {
9004                 lbalen->flags = CTL_LLF_VERIFY | flags;
9005                 ctsio->kern_total_len = 0;
9006         }
9007         ctsio->kern_rel_offset = 0;
9008
9009         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9010         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9011         return (retval);
9012 }
9013
9014 int
9015 ctl_report_luns(struct ctl_scsiio *ctsio)
9016 {
9017         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9018         struct ctl_port *port = CTL_PORT(ctsio);
9019         struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9020         struct scsi_report_luns *cdb;
9021         struct scsi_report_luns_data *lun_data;
9022         int num_filled, num_luns, num_port_luns, retval;
9023         uint32_t alloc_len, lun_datalen;
9024         uint32_t initidx, targ_lun_id, lun_id;
9025
9026         retval = CTL_RETVAL_COMPLETE;
9027         cdb = (struct scsi_report_luns *)ctsio->cdb;
9028
9029         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9030
9031         num_luns = 0;
9032         num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9033         mtx_lock(&softc->ctl_lock);
9034         for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9035                 if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9036                         num_luns++;
9037         }
9038         mtx_unlock(&softc->ctl_lock);
9039
9040         switch (cdb->select_report) {
9041         case RPL_REPORT_DEFAULT:
9042         case RPL_REPORT_ALL:
9043         case RPL_REPORT_NONSUBSID:
9044                 break;
9045         case RPL_REPORT_WELLKNOWN:
9046         case RPL_REPORT_ADMIN:
9047         case RPL_REPORT_CONGLOM:
9048                 num_luns = 0;
9049                 break;
9050         default:
9051                 ctl_set_invalid_field(ctsio,
9052                                       /*sks_valid*/ 1,
9053                                       /*command*/ 1,
9054                                       /*field*/ 2,
9055                                       /*bit_valid*/ 0,
9056                                       /*bit*/ 0);
9057                 ctl_done((union ctl_io *)ctsio);
9058                 return (retval);
9059                 break; /* NOTREACHED */
9060         }
9061
9062         alloc_len = scsi_4btoul(cdb->length);
9063         /*
9064          * The initiator has to allocate at least 16 bytes for this request,
9065          * so he can at least get the header and the first LUN.  Otherwise
9066          * we reject the request (per SPC-3 rev 14, section 6.21).
9067          */
9068         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9069             sizeof(struct scsi_report_luns_lundata))) {
9070                 ctl_set_invalid_field(ctsio,
9071                                       /*sks_valid*/ 1,
9072                                       /*command*/ 1,
9073                                       /*field*/ 6,
9074                                       /*bit_valid*/ 0,
9075                                       /*bit*/ 0);
9076                 ctl_done((union ctl_io *)ctsio);
9077                 return (retval);
9078         }
9079
9080         lun_datalen = sizeof(*lun_data) +
9081                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9082
9083         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9084         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9085         ctsio->kern_sg_entries = 0;
9086
9087         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9088
9089         mtx_lock(&softc->ctl_lock);
9090         for (targ_lun_id = 0, num_filled = 0;
9091             targ_lun_id < num_port_luns && num_filled < num_luns;
9092             targ_lun_id++) {
9093                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9094                 if (lun_id == UINT32_MAX)
9095                         continue;
9096                 lun = softc->ctl_luns[lun_id];
9097                 if (lun == NULL)
9098                         continue;
9099
9100                 be64enc(lun_data->luns[num_filled++].lundata,
9101                     ctl_encode_lun(targ_lun_id));
9102
9103                 /*
9104                  * According to SPC-3, rev 14 section 6.21:
9105                  *
9106                  * "The execution of a REPORT LUNS command to any valid and
9107                  * installed logical unit shall clear the REPORTED LUNS DATA
9108                  * HAS CHANGED unit attention condition for all logical
9109                  * units of that target with respect to the requesting
9110                  * initiator. A valid and installed logical unit is one
9111                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9112                  * INQUIRY data (see 6.4.2)."
9113                  *
9114                  * If request_lun is NULL, the LUN this report luns command
9115                  * was issued to is either disabled or doesn't exist. In that
9116                  * case, we shouldn't clear any pending lun change unit
9117                  * attention.
9118                  */
9119                 if (request_lun != NULL) {
9120                         mtx_lock(&lun->lun_lock);
9121                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9122                         mtx_unlock(&lun->lun_lock);
9123                 }
9124         }
9125         mtx_unlock(&softc->ctl_lock);
9126
9127         /*
9128          * It's quite possible that we've returned fewer LUNs than we allocated
9129          * space for.  Trim it.
9130          */
9131         lun_datalen = sizeof(*lun_data) +
9132                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9133
9134         if (lun_datalen < alloc_len) {
9135                 ctsio->residual = alloc_len - lun_datalen;
9136                 ctsio->kern_data_len = lun_datalen;
9137                 ctsio->kern_total_len = lun_datalen;
9138         } else {
9139                 ctsio->residual = 0;
9140                 ctsio->kern_data_len = alloc_len;
9141                 ctsio->kern_total_len = alloc_len;
9142         }
9143         ctsio->kern_data_resid = 0;
9144         ctsio->kern_rel_offset = 0;
9145         ctsio->kern_sg_entries = 0;
9146
9147         /*
9148          * We set this to the actual data length, regardless of how much
9149          * space we actually have to return results.  If the user looks at
9150          * this value, he'll know whether or not he allocated enough space
9151          * and reissue the command if necessary.  We don't support well
9152          * known logical units, so if the user asks for that, return none.
9153          */
9154         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9155
9156         /*
9157          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9158          * this request.
9159          */
9160         ctl_set_success(ctsio);
9161         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9162         ctsio->be_move_done = ctl_config_move_done;
9163         ctl_datamove((union ctl_io *)ctsio);
9164         return (retval);
9165 }
9166
9167 int
9168 ctl_request_sense(struct ctl_scsiio *ctsio)
9169 {
9170         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9171         struct ctl_lun *lun = CTL_LUN(ctsio);
9172         struct scsi_request_sense *cdb;
9173         struct scsi_sense_data *sense_ptr;
9174         uint32_t initidx;
9175         int have_error;
9176         u_int sense_len = SSD_FULL_SIZE;
9177         scsi_sense_data_type sense_format;
9178         ctl_ua_type ua_type;
9179         uint8_t asc = 0, ascq = 0;
9180
9181         cdb = (struct scsi_request_sense *)ctsio->cdb;
9182
9183         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9184
9185         /*
9186          * Determine which sense format the user wants.
9187          */
9188         if (cdb->byte2 & SRS_DESC)
9189                 sense_format = SSD_TYPE_DESC;
9190         else
9191                 sense_format = SSD_TYPE_FIXED;
9192
9193         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9194         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9195         ctsio->kern_sg_entries = 0;
9196
9197         /*
9198          * struct scsi_sense_data, which is currently set to 256 bytes, is
9199          * larger than the largest allowed value for the length field in the
9200          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9201          */
9202         ctsio->residual = 0;
9203         ctsio->kern_data_len = cdb->length;
9204         ctsio->kern_total_len = cdb->length;
9205
9206         ctsio->kern_data_resid = 0;
9207         ctsio->kern_rel_offset = 0;
9208         ctsio->kern_sg_entries = 0;
9209
9210         /*
9211          * If we don't have a LUN, we don't have any pending sense.
9212          */
9213         if (lun == NULL ||
9214             ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9215              softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9216                 /* "Logical unit not supported" */
9217                 ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9218                     /*current_error*/ 1,
9219                     /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9220                     /*asc*/ 0x25,
9221                     /*ascq*/ 0x00,
9222                     SSD_ELEM_NONE);
9223                 goto send;
9224         }
9225
9226         have_error = 0;
9227         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9228         /*
9229          * Check for pending sense, and then for pending unit attentions.
9230          * Pending sense gets returned first, then pending unit attentions.
9231          */
9232         mtx_lock(&lun->lun_lock);
9233 #ifdef CTL_WITH_CA
9234         if (ctl_is_set(lun->have_ca, initidx)) {
9235                 scsi_sense_data_type stored_format;
9236
9237                 /*
9238                  * Check to see which sense format was used for the stored
9239                  * sense data.
9240                  */
9241                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9242
9243                 /*
9244                  * If the user requested a different sense format than the
9245                  * one we stored, then we need to convert it to the other
9246                  * format.  If we're going from descriptor to fixed format
9247                  * sense data, we may lose things in translation, depending
9248                  * on what options were used.
9249                  *
9250                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9251                  * for some reason we'll just copy it out as-is.
9252                  */
9253                 if ((stored_format == SSD_TYPE_FIXED)
9254                  && (sense_format == SSD_TYPE_DESC))
9255                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9256                             &lun->pending_sense[initidx],
9257                             (struct scsi_sense_data_desc *)sense_ptr);
9258                 else if ((stored_format == SSD_TYPE_DESC)
9259                       && (sense_format == SSD_TYPE_FIXED))
9260                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9261                             &lun->pending_sense[initidx],
9262                             (struct scsi_sense_data_fixed *)sense_ptr);
9263                 else
9264                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9265                                MIN(sizeof(*sense_ptr),
9266                                sizeof(lun->pending_sense[initidx])));
9267
9268                 ctl_clear_mask(lun->have_ca, initidx);
9269                 have_error = 1;
9270         } else
9271 #endif
9272         if (have_error == 0) {
9273                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9274                     sense_format);
9275                 if (ua_type != CTL_UA_NONE)
9276                         have_error = 1;
9277         }
9278         if (have_error == 0) {
9279                 /*
9280                  * Report informational exception if have one and allowed.
9281                  */
9282                 if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9283                         asc = lun->ie_asc;
9284                         ascq = lun->ie_ascq;
9285                 }
9286                 ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9287                     /*current_error*/ 1,
9288                     /*sense_key*/ SSD_KEY_NO_SENSE,
9289                     /*asc*/ asc,
9290                     /*ascq*/ ascq,
9291                     SSD_ELEM_NONE);
9292         }
9293         mtx_unlock(&lun->lun_lock);
9294
9295 send:
9296         /*
9297          * We report the SCSI status as OK, since the status of the command
9298          * itself is OK.  We're reporting sense as parameter data.
9299          */
9300         ctl_set_success(ctsio);
9301         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9302         ctsio->be_move_done = ctl_config_move_done;
9303         ctl_datamove((union ctl_io *)ctsio);
9304         return (CTL_RETVAL_COMPLETE);
9305 }
9306
9307 int
9308 ctl_tur(struct ctl_scsiio *ctsio)
9309 {
9310
9311         CTL_DEBUG_PRINT(("ctl_tur\n"));
9312
9313         ctl_set_success(ctsio);
9314         ctl_done((union ctl_io *)ctsio);
9315
9316         return (CTL_RETVAL_COMPLETE);
9317 }
9318
9319 /*
9320  * SCSI VPD page 0x00, the Supported VPD Pages page.
9321  */
9322 static int
9323 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9324 {
9325         struct ctl_lun *lun = CTL_LUN(ctsio);
9326         struct scsi_vpd_supported_pages *pages;
9327         int sup_page_size;
9328         int p;
9329
9330         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9331             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9332         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9333         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9334         ctsio->kern_sg_entries = 0;
9335
9336         if (sup_page_size < alloc_len) {
9337                 ctsio->residual = alloc_len - sup_page_size;
9338                 ctsio->kern_data_len = sup_page_size;
9339                 ctsio->kern_total_len = sup_page_size;
9340         } else {
9341                 ctsio->residual = 0;
9342                 ctsio->kern_data_len = alloc_len;
9343                 ctsio->kern_total_len = alloc_len;
9344         }
9345         ctsio->kern_data_resid = 0;
9346         ctsio->kern_rel_offset = 0;
9347         ctsio->kern_sg_entries = 0;
9348
9349         /*
9350          * The control device is always connected.  The disk device, on the
9351          * other hand, may not be online all the time.  Need to change this
9352          * to figure out whether the disk device is actually online or not.
9353          */
9354         if (lun != NULL)
9355                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9356                                 lun->be_lun->lun_type;
9357         else
9358                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9359
9360         p = 0;
9361         /* Supported VPD pages */
9362         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9363         /* Serial Number */
9364         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9365         /* Device Identification */
9366         pages->page_list[p++] = SVPD_DEVICE_ID;
9367         /* Extended INQUIRY Data */
9368         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9369         /* Mode Page Policy */
9370         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9371         /* SCSI Ports */
9372         pages->page_list[p++] = SVPD_SCSI_PORTS;
9373         /* Third-party Copy */
9374         pages->page_list[p++] = SVPD_SCSI_TPC;
9375         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9376                 /* Block limits */
9377                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9378                 /* Block Device Characteristics */
9379                 pages->page_list[p++] = SVPD_BDC;
9380                 /* Logical Block Provisioning */
9381                 pages->page_list[p++] = SVPD_LBP;
9382         }
9383         pages->length = p;
9384
9385         ctl_set_success(ctsio);
9386         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9387         ctsio->be_move_done = ctl_config_move_done;
9388         ctl_datamove((union ctl_io *)ctsio);
9389         return (CTL_RETVAL_COMPLETE);
9390 }
9391
9392 /*
9393  * SCSI VPD page 0x80, the Unit Serial Number page.
9394  */
9395 static int
9396 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9397 {
9398         struct ctl_lun *lun = CTL_LUN(ctsio);
9399         struct scsi_vpd_unit_serial_number *sn_ptr;
9400         int data_len;
9401
9402         data_len = 4 + CTL_SN_LEN;
9403         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9404         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9405         if (data_len < alloc_len) {
9406                 ctsio->residual = alloc_len - data_len;
9407                 ctsio->kern_data_len = data_len;
9408                 ctsio->kern_total_len = data_len;
9409         } else {
9410                 ctsio->residual = 0;
9411                 ctsio->kern_data_len = alloc_len;
9412                 ctsio->kern_total_len = alloc_len;
9413         }
9414         ctsio->kern_data_resid = 0;
9415         ctsio->kern_rel_offset = 0;
9416         ctsio->kern_sg_entries = 0;
9417
9418         /*
9419          * The control device is always connected.  The disk device, on the
9420          * other hand, may not be online all the time.  Need to change this
9421          * to figure out whether the disk device is actually online or not.
9422          */
9423         if (lun != NULL)
9424                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9425                                   lun->be_lun->lun_type;
9426         else
9427                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9428
9429         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9430         sn_ptr->length = CTL_SN_LEN;
9431         /*
9432          * If we don't have a LUN, we just leave the serial number as
9433          * all spaces.
9434          */
9435         if (lun != NULL) {
9436                 strncpy((char *)sn_ptr->serial_num,
9437                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9438         } else
9439                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9440
9441         ctl_set_success(ctsio);
9442         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9443         ctsio->be_move_done = ctl_config_move_done;
9444         ctl_datamove((union ctl_io *)ctsio);
9445         return (CTL_RETVAL_COMPLETE);
9446 }
9447
9448
9449 /*
9450  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9451  */
9452 static int
9453 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9454 {
9455         struct ctl_lun *lun = CTL_LUN(ctsio);
9456         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9457         int data_len;
9458
9459         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9460         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9461         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9462         ctsio->kern_sg_entries = 0;
9463
9464         if (data_len < alloc_len) {
9465                 ctsio->residual = alloc_len - data_len;
9466                 ctsio->kern_data_len = data_len;
9467                 ctsio->kern_total_len = data_len;
9468         } else {
9469                 ctsio->residual = 0;
9470                 ctsio->kern_data_len = alloc_len;
9471                 ctsio->kern_total_len = alloc_len;
9472         }
9473         ctsio->kern_data_resid = 0;
9474         ctsio->kern_rel_offset = 0;
9475         ctsio->kern_sg_entries = 0;
9476
9477         /*
9478          * The control device is always connected.  The disk device, on the
9479          * other hand, may not be online all the time.
9480          */
9481         if (lun != NULL)
9482                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9483                                      lun->be_lun->lun_type;
9484         else
9485                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9486         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9487         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9488         /*
9489          * We support head of queue, ordered and simple tags.
9490          */
9491         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9492         /*
9493          * Volatile cache supported.
9494          */
9495         eid_ptr->flags3 = SVPD_EID_V_SUP;
9496
9497         /*
9498          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9499          * attention for a particular IT nexus on all LUNs once we report
9500          * it to that nexus once.  This bit is required as of SPC-4.
9501          */
9502         eid_ptr->flags4 = SVPD_EID_LUICLR;
9503
9504         /*
9505          * We support revert to defaults (RTD) bit in MODE SELECT.
9506          */
9507         eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9508
9509         /*
9510          * XXX KDM in order to correctly answer this, we would need
9511          * information from the SIM to determine how much sense data it
9512          * can send.  So this would really be a path inquiry field, most
9513          * likely.  This can be set to a maximum of 252 according to SPC-4,
9514          * but the hardware may or may not be able to support that much.
9515          * 0 just means that the maximum sense data length is not reported.
9516          */
9517         eid_ptr->max_sense_length = 0;
9518
9519         ctl_set_success(ctsio);
9520         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9521         ctsio->be_move_done = ctl_config_move_done;
9522         ctl_datamove((union ctl_io *)ctsio);
9523         return (CTL_RETVAL_COMPLETE);
9524 }
9525
9526 static int
9527 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9528 {
9529         struct ctl_lun *lun = CTL_LUN(ctsio);
9530         struct scsi_vpd_mode_page_policy *mpp_ptr;
9531         int data_len;
9532
9533         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9534             sizeof(struct scsi_vpd_mode_page_policy_descr);
9535
9536         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9537         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9538         ctsio->kern_sg_entries = 0;
9539
9540         if (data_len < alloc_len) {
9541                 ctsio->residual = alloc_len - data_len;
9542                 ctsio->kern_data_len = data_len;
9543                 ctsio->kern_total_len = data_len;
9544         } else {
9545                 ctsio->residual = 0;
9546                 ctsio->kern_data_len = alloc_len;
9547                 ctsio->kern_total_len = alloc_len;
9548         }
9549         ctsio->kern_data_resid = 0;
9550         ctsio->kern_rel_offset = 0;
9551         ctsio->kern_sg_entries = 0;
9552
9553         /*
9554          * The control device is always connected.  The disk device, on the
9555          * other hand, may not be online all the time.
9556          */
9557         if (lun != NULL)
9558                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9559                                      lun->be_lun->lun_type;
9560         else
9561                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9562         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9563         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9564         mpp_ptr->descr[0].page_code = 0x3f;
9565         mpp_ptr->descr[0].subpage_code = 0xff;
9566         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9567
9568         ctl_set_success(ctsio);
9569         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9570         ctsio->be_move_done = ctl_config_move_done;
9571         ctl_datamove((union ctl_io *)ctsio);
9572         return (CTL_RETVAL_COMPLETE);
9573 }
9574
9575 /*
9576  * SCSI VPD page 0x83, the Device Identification page.
9577  */
9578 static int
9579 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9580 {
9581         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9582         struct ctl_port *port = CTL_PORT(ctsio);
9583         struct ctl_lun *lun = CTL_LUN(ctsio);
9584         struct scsi_vpd_device_id *devid_ptr;
9585         struct scsi_vpd_id_descriptor *desc;
9586         int data_len, g;
9587         uint8_t proto;
9588
9589         data_len = sizeof(struct scsi_vpd_device_id) +
9590             sizeof(struct scsi_vpd_id_descriptor) +
9591                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9592             sizeof(struct scsi_vpd_id_descriptor) +
9593                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9594         if (lun && lun->lun_devid)
9595                 data_len += lun->lun_devid->len;
9596         if (port && port->port_devid)
9597                 data_len += port->port_devid->len;
9598         if (port && port->target_devid)
9599                 data_len += port->target_devid->len;
9600
9601         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9602         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9603         ctsio->kern_sg_entries = 0;
9604
9605         if (data_len < alloc_len) {
9606                 ctsio->residual = alloc_len - data_len;
9607                 ctsio->kern_data_len = data_len;
9608                 ctsio->kern_total_len = data_len;
9609         } else {
9610                 ctsio->residual = 0;
9611                 ctsio->kern_data_len = alloc_len;
9612                 ctsio->kern_total_len = alloc_len;
9613         }
9614         ctsio->kern_data_resid = 0;
9615         ctsio->kern_rel_offset = 0;
9616         ctsio->kern_sg_entries = 0;
9617
9618         /*
9619          * The control device is always connected.  The disk device, on the
9620          * other hand, may not be online all the time.
9621          */
9622         if (lun != NULL)
9623                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9624                                      lun->be_lun->lun_type;
9625         else
9626                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9627         devid_ptr->page_code = SVPD_DEVICE_ID;
9628         scsi_ulto2b(data_len - 4, devid_ptr->length);
9629
9630         if (port && port->port_type == CTL_PORT_FC)
9631                 proto = SCSI_PROTO_FC << 4;
9632         else if (port && port->port_type == CTL_PORT_ISCSI)
9633                 proto = SCSI_PROTO_ISCSI << 4;
9634         else
9635                 proto = SCSI_PROTO_SPI << 4;
9636         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9637
9638         /*
9639          * We're using a LUN association here.  i.e., this device ID is a
9640          * per-LUN identifier.
9641          */
9642         if (lun && lun->lun_devid) {
9643                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9644                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9645                     lun->lun_devid->len);
9646         }
9647
9648         /*
9649          * This is for the WWPN which is a port association.
9650          */
9651         if (port && port->port_devid) {
9652                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9653                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9654                     port->port_devid->len);
9655         }
9656
9657         /*
9658          * This is for the Relative Target Port(type 4h) identifier
9659          */
9660         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9661         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9662             SVPD_ID_TYPE_RELTARG;
9663         desc->length = 4;
9664         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9665         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9666             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9667
9668         /*
9669          * This is for the Target Port Group(type 5h) identifier
9670          */
9671         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9672         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9673             SVPD_ID_TYPE_TPORTGRP;
9674         desc->length = 4;
9675         if (softc->is_single ||
9676             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9677                 g = 1;
9678         else
9679                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9680         scsi_ulto2b(g, &desc->identifier[2]);
9681         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9682             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9683
9684         /*
9685          * This is for the Target identifier
9686          */
9687         if (port && port->target_devid) {
9688                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9689         }
9690
9691         ctl_set_success(ctsio);
9692         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9693         ctsio->be_move_done = ctl_config_move_done;
9694         ctl_datamove((union ctl_io *)ctsio);
9695         return (CTL_RETVAL_COMPLETE);
9696 }
9697
9698 static int
9699 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9700 {
9701         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9702         struct ctl_lun *lun = CTL_LUN(ctsio);
9703         struct scsi_vpd_scsi_ports *sp;
9704         struct scsi_vpd_port_designation *pd;
9705         struct scsi_vpd_port_designation_cont *pdc;
9706         struct ctl_port *port;
9707         int data_len, num_target_ports, iid_len, id_len;
9708
9709         num_target_ports = 0;
9710         iid_len = 0;
9711         id_len = 0;
9712         mtx_lock(&softc->ctl_lock);
9713         STAILQ_FOREACH(port, &softc->port_list, links) {
9714                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9715                         continue;
9716                 if (lun != NULL &&
9717                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9718                         continue;
9719                 num_target_ports++;
9720                 if (port->init_devid)
9721                         iid_len += port->init_devid->len;
9722                 if (port->port_devid)
9723                         id_len += port->port_devid->len;
9724         }
9725         mtx_unlock(&softc->ctl_lock);
9726
9727         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9728             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9729              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9730         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9731         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9732         ctsio->kern_sg_entries = 0;
9733
9734         if (data_len < alloc_len) {
9735                 ctsio->residual = alloc_len - data_len;
9736                 ctsio->kern_data_len = data_len;
9737                 ctsio->kern_total_len = data_len;
9738         } else {
9739                 ctsio->residual = 0;
9740                 ctsio->kern_data_len = alloc_len;
9741                 ctsio->kern_total_len = alloc_len;
9742         }
9743         ctsio->kern_data_resid = 0;
9744         ctsio->kern_rel_offset = 0;
9745         ctsio->kern_sg_entries = 0;
9746
9747         /*
9748          * The control device is always connected.  The disk device, on the
9749          * other hand, may not be online all the time.  Need to change this
9750          * to figure out whether the disk device is actually online or not.
9751          */
9752         if (lun != NULL)
9753                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9754                                   lun->be_lun->lun_type;
9755         else
9756                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9757
9758         sp->page_code = SVPD_SCSI_PORTS;
9759         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9760             sp->page_length);
9761         pd = &sp->design[0];
9762
9763         mtx_lock(&softc->ctl_lock);
9764         STAILQ_FOREACH(port, &softc->port_list, links) {
9765                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9766                         continue;
9767                 if (lun != NULL &&
9768                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9769                         continue;
9770                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9771                 if (port->init_devid) {
9772                         iid_len = port->init_devid->len;
9773                         memcpy(pd->initiator_transportid,
9774                             port->init_devid->data, port->init_devid->len);
9775                 } else
9776                         iid_len = 0;
9777                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9778                 pdc = (struct scsi_vpd_port_designation_cont *)
9779                     (&pd->initiator_transportid[iid_len]);
9780                 if (port->port_devid) {
9781                         id_len = port->port_devid->len;
9782                         memcpy(pdc->target_port_descriptors,
9783                             port->port_devid->data, port->port_devid->len);
9784                 } else
9785                         id_len = 0;
9786                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9787                 pd = (struct scsi_vpd_port_designation *)
9788                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9789         }
9790         mtx_unlock(&softc->ctl_lock);
9791
9792         ctl_set_success(ctsio);
9793         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9794         ctsio->be_move_done = ctl_config_move_done;
9795         ctl_datamove((union ctl_io *)ctsio);
9796         return (CTL_RETVAL_COMPLETE);
9797 }
9798
9799 static int
9800 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9801 {
9802         struct ctl_lun *lun = CTL_LUN(ctsio);
9803         struct scsi_vpd_block_limits *bl_ptr;
9804         uint64_t ival;
9805
9806         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9807         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9808         ctsio->kern_sg_entries = 0;
9809
9810         if (sizeof(*bl_ptr) < alloc_len) {
9811                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9812                 ctsio->kern_data_len = sizeof(*bl_ptr);
9813                 ctsio->kern_total_len = sizeof(*bl_ptr);
9814         } else {
9815                 ctsio->residual = 0;
9816                 ctsio->kern_data_len = alloc_len;
9817                 ctsio->kern_total_len = alloc_len;
9818         }
9819         ctsio->kern_data_resid = 0;
9820         ctsio->kern_rel_offset = 0;
9821         ctsio->kern_sg_entries = 0;
9822
9823         /*
9824          * The control device is always connected.  The disk device, on the
9825          * other hand, may not be online all the time.  Need to change this
9826          * to figure out whether the disk device is actually online or not.
9827          */
9828         if (lun != NULL)
9829                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9830                                   lun->be_lun->lun_type;
9831         else
9832                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9833
9834         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9835         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9836         bl_ptr->max_cmp_write_len = 0xff;
9837         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9838         if (lun != NULL) {
9839                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9840                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9841                         ival = 0xffffffff;
9842                         ctl_get_opt_number(&lun->be_lun->options,
9843                             "unmap_max_lba", &ival);
9844                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9845                         ival = 0xffffffff;
9846                         ctl_get_opt_number(&lun->be_lun->options,
9847                             "unmap_max_descr", &ival);
9848                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9849                         if (lun->be_lun->ublockexp != 0) {
9850                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9851                                     bl_ptr->opt_unmap_grain);
9852                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9853                                     bl_ptr->unmap_grain_align);
9854                         }
9855                 }
9856                 scsi_ulto4b(lun->be_lun->atomicblock,
9857                     bl_ptr->max_atomic_transfer_length);
9858                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9859                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9860                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9861                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9862                 ival = UINT64_MAX;
9863                 ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9864                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9865         }
9866
9867         ctl_set_success(ctsio);
9868         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9869         ctsio->be_move_done = ctl_config_move_done;
9870         ctl_datamove((union ctl_io *)ctsio);
9871         return (CTL_RETVAL_COMPLETE);
9872 }
9873
9874 static int
9875 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9876 {
9877         struct ctl_lun *lun = CTL_LUN(ctsio);
9878         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9879         const char *value;
9880         u_int i;
9881
9882         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9883         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9884         ctsio->kern_sg_entries = 0;
9885
9886         if (sizeof(*bdc_ptr) < alloc_len) {
9887                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9888                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9889                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9890         } else {
9891                 ctsio->residual = 0;
9892                 ctsio->kern_data_len = alloc_len;
9893                 ctsio->kern_total_len = alloc_len;
9894         }
9895         ctsio->kern_data_resid = 0;
9896         ctsio->kern_rel_offset = 0;
9897         ctsio->kern_sg_entries = 0;
9898
9899         /*
9900          * The control device is always connected.  The disk device, on the
9901          * other hand, may not be online all the time.  Need to change this
9902          * to figure out whether the disk device is actually online or not.
9903          */
9904         if (lun != NULL)
9905                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9906                                   lun->be_lun->lun_type;
9907         else
9908                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9909         bdc_ptr->page_code = SVPD_BDC;
9910         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9911         if (lun != NULL &&
9912             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9913                 i = strtol(value, NULL, 0);
9914         else
9915                 i = CTL_DEFAULT_ROTATION_RATE;
9916         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9917         if (lun != NULL &&
9918             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9919                 i = strtol(value, NULL, 0);
9920         else
9921                 i = 0;
9922         bdc_ptr->wab_wac_ff = (i & 0x0f);
9923         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9924
9925         ctl_set_success(ctsio);
9926         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9927         ctsio->be_move_done = ctl_config_move_done;
9928         ctl_datamove((union ctl_io *)ctsio);
9929         return (CTL_RETVAL_COMPLETE);
9930 }
9931
9932 static int
9933 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9934 {
9935         struct ctl_lun *lun = CTL_LUN(ctsio);
9936         struct scsi_vpd_logical_block_prov *lbp_ptr;
9937         const char *value;
9938
9939         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9940         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9941         ctsio->kern_sg_entries = 0;
9942
9943         if (sizeof(*lbp_ptr) < alloc_len) {
9944                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9945                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9946                 ctsio->kern_total_len = sizeof(*lbp_ptr);
9947         } else {
9948                 ctsio->residual = 0;
9949                 ctsio->kern_data_len = alloc_len;
9950                 ctsio->kern_total_len = alloc_len;
9951         }
9952         ctsio->kern_data_resid = 0;
9953         ctsio->kern_rel_offset = 0;
9954         ctsio->kern_sg_entries = 0;
9955
9956         /*
9957          * The control device is always connected.  The disk device, on the
9958          * other hand, may not be online all the time.  Need to change this
9959          * to figure out whether the disk device is actually online or not.
9960          */
9961         if (lun != NULL)
9962                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9963                                   lun->be_lun->lun_type;
9964         else
9965                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9966
9967         lbp_ptr->page_code = SVPD_LBP;
9968         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9969         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9970         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9971                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9972                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9973                 value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
9974                 if (value != NULL) {
9975                         if (strcmp(value, "resource") == 0)
9976                                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9977                         else if (strcmp(value, "thin") == 0)
9978                                 lbp_ptr->prov_type = SVPD_LBP_THIN;
9979                 } else
9980                         lbp_ptr->prov_type = SVPD_LBP_THIN;
9981         }
9982
9983         ctl_set_success(ctsio);
9984         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9985         ctsio->be_move_done = ctl_config_move_done;
9986         ctl_datamove((union ctl_io *)ctsio);
9987         return (CTL_RETVAL_COMPLETE);
9988 }
9989
9990 /*
9991  * INQUIRY with the EVPD bit set.
9992  */
9993 static int
9994 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9995 {
9996         struct ctl_lun *lun = CTL_LUN(ctsio);
9997         struct scsi_inquiry *cdb;
9998         int alloc_len, retval;
9999
10000         cdb = (struct scsi_inquiry *)ctsio->cdb;
10001         alloc_len = scsi_2btoul(cdb->length);
10002
10003         switch (cdb->page_code) {
10004         case SVPD_SUPPORTED_PAGES:
10005                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10006                 break;
10007         case SVPD_UNIT_SERIAL_NUMBER:
10008                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10009                 break;
10010         case SVPD_DEVICE_ID:
10011                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10012                 break;
10013         case SVPD_EXTENDED_INQUIRY_DATA:
10014                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10015                 break;
10016         case SVPD_MODE_PAGE_POLICY:
10017                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10018                 break;
10019         case SVPD_SCSI_PORTS:
10020                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10021                 break;
10022         case SVPD_SCSI_TPC:
10023                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10024                 break;
10025         case SVPD_BLOCK_LIMITS:
10026                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10027                         goto err;
10028                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10029                 break;
10030         case SVPD_BDC:
10031                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10032                         goto err;
10033                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10034                 break;
10035         case SVPD_LBP:
10036                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10037                         goto err;
10038                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10039                 break;
10040         default:
10041 err:
10042                 ctl_set_invalid_field(ctsio,
10043                                       /*sks_valid*/ 1,
10044                                       /*command*/ 1,
10045                                       /*field*/ 2,
10046                                       /*bit_valid*/ 0,
10047                                       /*bit*/ 0);
10048                 ctl_done((union ctl_io *)ctsio);
10049                 retval = CTL_RETVAL_COMPLETE;
10050                 break;
10051         }
10052
10053         return (retval);
10054 }
10055
10056 /*
10057  * Standard INQUIRY data.
10058  */
10059 static int
10060 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10061 {
10062         struct ctl_softc *softc = CTL_SOFTC(ctsio);
10063         struct ctl_port *port = CTL_PORT(ctsio);
10064         struct ctl_lun *lun = CTL_LUN(ctsio);
10065         struct scsi_inquiry_data *inq_ptr;
10066         struct scsi_inquiry *cdb;
10067         char *val;
10068         uint32_t alloc_len, data_len;
10069         ctl_port_type port_type;
10070
10071         port_type = port->port_type;
10072         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10073                 port_type = CTL_PORT_SCSI;
10074
10075         cdb = (struct scsi_inquiry *)ctsio->cdb;
10076         alloc_len = scsi_2btoul(cdb->length);
10077
10078         /*
10079          * We malloc the full inquiry data size here and fill it
10080          * in.  If the user only asks for less, we'll give him
10081          * that much.
10082          */
10083         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10084         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10085         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10086         ctsio->kern_sg_entries = 0;
10087         ctsio->kern_data_resid = 0;
10088         ctsio->kern_rel_offset = 0;
10089
10090         if (data_len < alloc_len) {
10091                 ctsio->residual = alloc_len - data_len;
10092                 ctsio->kern_data_len = data_len;
10093                 ctsio->kern_total_len = data_len;
10094         } else {
10095                 ctsio->residual = 0;
10096                 ctsio->kern_data_len = alloc_len;
10097                 ctsio->kern_total_len = alloc_len;
10098         }
10099
10100         if (lun != NULL) {
10101                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10102                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10103                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10104                             lun->be_lun->lun_type;
10105                 } else {
10106                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10107                             lun->be_lun->lun_type;
10108                 }
10109                 if (lun->flags & CTL_LUN_REMOVABLE)
10110                         inq_ptr->dev_qual2 |= SID_RMB;
10111         } else
10112                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10113
10114         /* RMB in byte 2 is 0 */
10115         inq_ptr->version = SCSI_REV_SPC5;
10116
10117         /*
10118          * According to SAM-3, even if a device only supports a single
10119          * level of LUN addressing, it should still set the HISUP bit:
10120          *
10121          * 4.9.1 Logical unit numbers overview
10122          *
10123          * All logical unit number formats described in this standard are
10124          * hierarchical in structure even when only a single level in that
10125          * hierarchy is used. The HISUP bit shall be set to one in the
10126          * standard INQUIRY data (see SPC-2) when any logical unit number
10127          * format described in this standard is used.  Non-hierarchical
10128          * formats are outside the scope of this standard.
10129          *
10130          * Therefore we set the HiSup bit here.
10131          *
10132          * The response format is 2, per SPC-3.
10133          */
10134         inq_ptr->response_format = SID_HiSup | 2;
10135
10136         inq_ptr->additional_length = data_len -
10137             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10138         CTL_DEBUG_PRINT(("additional_length = %d\n",
10139                          inq_ptr->additional_length));
10140
10141         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10142         if (port_type == CTL_PORT_SCSI)
10143                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10144         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10145         inq_ptr->flags = SID_CmdQue;
10146         if (port_type == CTL_PORT_SCSI)
10147                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10148
10149         /*
10150          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10151          * We have 8 bytes for the vendor name, and 16 bytes for the device
10152          * name and 4 bytes for the revision.
10153          */
10154         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10155             "vendor")) == NULL) {
10156                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10157         } else {
10158                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10159                 strncpy(inq_ptr->vendor, val,
10160                     min(sizeof(inq_ptr->vendor), strlen(val)));
10161         }
10162         if (lun == NULL) {
10163                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10164                     sizeof(inq_ptr->product));
10165         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10166                 switch (lun->be_lun->lun_type) {
10167                 case T_DIRECT:
10168                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10169                             sizeof(inq_ptr->product));
10170                         break;
10171                 case T_PROCESSOR:
10172                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10173                             sizeof(inq_ptr->product));
10174                         break;
10175                 case T_CDROM:
10176                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10177                             sizeof(inq_ptr->product));
10178                         break;
10179                 default:
10180                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10181                             sizeof(inq_ptr->product));
10182                         break;
10183                 }
10184         } else {
10185                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10186                 strncpy(inq_ptr->product, val,
10187                     min(sizeof(inq_ptr->product), strlen(val)));
10188         }
10189
10190         /*
10191          * XXX make this a macro somewhere so it automatically gets
10192          * incremented when we make changes.
10193          */
10194         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10195             "revision")) == NULL) {
10196                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10197         } else {
10198                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10199                 strncpy(inq_ptr->revision, val,
10200                     min(sizeof(inq_ptr->revision), strlen(val)));
10201         }
10202
10203         /*
10204          * For parallel SCSI, we support double transition and single
10205          * transition clocking.  We also support QAS (Quick Arbitration
10206          * and Selection) and Information Unit transfers on both the
10207          * control and array devices.
10208          */
10209         if (port_type == CTL_PORT_SCSI)
10210                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10211                                     SID_SPI_IUS;
10212
10213         /* SAM-6 (no version claimed) */
10214         scsi_ulto2b(0x00C0, inq_ptr->version1);
10215         /* SPC-5 (no version claimed) */
10216         scsi_ulto2b(0x05C0, inq_ptr->version2);
10217         if (port_type == CTL_PORT_FC) {
10218                 /* FCP-2 ANSI INCITS.350:2003 */
10219                 scsi_ulto2b(0x0917, inq_ptr->version3);
10220         } else if (port_type == CTL_PORT_SCSI) {
10221                 /* SPI-4 ANSI INCITS.362:200x */
10222                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10223         } else if (port_type == CTL_PORT_ISCSI) {
10224                 /* iSCSI (no version claimed) */
10225                 scsi_ulto2b(0x0960, inq_ptr->version3);
10226         } else if (port_type == CTL_PORT_SAS) {
10227                 /* SAS (no version claimed) */
10228                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10229         }
10230
10231         if (lun == NULL) {
10232                 /* SBC-4 (no version claimed) */
10233                 scsi_ulto2b(0x0600, inq_ptr->version4);
10234         } else {
10235                 switch (lun->be_lun->lun_type) {
10236                 case T_DIRECT:
10237                         /* SBC-4 (no version claimed) */
10238                         scsi_ulto2b(0x0600, inq_ptr->version4);
10239                         break;
10240                 case T_PROCESSOR:
10241                         break;
10242                 case T_CDROM:
10243                         /* MMC-6 (no version claimed) */
10244                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10245                         break;
10246                 default:
10247                         break;
10248                 }
10249         }
10250
10251         ctl_set_success(ctsio);
10252         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10253         ctsio->be_move_done = ctl_config_move_done;
10254         ctl_datamove((union ctl_io *)ctsio);
10255         return (CTL_RETVAL_COMPLETE);
10256 }
10257
10258 int
10259 ctl_inquiry(struct ctl_scsiio *ctsio)
10260 {
10261         struct scsi_inquiry *cdb;
10262         int retval;
10263
10264         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10265
10266         cdb = (struct scsi_inquiry *)ctsio->cdb;
10267         if (cdb->byte2 & SI_EVPD)
10268                 retval = ctl_inquiry_evpd(ctsio);
10269         else if (cdb->page_code == 0)
10270                 retval = ctl_inquiry_std(ctsio);
10271         else {
10272                 ctl_set_invalid_field(ctsio,
10273                                       /*sks_valid*/ 1,
10274                                       /*command*/ 1,
10275                                       /*field*/ 2,
10276                                       /*bit_valid*/ 0,
10277                                       /*bit*/ 0);
10278                 ctl_done((union ctl_io *)ctsio);
10279                 return (CTL_RETVAL_COMPLETE);
10280         }
10281
10282         return (retval);
10283 }
10284
10285 int
10286 ctl_get_config(struct ctl_scsiio *ctsio)
10287 {
10288         struct ctl_lun *lun = CTL_LUN(ctsio);
10289         struct scsi_get_config_header *hdr;
10290         struct scsi_get_config_feature *feature;
10291         struct scsi_get_config *cdb;
10292         uint32_t alloc_len, data_len;
10293         int rt, starting;
10294
10295         cdb = (struct scsi_get_config *)ctsio->cdb;
10296         rt = (cdb->rt & SGC_RT_MASK);
10297         starting = scsi_2btoul(cdb->starting_feature);
10298         alloc_len = scsi_2btoul(cdb->length);
10299
10300         data_len = sizeof(struct scsi_get_config_header) +
10301             sizeof(struct scsi_get_config_feature) + 8 +
10302             sizeof(struct scsi_get_config_feature) + 8 +
10303             sizeof(struct scsi_get_config_feature) + 4 +
10304             sizeof(struct scsi_get_config_feature) + 4 +
10305             sizeof(struct scsi_get_config_feature) + 8 +
10306             sizeof(struct scsi_get_config_feature) +
10307             sizeof(struct scsi_get_config_feature) + 4 +
10308             sizeof(struct scsi_get_config_feature) + 4 +
10309             sizeof(struct scsi_get_config_feature) + 4 +
10310             sizeof(struct scsi_get_config_feature) + 4 +
10311             sizeof(struct scsi_get_config_feature) + 4 +
10312             sizeof(struct scsi_get_config_feature) + 4;
10313         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10314         ctsio->kern_sg_entries = 0;
10315         ctsio->kern_data_resid = 0;
10316         ctsio->kern_rel_offset = 0;
10317
10318         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10319         if (lun->flags & CTL_LUN_NO_MEDIA)
10320                 scsi_ulto2b(0x0000, hdr->current_profile);
10321         else
10322                 scsi_ulto2b(0x0010, hdr->current_profile);
10323         feature = (struct scsi_get_config_feature *)(hdr + 1);
10324
10325         if (starting > 0x003b)
10326                 goto done;
10327         if (starting > 0x003a)
10328                 goto f3b;
10329         if (starting > 0x002b)
10330                 goto f3a;
10331         if (starting > 0x002a)
10332                 goto f2b;
10333         if (starting > 0x001f)
10334                 goto f2a;
10335         if (starting > 0x001e)
10336                 goto f1f;
10337         if (starting > 0x001d)
10338                 goto f1e;
10339         if (starting > 0x0010)
10340                 goto f1d;
10341         if (starting > 0x0003)
10342                 goto f10;
10343         if (starting > 0x0002)
10344                 goto f3;
10345         if (starting > 0x0001)
10346                 goto f2;
10347         if (starting > 0x0000)
10348                 goto f1;
10349
10350         /* Profile List */
10351         scsi_ulto2b(0x0000, feature->feature_code);
10352         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10353         feature->add_length = 8;
10354         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10355         feature->feature_data[2] = 0x00;
10356         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10357         feature->feature_data[6] = 0x01;
10358         feature = (struct scsi_get_config_feature *)
10359             &feature->feature_data[feature->add_length];
10360
10361 f1:     /* Core */
10362         scsi_ulto2b(0x0001, feature->feature_code);
10363         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10364         feature->add_length = 8;
10365         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10366         feature->feature_data[4] = 0x03;
10367         feature = (struct scsi_get_config_feature *)
10368             &feature->feature_data[feature->add_length];
10369
10370 f2:     /* Morphing */
10371         scsi_ulto2b(0x0002, feature->feature_code);
10372         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10373         feature->add_length = 4;
10374         feature->feature_data[0] = 0x02;
10375         feature = (struct scsi_get_config_feature *)
10376             &feature->feature_data[feature->add_length];
10377
10378 f3:     /* Removable Medium */
10379         scsi_ulto2b(0x0003, feature->feature_code);
10380         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10381         feature->add_length = 4;
10382         feature->feature_data[0] = 0x39;
10383         feature = (struct scsi_get_config_feature *)
10384             &feature->feature_data[feature->add_length];
10385
10386         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10387                 goto done;
10388
10389 f10:    /* Random Read */
10390         scsi_ulto2b(0x0010, feature->feature_code);
10391         feature->flags = 0x00;
10392         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10393                 feature->flags |= SGC_F_CURRENT;
10394         feature->add_length = 8;
10395         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10396         scsi_ulto2b(1, &feature->feature_data[4]);
10397         feature->feature_data[6] = 0x00;
10398         feature = (struct scsi_get_config_feature *)
10399             &feature->feature_data[feature->add_length];
10400
10401 f1d:    /* Multi-Read */
10402         scsi_ulto2b(0x001D, feature->feature_code);
10403         feature->flags = 0x00;
10404         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10405                 feature->flags |= SGC_F_CURRENT;
10406         feature->add_length = 0;
10407         feature = (struct scsi_get_config_feature *)
10408             &feature->feature_data[feature->add_length];
10409
10410 f1e:    /* CD Read */
10411         scsi_ulto2b(0x001E, feature->feature_code);
10412         feature->flags = 0x00;
10413         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10414                 feature->flags |= SGC_F_CURRENT;
10415         feature->add_length = 4;
10416         feature->feature_data[0] = 0x00;
10417         feature = (struct scsi_get_config_feature *)
10418             &feature->feature_data[feature->add_length];
10419
10420 f1f:    /* DVD Read */
10421         scsi_ulto2b(0x001F, feature->feature_code);
10422         feature->flags = 0x08;
10423         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10424                 feature->flags |= SGC_F_CURRENT;
10425         feature->add_length = 4;
10426         feature->feature_data[0] = 0x01;
10427         feature->feature_data[2] = 0x03;
10428         feature = (struct scsi_get_config_feature *)
10429             &feature->feature_data[feature->add_length];
10430
10431 f2a:    /* DVD+RW */
10432         scsi_ulto2b(0x002A, feature->feature_code);
10433         feature->flags = 0x04;
10434         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10435                 feature->flags |= SGC_F_CURRENT;
10436         feature->add_length = 4;
10437         feature->feature_data[0] = 0x00;
10438         feature->feature_data[1] = 0x00;
10439         feature = (struct scsi_get_config_feature *)
10440             &feature->feature_data[feature->add_length];
10441
10442 f2b:    /* DVD+R */
10443         scsi_ulto2b(0x002B, feature->feature_code);
10444         feature->flags = 0x00;
10445         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10446                 feature->flags |= SGC_F_CURRENT;
10447         feature->add_length = 4;
10448         feature->feature_data[0] = 0x00;
10449         feature = (struct scsi_get_config_feature *)
10450             &feature->feature_data[feature->add_length];
10451
10452 f3a:    /* DVD+RW Dual Layer */
10453         scsi_ulto2b(0x003A, feature->feature_code);
10454         feature->flags = 0x00;
10455         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10456                 feature->flags |= SGC_F_CURRENT;
10457         feature->add_length = 4;
10458         feature->feature_data[0] = 0x00;
10459         feature->feature_data[1] = 0x00;
10460         feature = (struct scsi_get_config_feature *)
10461             &feature->feature_data[feature->add_length];
10462
10463 f3b:    /* DVD+R Dual Layer */
10464         scsi_ulto2b(0x003B, feature->feature_code);
10465         feature->flags = 0x00;
10466         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10467                 feature->flags |= SGC_F_CURRENT;
10468         feature->add_length = 4;
10469         feature->feature_data[0] = 0x00;
10470         feature = (struct scsi_get_config_feature *)
10471             &feature->feature_data[feature->add_length];
10472
10473 done:
10474         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10475         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10476                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10477                 if (scsi_2btoul(feature->feature_code) == starting)
10478                         feature = (struct scsi_get_config_feature *)
10479                             &feature->feature_data[feature->add_length];
10480                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10481         }
10482         scsi_ulto4b(data_len - 4, hdr->data_length);
10483         if (data_len < alloc_len) {
10484                 ctsio->residual = alloc_len - data_len;
10485                 ctsio->kern_data_len = data_len;
10486                 ctsio->kern_total_len = data_len;
10487         } else {
10488                 ctsio->residual = 0;
10489                 ctsio->kern_data_len = alloc_len;
10490                 ctsio->kern_total_len = alloc_len;
10491         }
10492
10493         ctl_set_success(ctsio);
10494         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10495         ctsio->be_move_done = ctl_config_move_done;
10496         ctl_datamove((union ctl_io *)ctsio);
10497         return (CTL_RETVAL_COMPLETE);
10498 }
10499
10500 int
10501 ctl_get_event_status(struct ctl_scsiio *ctsio)
10502 {
10503         struct scsi_get_event_status_header *hdr;
10504         struct scsi_get_event_status *cdb;
10505         uint32_t alloc_len, data_len;
10506         int notif_class;
10507
10508         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10509         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10510                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10511                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10512                 ctl_done((union ctl_io *)ctsio);
10513                 return (CTL_RETVAL_COMPLETE);
10514         }
10515         notif_class = cdb->notif_class;
10516         alloc_len = scsi_2btoul(cdb->length);
10517
10518         data_len = sizeof(struct scsi_get_event_status_header);
10519         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10520         ctsio->kern_sg_entries = 0;
10521         ctsio->kern_data_resid = 0;
10522         ctsio->kern_rel_offset = 0;
10523
10524         if (data_len < alloc_len) {
10525                 ctsio->residual = alloc_len - data_len;
10526                 ctsio->kern_data_len = data_len;
10527                 ctsio->kern_total_len = data_len;
10528         } else {
10529                 ctsio->residual = 0;
10530                 ctsio->kern_data_len = alloc_len;
10531                 ctsio->kern_total_len = alloc_len;
10532         }
10533
10534         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10535         scsi_ulto2b(0, hdr->descr_length);
10536         hdr->nea_class = SGESN_NEA;
10537         hdr->supported_class = 0;
10538
10539         ctl_set_success(ctsio);
10540         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10541         ctsio->be_move_done = ctl_config_move_done;
10542         ctl_datamove((union ctl_io *)ctsio);
10543         return (CTL_RETVAL_COMPLETE);
10544 }
10545
10546 int
10547 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10548 {
10549         struct scsi_mechanism_status_header *hdr;
10550         struct scsi_mechanism_status *cdb;
10551         uint32_t alloc_len, data_len;
10552
10553         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10554         alloc_len = scsi_2btoul(cdb->length);
10555
10556         data_len = sizeof(struct scsi_mechanism_status_header);
10557         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10558         ctsio->kern_sg_entries = 0;
10559         ctsio->kern_data_resid = 0;
10560         ctsio->kern_rel_offset = 0;
10561
10562         if (data_len < alloc_len) {
10563                 ctsio->residual = alloc_len - data_len;
10564                 ctsio->kern_data_len = data_len;
10565                 ctsio->kern_total_len = data_len;
10566         } else {
10567                 ctsio->residual = 0;
10568                 ctsio->kern_data_len = alloc_len;
10569                 ctsio->kern_total_len = alloc_len;
10570         }
10571
10572         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10573         hdr->state1 = 0x00;
10574         hdr->state2 = 0xe0;
10575         scsi_ulto3b(0, hdr->lba);
10576         hdr->slots_num = 0;
10577         scsi_ulto2b(0, hdr->slots_length);
10578
10579         ctl_set_success(ctsio);
10580         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10581         ctsio->be_move_done = ctl_config_move_done;
10582         ctl_datamove((union ctl_io *)ctsio);
10583         return (CTL_RETVAL_COMPLETE);
10584 }
10585
10586 static void
10587 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10588 {
10589
10590         lba += 150;
10591         buf[0] = 0;
10592         buf[1] = bin2bcd((lba / 75) / 60);
10593         buf[2] = bin2bcd((lba / 75) % 60);
10594         buf[3] = bin2bcd(lba % 75);
10595 }
10596
10597 int
10598 ctl_read_toc(struct ctl_scsiio *ctsio)
10599 {
10600         struct ctl_lun *lun = CTL_LUN(ctsio);
10601         struct scsi_read_toc_hdr *hdr;
10602         struct scsi_read_toc_type01_descr *descr;
10603         struct scsi_read_toc *cdb;
10604         uint32_t alloc_len, data_len;
10605         int format, msf;
10606
10607         cdb = (struct scsi_read_toc *)ctsio->cdb;
10608         msf = (cdb->byte2 & CD_MSF) != 0;
10609         format = cdb->format;
10610         alloc_len = scsi_2btoul(cdb->data_len);
10611
10612         data_len = sizeof(struct scsi_read_toc_hdr);
10613         if (format == 0)
10614                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10615         else
10616                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10617         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10618         ctsio->kern_sg_entries = 0;
10619         ctsio->kern_data_resid = 0;
10620         ctsio->kern_rel_offset = 0;
10621
10622         if (data_len < alloc_len) {
10623                 ctsio->residual = alloc_len - data_len;
10624                 ctsio->kern_data_len = data_len;
10625                 ctsio->kern_total_len = data_len;
10626         } else {
10627                 ctsio->residual = 0;
10628                 ctsio->kern_data_len = alloc_len;
10629                 ctsio->kern_total_len = alloc_len;
10630         }
10631
10632         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10633         if (format == 0) {
10634                 scsi_ulto2b(0x12, hdr->data_length);
10635                 hdr->first = 1;
10636                 hdr->last = 1;
10637                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10638                 descr->addr_ctl = 0x14;
10639                 descr->track_number = 1;
10640                 if (msf)
10641                         ctl_ultomsf(0, descr->track_start);
10642                 else
10643                         scsi_ulto4b(0, descr->track_start);
10644                 descr++;
10645                 descr->addr_ctl = 0x14;
10646                 descr->track_number = 0xaa;
10647                 if (msf)
10648                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10649                 else
10650                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10651         } else {
10652                 scsi_ulto2b(0x0a, hdr->data_length);
10653                 hdr->first = 1;
10654                 hdr->last = 1;
10655                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10656                 descr->addr_ctl = 0x14;
10657                 descr->track_number = 1;
10658                 if (msf)
10659                         ctl_ultomsf(0, descr->track_start);
10660                 else
10661                         scsi_ulto4b(0, descr->track_start);
10662         }
10663
10664         ctl_set_success(ctsio);
10665         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10666         ctsio->be_move_done = ctl_config_move_done;
10667         ctl_datamove((union ctl_io *)ctsio);
10668         return (CTL_RETVAL_COMPLETE);
10669 }
10670
10671 /*
10672  * For known CDB types, parse the LBA and length.
10673  */
10674 static int
10675 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10676 {
10677         if (io->io_hdr.io_type != CTL_IO_SCSI)
10678                 return (1);
10679
10680         switch (io->scsiio.cdb[0]) {
10681         case COMPARE_AND_WRITE: {
10682                 struct scsi_compare_and_write *cdb;
10683
10684                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10685
10686                 *lba = scsi_8btou64(cdb->addr);
10687                 *len = cdb->length;
10688                 break;
10689         }
10690         case READ_6:
10691         case WRITE_6: {
10692                 struct scsi_rw_6 *cdb;
10693
10694                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10695
10696                 *lba = scsi_3btoul(cdb->addr);
10697                 /* only 5 bits are valid in the most significant address byte */
10698                 *lba &= 0x1fffff;
10699                 *len = cdb->length;
10700                 break;
10701         }
10702         case READ_10:
10703         case WRITE_10: {
10704                 struct scsi_rw_10 *cdb;
10705
10706                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10707
10708                 *lba = scsi_4btoul(cdb->addr);
10709                 *len = scsi_2btoul(cdb->length);
10710                 break;
10711         }
10712         case WRITE_VERIFY_10: {
10713                 struct scsi_write_verify_10 *cdb;
10714
10715                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10716
10717                 *lba = scsi_4btoul(cdb->addr);
10718                 *len = scsi_2btoul(cdb->length);
10719                 break;
10720         }
10721         case READ_12:
10722         case WRITE_12: {
10723                 struct scsi_rw_12 *cdb;
10724
10725                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10726
10727                 *lba = scsi_4btoul(cdb->addr);
10728                 *len = scsi_4btoul(cdb->length);
10729                 break;
10730         }
10731         case WRITE_VERIFY_12: {
10732                 struct scsi_write_verify_12 *cdb;
10733
10734                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10735
10736                 *lba = scsi_4btoul(cdb->addr);
10737                 *len = scsi_4btoul(cdb->length);
10738                 break;
10739         }
10740         case READ_16:
10741         case WRITE_16: {
10742                 struct scsi_rw_16 *cdb;
10743
10744                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10745
10746                 *lba = scsi_8btou64(cdb->addr);
10747                 *len = scsi_4btoul(cdb->length);
10748                 break;
10749         }
10750         case WRITE_ATOMIC_16: {
10751                 struct scsi_write_atomic_16 *cdb;
10752
10753                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10754
10755                 *lba = scsi_8btou64(cdb->addr);
10756                 *len = scsi_2btoul(cdb->length);
10757                 break;
10758         }
10759         case WRITE_VERIFY_16: {
10760                 struct scsi_write_verify_16 *cdb;
10761
10762                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10763
10764                 *lba = scsi_8btou64(cdb->addr);
10765                 *len = scsi_4btoul(cdb->length);
10766                 break;
10767         }
10768         case WRITE_SAME_10: {
10769                 struct scsi_write_same_10 *cdb;
10770
10771                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10772
10773                 *lba = scsi_4btoul(cdb->addr);
10774                 *len = scsi_2btoul(cdb->length);
10775                 break;
10776         }
10777         case WRITE_SAME_16: {
10778                 struct scsi_write_same_16 *cdb;
10779
10780                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10781
10782                 *lba = scsi_8btou64(cdb->addr);
10783                 *len = scsi_4btoul(cdb->length);
10784                 break;
10785         }
10786         case VERIFY_10: {
10787                 struct scsi_verify_10 *cdb;
10788
10789                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10790
10791                 *lba = scsi_4btoul(cdb->addr);
10792                 *len = scsi_2btoul(cdb->length);
10793                 break;
10794         }
10795         case VERIFY_12: {
10796                 struct scsi_verify_12 *cdb;
10797
10798                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10799
10800                 *lba = scsi_4btoul(cdb->addr);
10801                 *len = scsi_4btoul(cdb->length);
10802                 break;
10803         }
10804         case VERIFY_16: {
10805                 struct scsi_verify_16 *cdb;
10806
10807                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10808
10809                 *lba = scsi_8btou64(cdb->addr);
10810                 *len = scsi_4btoul(cdb->length);
10811                 break;
10812         }
10813         case UNMAP: {
10814                 *lba = 0;
10815                 *len = UINT64_MAX;
10816                 break;
10817         }
10818         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10819                 struct scsi_get_lba_status *cdb;
10820
10821                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10822                 *lba = scsi_8btou64(cdb->addr);
10823                 *len = UINT32_MAX;
10824                 break;
10825         }
10826         default:
10827                 return (1);
10828                 break; /* NOTREACHED */
10829         }
10830
10831         return (0);
10832 }
10833
10834 static ctl_action
10835 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10836     bool seq)
10837 {
10838         uint64_t endlba1, endlba2;
10839
10840         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10841         endlba2 = lba2 + len2 - 1;
10842
10843         if ((endlba1 < lba2) || (endlba2 < lba1))
10844                 return (CTL_ACTION_PASS);
10845         else
10846                 return (CTL_ACTION_BLOCK);
10847 }
10848
10849 static int
10850 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10851 {
10852         struct ctl_ptr_len_flags *ptrlen;
10853         struct scsi_unmap_desc *buf, *end, *range;
10854         uint64_t lba;
10855         uint32_t len;
10856
10857         /* If not UNMAP -- go other way. */
10858         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10859             io->scsiio.cdb[0] != UNMAP)
10860                 return (CTL_ACTION_ERROR);
10861
10862         /* If UNMAP without data -- block and wait for data. */
10863         ptrlen = (struct ctl_ptr_len_flags *)
10864             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10865         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10866             ptrlen->ptr == NULL)
10867                 return (CTL_ACTION_BLOCK);
10868
10869         /* UNMAP with data -- check for collision. */
10870         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10871         end = buf + ptrlen->len / sizeof(*buf);
10872         for (range = buf; range < end; range++) {
10873                 lba = scsi_8btou64(range->lba);
10874                 len = scsi_4btoul(range->length);
10875                 if ((lba < lba2 + len2) && (lba + len > lba2))
10876                         return (CTL_ACTION_BLOCK);
10877         }
10878         return (CTL_ACTION_PASS);
10879 }
10880
10881 static ctl_action
10882 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10883 {
10884         uint64_t lba1, lba2;
10885         uint64_t len1, len2;
10886         int retval;
10887
10888         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10889                 return (CTL_ACTION_ERROR);
10890
10891         retval = ctl_extent_check_unmap(io1, lba2, len2);
10892         if (retval != CTL_ACTION_ERROR)
10893                 return (retval);
10894
10895         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10896                 return (CTL_ACTION_ERROR);
10897
10898         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10899                 seq = FALSE;
10900         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10901 }
10902
10903 static ctl_action
10904 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10905 {
10906         uint64_t lba1, lba2;
10907         uint64_t len1, len2;
10908
10909         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10910                 return (CTL_ACTION_PASS);
10911         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10912                 return (CTL_ACTION_ERROR);
10913         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10914                 return (CTL_ACTION_ERROR);
10915
10916         if (lba1 + len1 == lba2)
10917                 return (CTL_ACTION_BLOCK);
10918         return (CTL_ACTION_PASS);
10919 }
10920
10921 static ctl_action
10922 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10923     union ctl_io *ooa_io)
10924 {
10925         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10926         const ctl_serialize_action *serialize_row;
10927
10928         /*
10929          * The initiator attempted multiple untagged commands at the same
10930          * time.  Can't do that.
10931          */
10932         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10933          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10934          && ((pending_io->io_hdr.nexus.targ_port ==
10935               ooa_io->io_hdr.nexus.targ_port)
10936           && (pending_io->io_hdr.nexus.initid ==
10937               ooa_io->io_hdr.nexus.initid))
10938          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10939               CTL_FLAG_STATUS_SENT)) == 0))
10940                 return (CTL_ACTION_OVERLAP);
10941
10942         /*
10943          * The initiator attempted to send multiple tagged commands with
10944          * the same ID.  (It's fine if different initiators have the same
10945          * tag ID.)
10946          *
10947          * Even if all of those conditions are true, we don't kill the I/O
10948          * if the command ahead of us has been aborted.  We won't end up
10949          * sending it to the FETD, and it's perfectly legal to resend a
10950          * command with the same tag number as long as the previous
10951          * instance of this tag number has been aborted somehow.
10952          */
10953         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10954          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10955          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10956          && ((pending_io->io_hdr.nexus.targ_port ==
10957               ooa_io->io_hdr.nexus.targ_port)
10958           && (pending_io->io_hdr.nexus.initid ==
10959               ooa_io->io_hdr.nexus.initid))
10960          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10961               CTL_FLAG_STATUS_SENT)) == 0))
10962                 return (CTL_ACTION_OVERLAP_TAG);
10963
10964         /*
10965          * If we get a head of queue tag, SAM-3 says that we should
10966          * immediately execute it.
10967          *
10968          * What happens if this command would normally block for some other
10969          * reason?  e.g. a request sense with a head of queue tag
10970          * immediately after a write.  Normally that would block, but this
10971          * will result in its getting executed immediately...
10972          *
10973          * We currently return "pass" instead of "skip", so we'll end up
10974          * going through the rest of the queue to check for overlapped tags.
10975          *
10976          * XXX KDM check for other types of blockage first??
10977          */
10978         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10979                 return (CTL_ACTION_PASS);
10980
10981         /*
10982          * Ordered tags have to block until all items ahead of them
10983          * have completed.  If we get called with an ordered tag, we always
10984          * block, if something else is ahead of us in the queue.
10985          */
10986         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10987                 return (CTL_ACTION_BLOCK);
10988
10989         /*
10990          * Simple tags get blocked until all head of queue and ordered tags
10991          * ahead of them have completed.  I'm lumping untagged commands in
10992          * with simple tags here.  XXX KDM is that the right thing to do?
10993          */
10994         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10995           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10996          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10997           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10998                 return (CTL_ACTION_BLOCK);
10999
11000         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11001         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11002             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11003              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11004              pending_io->scsiio.cdb[1], pending_io));
11005         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11006         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11007                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11008         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11009             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11010              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11011              ooa_io->scsiio.cdb[1], ooa_io));
11012
11013         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11014
11015         switch (serialize_row[pending_entry->seridx]) {
11016         case CTL_SER_BLOCK:
11017                 return (CTL_ACTION_BLOCK);
11018         case CTL_SER_EXTENT:
11019                 return (ctl_extent_check(ooa_io, pending_io,
11020                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11021         case CTL_SER_EXTENTOPT:
11022                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11023                     SCP_QUEUE_ALG_UNRESTRICTED)
11024                         return (ctl_extent_check(ooa_io, pending_io,
11025                             (lun->be_lun &&
11026                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11027                 return (CTL_ACTION_PASS);
11028         case CTL_SER_EXTENTSEQ:
11029                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11030                         return (ctl_extent_check_seq(ooa_io, pending_io));
11031                 return (CTL_ACTION_PASS);
11032         case CTL_SER_PASS:
11033                 return (CTL_ACTION_PASS);
11034         case CTL_SER_BLOCKOPT:
11035                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11036                     SCP_QUEUE_ALG_UNRESTRICTED)
11037                         return (CTL_ACTION_BLOCK);
11038                 return (CTL_ACTION_PASS);
11039         case CTL_SER_SKIP:
11040                 return (CTL_ACTION_SKIP);
11041         default:
11042                 panic("%s: Invalid serialization value %d for %d => %d",
11043                     __func__, serialize_row[pending_entry->seridx],
11044                     pending_entry->seridx, ooa_entry->seridx);
11045         }
11046
11047         return (CTL_ACTION_ERROR);
11048 }
11049
11050 /*
11051  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11052  * Assumptions:
11053  * - pending_io is generally either incoming, or on the blocked queue
11054  * - starting I/O is the I/O we want to start the check with.
11055  */
11056 static ctl_action
11057 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11058               union ctl_io *starting_io)
11059 {
11060         union ctl_io *ooa_io;
11061         ctl_action action;
11062
11063         mtx_assert(&lun->lun_lock, MA_OWNED);
11064
11065         /*
11066          * Run back along the OOA queue, starting with the current
11067          * blocked I/O and going through every I/O before it on the
11068          * queue.  If starting_io is NULL, we'll just end up returning
11069          * CTL_ACTION_PASS.
11070          */
11071         for (ooa_io = starting_io; ooa_io != NULL;
11072              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11073              ooa_links)){
11074
11075                 /*
11076                  * This routine just checks to see whether
11077                  * cur_blocked is blocked by ooa_io, which is ahead
11078                  * of it in the queue.  It doesn't queue/dequeue
11079                  * cur_blocked.
11080                  */
11081                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11082                 switch (action) {
11083                 case CTL_ACTION_BLOCK:
11084                 case CTL_ACTION_OVERLAP:
11085                 case CTL_ACTION_OVERLAP_TAG:
11086                 case CTL_ACTION_SKIP:
11087                 case CTL_ACTION_ERROR:
11088                         return (action);
11089                         break; /* NOTREACHED */
11090                 case CTL_ACTION_PASS:
11091                         break;
11092                 default:
11093                         panic("%s: Invalid action %d\n", __func__, action);
11094                 }
11095         }
11096
11097         return (CTL_ACTION_PASS);
11098 }
11099
11100 /*
11101  * Assumptions:
11102  * - An I/O has just completed, and has been removed from the per-LUN OOA
11103  *   queue, so some items on the blocked queue may now be unblocked.
11104  */
11105 static int
11106 ctl_check_blocked(struct ctl_lun *lun)
11107 {
11108         struct ctl_softc *softc = lun->ctl_softc;
11109         union ctl_io *cur_blocked, *next_blocked;
11110
11111         mtx_assert(&lun->lun_lock, MA_OWNED);
11112
11113         /*
11114          * Run forward from the head of the blocked queue, checking each
11115          * entry against the I/Os prior to it on the OOA queue to see if
11116          * there is still any blockage.
11117          *
11118          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11119          * with our removing a variable on it while it is traversing the
11120          * list.
11121          */
11122         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11123              cur_blocked != NULL; cur_blocked = next_blocked) {
11124                 union ctl_io *prev_ooa;
11125                 ctl_action action;
11126
11127                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11128                                                           blocked_links);
11129
11130                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11131                                                       ctl_ooaq, ooa_links);
11132
11133                 /*
11134                  * If cur_blocked happens to be the first item in the OOA
11135                  * queue now, prev_ooa will be NULL, and the action
11136                  * returned will just be CTL_ACTION_PASS.
11137                  */
11138                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11139
11140                 switch (action) {
11141                 case CTL_ACTION_BLOCK:
11142                         /* Nothing to do here, still blocked */
11143                         break;
11144                 case CTL_ACTION_OVERLAP:
11145                 case CTL_ACTION_OVERLAP_TAG:
11146                         /*
11147                          * This shouldn't happen!  In theory we've already
11148                          * checked this command for overlap...
11149                          */
11150                         break;
11151                 case CTL_ACTION_PASS:
11152                 case CTL_ACTION_SKIP: {
11153                         const struct ctl_cmd_entry *entry;
11154
11155                         /*
11156                          * The skip case shouldn't happen, this transaction
11157                          * should have never made it onto the blocked queue.
11158                          */
11159                         /*
11160                          * This I/O is no longer blocked, we can remove it
11161                          * from the blocked queue.  Since this is a TAILQ
11162                          * (doubly linked list), we can do O(1) removals
11163                          * from any place on the list.
11164                          */
11165                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11166                                      blocked_links);
11167                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11168
11169                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11170                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11171                                 /*
11172                                  * Need to send IO back to original side to
11173                                  * run
11174                                  */
11175                                 union ctl_ha_msg msg_info;
11176
11177                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11178                                 msg_info.hdr.original_sc =
11179                                         cur_blocked->io_hdr.original_sc;
11180                                 msg_info.hdr.serializing_sc = cur_blocked;
11181                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11182                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11183                                     sizeof(msg_info.hdr), M_NOWAIT);
11184                                 break;
11185                         }
11186                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11187
11188                         /*
11189                          * Check this I/O for LUN state changes that may
11190                          * have happened while this command was blocked.
11191                          * The LUN state may have been changed by a command
11192                          * ahead of us in the queue, so we need to re-check
11193                          * for any states that can be caused by SCSI
11194                          * commands.
11195                          */
11196                         if (ctl_scsiio_lun_check(lun, entry,
11197                                                  &cur_blocked->scsiio) == 0) {
11198                                 cur_blocked->io_hdr.flags |=
11199                                                       CTL_FLAG_IS_WAS_ON_RTR;
11200                                 ctl_enqueue_rtr(cur_blocked);
11201                         } else
11202                                 ctl_done(cur_blocked);
11203                         break;
11204                 }
11205                 default:
11206                         /*
11207                          * This probably shouldn't happen -- we shouldn't
11208                          * get CTL_ACTION_ERROR, or anything else.
11209                          */
11210                         break;
11211                 }
11212         }
11213
11214         return (CTL_RETVAL_COMPLETE);
11215 }
11216
11217 /*
11218  * This routine (with one exception) checks LUN flags that can be set by
11219  * commands ahead of us in the OOA queue.  These flags have to be checked
11220  * when a command initially comes in, and when we pull a command off the
11221  * blocked queue and are preparing to execute it.  The reason we have to
11222  * check these flags for commands on the blocked queue is that the LUN
11223  * state may have been changed by a command ahead of us while we're on the
11224  * blocked queue.
11225  *
11226  * Ordering is somewhat important with these checks, so please pay
11227  * careful attention to the placement of any new checks.
11228  */
11229 static int
11230 ctl_scsiio_lun_check(struct ctl_lun *lun,
11231     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11232 {
11233         struct ctl_softc *softc = lun->ctl_softc;
11234         int retval;
11235         uint32_t residx;
11236
11237         retval = 0;
11238
11239         mtx_assert(&lun->lun_lock, MA_OWNED);
11240
11241         /*
11242          * If this shelf is a secondary shelf controller, we may have to
11243          * reject some commands disallowed by HA mode and link state.
11244          */
11245         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11246                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11247                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11248                         ctl_set_lun_unavail(ctsio);
11249                         retval = 1;
11250                         goto bailout;
11251                 }
11252                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11253                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11254                         ctl_set_lun_transit(ctsio);
11255                         retval = 1;
11256                         goto bailout;
11257                 }
11258                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11259                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11260                         ctl_set_lun_standby(ctsio);
11261                         retval = 1;
11262                         goto bailout;
11263                 }
11264
11265                 /* The rest of checks are only done on executing side */
11266                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11267                         goto bailout;
11268         }
11269
11270         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11271                 if (lun->be_lun &&
11272                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11273                         ctl_set_hw_write_protected(ctsio);
11274                         retval = 1;
11275                         goto bailout;
11276                 }
11277                 if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11278                         ctl_set_sense(ctsio, /*current_error*/ 1,
11279                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11280                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11281                         retval = 1;
11282                         goto bailout;
11283                 }
11284         }
11285
11286         /*
11287          * Check for a reservation conflict.  If this command isn't allowed
11288          * even on reserved LUNs, and if this initiator isn't the one who
11289          * reserved us, reject the command with a reservation conflict.
11290          */
11291         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11292         if ((lun->flags & CTL_LUN_RESERVED)
11293          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11294                 if (lun->res_idx != residx) {
11295                         ctl_set_reservation_conflict(ctsio);
11296                         retval = 1;
11297                         goto bailout;
11298                 }
11299         }
11300
11301         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11302             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11303                 /* No reservation or command is allowed. */;
11304         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11305             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11306              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11307              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11308                 /* The command is allowed for Write Exclusive resv. */;
11309         } else {
11310                 /*
11311                  * if we aren't registered or it's a res holder type
11312                  * reservation and this isn't the res holder then set a
11313                  * conflict.
11314                  */
11315                 if (ctl_get_prkey(lun, residx) == 0 ||
11316                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11317                         ctl_set_reservation_conflict(ctsio);
11318                         retval = 1;
11319                         goto bailout;
11320                 }
11321         }
11322
11323         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11324                 if (lun->flags & CTL_LUN_EJECTED)
11325                         ctl_set_lun_ejected(ctsio);
11326                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11327                         if (lun->flags & CTL_LUN_REMOVABLE)
11328                                 ctl_set_lun_no_media(ctsio);
11329                         else
11330                                 ctl_set_lun_int_reqd(ctsio);
11331                 } else if (lun->flags & CTL_LUN_STOPPED)
11332                         ctl_set_lun_stopped(ctsio);
11333                 else
11334                         goto bailout;
11335                 retval = 1;
11336                 goto bailout;
11337         }
11338
11339 bailout:
11340         return (retval);
11341 }
11342
11343 static void
11344 ctl_failover_io(union ctl_io *io, int have_lock)
11345 {
11346         ctl_set_busy(&io->scsiio);
11347         ctl_done(io);
11348 }
11349
11350 static void
11351 ctl_failover_lun(union ctl_io *rio)
11352 {
11353         struct ctl_softc *softc = CTL_SOFTC(rio);
11354         struct ctl_lun *lun;
11355         struct ctl_io_hdr *io, *next_io;
11356         uint32_t targ_lun;
11357
11358         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11359         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11360
11361         /* Find and lock the LUN. */
11362         mtx_lock(&softc->ctl_lock);
11363         if (targ_lun > CTL_MAX_LUNS ||
11364             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11365                 mtx_unlock(&softc->ctl_lock);
11366                 return;
11367         }
11368         mtx_lock(&lun->lun_lock);
11369         mtx_unlock(&softc->ctl_lock);
11370         if (lun->flags & CTL_LUN_DISABLED) {
11371                 mtx_unlock(&lun->lun_lock);
11372                 return;
11373         }
11374
11375         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11376                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11377                         /* We are master */
11378                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11379                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11380                                         io->flags |= CTL_FLAG_ABORT;
11381                                         io->flags |= CTL_FLAG_FAILOVER;
11382                                 } else { /* This can be only due to DATAMOVE */
11383                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11384                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11385                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11386                                         io->port_status = 31340;
11387                                         ctl_enqueue_isc((union ctl_io *)io);
11388                                 }
11389                         }
11390                         /* We are slave */
11391                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11392                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11393                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11394                                         io->flags |= CTL_FLAG_FAILOVER;
11395                                 } else {
11396                                         ctl_set_busy(&((union ctl_io *)io)->
11397                                             scsiio);
11398                                         ctl_done((union ctl_io *)io);
11399                                 }
11400                         }
11401                 }
11402         } else { /* SERIALIZE modes */
11403                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11404                     next_io) {
11405                         /* We are master */
11406                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11407                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11408                                     blocked_links);
11409                                 io->flags &= ~CTL_FLAG_BLOCKED;
11410                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11411                                 ctl_free_io((union ctl_io *)io);
11412                         }
11413                 }
11414                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11415                         /* We are master */
11416                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11417                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11418                                 ctl_free_io((union ctl_io *)io);
11419                         }
11420                         /* We are slave */
11421                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11422                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11423                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11424                                         ctl_set_busy(&((union ctl_io *)io)->
11425                                             scsiio);
11426                                         ctl_done((union ctl_io *)io);
11427                                 }
11428                         }
11429                 }
11430                 ctl_check_blocked(lun);
11431         }
11432         mtx_unlock(&lun->lun_lock);
11433 }
11434
11435 static int
11436 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11437 {
11438         struct ctl_lun *lun;
11439         const struct ctl_cmd_entry *entry;
11440         uint32_t initidx, targ_lun;
11441         int retval = 0;
11442
11443         lun = NULL;
11444         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11445         if (targ_lun < CTL_MAX_LUNS)
11446                 lun = softc->ctl_luns[targ_lun];
11447         if (lun) {
11448                 /*
11449                  * If the LUN is invalid, pretend that it doesn't exist.
11450                  * It will go away as soon as all pending I/O has been
11451                  * completed.
11452                  */
11453                 mtx_lock(&lun->lun_lock);
11454                 if (lun->flags & CTL_LUN_DISABLED) {
11455                         mtx_unlock(&lun->lun_lock);
11456                         lun = NULL;
11457                 }
11458         }
11459         CTL_LUN(ctsio) = lun;
11460         if (lun) {
11461                 CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11462
11463                 /*
11464                  * Every I/O goes into the OOA queue for a particular LUN,
11465                  * and stays there until completion.
11466                  */
11467 #ifdef CTL_TIME_IO
11468                 if (TAILQ_EMPTY(&lun->ooa_queue))
11469                         lun->idle_time += getsbinuptime() - lun->last_busy;
11470 #endif
11471                 TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11472         }
11473
11474         /* Get command entry and return error if it is unsuppotyed. */
11475         entry = ctl_validate_command(ctsio);
11476         if (entry == NULL) {
11477                 if (lun)
11478                         mtx_unlock(&lun->lun_lock);
11479                 return (retval);
11480         }
11481
11482         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11483         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11484
11485         /*
11486          * Check to see whether we can send this command to LUNs that don't
11487          * exist.  This should pretty much only be the case for inquiry
11488          * and request sense.  Further checks, below, really require having
11489          * a LUN, so we can't really check the command anymore.  Just put
11490          * it on the rtr queue.
11491          */
11492         if (lun == NULL) {
11493                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11494                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11495                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11496                         return (retval);
11497                 }
11498
11499                 ctl_set_unsupported_lun(ctsio);
11500                 ctl_done((union ctl_io *)ctsio);
11501                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11502                 return (retval);
11503         } else {
11504                 /*
11505                  * Make sure we support this particular command on this LUN.
11506                  * e.g., we don't support writes to the control LUN.
11507                  */
11508                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11509                         mtx_unlock(&lun->lun_lock);
11510                         ctl_set_invalid_opcode(ctsio);
11511                         ctl_done((union ctl_io *)ctsio);
11512                         return (retval);
11513                 }
11514         }
11515
11516         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11517
11518 #ifdef CTL_WITH_CA
11519         /*
11520          * If we've got a request sense, it'll clear the contingent
11521          * allegiance condition.  Otherwise, if we have a CA condition for
11522          * this initiator, clear it, because it sent down a command other
11523          * than request sense.
11524          */
11525         if ((ctsio->cdb[0] != REQUEST_SENSE)
11526          && (ctl_is_set(lun->have_ca, initidx)))
11527                 ctl_clear_mask(lun->have_ca, initidx);
11528 #endif
11529
11530         /*
11531          * If the command has this flag set, it handles its own unit
11532          * attention reporting, we shouldn't do anything.  Otherwise we
11533          * check for any pending unit attentions, and send them back to the
11534          * initiator.  We only do this when a command initially comes in,
11535          * not when we pull it off the blocked queue.
11536          *
11537          * According to SAM-3, section 5.3.2, the order that things get
11538          * presented back to the host is basically unit attentions caused
11539          * by some sort of reset event, busy status, reservation conflicts
11540          * or task set full, and finally any other status.
11541          *
11542          * One issue here is that some of the unit attentions we report
11543          * don't fall into the "reset" category (e.g. "reported luns data
11544          * has changed").  So reporting it here, before the reservation
11545          * check, may be technically wrong.  I guess the only thing to do
11546          * would be to check for and report the reset events here, and then
11547          * check for the other unit attention types after we check for a
11548          * reservation conflict.
11549          *
11550          * XXX KDM need to fix this
11551          */
11552         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11553                 ctl_ua_type ua_type;
11554                 u_int sense_len = 0;
11555
11556                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11557                     &sense_len, SSD_TYPE_NONE);
11558                 if (ua_type != CTL_UA_NONE) {
11559                         mtx_unlock(&lun->lun_lock);
11560                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11561                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11562                         ctsio->sense_len = sense_len;
11563                         ctl_done((union ctl_io *)ctsio);
11564                         return (retval);
11565                 }
11566         }
11567
11568
11569         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11570                 mtx_unlock(&lun->lun_lock);
11571                 ctl_done((union ctl_io *)ctsio);
11572                 return (retval);
11573         }
11574
11575         /*
11576          * XXX CHD this is where we want to send IO to other side if
11577          * this LUN is secondary on this SC. We will need to make a copy
11578          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11579          * the copy we send as FROM_OTHER.
11580          * We also need to stuff the address of the original IO so we can
11581          * find it easily. Something similar will need be done on the other
11582          * side so when we are done we can find the copy.
11583          */
11584         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11585             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11586             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11587                 union ctl_ha_msg msg_info;
11588                 int isc_retval;
11589
11590                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11591                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11592                 mtx_unlock(&lun->lun_lock);
11593
11594                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11595                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11596                 msg_info.hdr.serializing_sc = NULL;
11597                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11598                 msg_info.scsi.tag_num = ctsio->tag_num;
11599                 msg_info.scsi.tag_type = ctsio->tag_type;
11600                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11601                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11602
11603                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11604                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11605                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11606                         ctl_set_busy(ctsio);
11607                         ctl_done((union ctl_io *)ctsio);
11608                         return (retval);
11609                 }
11610                 return (retval);
11611         }
11612
11613         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11614                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11615                               ctl_ooaq, ooa_links))) {
11616         case CTL_ACTION_BLOCK:
11617                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11618                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11619                                   blocked_links);
11620                 mtx_unlock(&lun->lun_lock);
11621                 return (retval);
11622         case CTL_ACTION_PASS:
11623         case CTL_ACTION_SKIP:
11624                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11625                 mtx_unlock(&lun->lun_lock);
11626                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11627                 break;
11628         case CTL_ACTION_OVERLAP:
11629                 mtx_unlock(&lun->lun_lock);
11630                 ctl_set_overlapped_cmd(ctsio);
11631                 ctl_done((union ctl_io *)ctsio);
11632                 break;
11633         case CTL_ACTION_OVERLAP_TAG:
11634                 mtx_unlock(&lun->lun_lock);
11635                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11636                 ctl_done((union ctl_io *)ctsio);
11637                 break;
11638         case CTL_ACTION_ERROR:
11639         default:
11640                 mtx_unlock(&lun->lun_lock);
11641                 ctl_set_internal_failure(ctsio,
11642                                          /*sks_valid*/ 0,
11643                                          /*retry_count*/ 0);
11644                 ctl_done((union ctl_io *)ctsio);
11645                 break;
11646         }
11647         return (retval);
11648 }
11649
11650 const struct ctl_cmd_entry *
11651 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11652 {
11653         const struct ctl_cmd_entry *entry;
11654         int service_action;
11655
11656         entry = &ctl_cmd_table[ctsio->cdb[0]];
11657         if (sa)
11658                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11659         if (entry->flags & CTL_CMD_FLAG_SA5) {
11660                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11661                 entry = &((const struct ctl_cmd_entry *)
11662                     entry->execute)[service_action];
11663         }
11664         return (entry);
11665 }
11666
11667 const struct ctl_cmd_entry *
11668 ctl_validate_command(struct ctl_scsiio *ctsio)
11669 {
11670         const struct ctl_cmd_entry *entry;
11671         int i, sa;
11672         uint8_t diff;
11673
11674         entry = ctl_get_cmd_entry(ctsio, &sa);
11675         if (entry->execute == NULL) {
11676                 if (sa)
11677                         ctl_set_invalid_field(ctsio,
11678                                               /*sks_valid*/ 1,
11679                                               /*command*/ 1,
11680                                               /*field*/ 1,
11681                                               /*bit_valid*/ 1,
11682                                               /*bit*/ 4);
11683                 else
11684                         ctl_set_invalid_opcode(ctsio);
11685                 ctl_done((union ctl_io *)ctsio);
11686                 return (NULL);
11687         }
11688         KASSERT(entry->length > 0,
11689             ("Not defined length for command 0x%02x/0x%02x",
11690              ctsio->cdb[0], ctsio->cdb[1]));
11691         for (i = 1; i < entry->length; i++) {
11692                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11693                 if (diff == 0)
11694                         continue;
11695                 ctl_set_invalid_field(ctsio,
11696                                       /*sks_valid*/ 1,
11697                                       /*command*/ 1,
11698                                       /*field*/ i,
11699                                       /*bit_valid*/ 1,
11700                                       /*bit*/ fls(diff) - 1);
11701                 ctl_done((union ctl_io *)ctsio);
11702                 return (NULL);
11703         }
11704         return (entry);
11705 }
11706
11707 static int
11708 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11709 {
11710
11711         switch (lun_type) {
11712         case T_DIRECT:
11713                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11714                         return (0);
11715                 break;
11716         case T_PROCESSOR:
11717                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11718                         return (0);
11719                 break;
11720         case T_CDROM:
11721                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11722                         return (0);
11723                 break;
11724         default:
11725                 return (0);
11726         }
11727         return (1);
11728 }
11729
11730 static int
11731 ctl_scsiio(struct ctl_scsiio *ctsio)
11732 {
11733         int retval;
11734         const struct ctl_cmd_entry *entry;
11735
11736         retval = CTL_RETVAL_COMPLETE;
11737
11738         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11739
11740         entry = ctl_get_cmd_entry(ctsio, NULL);
11741
11742         /*
11743          * If this I/O has been aborted, just send it straight to
11744          * ctl_done() without executing it.
11745          */
11746         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11747                 ctl_done((union ctl_io *)ctsio);
11748                 goto bailout;
11749         }
11750
11751         /*
11752          * All the checks should have been handled by ctl_scsiio_precheck().
11753          * We should be clear now to just execute the I/O.
11754          */
11755         retval = entry->execute(ctsio);
11756
11757 bailout:
11758         return (retval);
11759 }
11760
11761 /*
11762  * Since we only implement one target right now, a bus reset simply resets
11763  * our single target.
11764  */
11765 static int
11766 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11767 {
11768         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11769 }
11770
11771 static int
11772 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11773                  ctl_ua_type ua_type)
11774 {
11775         struct ctl_port *port = CTL_PORT(io);
11776         struct ctl_lun *lun;
11777         int retval;
11778
11779         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11780                 union ctl_ha_msg msg_info;
11781
11782                 msg_info.hdr.nexus = io->io_hdr.nexus;
11783                 if (ua_type==CTL_UA_TARG_RESET)
11784                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11785                 else
11786                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11787                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11788                 msg_info.hdr.original_sc = NULL;
11789                 msg_info.hdr.serializing_sc = NULL;
11790                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11791                     sizeof(msg_info.task), M_WAITOK);
11792         }
11793         retval = 0;
11794
11795         mtx_lock(&softc->ctl_lock);
11796         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11797                 if (port != NULL &&
11798                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11799                         continue;
11800                 retval += ctl_do_lun_reset(lun, io, ua_type);
11801         }
11802         mtx_unlock(&softc->ctl_lock);
11803         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11804         return (retval);
11805 }
11806
11807 /*
11808  * The LUN should always be set.  The I/O is optional, and is used to
11809  * distinguish between I/Os sent by this initiator, and by other
11810  * initiators.  We set unit attention for initiators other than this one.
11811  * SAM-3 is vague on this point.  It does say that a unit attention should
11812  * be established for other initiators when a LUN is reset (see section
11813  * 5.7.3), but it doesn't specifically say that the unit attention should
11814  * be established for this particular initiator when a LUN is reset.  Here
11815  * is the relevant text, from SAM-3 rev 8:
11816  *
11817  * 5.7.2 When a SCSI initiator port aborts its own tasks
11818  *
11819  * When a SCSI initiator port causes its own task(s) to be aborted, no
11820  * notification that the task(s) have been aborted shall be returned to
11821  * the SCSI initiator port other than the completion response for the
11822  * command or task management function action that caused the task(s) to
11823  * be aborted and notification(s) associated with related effects of the
11824  * action (e.g., a reset unit attention condition).
11825  *
11826  * XXX KDM for now, we're setting unit attention for all initiators.
11827  */
11828 static int
11829 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11830 {
11831         union ctl_io *xio;
11832 #if 0
11833         uint32_t initidx;
11834 #endif
11835         int i;
11836
11837         mtx_lock(&lun->lun_lock);
11838         /*
11839          * Run through the OOA queue and abort each I/O.
11840          */
11841         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11842              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11843                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11844         }
11845
11846         /*
11847          * This version sets unit attention for every
11848          */
11849 #if 0
11850         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11851         ctl_est_ua_all(lun, initidx, ua_type);
11852 #else
11853         ctl_est_ua_all(lun, -1, ua_type);
11854 #endif
11855
11856         /*
11857          * A reset (any kind, really) clears reservations established with
11858          * RESERVE/RELEASE.  It does not clear reservations established
11859          * with PERSISTENT RESERVE OUT, but we don't support that at the
11860          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11861          * reservations made with the RESERVE/RELEASE commands, because
11862          * those commands are obsolete in SPC-3.
11863          */
11864         lun->flags &= ~CTL_LUN_RESERVED;
11865
11866 #ifdef CTL_WITH_CA
11867         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11868                 ctl_clear_mask(lun->have_ca, i);
11869 #endif
11870         lun->prevent_count = 0;
11871         if (lun->prevent) {
11872                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
11873                         ctl_clear_mask(lun->prevent, i);
11874         }
11875         mtx_unlock(&lun->lun_lock);
11876
11877         return (0);
11878 }
11879
11880 static int
11881 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11882 {
11883         struct ctl_lun *lun;
11884         uint32_t targ_lun;
11885         int retval;
11886
11887         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11888         mtx_lock(&softc->ctl_lock);
11889         if (targ_lun >= CTL_MAX_LUNS ||
11890             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11891                 mtx_unlock(&softc->ctl_lock);
11892                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11893                 return (1);
11894         }
11895         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11896         mtx_unlock(&softc->ctl_lock);
11897         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11898
11899         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11900                 union ctl_ha_msg msg_info;
11901
11902                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11903                 msg_info.hdr.nexus = io->io_hdr.nexus;
11904                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11905                 msg_info.hdr.original_sc = NULL;
11906                 msg_info.hdr.serializing_sc = NULL;
11907                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11908                     sizeof(msg_info.task), M_WAITOK);
11909         }
11910         return (retval);
11911 }
11912
11913 static void
11914 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11915     int other_sc)
11916 {
11917         union ctl_io *xio;
11918
11919         mtx_assert(&lun->lun_lock, MA_OWNED);
11920
11921         /*
11922          * Run through the OOA queue and attempt to find the given I/O.
11923          * The target port, initiator ID, tag type and tag number have to
11924          * match the values that we got from the initiator.  If we have an
11925          * untagged command to abort, simply abort the first untagged command
11926          * we come to.  We only allow one untagged command at a time of course.
11927          */
11928         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11929              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11930
11931                 if ((targ_port == UINT32_MAX ||
11932                      targ_port == xio->io_hdr.nexus.targ_port) &&
11933                     (init_id == UINT32_MAX ||
11934                      init_id == xio->io_hdr.nexus.initid)) {
11935                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11936                             init_id != xio->io_hdr.nexus.initid)
11937                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11938                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11939                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11940                                 union ctl_ha_msg msg_info;
11941
11942                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11943                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11944                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11945                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11946                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11947                                 msg_info.hdr.original_sc = NULL;
11948                                 msg_info.hdr.serializing_sc = NULL;
11949                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11950                                     sizeof(msg_info.task), M_NOWAIT);
11951                         }
11952                 }
11953         }
11954 }
11955
11956 static int
11957 ctl_abort_task_set(union ctl_io *io)
11958 {
11959         struct ctl_softc *softc = CTL_SOFTC(io);
11960         struct ctl_lun *lun;
11961         uint32_t targ_lun;
11962
11963         /*
11964          * Look up the LUN.
11965          */
11966         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11967         mtx_lock(&softc->ctl_lock);
11968         if (targ_lun >= CTL_MAX_LUNS ||
11969             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11970                 mtx_unlock(&softc->ctl_lock);
11971                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11972                 return (1);
11973         }
11974
11975         mtx_lock(&lun->lun_lock);
11976         mtx_unlock(&softc->ctl_lock);
11977         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11978                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11979                     io->io_hdr.nexus.initid,
11980                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11981         } else { /* CTL_TASK_CLEAR_TASK_SET */
11982                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11983                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11984         }
11985         mtx_unlock(&lun->lun_lock);
11986         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11987         return (0);
11988 }
11989
11990 static int
11991 ctl_i_t_nexus_reset(union ctl_io *io)
11992 {
11993         struct ctl_softc *softc = CTL_SOFTC(io);
11994         struct ctl_lun *lun;
11995         uint32_t initidx;
11996
11997         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11998                 union ctl_ha_msg msg_info;
11999
12000                 msg_info.hdr.nexus = io->io_hdr.nexus;
12001                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12002                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12003                 msg_info.hdr.original_sc = NULL;
12004                 msg_info.hdr.serializing_sc = NULL;
12005                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12006                     sizeof(msg_info.task), M_WAITOK);
12007         }
12008
12009         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12010         mtx_lock(&softc->ctl_lock);
12011         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12012                 mtx_lock(&lun->lun_lock);
12013                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12014                     io->io_hdr.nexus.initid, 1);
12015 #ifdef CTL_WITH_CA
12016                 ctl_clear_mask(lun->have_ca, initidx);
12017 #endif
12018                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12019                         lun->flags &= ~CTL_LUN_RESERVED;
12020                 if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12021                         ctl_clear_mask(lun->prevent, initidx);
12022                         lun->prevent_count--;
12023                 }
12024                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12025                 mtx_unlock(&lun->lun_lock);
12026         }
12027         mtx_unlock(&softc->ctl_lock);
12028         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12029         return (0);
12030 }
12031
12032 static int
12033 ctl_abort_task(union ctl_io *io)
12034 {
12035         struct ctl_softc *softc = CTL_SOFTC(io);
12036         union ctl_io *xio;
12037         struct ctl_lun *lun;
12038 #if 0
12039         struct sbuf sb;
12040         char printbuf[128];
12041 #endif
12042         int found;
12043         uint32_t targ_lun;
12044
12045         found = 0;
12046
12047         /*
12048          * Look up the LUN.
12049          */
12050         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12051         mtx_lock(&softc->ctl_lock);
12052         if (targ_lun >= CTL_MAX_LUNS ||
12053             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12054                 mtx_unlock(&softc->ctl_lock);
12055                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12056                 return (1);
12057         }
12058
12059 #if 0
12060         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12061                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12062 #endif
12063
12064         mtx_lock(&lun->lun_lock);
12065         mtx_unlock(&softc->ctl_lock);
12066         /*
12067          * Run through the OOA queue and attempt to find the given I/O.
12068          * The target port, initiator ID, tag type and tag number have to
12069          * match the values that we got from the initiator.  If we have an
12070          * untagged command to abort, simply abort the first untagged command
12071          * we come to.  We only allow one untagged command at a time of course.
12072          */
12073         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12074              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12075 #if 0
12076                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12077
12078                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12079                             lun->lun, xio->scsiio.tag_num,
12080                             xio->scsiio.tag_type,
12081                             (xio->io_hdr.blocked_links.tqe_prev
12082                             == NULL) ? "" : " BLOCKED",
12083                             (xio->io_hdr.flags &
12084                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12085                             (xio->io_hdr.flags &
12086                             CTL_FLAG_ABORT) ? " ABORT" : "",
12087                             (xio->io_hdr.flags &
12088                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12089                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12090                 sbuf_finish(&sb);
12091                 printf("%s\n", sbuf_data(&sb));
12092 #endif
12093
12094                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12095                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12096                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12097                         continue;
12098
12099                 /*
12100                  * If the abort says that the task is untagged, the
12101                  * task in the queue must be untagged.  Otherwise,
12102                  * we just check to see whether the tag numbers
12103                  * match.  This is because the QLogic firmware
12104                  * doesn't pass back the tag type in an abort
12105                  * request.
12106                  */
12107 #if 0
12108                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12109                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12110                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12111 #endif
12112                 /*
12113                  * XXX KDM we've got problems with FC, because it
12114                  * doesn't send down a tag type with aborts.  So we
12115                  * can only really go by the tag number...
12116                  * This may cause problems with parallel SCSI.
12117                  * Need to figure that out!!
12118                  */
12119                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12120                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12121                         found = 1;
12122                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12123                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12124                                 union ctl_ha_msg msg_info;
12125
12126                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12127                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12128                                 msg_info.task.tag_num = io->taskio.tag_num;
12129                                 msg_info.task.tag_type = io->taskio.tag_type;
12130                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12131                                 msg_info.hdr.original_sc = NULL;
12132                                 msg_info.hdr.serializing_sc = NULL;
12133 #if 0
12134                                 printf("Sent Abort to other side\n");
12135 #endif
12136                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12137                                     sizeof(msg_info.task), M_NOWAIT);
12138                         }
12139 #if 0
12140                         printf("ctl_abort_task: found I/O to abort\n");
12141 #endif
12142                 }
12143         }
12144         mtx_unlock(&lun->lun_lock);
12145
12146         if (found == 0) {
12147                 /*
12148                  * This isn't really an error.  It's entirely possible for
12149                  * the abort and command completion to cross on the wire.
12150                  * This is more of an informative/diagnostic error.
12151                  */
12152 #if 0
12153                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12154                        "%u:%u:%u tag %d type %d\n",
12155                        io->io_hdr.nexus.initid,
12156                        io->io_hdr.nexus.targ_port,
12157                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12158                        io->taskio.tag_type);
12159 #endif
12160         }
12161         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12162         return (0);
12163 }
12164
12165 static int
12166 ctl_query_task(union ctl_io *io, int task_set)
12167 {
12168         struct ctl_softc *softc = CTL_SOFTC(io);
12169         union ctl_io *xio;
12170         struct ctl_lun *lun;
12171         int found = 0;
12172         uint32_t targ_lun;
12173
12174         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12175         mtx_lock(&softc->ctl_lock);
12176         if (targ_lun >= CTL_MAX_LUNS ||
12177             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12178                 mtx_unlock(&softc->ctl_lock);
12179                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12180                 return (1);
12181         }
12182         mtx_lock(&lun->lun_lock);
12183         mtx_unlock(&softc->ctl_lock);
12184         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12185              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12186
12187                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12188                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12189                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12190                         continue;
12191
12192                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12193                         found = 1;
12194                         break;
12195                 }
12196         }
12197         mtx_unlock(&lun->lun_lock);
12198         if (found)
12199                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12200         else
12201                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12202         return (0);
12203 }
12204
12205 static int
12206 ctl_query_async_event(union ctl_io *io)
12207 {
12208         struct ctl_softc *softc = CTL_SOFTC(io);
12209         struct ctl_lun *lun;
12210         ctl_ua_type ua;
12211         uint32_t targ_lun, initidx;
12212
12213         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12214         mtx_lock(&softc->ctl_lock);
12215         if (targ_lun >= CTL_MAX_LUNS ||
12216             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12217                 mtx_unlock(&softc->ctl_lock);
12218                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12219                 return (1);
12220         }
12221         mtx_lock(&lun->lun_lock);
12222         mtx_unlock(&softc->ctl_lock);
12223         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12224         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12225         mtx_unlock(&lun->lun_lock);
12226         if (ua != CTL_UA_NONE)
12227                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12228         else
12229                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12230         return (0);
12231 }
12232
12233 static void
12234 ctl_run_task(union ctl_io *io)
12235 {
12236         struct ctl_softc *softc = CTL_SOFTC(io);
12237         int retval = 1;
12238
12239         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12240         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12241             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12242         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12243         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12244         switch (io->taskio.task_action) {
12245         case CTL_TASK_ABORT_TASK:
12246                 retval = ctl_abort_task(io);
12247                 break;
12248         case CTL_TASK_ABORT_TASK_SET:
12249         case CTL_TASK_CLEAR_TASK_SET:
12250                 retval = ctl_abort_task_set(io);
12251                 break;
12252         case CTL_TASK_CLEAR_ACA:
12253                 break;
12254         case CTL_TASK_I_T_NEXUS_RESET:
12255                 retval = ctl_i_t_nexus_reset(io);
12256                 break;
12257         case CTL_TASK_LUN_RESET:
12258                 retval = ctl_lun_reset(softc, io);
12259                 break;
12260         case CTL_TASK_TARGET_RESET:
12261                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12262                 break;
12263         case CTL_TASK_BUS_RESET:
12264                 retval = ctl_bus_reset(softc, io);
12265                 break;
12266         case CTL_TASK_PORT_LOGIN:
12267                 break;
12268         case CTL_TASK_PORT_LOGOUT:
12269                 break;
12270         case CTL_TASK_QUERY_TASK:
12271                 retval = ctl_query_task(io, 0);
12272                 break;
12273         case CTL_TASK_QUERY_TASK_SET:
12274                 retval = ctl_query_task(io, 1);
12275                 break;
12276         case CTL_TASK_QUERY_ASYNC_EVENT:
12277                 retval = ctl_query_async_event(io);
12278                 break;
12279         default:
12280                 printf("%s: got unknown task management event %d\n",
12281                        __func__, io->taskio.task_action);
12282                 break;
12283         }
12284         if (retval == 0)
12285                 io->io_hdr.status = CTL_SUCCESS;
12286         else
12287                 io->io_hdr.status = CTL_ERROR;
12288         ctl_done(io);
12289 }
12290
12291 /*
12292  * For HA operation.  Handle commands that come in from the other
12293  * controller.
12294  */
12295 static void
12296 ctl_handle_isc(union ctl_io *io)
12297 {
12298         struct ctl_softc *softc = CTL_SOFTC(io);
12299         struct ctl_lun *lun;
12300         const struct ctl_cmd_entry *entry;
12301         uint32_t targ_lun;
12302
12303         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12304         switch (io->io_hdr.msg_type) {
12305         case CTL_MSG_SERIALIZE:
12306                 ctl_serialize_other_sc_cmd(&io->scsiio);
12307                 break;
12308         case CTL_MSG_R2R:               /* Only used in SER_ONLY mode. */
12309                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12310                 if (targ_lun >= CTL_MAX_LUNS ||
12311                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12312                         ctl_done(io);
12313                         break;
12314                 }
12315                 mtx_lock(&lun->lun_lock);
12316                 if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12317                         mtx_unlock(&lun->lun_lock);
12318                         ctl_done(io);
12319                         break;
12320                 }
12321                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12322                 mtx_unlock(&lun->lun_lock);
12323                 ctl_enqueue_rtr(io);
12324                 break;
12325         case CTL_MSG_FINISH_IO:
12326                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12327                         ctl_done(io);
12328                         break;
12329                 }
12330                 if (targ_lun >= CTL_MAX_LUNS ||
12331                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12332                         ctl_free_io(io);
12333                         break;
12334                 }
12335                 mtx_lock(&lun->lun_lock);
12336                 TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12337                 ctl_check_blocked(lun);
12338                 mtx_unlock(&lun->lun_lock);
12339                 ctl_free_io(io);
12340                 break;
12341         case CTL_MSG_PERS_ACTION:
12342                 ctl_hndl_per_res_out_on_other_sc(io);
12343                 ctl_free_io(io);
12344                 break;
12345         case CTL_MSG_BAD_JUJU:
12346                 ctl_done(io);
12347                 break;
12348         case CTL_MSG_DATAMOVE:          /* Only used in XFER mode */
12349                 ctl_datamove_remote(io);
12350                 break;
12351         case CTL_MSG_DATAMOVE_DONE:     /* Only used in XFER mode */
12352                 io->scsiio.be_move_done(io);
12353                 break;
12354         case CTL_MSG_FAILOVER:
12355                 ctl_failover_lun(io);
12356                 ctl_free_io(io);
12357                 break;
12358         default:
12359                 printf("%s: Invalid message type %d\n",
12360                        __func__, io->io_hdr.msg_type);
12361                 ctl_free_io(io);
12362                 break;
12363         }
12364
12365 }
12366
12367
12368 /*
12369  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12370  * there is no match.
12371  */
12372 static ctl_lun_error_pattern
12373 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12374 {
12375         const struct ctl_cmd_entry *entry;
12376         ctl_lun_error_pattern filtered_pattern, pattern;
12377
12378         pattern = desc->error_pattern;
12379
12380         /*
12381          * XXX KDM we need more data passed into this function to match a
12382          * custom pattern, and we actually need to implement custom pattern
12383          * matching.
12384          */
12385         if (pattern & CTL_LUN_PAT_CMD)
12386                 return (CTL_LUN_PAT_CMD);
12387
12388         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12389                 return (CTL_LUN_PAT_ANY);
12390
12391         entry = ctl_get_cmd_entry(ctsio, NULL);
12392
12393         filtered_pattern = entry->pattern & pattern;
12394
12395         /*
12396          * If the user requested specific flags in the pattern (e.g.
12397          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12398          * flags.
12399          *
12400          * If the user did not specify any flags, it doesn't matter whether
12401          * or not the command supports the flags.
12402          */
12403         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12404              (pattern & ~CTL_LUN_PAT_MASK))
12405                 return (CTL_LUN_PAT_NONE);
12406
12407         /*
12408          * If the user asked for a range check, see if the requested LBA
12409          * range overlaps with this command's LBA range.
12410          */
12411         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12412                 uint64_t lba1;
12413                 uint64_t len1;
12414                 ctl_action action;
12415                 int retval;
12416
12417                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12418                 if (retval != 0)
12419                         return (CTL_LUN_PAT_NONE);
12420
12421                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12422                                               desc->lba_range.len, FALSE);
12423                 /*
12424                  * A "pass" means that the LBA ranges don't overlap, so
12425                  * this doesn't match the user's range criteria.
12426                  */
12427                 if (action == CTL_ACTION_PASS)
12428                         return (CTL_LUN_PAT_NONE);
12429         }
12430
12431         return (filtered_pattern);
12432 }
12433
12434 static void
12435 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12436 {
12437         struct ctl_error_desc *desc, *desc2;
12438
12439         mtx_assert(&lun->lun_lock, MA_OWNED);
12440
12441         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12442                 ctl_lun_error_pattern pattern;
12443                 /*
12444                  * Check to see whether this particular command matches
12445                  * the pattern in the descriptor.
12446                  */
12447                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12448                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12449                         continue;
12450
12451                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12452                 case CTL_LUN_INJ_ABORTED:
12453                         ctl_set_aborted(&io->scsiio);
12454                         break;
12455                 case CTL_LUN_INJ_MEDIUM_ERR:
12456                         ctl_set_medium_error(&io->scsiio,
12457                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12458                              CTL_FLAG_DATA_OUT);
12459                         break;
12460                 case CTL_LUN_INJ_UA:
12461                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12462                          * OCCURRED */
12463                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12464                         break;
12465                 case CTL_LUN_INJ_CUSTOM:
12466                         /*
12467                          * We're assuming the user knows what he is doing.
12468                          * Just copy the sense information without doing
12469                          * checks.
12470                          */
12471                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12472                               MIN(sizeof(desc->custom_sense),
12473                                   sizeof(io->scsiio.sense_data)));
12474                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12475                         io->scsiio.sense_len = SSD_FULL_SIZE;
12476                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12477                         break;
12478                 case CTL_LUN_INJ_NONE:
12479                 default:
12480                         /*
12481                          * If this is an error injection type we don't know
12482                          * about, clear the continuous flag (if it is set)
12483                          * so it will get deleted below.
12484                          */
12485                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12486                         break;
12487                 }
12488                 /*
12489                  * By default, each error injection action is a one-shot
12490                  */
12491                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12492                         continue;
12493
12494                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12495
12496                 free(desc, M_CTL);
12497         }
12498 }
12499
12500 #ifdef CTL_IO_DELAY
12501 static void
12502 ctl_datamove_timer_wakeup(void *arg)
12503 {
12504         union ctl_io *io;
12505
12506         io = (union ctl_io *)arg;
12507
12508         ctl_datamove(io);
12509 }
12510 #endif /* CTL_IO_DELAY */
12511
12512 void
12513 ctl_datamove(union ctl_io *io)
12514 {
12515         void (*fe_datamove)(union ctl_io *io);
12516
12517         mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12518
12519         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12520
12521 #ifdef CTL_TIME_IO
12522         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12523                 char str[256];
12524                 char path_str[64];
12525                 struct sbuf sb;
12526
12527                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12528                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12529
12530                 sbuf_cat(&sb, path_str);
12531                 switch (io->io_hdr.io_type) {
12532                 case CTL_IO_SCSI:
12533                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12534                         sbuf_printf(&sb, "\n");
12535                         sbuf_cat(&sb, path_str);
12536                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12537                                     io->scsiio.tag_num, io->scsiio.tag_type);
12538                         break;
12539                 case CTL_IO_TASK:
12540                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12541                                     "Tag Type: %d\n", io->taskio.task_action,
12542                                     io->taskio.tag_num, io->taskio.tag_type);
12543                         break;
12544                 default:
12545                         panic("%s: Invalid CTL I/O type %d\n",
12546                             __func__, io->io_hdr.io_type);
12547                 }
12548                 sbuf_cat(&sb, path_str);
12549                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12550                             (intmax_t)time_uptime - io->io_hdr.start_time);
12551                 sbuf_finish(&sb);
12552                 printf("%s", sbuf_data(&sb));
12553         }
12554 #endif /* CTL_TIME_IO */
12555
12556 #ifdef CTL_IO_DELAY
12557         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12558                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12559         } else {
12560                 if ((lun != NULL)
12561                  && (lun->delay_info.datamove_delay > 0)) {
12562
12563                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12564                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12565                         callout_reset(&io->io_hdr.delay_callout,
12566                                       lun->delay_info.datamove_delay * hz,
12567                                       ctl_datamove_timer_wakeup, io);
12568                         if (lun->delay_info.datamove_type ==
12569                             CTL_DELAY_TYPE_ONESHOT)
12570                                 lun->delay_info.datamove_delay = 0;
12571                         return;
12572                 }
12573         }
12574 #endif
12575
12576         /*
12577          * This command has been aborted.  Set the port status, so we fail
12578          * the data move.
12579          */
12580         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12581                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12582                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12583                        io->io_hdr.nexus.targ_port,
12584                        io->io_hdr.nexus.targ_lun);
12585                 io->io_hdr.port_status = 31337;
12586                 /*
12587                  * Note that the backend, in this case, will get the
12588                  * callback in its context.  In other cases it may get
12589                  * called in the frontend's interrupt thread context.
12590                  */
12591                 io->scsiio.be_move_done(io);
12592                 return;
12593         }
12594
12595         /* Don't confuse frontend with zero length data move. */
12596         if (io->scsiio.kern_data_len == 0) {
12597                 io->scsiio.be_move_done(io);
12598                 return;
12599         }
12600
12601         fe_datamove = CTL_PORT(io)->fe_datamove;
12602         fe_datamove(io);
12603 }
12604
12605 static void
12606 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12607 {
12608         union ctl_ha_msg msg;
12609 #ifdef CTL_TIME_IO
12610         struct bintime cur_bt;
12611 #endif
12612
12613         memset(&msg, 0, sizeof(msg));
12614         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12615         msg.hdr.original_sc = io;
12616         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12617         msg.hdr.nexus = io->io_hdr.nexus;
12618         msg.hdr.status = io->io_hdr.status;
12619         msg.scsi.tag_num = io->scsiio.tag_num;
12620         msg.scsi.tag_type = io->scsiio.tag_type;
12621         msg.scsi.scsi_status = io->scsiio.scsi_status;
12622         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12623                io->scsiio.sense_len);
12624         msg.scsi.sense_len = io->scsiio.sense_len;
12625         msg.scsi.sense_residual = io->scsiio.sense_residual;
12626         msg.scsi.fetd_status = io->io_hdr.port_status;
12627         msg.scsi.residual = io->scsiio.residual;
12628         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12629         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12630                 ctl_failover_io(io, /*have_lock*/ have_lock);
12631                 return;
12632         }
12633         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12634             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12635             msg.scsi.sense_len, M_WAITOK);
12636
12637 #ifdef CTL_TIME_IO
12638         getbinuptime(&cur_bt);
12639         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12640         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12641 #endif
12642         io->io_hdr.num_dmas++;
12643 }
12644
12645 /*
12646  * The DMA to the remote side is done, now we need to tell the other side
12647  * we're done so it can continue with its data movement.
12648  */
12649 static void
12650 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12651 {
12652         union ctl_io *io;
12653         uint32_t i;
12654
12655         io = rq->context;
12656
12657         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12658                 printf("%s: ISC DMA write failed with error %d", __func__,
12659                        rq->ret);
12660                 ctl_set_internal_failure(&io->scsiio,
12661                                          /*sks_valid*/ 1,
12662                                          /*retry_count*/ rq->ret);
12663         }
12664
12665         ctl_dt_req_free(rq);
12666
12667         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12668                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12669         free(io->io_hdr.remote_sglist, M_CTL);
12670         io->io_hdr.remote_sglist = NULL;
12671         io->io_hdr.local_sglist = NULL;
12672
12673         /*
12674          * The data is in local and remote memory, so now we need to send
12675          * status (good or back) back to the other side.
12676          */
12677         ctl_send_datamove_done(io, /*have_lock*/ 0);
12678 }
12679
12680 /*
12681  * We've moved the data from the host/controller into local memory.  Now we
12682  * need to push it over to the remote controller's memory.
12683  */
12684 static int
12685 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12686 {
12687         int retval;
12688
12689         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12690                                           ctl_datamove_remote_write_cb);
12691         return (retval);
12692 }
12693
12694 static void
12695 ctl_datamove_remote_write(union ctl_io *io)
12696 {
12697         int retval;
12698         void (*fe_datamove)(union ctl_io *io);
12699
12700         /*
12701          * - Get the data from the host/HBA into local memory.
12702          * - DMA memory from the local controller to the remote controller.
12703          * - Send status back to the remote controller.
12704          */
12705
12706         retval = ctl_datamove_remote_sgl_setup(io);
12707         if (retval != 0)
12708                 return;
12709
12710         /* Switch the pointer over so the FETD knows what to do */
12711         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12712
12713         /*
12714          * Use a custom move done callback, since we need to send completion
12715          * back to the other controller, not to the backend on this side.
12716          */
12717         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12718
12719         fe_datamove = CTL_PORT(io)->fe_datamove;
12720         fe_datamove(io);
12721 }
12722
12723 static int
12724 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12725 {
12726 #if 0
12727         char str[256];
12728         char path_str[64];
12729         struct sbuf sb;
12730 #endif
12731         uint32_t i;
12732
12733         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12734                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12735         free(io->io_hdr.remote_sglist, M_CTL);
12736         io->io_hdr.remote_sglist = NULL;
12737         io->io_hdr.local_sglist = NULL;
12738
12739 #if 0
12740         scsi_path_string(io, path_str, sizeof(path_str));
12741         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12742         sbuf_cat(&sb, path_str);
12743         scsi_command_string(&io->scsiio, NULL, &sb);
12744         sbuf_printf(&sb, "\n");
12745         sbuf_cat(&sb, path_str);
12746         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12747                     io->scsiio.tag_num, io->scsiio.tag_type);
12748         sbuf_cat(&sb, path_str);
12749         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12750                     io->io_hdr.flags, io->io_hdr.status);
12751         sbuf_finish(&sb);
12752         printk("%s", sbuf_data(&sb));
12753 #endif
12754
12755
12756         /*
12757          * The read is done, now we need to send status (good or bad) back
12758          * to the other side.
12759          */
12760         ctl_send_datamove_done(io, /*have_lock*/ 0);
12761
12762         return (0);
12763 }
12764
12765 static void
12766 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12767 {
12768         union ctl_io *io;
12769         void (*fe_datamove)(union ctl_io *io);
12770
12771         io = rq->context;
12772
12773         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12774                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12775                        rq->ret);
12776                 ctl_set_internal_failure(&io->scsiio,
12777                                          /*sks_valid*/ 1,
12778                                          /*retry_count*/ rq->ret);
12779         }
12780
12781         ctl_dt_req_free(rq);
12782
12783         /* Switch the pointer over so the FETD knows what to do */
12784         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12785
12786         /*
12787          * Use a custom move done callback, since we need to send completion
12788          * back to the other controller, not to the backend on this side.
12789          */
12790         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12791
12792         /* XXX KDM add checks like the ones in ctl_datamove? */
12793
12794         fe_datamove = CTL_PORT(io)->fe_datamove;
12795         fe_datamove(io);
12796 }
12797
12798 static int
12799 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12800 {
12801         struct ctl_sg_entry *local_sglist;
12802         uint32_t len_to_go;
12803         int retval;
12804         int i;
12805
12806         retval = 0;
12807         local_sglist = io->io_hdr.local_sglist;
12808         len_to_go = io->scsiio.kern_data_len;
12809
12810         /*
12811          * The difficult thing here is that the size of the various
12812          * S/G segments may be different than the size from the
12813          * remote controller.  That'll make it harder when DMAing
12814          * the data back to the other side.
12815          */
12816         for (i = 0; len_to_go > 0; i++) {
12817                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12818                 local_sglist[i].addr =
12819                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12820
12821                 len_to_go -= local_sglist[i].len;
12822         }
12823         /*
12824          * Reset the number of S/G entries accordingly.  The original
12825          * number of S/G entries is available in rem_sg_entries.
12826          */
12827         io->scsiio.kern_sg_entries = i;
12828
12829 #if 0
12830         printf("%s: kern_sg_entries = %d\n", __func__,
12831                io->scsiio.kern_sg_entries);
12832         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12833                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12834                        local_sglist[i].addr, local_sglist[i].len);
12835 #endif
12836
12837         return (retval);
12838 }
12839
12840 static int
12841 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12842                          ctl_ha_dt_cb callback)
12843 {
12844         struct ctl_ha_dt_req *rq;
12845         struct ctl_sg_entry *remote_sglist, *local_sglist;
12846         uint32_t local_used, remote_used, total_used;
12847         int i, j, isc_ret;
12848
12849         rq = ctl_dt_req_alloc();
12850
12851         /*
12852          * If we failed to allocate the request, and if the DMA didn't fail
12853          * anyway, set busy status.  This is just a resource allocation
12854          * failure.
12855          */
12856         if ((rq == NULL)
12857          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12858              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12859                 ctl_set_busy(&io->scsiio);
12860
12861         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12862             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12863
12864                 if (rq != NULL)
12865                         ctl_dt_req_free(rq);
12866
12867                 /*
12868                  * The data move failed.  We need to return status back
12869                  * to the other controller.  No point in trying to DMA
12870                  * data to the remote controller.
12871                  */
12872
12873                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12874
12875                 return (1);
12876         }
12877
12878         local_sglist = io->io_hdr.local_sglist;
12879         remote_sglist = io->io_hdr.remote_sglist;
12880         local_used = 0;
12881         remote_used = 0;
12882         total_used = 0;
12883
12884         /*
12885          * Pull/push the data over the wire from/to the other controller.
12886          * This takes into account the possibility that the local and
12887          * remote sglists may not be identical in terms of the size of
12888          * the elements and the number of elements.
12889          *
12890          * One fundamental assumption here is that the length allocated for
12891          * both the local and remote sglists is identical.  Otherwise, we've
12892          * essentially got a coding error of some sort.
12893          */
12894         isc_ret = CTL_HA_STATUS_SUCCESS;
12895         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12896                 uint32_t cur_len;
12897                 uint8_t *tmp_ptr;
12898
12899                 rq->command = command;
12900                 rq->context = io;
12901
12902                 /*
12903                  * Both pointers should be aligned.  But it is possible
12904                  * that the allocation length is not.  They should both
12905                  * also have enough slack left over at the end, though,
12906                  * to round up to the next 8 byte boundary.
12907                  */
12908                 cur_len = MIN(local_sglist[i].len - local_used,
12909                               remote_sglist[j].len - remote_used);
12910                 rq->size = cur_len;
12911
12912                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12913                 tmp_ptr += local_used;
12914
12915 #if 0
12916                 /* Use physical addresses when talking to ISC hardware */
12917                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12918                         /* XXX KDM use busdma */
12919                         rq->local = vtophys(tmp_ptr);
12920                 } else
12921                         rq->local = tmp_ptr;
12922 #else
12923                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12924                     ("HA does not support BUS_ADDR"));
12925                 rq->local = tmp_ptr;
12926 #endif
12927
12928                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12929                 tmp_ptr += remote_used;
12930                 rq->remote = tmp_ptr;
12931
12932                 rq->callback = NULL;
12933
12934                 local_used += cur_len;
12935                 if (local_used >= local_sglist[i].len) {
12936                         i++;
12937                         local_used = 0;
12938                 }
12939
12940                 remote_used += cur_len;
12941                 if (remote_used >= remote_sglist[j].len) {
12942                         j++;
12943                         remote_used = 0;
12944                 }
12945                 total_used += cur_len;
12946
12947                 if (total_used >= io->scsiio.kern_data_len)
12948                         rq->callback = callback;
12949
12950 #if 0
12951                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12952                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12953                        rq->local, rq->remote, rq->size);
12954 #endif
12955
12956                 isc_ret = ctl_dt_single(rq);
12957                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12958                         break;
12959         }
12960         if (isc_ret != CTL_HA_STATUS_WAIT) {
12961                 rq->ret = isc_ret;
12962                 callback(rq);
12963         }
12964
12965         return (0);
12966 }
12967
12968 static void
12969 ctl_datamove_remote_read(union ctl_io *io)
12970 {
12971         int retval;
12972         uint32_t i;
12973
12974         /*
12975          * This will send an error to the other controller in the case of a
12976          * failure.
12977          */
12978         retval = ctl_datamove_remote_sgl_setup(io);
12979         if (retval != 0)
12980                 return;
12981
12982         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12983                                           ctl_datamove_remote_read_cb);
12984         if (retval != 0) {
12985                 /*
12986                  * Make sure we free memory if there was an error..  The
12987                  * ctl_datamove_remote_xfer() function will send the
12988                  * datamove done message, or call the callback with an
12989                  * error if there is a problem.
12990                  */
12991                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12992                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12993                 free(io->io_hdr.remote_sglist, M_CTL);
12994                 io->io_hdr.remote_sglist = NULL;
12995                 io->io_hdr.local_sglist = NULL;
12996         }
12997 }
12998
12999 /*
13000  * Process a datamove request from the other controller.  This is used for
13001  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13002  * first.  Once that is complete, the data gets DMAed into the remote
13003  * controller's memory.  For reads, we DMA from the remote controller's
13004  * memory into our memory first, and then move it out to the FETD.
13005  */
13006 static void
13007 ctl_datamove_remote(union ctl_io *io)
13008 {
13009
13010         mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13011
13012         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13013                 ctl_failover_io(io, /*have_lock*/ 0);
13014                 return;
13015         }
13016
13017         /*
13018          * Note that we look for an aborted I/O here, but don't do some of
13019          * the other checks that ctl_datamove() normally does.
13020          * We don't need to run the datamove delay code, since that should
13021          * have been done if need be on the other controller.
13022          */
13023         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13024                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13025                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13026                        io->io_hdr.nexus.targ_port,
13027                        io->io_hdr.nexus.targ_lun);
13028                 io->io_hdr.port_status = 31338;
13029                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13030                 return;
13031         }
13032
13033         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13034                 ctl_datamove_remote_write(io);
13035         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13036                 ctl_datamove_remote_read(io);
13037         else {
13038                 io->io_hdr.port_status = 31339;
13039                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13040         }
13041 }
13042
13043 static void
13044 ctl_process_done(union ctl_io *io)
13045 {
13046         struct ctl_softc *softc = CTL_SOFTC(io);
13047         struct ctl_lun *lun = CTL_LUN(io);
13048         void (*fe_done)(union ctl_io *io);
13049         union ctl_ha_msg msg;
13050         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13051
13052         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13053         fe_done = softc->ctl_ports[targ_port]->fe_done;
13054
13055 #ifdef CTL_TIME_IO
13056         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13057                 char str[256];
13058                 char path_str[64];
13059                 struct sbuf sb;
13060
13061                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13062                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13063
13064                 sbuf_cat(&sb, path_str);
13065                 switch (io->io_hdr.io_type) {
13066                 case CTL_IO_SCSI:
13067                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13068                         sbuf_printf(&sb, "\n");
13069                         sbuf_cat(&sb, path_str);
13070                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13071                                     io->scsiio.tag_num, io->scsiio.tag_type);
13072                         break;
13073                 case CTL_IO_TASK:
13074                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13075                                     "Tag Type: %d\n", io->taskio.task_action,
13076                                     io->taskio.tag_num, io->taskio.tag_type);
13077                         break;
13078                 default:
13079                         panic("%s: Invalid CTL I/O type %d\n",
13080                             __func__, io->io_hdr.io_type);
13081                 }
13082                 sbuf_cat(&sb, path_str);
13083                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13084                             (intmax_t)time_uptime - io->io_hdr.start_time);
13085                 sbuf_finish(&sb);
13086                 printf("%s", sbuf_data(&sb));
13087         }
13088 #endif /* CTL_TIME_IO */
13089
13090         switch (io->io_hdr.io_type) {
13091         case CTL_IO_SCSI:
13092                 break;
13093         case CTL_IO_TASK:
13094                 if (ctl_debug & CTL_DEBUG_INFO)
13095                         ctl_io_error_print(io, NULL);
13096                 fe_done(io);
13097                 return;
13098         default:
13099                 panic("%s: Invalid CTL I/O type %d\n",
13100                     __func__, io->io_hdr.io_type);
13101         }
13102
13103         if (lun == NULL) {
13104                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13105                                  io->io_hdr.nexus.targ_mapped_lun));
13106                 goto bailout;
13107         }
13108
13109         mtx_lock(&lun->lun_lock);
13110
13111         /*
13112          * Check to see if we have any informational exception and status
13113          * of this command can be modified to report it in form of either
13114          * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13115          */
13116         if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13117             io->io_hdr.status == CTL_SUCCESS &&
13118             (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13119                 uint8_t mrie = lun->MODE_IE.mrie;
13120                 uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13121                     (lun->MODE_VER.byte3 & SMS_VER_PER));
13122                 if (((mrie == SIEP_MRIE_REC_COND && per) ||
13123                      mrie == SIEP_MRIE_REC_UNCOND ||
13124                      mrie == SIEP_MRIE_NO_SENSE) &&
13125                     (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13126                      CTL_CMD_FLAG_NO_SENSE) == 0) {
13127                         ctl_set_sense(&io->scsiio,
13128                               /*current_error*/ 1,
13129                               /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13130                                 SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13131                               /*asc*/ lun->ie_asc,
13132                               /*ascq*/ lun->ie_ascq,
13133                               SSD_ELEM_NONE);
13134                         lun->ie_reported = 1;
13135                 }
13136         } else if (lun->ie_reported < 0)
13137                 lun->ie_reported = 0;
13138
13139         /*
13140          * Check to see if we have any errors to inject here.  We only
13141          * inject errors for commands that don't already have errors set.
13142          */
13143         if (!STAILQ_EMPTY(&lun->error_list) &&
13144             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13145             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13146                 ctl_inject_error(lun, io);
13147
13148         /*
13149          * XXX KDM how do we treat commands that aren't completed
13150          * successfully?
13151          *
13152          * XXX KDM should we also track I/O latency?
13153          */
13154         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13155             io->io_hdr.io_type == CTL_IO_SCSI) {
13156 #ifdef CTL_TIME_IO
13157                 struct bintime cur_bt;
13158 #endif
13159                 int type;
13160
13161                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13162                     CTL_FLAG_DATA_IN)
13163                         type = CTL_STATS_READ;
13164                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13165                     CTL_FLAG_DATA_OUT)
13166                         type = CTL_STATS_WRITE;
13167                 else
13168                         type = CTL_STATS_NO_IO;
13169
13170                 lun->stats.ports[targ_port].bytes[type] +=
13171                     io->scsiio.kern_total_len;
13172                 lun->stats.ports[targ_port].operations[type]++;
13173 #ifdef CTL_TIME_IO
13174                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13175                    &io->io_hdr.dma_bt);
13176                 getbinuptime(&cur_bt);
13177                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13178                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13179 #endif
13180                 lun->stats.ports[targ_port].num_dmas[type] +=
13181                     io->io_hdr.num_dmas;
13182         }
13183
13184         /*
13185          * Remove this from the OOA queue.
13186          */
13187         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13188 #ifdef CTL_TIME_IO
13189         if (TAILQ_EMPTY(&lun->ooa_queue))
13190                 lun->last_busy = getsbinuptime();
13191 #endif
13192
13193         /*
13194          * Run through the blocked queue on this LUN and see if anything
13195          * has become unblocked, now that this transaction is done.
13196          */
13197         ctl_check_blocked(lun);
13198
13199         /*
13200          * If the LUN has been invalidated, free it if there is nothing
13201          * left on its OOA queue.
13202          */
13203         if ((lun->flags & CTL_LUN_INVALID)
13204          && TAILQ_EMPTY(&lun->ooa_queue)) {
13205                 mtx_unlock(&lun->lun_lock);
13206                 mtx_lock(&softc->ctl_lock);
13207                 ctl_free_lun(lun);
13208                 mtx_unlock(&softc->ctl_lock);
13209         } else
13210                 mtx_unlock(&lun->lun_lock);
13211
13212 bailout:
13213
13214         /*
13215          * If this command has been aborted, make sure we set the status
13216          * properly.  The FETD is responsible for freeing the I/O and doing
13217          * whatever it needs to do to clean up its state.
13218          */
13219         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13220                 ctl_set_task_aborted(&io->scsiio);
13221
13222         /*
13223          * If enabled, print command error status.
13224          */
13225         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13226             (ctl_debug & CTL_DEBUG_INFO) != 0)
13227                 ctl_io_error_print(io, NULL);
13228
13229         /*
13230          * Tell the FETD or the other shelf controller we're done with this
13231          * command.  Note that only SCSI commands get to this point.  Task
13232          * management commands are completed above.
13233          */
13234         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13235             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13236                 memset(&msg, 0, sizeof(msg));
13237                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13238                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13239                 msg.hdr.nexus = io->io_hdr.nexus;
13240                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13241                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13242                     M_WAITOK);
13243         }
13244
13245         fe_done(io);
13246 }
13247
13248 #ifdef CTL_WITH_CA
13249 /*
13250  * Front end should call this if it doesn't do autosense.  When the request
13251  * sense comes back in from the initiator, we'll dequeue this and send it.
13252  */
13253 int
13254 ctl_queue_sense(union ctl_io *io)
13255 {
13256         struct ctl_softc *softc = CTL_SOFTC(io);
13257         struct ctl_port *port = CTL_PORT(io);
13258         struct ctl_lun *lun;
13259         uint32_t initidx, targ_lun;
13260
13261         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13262
13263         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13264
13265         /*
13266          * LUN lookup will likely move to the ctl_work_thread() once we
13267          * have our new queueing infrastructure (that doesn't put things on
13268          * a per-LUN queue initially).  That is so that we can handle
13269          * things like an INQUIRY to a LUN that we don't have enabled.  We
13270          * can't deal with that right now.
13271          * If we don't have a LUN for this, just toss the sense information.
13272          */
13273         mtx_lock(&softc->ctl_lock);
13274         if (targ_lun >= CTL_MAX_LUNS ||
13275             (lun = softc->ctl_luns[targ_lun]) == NULL) {
13276                 mtx_unlock(&softc->ctl_lock);
13277                 goto bailout;
13278         }
13279         mtx_lock(&lun->lun_lock);
13280         mtx_unlock(&softc->ctl_lock);
13281
13282         /*
13283          * Already have CA set for this LUN...toss the sense information.
13284          */
13285         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13286         if (ctl_is_set(lun->have_ca, initidx)) {
13287                 mtx_unlock(&lun->lun_lock);
13288                 goto bailout;
13289         }
13290
13291         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13292                MIN(sizeof(lun->pending_sense[initidx]),
13293                sizeof(io->scsiio.sense_data)));
13294         ctl_set_mask(lun->have_ca, initidx);
13295         mtx_unlock(&lun->lun_lock);
13296
13297 bailout:
13298         ctl_free_io(io);
13299         return (CTL_RETVAL_COMPLETE);
13300 }
13301 #endif
13302
13303 /*
13304  * Primary command inlet from frontend ports.  All SCSI and task I/O
13305  * requests must go through this function.
13306  */
13307 int
13308 ctl_queue(union ctl_io *io)
13309 {
13310         struct ctl_port *port = CTL_PORT(io);
13311
13312         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13313
13314 #ifdef CTL_TIME_IO
13315         io->io_hdr.start_time = time_uptime;
13316         getbinuptime(&io->io_hdr.start_bt);
13317 #endif /* CTL_TIME_IO */
13318
13319         /* Map FE-specific LUN ID into global one. */
13320         io->io_hdr.nexus.targ_mapped_lun =
13321             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13322
13323         switch (io->io_hdr.io_type) {
13324         case CTL_IO_SCSI:
13325         case CTL_IO_TASK:
13326                 if (ctl_debug & CTL_DEBUG_CDB)
13327                         ctl_io_print(io);
13328                 ctl_enqueue_incoming(io);
13329                 break;
13330         default:
13331                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13332                 return (EINVAL);
13333         }
13334
13335         return (CTL_RETVAL_COMPLETE);
13336 }
13337
13338 #ifdef CTL_IO_DELAY
13339 static void
13340 ctl_done_timer_wakeup(void *arg)
13341 {
13342         union ctl_io *io;
13343
13344         io = (union ctl_io *)arg;
13345         ctl_done(io);
13346 }
13347 #endif /* CTL_IO_DELAY */
13348
13349 void
13350 ctl_serseq_done(union ctl_io *io)
13351 {
13352         struct ctl_lun *lun = CTL_LUN(io);;
13353
13354         if (lun->be_lun == NULL ||
13355             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13356                 return;
13357         mtx_lock(&lun->lun_lock);
13358         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13359         ctl_check_blocked(lun);
13360         mtx_unlock(&lun->lun_lock);
13361 }
13362
13363 void
13364 ctl_done(union ctl_io *io)
13365 {
13366
13367         /*
13368          * Enable this to catch duplicate completion issues.
13369          */
13370 #if 0
13371         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13372                 printf("%s: type %d msg %d cdb %x iptl: "
13373                        "%u:%u:%u tag 0x%04x "
13374                        "flag %#x status %x\n",
13375                         __func__,
13376                         io->io_hdr.io_type,
13377                         io->io_hdr.msg_type,
13378                         io->scsiio.cdb[0],
13379                         io->io_hdr.nexus.initid,
13380                         io->io_hdr.nexus.targ_port,
13381                         io->io_hdr.nexus.targ_lun,
13382                         (io->io_hdr.io_type ==
13383                         CTL_IO_TASK) ?
13384                         io->taskio.tag_num :
13385                         io->scsiio.tag_num,
13386                         io->io_hdr.flags,
13387                         io->io_hdr.status);
13388         } else
13389                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13390 #endif
13391
13392         /*
13393          * This is an internal copy of an I/O, and should not go through
13394          * the normal done processing logic.
13395          */
13396         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13397                 return;
13398
13399 #ifdef CTL_IO_DELAY
13400         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13401                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13402         } else {
13403                 struct ctl_lun *lun = CTL_LUN(io);
13404
13405                 if ((lun != NULL)
13406                  && (lun->delay_info.done_delay > 0)) {
13407
13408                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13409                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13410                         callout_reset(&io->io_hdr.delay_callout,
13411                                       lun->delay_info.done_delay * hz,
13412                                       ctl_done_timer_wakeup, io);
13413                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13414                                 lun->delay_info.done_delay = 0;
13415                         return;
13416                 }
13417         }
13418 #endif /* CTL_IO_DELAY */
13419
13420         ctl_enqueue_done(io);
13421 }
13422
13423 static void
13424 ctl_work_thread(void *arg)
13425 {
13426         struct ctl_thread *thr = (struct ctl_thread *)arg;
13427         struct ctl_softc *softc = thr->ctl_softc;
13428         union ctl_io *io;
13429         int retval;
13430
13431         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13432
13433         for (;;) {
13434                 /*
13435                  * We handle the queues in this order:
13436                  * - ISC
13437                  * - done queue (to free up resources, unblock other commands)
13438                  * - RtR queue
13439                  * - incoming queue
13440                  *
13441                  * If those queues are empty, we break out of the loop and
13442                  * go to sleep.
13443                  */
13444                 mtx_lock(&thr->queue_lock);
13445                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13446                 if (io != NULL) {
13447                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13448                         mtx_unlock(&thr->queue_lock);
13449                         ctl_handle_isc(io);
13450                         continue;
13451                 }
13452                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13453                 if (io != NULL) {
13454                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13455                         /* clear any blocked commands, call fe_done */
13456                         mtx_unlock(&thr->queue_lock);
13457                         ctl_process_done(io);
13458                         continue;
13459                 }
13460                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13461                 if (io != NULL) {
13462                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13463                         mtx_unlock(&thr->queue_lock);
13464                         if (io->io_hdr.io_type == CTL_IO_TASK)
13465                                 ctl_run_task(io);
13466                         else
13467                                 ctl_scsiio_precheck(softc, &io->scsiio);
13468                         continue;
13469                 }
13470                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13471                 if (io != NULL) {
13472                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13473                         mtx_unlock(&thr->queue_lock);
13474                         retval = ctl_scsiio(&io->scsiio);
13475                         if (retval != CTL_RETVAL_COMPLETE)
13476                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13477                         continue;
13478                 }
13479
13480                 /* Sleep until we have something to do. */
13481                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13482         }
13483 }
13484
13485 static void
13486 ctl_lun_thread(void *arg)
13487 {
13488         struct ctl_softc *softc = (struct ctl_softc *)arg;
13489         struct ctl_be_lun *be_lun;
13490
13491         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13492
13493         for (;;) {
13494                 mtx_lock(&softc->ctl_lock);
13495                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13496                 if (be_lun != NULL) {
13497                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13498                         mtx_unlock(&softc->ctl_lock);
13499                         ctl_create_lun(be_lun);
13500                         continue;
13501                 }
13502
13503                 /* Sleep until we have something to do. */
13504                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13505                     PDROP | PRIBIO, "-", 0);
13506         }
13507 }
13508
13509 static void
13510 ctl_thresh_thread(void *arg)
13511 {
13512         struct ctl_softc *softc = (struct ctl_softc *)arg;
13513         struct ctl_lun *lun;
13514         struct ctl_logical_block_provisioning_page *page;
13515         const char *attr;
13516         union ctl_ha_msg msg;
13517         uint64_t thres, val;
13518         int i, e, set;
13519
13520         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13521
13522         for (;;) {
13523                 mtx_lock(&softc->ctl_lock);
13524                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13525                         if ((lun->flags & CTL_LUN_DISABLED) ||
13526                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13527                             lun->backend->lun_attr == NULL)
13528                                 continue;
13529                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13530                             softc->ha_mode == CTL_HA_MODE_XFER)
13531                                 continue;
13532                         if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13533                                 continue;
13534                         e = 0;
13535                         page = &lun->MODE_LBP;
13536                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13537                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13538                                         continue;
13539                                 thres = scsi_4btoul(page->descr[i].count);
13540                                 thres <<= CTL_LBP_EXPONENT;
13541                                 switch (page->descr[i].resource) {
13542                                 case 0x01:
13543                                         attr = "blocksavail";
13544                                         break;
13545                                 case 0x02:
13546                                         attr = "blocksused";
13547                                         break;
13548                                 case 0xf1:
13549                                         attr = "poolblocksavail";
13550                                         break;
13551                                 case 0xf2:
13552                                         attr = "poolblocksused";
13553                                         break;
13554                                 default:
13555                                         continue;
13556                                 }
13557                                 mtx_unlock(&softc->ctl_lock); // XXX
13558                                 val = lun->backend->lun_attr(
13559                                     lun->be_lun->be_lun, attr);
13560                                 mtx_lock(&softc->ctl_lock);
13561                                 if (val == UINT64_MAX)
13562                                         continue;
13563                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13564                                     == SLBPPD_ARMING_INC)
13565                                         e = (val >= thres);
13566                                 else
13567                                         e = (val <= thres);
13568                                 if (e)
13569                                         break;
13570                         }
13571                         mtx_lock(&lun->lun_lock);
13572                         if (e) {
13573                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13574                                     (uint8_t *)page, lun->ua_tpt_info);
13575                                 if (lun->lasttpt == 0 ||
13576                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13577                                         lun->lasttpt = time_uptime;
13578                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13579                                         set = 1;
13580                                 } else
13581                                         set = 0;
13582                         } else {
13583                                 lun->lasttpt = 0;
13584                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13585                                 set = -1;
13586                         }
13587                         mtx_unlock(&lun->lun_lock);
13588                         if (set != 0 &&
13589                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13590                                 /* Send msg to other side. */
13591                                 bzero(&msg.ua, sizeof(msg.ua));
13592                                 msg.hdr.msg_type = CTL_MSG_UA;
13593                                 msg.hdr.nexus.initid = -1;
13594                                 msg.hdr.nexus.targ_port = -1;
13595                                 msg.hdr.nexus.targ_lun = lun->lun;
13596                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13597                                 msg.ua.ua_all = 1;
13598                                 msg.ua.ua_set = (set > 0);
13599                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13600                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13601                                 mtx_unlock(&softc->ctl_lock); // XXX
13602                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13603                                     sizeof(msg.ua), M_WAITOK);
13604                                 mtx_lock(&softc->ctl_lock);
13605                         }
13606                 }
13607                 mtx_unlock(&softc->ctl_lock);
13608                 pause("-", CTL_LBP_PERIOD * hz);
13609         }
13610 }
13611
13612 static void
13613 ctl_enqueue_incoming(union ctl_io *io)
13614 {
13615         struct ctl_softc *softc = CTL_SOFTC(io);
13616         struct ctl_thread *thr;
13617         u_int idx;
13618
13619         idx = (io->io_hdr.nexus.targ_port * 127 +
13620                io->io_hdr.nexus.initid) % worker_threads;
13621         thr = &softc->threads[idx];
13622         mtx_lock(&thr->queue_lock);
13623         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13624         mtx_unlock(&thr->queue_lock);
13625         wakeup(thr);
13626 }
13627
13628 static void
13629 ctl_enqueue_rtr(union ctl_io *io)
13630 {
13631         struct ctl_softc *softc = CTL_SOFTC(io);
13632         struct ctl_thread *thr;
13633
13634         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13635         mtx_lock(&thr->queue_lock);
13636         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13637         mtx_unlock(&thr->queue_lock);
13638         wakeup(thr);
13639 }
13640
13641 static void
13642 ctl_enqueue_done(union ctl_io *io)
13643 {
13644         struct ctl_softc *softc = CTL_SOFTC(io);
13645         struct ctl_thread *thr;
13646
13647         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13648         mtx_lock(&thr->queue_lock);
13649         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13650         mtx_unlock(&thr->queue_lock);
13651         wakeup(thr);
13652 }
13653
13654 static void
13655 ctl_enqueue_isc(union ctl_io *io)
13656 {
13657         struct ctl_softc *softc = CTL_SOFTC(io);
13658         struct ctl_thread *thr;
13659
13660         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13661         mtx_lock(&thr->queue_lock);
13662         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13663         mtx_unlock(&thr->queue_lock);
13664         wakeup(thr);
13665 }
13666
13667 /*
13668  *  vim: ts=8
13669  */