]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r310646: Do not update "saved" mode page on every MODE SELECT.
[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 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
443
444 static int ctl_do_mode_select(union ctl_io *io);
445 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
446                            uint64_t res_key, uint64_t sa_res_key,
447                            uint8_t type, uint32_t residx,
448                            struct ctl_scsiio *ctsio,
449                            struct scsi_per_res_out *cdb,
450                            struct scsi_per_res_out_parms* param);
451 static void ctl_pro_preempt_other(struct ctl_lun *lun,
452                                   union ctl_ha_msg *msg);
453 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
454 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
457 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
458 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
459 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
460                                          int alloc_len);
461 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
462                                          int alloc_len);
463 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
464 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
465 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
466 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
467 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
468 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
469     bool seq);
470 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
471 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
472     union ctl_io *pending_io, union ctl_io *ooa_io);
473 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
474                                 union ctl_io *starting_io);
475 static int ctl_check_blocked(struct ctl_lun *lun);
476 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
477                                 const struct ctl_cmd_entry *entry,
478                                 struct ctl_scsiio *ctsio);
479 static void ctl_failover_lun(union ctl_io *io);
480 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
481                                struct ctl_scsiio *ctsio);
482 static int ctl_scsiio(struct ctl_scsiio *ctsio);
483
484 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
485 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
486                             ctl_ua_type ua_type);
487 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
488                          ctl_ua_type ua_type);
489 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
490 static int ctl_abort_task(union ctl_io *io);
491 static int ctl_abort_task_set(union ctl_io *io);
492 static int ctl_query_task(union ctl_io *io, int task_set);
493 static int ctl_i_t_nexus_reset(union ctl_io *io);
494 static int ctl_query_async_event(union ctl_io *io);
495 static void ctl_run_task(union ctl_io *io);
496 #ifdef CTL_IO_DELAY
497 static void ctl_datamove_timer_wakeup(void *arg);
498 static void ctl_done_timer_wakeup(void *arg);
499 #endif /* CTL_IO_DELAY */
500
501 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
502 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
503 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
504 static void ctl_datamove_remote_write(union ctl_io *io);
505 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
506 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
507 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
508 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
509                                     ctl_ha_dt_cb callback);
510 static void ctl_datamove_remote_read(union ctl_io *io);
511 static void ctl_datamove_remote(union ctl_io *io);
512 static void ctl_process_done(union ctl_io *io);
513 static void ctl_lun_thread(void *arg);
514 static void ctl_thresh_thread(void *arg);
515 static void ctl_work_thread(void *arg);
516 static void ctl_enqueue_incoming(union ctl_io *io);
517 static void ctl_enqueue_rtr(union ctl_io *io);
518 static void ctl_enqueue_done(union ctl_io *io);
519 static void ctl_enqueue_isc(union ctl_io *io);
520 static const struct ctl_cmd_entry *
521     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
522 static const struct ctl_cmd_entry *
523     ctl_validate_command(struct ctl_scsiio *ctsio);
524 static int ctl_cmd_applicable(uint8_t lun_type,
525     const struct ctl_cmd_entry *entry);
526
527 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
528 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
529 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
530 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
531
532 /*
533  * Load the serialization table.  This isn't very pretty, but is probably
534  * the easiest way to do it.
535  */
536 #include "ctl_ser_table.c"
537
538 /*
539  * We only need to define open, close and ioctl routines for this driver.
540  */
541 static struct cdevsw ctl_cdevsw = {
542         .d_version =    D_VERSION,
543         .d_flags =      0,
544         .d_open =       ctl_open,
545         .d_close =      ctl_close,
546         .d_ioctl =      ctl_ioctl,
547         .d_name =       "ctl",
548 };
549
550
551 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
552
553 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
554
555 static moduledata_t ctl_moduledata = {
556         "ctl",
557         ctl_module_event_handler,
558         NULL
559 };
560
561 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
562 MODULE_VERSION(ctl, 1);
563
564 static struct ctl_frontend ha_frontend =
565 {
566         .name = "ha",
567 };
568
569 static void
570 ctl_ha_datamove(union ctl_io *io)
571 {
572         struct ctl_lun *lun;
573         struct ctl_sg_entry *sgl;
574         union ctl_ha_msg msg;
575         uint32_t sg_entries_sent;
576         int do_sg_copy, i, j;
577
578         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
579         memset(&msg.dt, 0, sizeof(msg.dt));
580         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
581         msg.hdr.original_sc = io->io_hdr.original_sc;
582         msg.hdr.serializing_sc = io;
583         msg.hdr.nexus = io->io_hdr.nexus;
584         msg.hdr.status = io->io_hdr.status;
585         msg.dt.flags = io->io_hdr.flags;
586
587         /*
588          * We convert everything into a S/G list here.  We can't
589          * pass by reference, only by value between controllers.
590          * So we can't pass a pointer to the S/G list, only as many
591          * S/G entries as we can fit in here.  If it's possible for
592          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
593          * then we need to break this up into multiple transfers.
594          */
595         if (io->scsiio.kern_sg_entries == 0) {
596                 msg.dt.kern_sg_entries = 1;
597 #if 0
598                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
599                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
600                 } else {
601                         /* XXX KDM use busdma here! */
602                         msg.dt.sg_list[0].addr =
603                             (void *)vtophys(io->scsiio.kern_data_ptr);
604                 }
605 #else
606                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
607                     ("HA does not support BUS_ADDR"));
608                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
609 #endif
610                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
611                 do_sg_copy = 0;
612         } else {
613                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
614                 do_sg_copy = 1;
615         }
616
617         msg.dt.kern_data_len = io->scsiio.kern_data_len;
618         msg.dt.kern_total_len = io->scsiio.kern_total_len;
619         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
620         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
621         msg.dt.sg_sequence = 0;
622
623         /*
624          * Loop until we've sent all of the S/G entries.  On the
625          * other end, we'll recompose these S/G entries into one
626          * contiguous list before processing.
627          */
628         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
629             msg.dt.sg_sequence++) {
630                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
631                     sizeof(msg.dt.sg_list[0])),
632                     msg.dt.kern_sg_entries - sg_entries_sent);
633                 if (do_sg_copy != 0) {
634                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
635                         for (i = sg_entries_sent, j = 0;
636                              i < msg.dt.cur_sg_entries; i++, j++) {
637 #if 0
638                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
639                                         msg.dt.sg_list[j].addr = sgl[i].addr;
640                                 } else {
641                                         /* XXX KDM use busdma here! */
642                                         msg.dt.sg_list[j].addr =
643                                             (void *)vtophys(sgl[i].addr);
644                                 }
645 #else
646                                 KASSERT((io->io_hdr.flags &
647                                     CTL_FLAG_BUS_ADDR) == 0,
648                                     ("HA does not support BUS_ADDR"));
649                                 msg.dt.sg_list[j].addr = sgl[i].addr;
650 #endif
651                                 msg.dt.sg_list[j].len = sgl[i].len;
652                         }
653                 }
654
655                 sg_entries_sent += msg.dt.cur_sg_entries;
656                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
657                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
658                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
659                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
660                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
661                         io->io_hdr.port_status = 31341;
662                         io->scsiio.be_move_done(io);
663                         return;
664                 }
665                 msg.dt.sent_sg_entries = sg_entries_sent;
666         }
667
668         /*
669          * Officially handover the request from us to peer.
670          * If failover has just happened, then we must return error.
671          * If failover happen just after, then it is not our problem.
672          */
673         if (lun)
674                 mtx_lock(&lun->lun_lock);
675         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
676                 if (lun)
677                         mtx_unlock(&lun->lun_lock);
678                 io->io_hdr.port_status = 31342;
679                 io->scsiio.be_move_done(io);
680                 return;
681         }
682         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
683         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
684         if (lun)
685                 mtx_unlock(&lun->lun_lock);
686 }
687
688 static void
689 ctl_ha_done(union ctl_io *io)
690 {
691         union ctl_ha_msg msg;
692
693         if (io->io_hdr.io_type == CTL_IO_SCSI) {
694                 memset(&msg, 0, sizeof(msg));
695                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
696                 msg.hdr.original_sc = io->io_hdr.original_sc;
697                 msg.hdr.nexus = io->io_hdr.nexus;
698                 msg.hdr.status = io->io_hdr.status;
699                 msg.scsi.scsi_status = io->scsiio.scsi_status;
700                 msg.scsi.tag_num = io->scsiio.tag_num;
701                 msg.scsi.tag_type = io->scsiio.tag_type;
702                 msg.scsi.sense_len = io->scsiio.sense_len;
703                 msg.scsi.sense_residual = io->scsiio.sense_residual;
704                 msg.scsi.residual = io->scsiio.residual;
705                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
706                     io->scsiio.sense_len);
707                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
708                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
709                     msg.scsi.sense_len, M_WAITOK);
710         }
711         ctl_free_io(io);
712 }
713
714 static void
715 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
716                             union ctl_ha_msg *msg_info)
717 {
718         struct ctl_scsiio *ctsio;
719
720         if (msg_info->hdr.original_sc == NULL) {
721                 printf("%s: original_sc == NULL!\n", __func__);
722                 /* XXX KDM now what? */
723                 return;
724         }
725
726         ctsio = &msg_info->hdr.original_sc->scsiio;
727         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
728         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
729         ctsio->io_hdr.status = msg_info->hdr.status;
730         ctsio->scsi_status = msg_info->scsi.scsi_status;
731         ctsio->sense_len = msg_info->scsi.sense_len;
732         ctsio->sense_residual = msg_info->scsi.sense_residual;
733         ctsio->residual = msg_info->scsi.residual;
734         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
735                msg_info->scsi.sense_len);
736         ctl_enqueue_isc((union ctl_io *)ctsio);
737 }
738
739 static void
740 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
741                                 union ctl_ha_msg *msg_info)
742 {
743         struct ctl_scsiio *ctsio;
744
745         if (msg_info->hdr.serializing_sc == NULL) {
746                 printf("%s: serializing_sc == NULL!\n", __func__);
747                 /* XXX KDM now what? */
748                 return;
749         }
750
751         ctsio = &msg_info->hdr.serializing_sc->scsiio;
752         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
753         ctl_enqueue_isc((union ctl_io *)ctsio);
754 }
755
756 void
757 ctl_isc_announce_lun(struct ctl_lun *lun)
758 {
759         struct ctl_softc *softc = lun->ctl_softc;
760         union ctl_ha_msg *msg;
761         struct ctl_ha_msg_lun_pr_key pr_key;
762         int i, k;
763
764         if (softc->ha_link != CTL_HA_LINK_ONLINE)
765                 return;
766         mtx_lock(&lun->lun_lock);
767         i = sizeof(msg->lun);
768         if (lun->lun_devid)
769                 i += lun->lun_devid->len;
770         i += sizeof(pr_key) * lun->pr_key_count;
771 alloc:
772         mtx_unlock(&lun->lun_lock);
773         msg = malloc(i, M_CTL, M_WAITOK);
774         mtx_lock(&lun->lun_lock);
775         k = sizeof(msg->lun);
776         if (lun->lun_devid)
777                 k += lun->lun_devid->len;
778         k += sizeof(pr_key) * lun->pr_key_count;
779         if (i < k) {
780                 free(msg, M_CTL);
781                 i = k;
782                 goto alloc;
783         }
784         bzero(&msg->lun, sizeof(msg->lun));
785         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
786         msg->hdr.nexus.targ_lun = lun->lun;
787         msg->hdr.nexus.targ_mapped_lun = lun->lun;
788         msg->lun.flags = lun->flags;
789         msg->lun.pr_generation = lun->pr_generation;
790         msg->lun.pr_res_idx = lun->pr_res_idx;
791         msg->lun.pr_res_type = lun->pr_res_type;
792         msg->lun.pr_key_count = lun->pr_key_count;
793         i = 0;
794         if (lun->lun_devid) {
795                 msg->lun.lun_devid_len = lun->lun_devid->len;
796                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
797                     msg->lun.lun_devid_len);
798                 i += msg->lun.lun_devid_len;
799         }
800         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
801                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
802                         continue;
803                 pr_key.pr_iid = k;
804                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
805                 i += sizeof(pr_key);
806         }
807         mtx_unlock(&lun->lun_lock);
808         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
809             M_WAITOK);
810         free(msg, M_CTL);
811
812         if (lun->flags & CTL_LUN_PRIMARY_SC) {
813                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
814                         ctl_isc_announce_mode(lun, -1,
815                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
816                             lun->mode_pages.index[i].subpage);
817                 }
818         }
819 }
820
821 void
822 ctl_isc_announce_port(struct ctl_port *port)
823 {
824         struct ctl_softc *softc = port->ctl_softc;
825         union ctl_ha_msg *msg;
826         int i;
827
828         if (port->targ_port < softc->port_min ||
829             port->targ_port >= softc->port_max ||
830             softc->ha_link != CTL_HA_LINK_ONLINE)
831                 return;
832         i = sizeof(msg->port) + strlen(port->port_name) + 1;
833         if (port->lun_map)
834                 i += port->lun_map_size * sizeof(uint32_t);
835         if (port->port_devid)
836                 i += port->port_devid->len;
837         if (port->target_devid)
838                 i += port->target_devid->len;
839         if (port->init_devid)
840                 i += port->init_devid->len;
841         msg = malloc(i, M_CTL, M_WAITOK);
842         bzero(&msg->port, sizeof(msg->port));
843         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
844         msg->hdr.nexus.targ_port = port->targ_port;
845         msg->port.port_type = port->port_type;
846         msg->port.physical_port = port->physical_port;
847         msg->port.virtual_port = port->virtual_port;
848         msg->port.status = port->status;
849         i = 0;
850         msg->port.name_len = sprintf(&msg->port.data[i],
851             "%d:%s", softc->ha_id, port->port_name) + 1;
852         i += msg->port.name_len;
853         if (port->lun_map) {
854                 msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
855                 memcpy(&msg->port.data[i], port->lun_map,
856                     msg->port.lun_map_len);
857                 i += msg->port.lun_map_len;
858         }
859         if (port->port_devid) {
860                 msg->port.port_devid_len = port->port_devid->len;
861                 memcpy(&msg->port.data[i], port->port_devid->data,
862                     msg->port.port_devid_len);
863                 i += msg->port.port_devid_len;
864         }
865         if (port->target_devid) {
866                 msg->port.target_devid_len = port->target_devid->len;
867                 memcpy(&msg->port.data[i], port->target_devid->data,
868                     msg->port.target_devid_len);
869                 i += msg->port.target_devid_len;
870         }
871         if (port->init_devid) {
872                 msg->port.init_devid_len = port->init_devid->len;
873                 memcpy(&msg->port.data[i], port->init_devid->data,
874                     msg->port.init_devid_len);
875                 i += msg->port.init_devid_len;
876         }
877         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
878             M_WAITOK);
879         free(msg, M_CTL);
880 }
881
882 void
883 ctl_isc_announce_iid(struct ctl_port *port, int iid)
884 {
885         struct ctl_softc *softc = port->ctl_softc;
886         union ctl_ha_msg *msg;
887         int i, l;
888
889         if (port->targ_port < softc->port_min ||
890             port->targ_port >= softc->port_max ||
891             softc->ha_link != CTL_HA_LINK_ONLINE)
892                 return;
893         mtx_lock(&softc->ctl_lock);
894         i = sizeof(msg->iid);
895         l = 0;
896         if (port->wwpn_iid[iid].name)
897                 l = strlen(port->wwpn_iid[iid].name) + 1;
898         i += l;
899         msg = malloc(i, M_CTL, M_NOWAIT);
900         if (msg == NULL) {
901                 mtx_unlock(&softc->ctl_lock);
902                 return;
903         }
904         bzero(&msg->iid, sizeof(msg->iid));
905         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
906         msg->hdr.nexus.targ_port = port->targ_port;
907         msg->hdr.nexus.initid = iid;
908         msg->iid.in_use = port->wwpn_iid[iid].in_use;
909         msg->iid.name_len = l;
910         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
911         if (port->wwpn_iid[iid].name)
912                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
913         mtx_unlock(&softc->ctl_lock);
914         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
915         free(msg, M_CTL);
916 }
917
918 void
919 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
920     uint8_t page, uint8_t subpage)
921 {
922         struct ctl_softc *softc = lun->ctl_softc;
923         union ctl_ha_msg msg;
924         u_int i;
925
926         if (softc->ha_link != CTL_HA_LINK_ONLINE)
927                 return;
928         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
929                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
930                     page && lun->mode_pages.index[i].subpage == subpage)
931                         break;
932         }
933         if (i == CTL_NUM_MODE_PAGES)
934                 return;
935
936         /* Don't try to replicate pages not present on this device. */
937         if (lun->mode_pages.index[i].page_data == NULL)
938                 return;
939
940         bzero(&msg.mode, sizeof(msg.mode));
941         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
942         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
943         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
944         msg.hdr.nexus.targ_lun = lun->lun;
945         msg.hdr.nexus.targ_mapped_lun = lun->lun;
946         msg.mode.page_code = page;
947         msg.mode.subpage = subpage;
948         msg.mode.page_len = lun->mode_pages.index[i].page_len;
949         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
950             msg.mode.page_len);
951         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
952             M_WAITOK);
953 }
954
955 static void
956 ctl_isc_ha_link_up(struct ctl_softc *softc)
957 {
958         struct ctl_port *port;
959         struct ctl_lun *lun;
960         union ctl_ha_msg msg;
961         int i;
962
963         /* Announce this node parameters to peer for validation. */
964         msg.login.msg_type = CTL_MSG_LOGIN;
965         msg.login.version = CTL_HA_VERSION;
966         msg.login.ha_mode = softc->ha_mode;
967         msg.login.ha_id = softc->ha_id;
968         msg.login.max_luns = CTL_MAX_LUNS;
969         msg.login.max_ports = CTL_MAX_PORTS;
970         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
971         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
972             M_WAITOK);
973
974         STAILQ_FOREACH(port, &softc->port_list, links) {
975                 ctl_isc_announce_port(port);
976                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
977                         if (port->wwpn_iid[i].in_use)
978                                 ctl_isc_announce_iid(port, i);
979                 }
980         }
981         STAILQ_FOREACH(lun, &softc->lun_list, links)
982                 ctl_isc_announce_lun(lun);
983 }
984
985 static void
986 ctl_isc_ha_link_down(struct ctl_softc *softc)
987 {
988         struct ctl_port *port;
989         struct ctl_lun *lun;
990         union ctl_io *io;
991         int i;
992
993         mtx_lock(&softc->ctl_lock);
994         STAILQ_FOREACH(lun, &softc->lun_list, links) {
995                 mtx_lock(&lun->lun_lock);
996                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
997                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
998                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
999                 }
1000                 mtx_unlock(&lun->lun_lock);
1001
1002                 mtx_unlock(&softc->ctl_lock);
1003                 io = ctl_alloc_io(softc->othersc_pool);
1004                 mtx_lock(&softc->ctl_lock);
1005                 ctl_zero_io(io);
1006                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1007                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1008                 ctl_enqueue_isc(io);
1009         }
1010
1011         STAILQ_FOREACH(port, &softc->port_list, links) {
1012                 if (port->targ_port >= softc->port_min &&
1013                     port->targ_port < softc->port_max)
1014                         continue;
1015                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1016                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1017                         port->wwpn_iid[i].in_use = 0;
1018                         free(port->wwpn_iid[i].name, M_CTL);
1019                         port->wwpn_iid[i].name = NULL;
1020                 }
1021         }
1022         mtx_unlock(&softc->ctl_lock);
1023 }
1024
1025 static void
1026 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1027 {
1028         struct ctl_lun *lun;
1029         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1030
1031         mtx_lock(&softc->ctl_lock);
1032         if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1033             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1034                 mtx_unlock(&softc->ctl_lock);
1035                 return;
1036         }
1037         mtx_lock(&lun->lun_lock);
1038         mtx_unlock(&softc->ctl_lock);
1039         if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1040                 memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1041         if (msg->ua.ua_all) {
1042                 if (msg->ua.ua_set)
1043                         ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1044                 else
1045                         ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1046         } else {
1047                 if (msg->ua.ua_set)
1048                         ctl_est_ua(lun, iid, msg->ua.ua_type);
1049                 else
1050                         ctl_clr_ua(lun, iid, msg->ua.ua_type);
1051         }
1052         mtx_unlock(&lun->lun_lock);
1053 }
1054
1055 static void
1056 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1057 {
1058         struct ctl_lun *lun;
1059         struct ctl_ha_msg_lun_pr_key pr_key;
1060         int i, k;
1061         ctl_lun_flags oflags;
1062         uint32_t targ_lun;
1063
1064         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1065         mtx_lock(&softc->ctl_lock);
1066         if (targ_lun >= CTL_MAX_LUNS ||
1067             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1068                 mtx_unlock(&softc->ctl_lock);
1069                 return;
1070         }
1071         mtx_lock(&lun->lun_lock);
1072         mtx_unlock(&softc->ctl_lock);
1073         if (lun->flags & CTL_LUN_DISABLED) {
1074                 mtx_unlock(&lun->lun_lock);
1075                 return;
1076         }
1077         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1078         if (msg->lun.lun_devid_len != i || (i > 0 &&
1079             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1080                 mtx_unlock(&lun->lun_lock);
1081                 printf("%s: Received conflicting HA LUN %d\n",
1082                     __func__, targ_lun);
1083                 return;
1084         } else {
1085                 /* Record whether peer is primary. */
1086                 oflags = lun->flags;
1087                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1088                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1089                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1090                 else
1091                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1092                 if (oflags != lun->flags)
1093                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1094
1095                 /* If peer is primary and we are not -- use data */
1096                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1097                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1098                         lun->pr_generation = msg->lun.pr_generation;
1099                         lun->pr_res_idx = msg->lun.pr_res_idx;
1100                         lun->pr_res_type = msg->lun.pr_res_type;
1101                         lun->pr_key_count = msg->lun.pr_key_count;
1102                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1103                                 ctl_clr_prkey(lun, k);
1104                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1105                                 memcpy(&pr_key, &msg->lun.data[i],
1106                                     sizeof(pr_key));
1107                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1108                                 ctl_set_prkey(lun, pr_key.pr_iid,
1109                                     pr_key.pr_key);
1110                                 i += sizeof(pr_key);
1111                         }
1112                 }
1113
1114                 mtx_unlock(&lun->lun_lock);
1115                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1116                     __func__, targ_lun,
1117                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1118                     "primary" : "secondary"));
1119
1120                 /* If we are primary but peer doesn't know -- notify */
1121                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1122                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1123                         ctl_isc_announce_lun(lun);
1124         }
1125 }
1126
1127 static void
1128 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1129 {
1130         struct ctl_port *port;
1131         struct ctl_lun *lun;
1132         int i, new;
1133
1134         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1135         if (port == NULL) {
1136                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1137                     msg->hdr.nexus.targ_port));
1138                 new = 1;
1139                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1140                 port->frontend = &ha_frontend;
1141                 port->targ_port = msg->hdr.nexus.targ_port;
1142                 port->fe_datamove = ctl_ha_datamove;
1143                 port->fe_done = ctl_ha_done;
1144         } else if (port->frontend == &ha_frontend) {
1145                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1146                     msg->hdr.nexus.targ_port));
1147                 new = 0;
1148         } else {
1149                 printf("%s: Received conflicting HA port %d\n",
1150                     __func__, msg->hdr.nexus.targ_port);
1151                 return;
1152         }
1153         port->port_type = msg->port.port_type;
1154         port->physical_port = msg->port.physical_port;
1155         port->virtual_port = msg->port.virtual_port;
1156         port->status = msg->port.status;
1157         i = 0;
1158         free(port->port_name, M_CTL);
1159         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1160             M_CTL);
1161         i += msg->port.name_len;
1162         if (msg->port.lun_map_len != 0) {
1163                 if (port->lun_map == NULL ||
1164                     port->lun_map_size * sizeof(uint32_t) <
1165                     msg->port.lun_map_len) {
1166                         port->lun_map_size = 0;
1167                         free(port->lun_map, M_CTL);
1168                         port->lun_map = malloc(msg->port.lun_map_len,
1169                             M_CTL, M_WAITOK);
1170                 }
1171                 memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1172                 port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1173                 i += msg->port.lun_map_len;
1174         } else {
1175                 port->lun_map_size = 0;
1176                 free(port->lun_map, M_CTL);
1177                 port->lun_map = NULL;
1178         }
1179         if (msg->port.port_devid_len != 0) {
1180                 if (port->port_devid == NULL ||
1181                     port->port_devid->len < msg->port.port_devid_len) {
1182                         free(port->port_devid, M_CTL);
1183                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1184                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1185                 }
1186                 memcpy(port->port_devid->data, &msg->port.data[i],
1187                     msg->port.port_devid_len);
1188                 port->port_devid->len = msg->port.port_devid_len;
1189                 i += msg->port.port_devid_len;
1190         } else {
1191                 free(port->port_devid, M_CTL);
1192                 port->port_devid = NULL;
1193         }
1194         if (msg->port.target_devid_len != 0) {
1195                 if (port->target_devid == NULL ||
1196                     port->target_devid->len < msg->port.target_devid_len) {
1197                         free(port->target_devid, M_CTL);
1198                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1199                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1200                 }
1201                 memcpy(port->target_devid->data, &msg->port.data[i],
1202                     msg->port.target_devid_len);
1203                 port->target_devid->len = msg->port.target_devid_len;
1204                 i += msg->port.target_devid_len;
1205         } else {
1206                 free(port->target_devid, M_CTL);
1207                 port->target_devid = NULL;
1208         }
1209         if (msg->port.init_devid_len != 0) {
1210                 if (port->init_devid == NULL ||
1211                     port->init_devid->len < msg->port.init_devid_len) {
1212                         free(port->init_devid, M_CTL);
1213                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1214                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1215                 }
1216                 memcpy(port->init_devid->data, &msg->port.data[i],
1217                     msg->port.init_devid_len);
1218                 port->init_devid->len = msg->port.init_devid_len;
1219                 i += msg->port.init_devid_len;
1220         } else {
1221                 free(port->init_devid, M_CTL);
1222                 port->init_devid = NULL;
1223         }
1224         if (new) {
1225                 if (ctl_port_register(port) != 0) {
1226                         printf("%s: ctl_port_register() failed with error\n",
1227                             __func__);
1228                 }
1229         }
1230         mtx_lock(&softc->ctl_lock);
1231         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1232                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1233                         continue;
1234                 mtx_lock(&lun->lun_lock);
1235                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1236                 mtx_unlock(&lun->lun_lock);
1237         }
1238         mtx_unlock(&softc->ctl_lock);
1239 }
1240
1241 static void
1242 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1243 {
1244         struct ctl_port *port;
1245         int iid;
1246
1247         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1248         if (port == NULL) {
1249                 printf("%s: Received IID for unknown port %d\n",
1250                     __func__, msg->hdr.nexus.targ_port);
1251                 return;
1252         }
1253         iid = msg->hdr.nexus.initid;
1254         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1255         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1256         free(port->wwpn_iid[iid].name, M_CTL);
1257         if (msg->iid.name_len) {
1258                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1259                     msg->iid.name_len, M_CTL);
1260         } else
1261                 port->wwpn_iid[iid].name = NULL;
1262 }
1263
1264 static void
1265 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1266 {
1267
1268         if (msg->login.version != CTL_HA_VERSION) {
1269                 printf("CTL HA peers have different versions %d != %d\n",
1270                     msg->login.version, CTL_HA_VERSION);
1271                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1272                 return;
1273         }
1274         if (msg->login.ha_mode != softc->ha_mode) {
1275                 printf("CTL HA peers have different ha_mode %d != %d\n",
1276                     msg->login.ha_mode, softc->ha_mode);
1277                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1278                 return;
1279         }
1280         if (msg->login.ha_id == softc->ha_id) {
1281                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1282                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1283                 return;
1284         }
1285         if (msg->login.max_luns != CTL_MAX_LUNS ||
1286             msg->login.max_ports != CTL_MAX_PORTS ||
1287             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1288                 printf("CTL HA peers have different limits\n");
1289                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1290                 return;
1291         }
1292 }
1293
1294 static void
1295 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1296 {
1297         struct ctl_lun *lun;
1298         u_int i;
1299         uint32_t initidx, targ_lun;
1300
1301         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1302         mtx_lock(&softc->ctl_lock);
1303         if (targ_lun >= CTL_MAX_LUNS ||
1304             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1305                 mtx_unlock(&softc->ctl_lock);
1306                 return;
1307         }
1308         mtx_lock(&lun->lun_lock);
1309         mtx_unlock(&softc->ctl_lock);
1310         if (lun->flags & CTL_LUN_DISABLED) {
1311                 mtx_unlock(&lun->lun_lock);
1312                 return;
1313         }
1314         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1315                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1316                     msg->mode.page_code &&
1317                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1318                         break;
1319         }
1320         if (i == CTL_NUM_MODE_PAGES) {
1321                 mtx_unlock(&lun->lun_lock);
1322                 return;
1323         }
1324         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1325             lun->mode_pages.index[i].page_len);
1326         initidx = ctl_get_initindex(&msg->hdr.nexus);
1327         if (initidx != -1)
1328                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1329         mtx_unlock(&lun->lun_lock);
1330 }
1331
1332 /*
1333  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1334  * subsystem come in here.
1335  */
1336 static void
1337 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1338 {
1339         struct ctl_softc *softc = control_softc;
1340         union ctl_io *io;
1341         struct ctl_prio *presio;
1342         ctl_ha_status isc_status;
1343
1344         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1345         if (event == CTL_HA_EVT_MSG_RECV) {
1346                 union ctl_ha_msg *msg, msgbuf;
1347
1348                 if (param > sizeof(msgbuf))
1349                         msg = malloc(param, M_CTL, M_WAITOK);
1350                 else
1351                         msg = &msgbuf;
1352                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1353                     M_WAITOK);
1354                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1355                         printf("%s: Error receiving message: %d\n",
1356                             __func__, isc_status);
1357                         if (msg != &msgbuf)
1358                                 free(msg, M_CTL);
1359                         return;
1360                 }
1361
1362                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1363                 switch (msg->hdr.msg_type) {
1364                 case CTL_MSG_SERIALIZE:
1365                         io = ctl_alloc_io(softc->othersc_pool);
1366                         ctl_zero_io(io);
1367                         // populate ctsio from msg
1368                         io->io_hdr.io_type = CTL_IO_SCSI;
1369                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1370                         io->io_hdr.original_sc = msg->hdr.original_sc;
1371                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1372                                             CTL_FLAG_IO_ACTIVE;
1373                         /*
1374                          * If we're in serialization-only mode, we don't
1375                          * want to go through full done processing.  Thus
1376                          * the COPY flag.
1377                          *
1378                          * XXX KDM add another flag that is more specific.
1379                          */
1380                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1381                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1382                         io->io_hdr.nexus = msg->hdr.nexus;
1383 #if 0
1384                         printf("port %u, iid %u, lun %u\n",
1385                                io->io_hdr.nexus.targ_port,
1386                                io->io_hdr.nexus.initid,
1387                                io->io_hdr.nexus.targ_lun);
1388 #endif
1389                         io->scsiio.tag_num = msg->scsi.tag_num;
1390                         io->scsiio.tag_type = msg->scsi.tag_type;
1391 #ifdef CTL_TIME_IO
1392                         io->io_hdr.start_time = time_uptime;
1393                         getbinuptime(&io->io_hdr.start_bt);
1394 #endif /* CTL_TIME_IO */
1395                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1396                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1397                                CTL_MAX_CDBLEN);
1398                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1399                                 const struct ctl_cmd_entry *entry;
1400
1401                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1402                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1403                                 io->io_hdr.flags |=
1404                                         entry->flags & CTL_FLAG_DATA_MASK;
1405                         }
1406                         ctl_enqueue_isc(io);
1407                         break;
1408
1409                 /* Performed on the Originating SC, XFER mode only */
1410                 case CTL_MSG_DATAMOVE: {
1411                         struct ctl_sg_entry *sgl;
1412                         int i, j;
1413
1414                         io = msg->hdr.original_sc;
1415                         if (io == NULL) {
1416                                 printf("%s: original_sc == NULL!\n", __func__);
1417                                 /* XXX KDM do something here */
1418                                 break;
1419                         }
1420                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1421                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1422                         /*
1423                          * Keep track of this, we need to send it back over
1424                          * when the datamove is complete.
1425                          */
1426                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1427                         if (msg->hdr.status == CTL_SUCCESS)
1428                                 io->io_hdr.status = msg->hdr.status;
1429
1430                         if (msg->dt.sg_sequence == 0) {
1431 #ifdef CTL_TIME_IO
1432                                 getbinuptime(&io->io_hdr.dma_start_bt);
1433 #endif
1434                                 i = msg->dt.kern_sg_entries +
1435                                     msg->dt.kern_data_len /
1436                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1437                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1438                                     M_WAITOK | M_ZERO);
1439                                 io->io_hdr.remote_sglist = sgl;
1440                                 io->io_hdr.local_sglist =
1441                                     &sgl[msg->dt.kern_sg_entries];
1442
1443                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1444
1445                                 io->scsiio.kern_sg_entries =
1446                                         msg->dt.kern_sg_entries;
1447                                 io->scsiio.rem_sg_entries =
1448                                         msg->dt.kern_sg_entries;
1449                                 io->scsiio.kern_data_len =
1450                                         msg->dt.kern_data_len;
1451                                 io->scsiio.kern_total_len =
1452                                         msg->dt.kern_total_len;
1453                                 io->scsiio.kern_data_resid =
1454                                         msg->dt.kern_data_resid;
1455                                 io->scsiio.kern_rel_offset =
1456                                         msg->dt.kern_rel_offset;
1457                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1458                                 io->io_hdr.flags |= msg->dt.flags &
1459                                     CTL_FLAG_BUS_ADDR;
1460                         } else
1461                                 sgl = (struct ctl_sg_entry *)
1462                                         io->scsiio.kern_data_ptr;
1463
1464                         for (i = msg->dt.sent_sg_entries, j = 0;
1465                              i < (msg->dt.sent_sg_entries +
1466                              msg->dt.cur_sg_entries); i++, j++) {
1467                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1468                                 sgl[i].len = msg->dt.sg_list[j].len;
1469
1470 #if 0
1471                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1472                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1473 #endif
1474                         }
1475
1476                         /*
1477                          * If this is the last piece of the I/O, we've got
1478                          * the full S/G list.  Queue processing in the thread.
1479                          * Otherwise wait for the next piece.
1480                          */
1481                         if (msg->dt.sg_last != 0)
1482                                 ctl_enqueue_isc(io);
1483                         break;
1484                 }
1485                 /* Performed on the Serializing (primary) SC, XFER mode only */
1486                 case CTL_MSG_DATAMOVE_DONE: {
1487                         if (msg->hdr.serializing_sc == NULL) {
1488                                 printf("%s: serializing_sc == NULL!\n",
1489                                        __func__);
1490                                 /* XXX KDM now what? */
1491                                 break;
1492                         }
1493                         /*
1494                          * We grab the sense information here in case
1495                          * there was a failure, so we can return status
1496                          * back to the initiator.
1497                          */
1498                         io = msg->hdr.serializing_sc;
1499                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1500                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1501                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1502                         io->io_hdr.port_status = msg->scsi.fetd_status;
1503                         io->scsiio.residual = msg->scsi.residual;
1504                         if (msg->hdr.status != CTL_STATUS_NONE) {
1505                                 io->io_hdr.status = msg->hdr.status;
1506                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1507                                 io->scsiio.sense_len = msg->scsi.sense_len;
1508                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1509                                 memcpy(&io->scsiio.sense_data,
1510                                     &msg->scsi.sense_data,
1511                                     msg->scsi.sense_len);
1512                                 if (msg->hdr.status == CTL_SUCCESS)
1513                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1514                         }
1515                         ctl_enqueue_isc(io);
1516                         break;
1517                 }
1518
1519                 /* Preformed on Originating SC, SER_ONLY mode */
1520                 case CTL_MSG_R2R:
1521                         io = msg->hdr.original_sc;
1522                         if (io == NULL) {
1523                                 printf("%s: original_sc == NULL!\n",
1524                                     __func__);
1525                                 break;
1526                         }
1527                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1528                         io->io_hdr.msg_type = CTL_MSG_R2R;
1529                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1530                         ctl_enqueue_isc(io);
1531                         break;
1532
1533                 /*
1534                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1535                  * mode.
1536                  * Performed on the Originating (i.e. secondary) SC in XFER
1537                  * mode
1538                  */
1539                 case CTL_MSG_FINISH_IO:
1540                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1541                                 ctl_isc_handler_finish_xfer(softc, msg);
1542                         else
1543                                 ctl_isc_handler_finish_ser_only(softc, msg);
1544                         break;
1545
1546                 /* Preformed on Originating SC */
1547                 case CTL_MSG_BAD_JUJU:
1548                         io = msg->hdr.original_sc;
1549                         if (io == NULL) {
1550                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1551                                        __func__);
1552                                 break;
1553                         }
1554                         ctl_copy_sense_data(msg, io);
1555                         /*
1556                          * IO should have already been cleaned up on other
1557                          * SC so clear this flag so we won't send a message
1558                          * back to finish the IO there.
1559                          */
1560                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1561                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1562
1563                         /* io = msg->hdr.serializing_sc; */
1564                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1565                         ctl_enqueue_isc(io);
1566                         break;
1567
1568                 /* Handle resets sent from the other side */
1569                 case CTL_MSG_MANAGE_TASKS: {
1570                         struct ctl_taskio *taskio;
1571                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1572                             softc->othersc_pool);
1573                         ctl_zero_io((union ctl_io *)taskio);
1574                         taskio->io_hdr.io_type = CTL_IO_TASK;
1575                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1576                         taskio->io_hdr.nexus = msg->hdr.nexus;
1577                         taskio->task_action = msg->task.task_action;
1578                         taskio->tag_num = msg->task.tag_num;
1579                         taskio->tag_type = msg->task.tag_type;
1580 #ifdef CTL_TIME_IO
1581                         taskio->io_hdr.start_time = time_uptime;
1582                         getbinuptime(&taskio->io_hdr.start_bt);
1583 #endif /* CTL_TIME_IO */
1584                         ctl_run_task((union ctl_io *)taskio);
1585                         break;
1586                 }
1587                 /* Persistent Reserve action which needs attention */
1588                 case CTL_MSG_PERS_ACTION:
1589                         presio = (struct ctl_prio *)ctl_alloc_io(
1590                             softc->othersc_pool);
1591                         ctl_zero_io((union ctl_io *)presio);
1592                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1593                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1594                         presio->io_hdr.nexus = msg->hdr.nexus;
1595                         presio->pr_msg = msg->pr;
1596                         ctl_enqueue_isc((union ctl_io *)presio);
1597                         break;
1598                 case CTL_MSG_UA:
1599                         ctl_isc_ua(softc, msg, param);
1600                         break;
1601                 case CTL_MSG_PORT_SYNC:
1602                         ctl_isc_port_sync(softc, msg, param);
1603                         break;
1604                 case CTL_MSG_LUN_SYNC:
1605                         ctl_isc_lun_sync(softc, msg, param);
1606                         break;
1607                 case CTL_MSG_IID_SYNC:
1608                         ctl_isc_iid_sync(softc, msg, param);
1609                         break;
1610                 case CTL_MSG_LOGIN:
1611                         ctl_isc_login(softc, msg, param);
1612                         break;
1613                 case CTL_MSG_MODE_SYNC:
1614                         ctl_isc_mode_sync(softc, msg, param);
1615                         break;
1616                 default:
1617                         printf("Received HA message of unknown type %d\n",
1618                             msg->hdr.msg_type);
1619                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1620                         break;
1621                 }
1622                 if (msg != &msgbuf)
1623                         free(msg, M_CTL);
1624         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1625                 printf("CTL: HA link status changed from %d to %d\n",
1626                     softc->ha_link, param);
1627                 if (param == softc->ha_link)
1628                         return;
1629                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1630                         softc->ha_link = param;
1631                         ctl_isc_ha_link_down(softc);
1632                 } else {
1633                         softc->ha_link = param;
1634                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1635                                 ctl_isc_ha_link_up(softc);
1636                 }
1637                 return;
1638         } else {
1639                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1640                 return;
1641         }
1642 }
1643
1644 static void
1645 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1646 {
1647
1648         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1649             src->scsi.sense_len);
1650         dest->scsiio.scsi_status = src->scsi.scsi_status;
1651         dest->scsiio.sense_len = src->scsi.sense_len;
1652         dest->io_hdr.status = src->hdr.status;
1653 }
1654
1655 static void
1656 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1657 {
1658
1659         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1660             src->scsiio.sense_len);
1661         dest->scsi.scsi_status = src->scsiio.scsi_status;
1662         dest->scsi.sense_len = src->scsiio.sense_len;
1663         dest->hdr.status = src->io_hdr.status;
1664 }
1665
1666 void
1667 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1668 {
1669         struct ctl_softc *softc = lun->ctl_softc;
1670         ctl_ua_type *pu;
1671
1672         if (initidx < softc->init_min || initidx >= softc->init_max)
1673                 return;
1674         mtx_assert(&lun->lun_lock, MA_OWNED);
1675         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1676         if (pu == NULL)
1677                 return;
1678         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1679 }
1680
1681 void
1682 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1683 {
1684         int i;
1685
1686         mtx_assert(&lun->lun_lock, MA_OWNED);
1687         if (lun->pending_ua[port] == NULL)
1688                 return;
1689         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1690                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1691                         continue;
1692                 lun->pending_ua[port][i] |= ua;
1693         }
1694 }
1695
1696 void
1697 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1698 {
1699         struct ctl_softc *softc = lun->ctl_softc;
1700         int i;
1701
1702         mtx_assert(&lun->lun_lock, MA_OWNED);
1703         for (i = softc->port_min; i < softc->port_max; i++)
1704                 ctl_est_ua_port(lun, i, except, ua);
1705 }
1706
1707 void
1708 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1709 {
1710         struct ctl_softc *softc = lun->ctl_softc;
1711         ctl_ua_type *pu;
1712
1713         if (initidx < softc->init_min || initidx >= softc->init_max)
1714                 return;
1715         mtx_assert(&lun->lun_lock, MA_OWNED);
1716         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1717         if (pu == NULL)
1718                 return;
1719         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1720 }
1721
1722 void
1723 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1724 {
1725         struct ctl_softc *softc = lun->ctl_softc;
1726         int i, j;
1727
1728         mtx_assert(&lun->lun_lock, MA_OWNED);
1729         for (i = softc->port_min; i < softc->port_max; i++) {
1730                 if (lun->pending_ua[i] == NULL)
1731                         continue;
1732                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1733                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1734                                 continue;
1735                         lun->pending_ua[i][j] &= ~ua;
1736                 }
1737         }
1738 }
1739
1740 void
1741 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1742     ctl_ua_type ua_type)
1743 {
1744         struct ctl_lun *lun;
1745
1746         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1747         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1748                 mtx_lock(&lun->lun_lock);
1749                 ctl_clr_ua(lun, initidx, ua_type);
1750                 mtx_unlock(&lun->lun_lock);
1751         }
1752 }
1753
1754 static int
1755 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1756 {
1757         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1758         struct ctl_lun *lun;
1759         struct ctl_lun_req ireq;
1760         int error, value;
1761
1762         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1763         error = sysctl_handle_int(oidp, &value, 0, req);
1764         if ((error != 0) || (req->newptr == NULL))
1765                 return (error);
1766
1767         mtx_lock(&softc->ctl_lock);
1768         if (value == 0)
1769                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1770         else
1771                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1772         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1773                 mtx_unlock(&softc->ctl_lock);
1774                 bzero(&ireq, sizeof(ireq));
1775                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1776                 ireq.reqdata.modify.lun_id = lun->lun;
1777                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1778                     curthread);
1779                 if (ireq.status != CTL_LUN_OK) {
1780                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1781                             __func__, ireq.status, ireq.error_str);
1782                 }
1783                 mtx_lock(&softc->ctl_lock);
1784         }
1785         mtx_unlock(&softc->ctl_lock);
1786         return (0);
1787 }
1788
1789 static int
1790 ctl_init(void)
1791 {
1792         struct make_dev_args args;
1793         struct ctl_softc *softc;
1794         void *other_pool;
1795         int i, error;
1796
1797         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1798                                M_WAITOK | M_ZERO);
1799
1800         make_dev_args_init(&args);
1801         args.mda_devsw = &ctl_cdevsw;
1802         args.mda_uid = UID_ROOT;
1803         args.mda_gid = GID_OPERATOR;
1804         args.mda_mode = 0600;
1805         args.mda_si_drv1 = softc;
1806         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1807         if (error != 0) {
1808                 free(control_softc, M_DEVBUF);
1809                 return (error);
1810         }
1811
1812         sysctl_ctx_init(&softc->sysctl_ctx);
1813         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1814                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1815                 CTLFLAG_RD, 0, "CAM Target Layer");
1816
1817         if (softc->sysctl_tree == NULL) {
1818                 printf("%s: unable to allocate sysctl tree\n", __func__);
1819                 destroy_dev(softc->dev);
1820                 free(control_softc, M_DEVBUF);
1821                 control_softc = NULL;
1822                 return (ENOMEM);
1823         }
1824
1825         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1826         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1827             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1828         softc->flags = 0;
1829
1830         TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1831         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1832             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1833             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1834
1835         /*
1836          * In Copan's HA scheme, the "master" and "slave" roles are
1837          * figured out through the slot the controller is in.  Although it
1838          * is an active/active system, someone has to be in charge.
1839          */
1840         TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1841         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1842             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1843             "HA head ID (0 - no HA)");
1844         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1845                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1846                 softc->is_single = 1;
1847                 softc->port_cnt = CTL_MAX_PORTS;
1848                 softc->port_min = 0;
1849         } else {
1850                 softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1851                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1852         }
1853         softc->port_max = softc->port_min + softc->port_cnt;
1854         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1855         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1856
1857         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1858             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1859             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1860
1861         STAILQ_INIT(&softc->lun_list);
1862         STAILQ_INIT(&softc->pending_lun_queue);
1863         STAILQ_INIT(&softc->fe_list);
1864         STAILQ_INIT(&softc->port_list);
1865         STAILQ_INIT(&softc->be_list);
1866         ctl_tpc_init(softc);
1867
1868         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1869                             &other_pool) != 0)
1870         {
1871                 printf("ctl: can't allocate %d entry other SC pool, "
1872                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1873                 return (ENOMEM);
1874         }
1875         softc->othersc_pool = other_pool;
1876
1877         if (worker_threads <= 0)
1878                 worker_threads = max(1, mp_ncpus / 4);
1879         if (worker_threads > CTL_MAX_THREADS)
1880                 worker_threads = CTL_MAX_THREADS;
1881
1882         for (i = 0; i < worker_threads; i++) {
1883                 struct ctl_thread *thr = &softc->threads[i];
1884
1885                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1886                 thr->ctl_softc = softc;
1887                 STAILQ_INIT(&thr->incoming_queue);
1888                 STAILQ_INIT(&thr->rtr_queue);
1889                 STAILQ_INIT(&thr->done_queue);
1890                 STAILQ_INIT(&thr->isc_queue);
1891
1892                 error = kproc_kthread_add(ctl_work_thread, thr,
1893                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1894                 if (error != 0) {
1895                         printf("error creating CTL work thread!\n");
1896                         ctl_pool_free(other_pool);
1897                         return (error);
1898                 }
1899         }
1900         error = kproc_kthread_add(ctl_lun_thread, softc,
1901             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1902         if (error != 0) {
1903                 printf("error creating CTL lun thread!\n");
1904                 ctl_pool_free(other_pool);
1905                 return (error);
1906         }
1907         error = kproc_kthread_add(ctl_thresh_thread, softc,
1908             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1909         if (error != 0) {
1910                 printf("error creating CTL threshold thread!\n");
1911                 ctl_pool_free(other_pool);
1912                 return (error);
1913         }
1914
1915         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1916             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1917             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1918
1919         if (softc->is_single == 0) {
1920                 ctl_frontend_register(&ha_frontend);
1921                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1922                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1923                         softc->is_single = 1;
1924                 } else
1925                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1926                     != CTL_HA_STATUS_SUCCESS) {
1927                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1928                         softc->is_single = 1;
1929                 }
1930         }
1931         return (0);
1932 }
1933
1934 void
1935 ctl_shutdown(void)
1936 {
1937         struct ctl_softc *softc = control_softc;
1938         struct ctl_lun *lun, *next_lun;
1939
1940         if (softc->is_single == 0) {
1941                 ctl_ha_msg_shutdown(softc);
1942                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1943                     != CTL_HA_STATUS_SUCCESS)
1944                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1945                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1946                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1947                 ctl_frontend_deregister(&ha_frontend);
1948         }
1949
1950         mtx_lock(&softc->ctl_lock);
1951
1952         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1953                 ctl_free_lun(lun);
1954
1955         mtx_unlock(&softc->ctl_lock);
1956
1957 #if 0
1958         ctl_shutdown_thread(softc->work_thread);
1959         mtx_destroy(&softc->queue_lock);
1960 #endif
1961
1962         ctl_tpc_shutdown(softc);
1963         uma_zdestroy(softc->io_zone);
1964         mtx_destroy(&softc->ctl_lock);
1965
1966         destroy_dev(softc->dev);
1967
1968         sysctl_ctx_free(&softc->sysctl_ctx);
1969
1970         free(control_softc, M_DEVBUF);
1971         control_softc = NULL;
1972 }
1973
1974 static int
1975 ctl_module_event_handler(module_t mod, int what, void *arg)
1976 {
1977
1978         switch (what) {
1979         case MOD_LOAD:
1980                 return (ctl_init());
1981         case MOD_UNLOAD:
1982                 return (EBUSY);
1983         default:
1984                 return (EOPNOTSUPP);
1985         }
1986 }
1987
1988 /*
1989  * XXX KDM should we do some access checks here?  Bump a reference count to
1990  * prevent a CTL module from being unloaded while someone has it open?
1991  */
1992 static int
1993 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1994 {
1995         return (0);
1996 }
1997
1998 static int
1999 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2000 {
2001         return (0);
2002 }
2003
2004 /*
2005  * Remove an initiator by port number and initiator ID.
2006  * Returns 0 for success, -1 for failure.
2007  */
2008 int
2009 ctl_remove_initiator(struct ctl_port *port, int iid)
2010 {
2011         struct ctl_softc *softc = port->ctl_softc;
2012
2013         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2014
2015         if (iid > CTL_MAX_INIT_PER_PORT) {
2016                 printf("%s: initiator ID %u > maximun %u!\n",
2017                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2018                 return (-1);
2019         }
2020
2021         mtx_lock(&softc->ctl_lock);
2022         port->wwpn_iid[iid].in_use--;
2023         port->wwpn_iid[iid].last_use = time_uptime;
2024         mtx_unlock(&softc->ctl_lock);
2025         ctl_isc_announce_iid(port, iid);
2026
2027         return (0);
2028 }
2029
2030 /*
2031  * Add an initiator to the initiator map.
2032  * Returns iid for success, < 0 for failure.
2033  */
2034 int
2035 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2036 {
2037         struct ctl_softc *softc = port->ctl_softc;
2038         time_t best_time;
2039         int i, best;
2040
2041         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2042
2043         if (iid >= CTL_MAX_INIT_PER_PORT) {
2044                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2045                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2046                 free(name, M_CTL);
2047                 return (-1);
2048         }
2049
2050         mtx_lock(&softc->ctl_lock);
2051
2052         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2053                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2054                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2055                                 iid = i;
2056                                 break;
2057                         }
2058                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2059                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2060                                 iid = i;
2061                                 break;
2062                         }
2063                 }
2064         }
2065
2066         if (iid < 0) {
2067                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2068                         if (port->wwpn_iid[i].in_use == 0 &&
2069                             port->wwpn_iid[i].wwpn == 0 &&
2070                             port->wwpn_iid[i].name == NULL) {
2071                                 iid = i;
2072                                 break;
2073                         }
2074                 }
2075         }
2076
2077         if (iid < 0) {
2078                 best = -1;
2079                 best_time = INT32_MAX;
2080                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2081                         if (port->wwpn_iid[i].in_use == 0) {
2082                                 if (port->wwpn_iid[i].last_use < best_time) {
2083                                         best = i;
2084                                         best_time = port->wwpn_iid[i].last_use;
2085                                 }
2086                         }
2087                 }
2088                 iid = best;
2089         }
2090
2091         if (iid < 0) {
2092                 mtx_unlock(&softc->ctl_lock);
2093                 free(name, M_CTL);
2094                 return (-2);
2095         }
2096
2097         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2098                 /*
2099                  * This is not an error yet.
2100                  */
2101                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2102 #if 0
2103                         printf("%s: port %d iid %u WWPN %#jx arrived"
2104                             " again\n", __func__, port->targ_port,
2105                             iid, (uintmax_t)wwpn);
2106 #endif
2107                         goto take;
2108                 }
2109                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2110                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2111 #if 0
2112                         printf("%s: port %d iid %u name '%s' arrived"
2113                             " again\n", __func__, port->targ_port,
2114                             iid, name);
2115 #endif
2116                         goto take;
2117                 }
2118
2119                 /*
2120                  * This is an error, but what do we do about it?  The
2121                  * driver is telling us we have a new WWPN for this
2122                  * initiator ID, so we pretty much need to use it.
2123                  */
2124                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2125                     " but WWPN %#jx '%s' is still at that address\n",
2126                     __func__, port->targ_port, iid, wwpn, name,
2127                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2128                     port->wwpn_iid[iid].name);
2129
2130                 /*
2131                  * XXX KDM clear have_ca and ua_pending on each LUN for
2132                  * this initiator.
2133                  */
2134         }
2135 take:
2136         free(port->wwpn_iid[iid].name, M_CTL);
2137         port->wwpn_iid[iid].name = name;
2138         port->wwpn_iid[iid].wwpn = wwpn;
2139         port->wwpn_iid[iid].in_use++;
2140         mtx_unlock(&softc->ctl_lock);
2141         ctl_isc_announce_iid(port, iid);
2142
2143         return (iid);
2144 }
2145
2146 static int
2147 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2148 {
2149         int len;
2150
2151         switch (port->port_type) {
2152         case CTL_PORT_FC:
2153         {
2154                 struct scsi_transportid_fcp *id =
2155                     (struct scsi_transportid_fcp *)buf;
2156                 if (port->wwpn_iid[iid].wwpn == 0)
2157                         return (0);
2158                 memset(id, 0, sizeof(*id));
2159                 id->format_protocol = SCSI_PROTO_FC;
2160                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2161                 return (sizeof(*id));
2162         }
2163         case CTL_PORT_ISCSI:
2164         {
2165                 struct scsi_transportid_iscsi_port *id =
2166                     (struct scsi_transportid_iscsi_port *)buf;
2167                 if (port->wwpn_iid[iid].name == NULL)
2168                         return (0);
2169                 memset(id, 0, 256);
2170                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2171                     SCSI_PROTO_ISCSI;
2172                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2173                 len = roundup2(min(len, 252), 4);
2174                 scsi_ulto2b(len, id->additional_length);
2175                 return (sizeof(*id) + len);
2176         }
2177         case CTL_PORT_SAS:
2178         {
2179                 struct scsi_transportid_sas *id =
2180                     (struct scsi_transportid_sas *)buf;
2181                 if (port->wwpn_iid[iid].wwpn == 0)
2182                         return (0);
2183                 memset(id, 0, sizeof(*id));
2184                 id->format_protocol = SCSI_PROTO_SAS;
2185                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2186                 return (sizeof(*id));
2187         }
2188         default:
2189         {
2190                 struct scsi_transportid_spi *id =
2191                     (struct scsi_transportid_spi *)buf;
2192                 memset(id, 0, sizeof(*id));
2193                 id->format_protocol = SCSI_PROTO_SPI;
2194                 scsi_ulto2b(iid, id->scsi_addr);
2195                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2196                 return (sizeof(*id));
2197         }
2198         }
2199 }
2200
2201 /*
2202  * Serialize a command that went down the "wrong" side, and so was sent to
2203  * this controller for execution.  The logic is a little different than the
2204  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2205  * sent back to the other side, but in the success case, we execute the
2206  * command on this side (XFER mode) or tell the other side to execute it
2207  * (SER_ONLY mode).
2208  */
2209 static void
2210 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2211 {
2212         struct ctl_softc *softc = control_softc;
2213         union ctl_ha_msg msg_info;
2214         struct ctl_port *port;
2215         struct ctl_lun *lun;
2216         const struct ctl_cmd_entry *entry;
2217         uint32_t targ_lun;
2218
2219         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2220         mtx_lock(&softc->ctl_lock);
2221
2222         /* Make sure that we know about this port. */
2223         port = ctl_io_port(&ctsio->io_hdr);
2224         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2225                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2226                                          /*retry_count*/ 1);
2227                 goto badjuju;
2228         }
2229
2230         /* Make sure that we know about this LUN. */
2231         if (targ_lun >= CTL_MAX_LUNS ||
2232             (lun = softc->ctl_luns[targ_lun]) == NULL) {
2233                 mtx_unlock(&softc->ctl_lock);
2234
2235                 /*
2236                  * The other node would not send this request to us unless
2237                  * received announce that we are primary node for this LUN.
2238                  * If this LUN does not exist now, it is probably result of
2239                  * a race, so respond to initiator in the most opaque way.
2240                  */
2241                 ctl_set_busy(ctsio);
2242                 goto badjuju;
2243         }
2244         mtx_lock(&lun->lun_lock);
2245         mtx_unlock(&softc->ctl_lock);
2246
2247         /*
2248          * If the LUN is invalid, pretend that it doesn't exist.
2249          * It will go away as soon as all pending I/Os completed.
2250          */
2251         if (lun->flags & CTL_LUN_DISABLED) {
2252                 mtx_unlock(&lun->lun_lock);
2253                 ctl_set_busy(ctsio);
2254                 goto badjuju;
2255         }
2256
2257         entry = ctl_get_cmd_entry(ctsio, NULL);
2258         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2259                 mtx_unlock(&lun->lun_lock);
2260                 goto badjuju;
2261         }
2262
2263         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2264         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2265
2266         /*
2267          * Every I/O goes into the OOA queue for a
2268          * particular LUN, and stays there until completion.
2269          */
2270 #ifdef CTL_TIME_IO
2271         if (TAILQ_EMPTY(&lun->ooa_queue))
2272                 lun->idle_time += getsbinuptime() - lun->last_busy;
2273 #endif
2274         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2275
2276         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2277                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2278                  ooa_links))) {
2279         case CTL_ACTION_BLOCK:
2280                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2281                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2282                                   blocked_links);
2283                 mtx_unlock(&lun->lun_lock);
2284                 break;
2285         case CTL_ACTION_PASS:
2286         case CTL_ACTION_SKIP:
2287                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2288                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2289                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2290                         mtx_unlock(&lun->lun_lock);
2291                 } else {
2292                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2293                         mtx_unlock(&lun->lun_lock);
2294
2295                         /* send msg back to other side */
2296                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2297                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2298                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2299                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2300                             sizeof(msg_info.hdr), M_WAITOK);
2301                 }
2302                 break;
2303         case CTL_ACTION_OVERLAP:
2304                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2305                 mtx_unlock(&lun->lun_lock);
2306                 ctl_set_overlapped_cmd(ctsio);
2307                 goto badjuju;
2308         case CTL_ACTION_OVERLAP_TAG:
2309                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2310                 mtx_unlock(&lun->lun_lock);
2311                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2312                 goto badjuju;
2313         case CTL_ACTION_ERROR:
2314         default:
2315                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2316                 mtx_unlock(&lun->lun_lock);
2317
2318                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2319                                          /*retry_count*/ 0);
2320 badjuju:
2321                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2322                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2323                 msg_info.hdr.serializing_sc = NULL;
2324                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2325                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2326                     sizeof(msg_info.scsi), M_WAITOK);
2327                 ctl_free_io((union ctl_io *)ctsio);
2328                 break;
2329         }
2330 }
2331
2332 /*
2333  * Returns 0 for success, errno for failure.
2334  */
2335 static void
2336 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2337                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2338 {
2339         union ctl_io *io;
2340
2341         mtx_lock(&lun->lun_lock);
2342         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2343              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2344              ooa_links)) {
2345                 struct ctl_ooa_entry *entry;
2346
2347                 /*
2348                  * If we've got more than we can fit, just count the
2349                  * remaining entries.
2350                  */
2351                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2352                         continue;
2353
2354                 entry = &kern_entries[*cur_fill_num];
2355
2356                 entry->tag_num = io->scsiio.tag_num;
2357                 entry->lun_num = lun->lun;
2358 #ifdef CTL_TIME_IO
2359                 entry->start_bt = io->io_hdr.start_bt;
2360 #endif
2361                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2362                 entry->cdb_len = io->scsiio.cdb_len;
2363                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2364                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2365
2366                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2367                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2368
2369                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2370                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2371
2372                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2373                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2374
2375                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2376                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2377         }
2378         mtx_unlock(&lun->lun_lock);
2379 }
2380
2381 static void *
2382 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2383                  size_t error_str_len)
2384 {
2385         void *kptr;
2386
2387         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2388
2389         if (copyin(user_addr, kptr, len) != 0) {
2390                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2391                          "from user address %p to kernel address %p", len,
2392                          user_addr, kptr);
2393                 free(kptr, M_CTL);
2394                 return (NULL);
2395         }
2396
2397         return (kptr);
2398 }
2399
2400 static void
2401 ctl_free_args(int num_args, struct ctl_be_arg *args)
2402 {
2403         int i;
2404
2405         if (args == NULL)
2406                 return;
2407
2408         for (i = 0; i < num_args; i++) {
2409                 free(args[i].kname, M_CTL);
2410                 free(args[i].kvalue, M_CTL);
2411         }
2412
2413         free(args, M_CTL);
2414 }
2415
2416 static struct ctl_be_arg *
2417 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2418                 char *error_str, size_t error_str_len)
2419 {
2420         struct ctl_be_arg *args;
2421         int i;
2422
2423         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2424                                 error_str, error_str_len);
2425
2426         if (args == NULL)
2427                 goto bailout;
2428
2429         for (i = 0; i < num_args; i++) {
2430                 args[i].kname = NULL;
2431                 args[i].kvalue = NULL;
2432         }
2433
2434         for (i = 0; i < num_args; i++) {
2435                 uint8_t *tmpptr;
2436
2437                 args[i].kname = ctl_copyin_alloc(args[i].name,
2438                         args[i].namelen, error_str, error_str_len);
2439                 if (args[i].kname == NULL)
2440                         goto bailout;
2441
2442                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2443                         snprintf(error_str, error_str_len, "Argument %d "
2444                                  "name is not NUL-terminated", i);
2445                         goto bailout;
2446                 }
2447
2448                 if (args[i].flags & CTL_BEARG_RD) {
2449                         tmpptr = ctl_copyin_alloc(args[i].value,
2450                                 args[i].vallen, error_str, error_str_len);
2451                         if (tmpptr == NULL)
2452                                 goto bailout;
2453                         if ((args[i].flags & CTL_BEARG_ASCII)
2454                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2455                                 snprintf(error_str, error_str_len, "Argument "
2456                                     "%d value is not NUL-terminated", i);
2457                                 free(tmpptr, M_CTL);
2458                                 goto bailout;
2459                         }
2460                         args[i].kvalue = tmpptr;
2461                 } else {
2462                         args[i].kvalue = malloc(args[i].vallen,
2463                             M_CTL, M_WAITOK | M_ZERO);
2464                 }
2465         }
2466
2467         return (args);
2468 bailout:
2469
2470         ctl_free_args(num_args, args);
2471
2472         return (NULL);
2473 }
2474
2475 static void
2476 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2477 {
2478         int i;
2479
2480         for (i = 0; i < num_args; i++) {
2481                 if (args[i].flags & CTL_BEARG_WR)
2482                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2483         }
2484 }
2485
2486 /*
2487  * Escape characters that are illegal or not recommended in XML.
2488  */
2489 int
2490 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2491 {
2492         char *end = str + size;
2493         int retval;
2494
2495         retval = 0;
2496
2497         for (; *str && str < end; str++) {
2498                 switch (*str) {
2499                 case '&':
2500                         retval = sbuf_printf(sb, "&amp;");
2501                         break;
2502                 case '>':
2503                         retval = sbuf_printf(sb, "&gt;");
2504                         break;
2505                 case '<':
2506                         retval = sbuf_printf(sb, "&lt;");
2507                         break;
2508                 default:
2509                         retval = sbuf_putc(sb, *str);
2510                         break;
2511                 }
2512
2513                 if (retval != 0)
2514                         break;
2515
2516         }
2517
2518         return (retval);
2519 }
2520
2521 static void
2522 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2523 {
2524         struct scsi_vpd_id_descriptor *desc;
2525         int i;
2526
2527         if (id == NULL || id->len < 4)
2528                 return;
2529         desc = (struct scsi_vpd_id_descriptor *)id->data;
2530         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2531         case SVPD_ID_TYPE_T10:
2532                 sbuf_printf(sb, "t10.");
2533                 break;
2534         case SVPD_ID_TYPE_EUI64:
2535                 sbuf_printf(sb, "eui.");
2536                 break;
2537         case SVPD_ID_TYPE_NAA:
2538                 sbuf_printf(sb, "naa.");
2539                 break;
2540         case SVPD_ID_TYPE_SCSI_NAME:
2541                 break;
2542         }
2543         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2544         case SVPD_ID_CODESET_BINARY:
2545                 for (i = 0; i < desc->length; i++)
2546                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2547                 break;
2548         case SVPD_ID_CODESET_ASCII:
2549                 sbuf_printf(sb, "%.*s", (int)desc->length,
2550                     (char *)desc->identifier);
2551                 break;
2552         case SVPD_ID_CODESET_UTF8:
2553                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2554                 break;
2555         }
2556 }
2557
2558 static int
2559 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2560           struct thread *td)
2561 {
2562         struct ctl_softc *softc = dev->si_drv1;
2563         struct ctl_lun *lun;
2564         int retval;
2565
2566         retval = 0;
2567
2568         switch (cmd) {
2569         case CTL_IO:
2570                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2571                 break;
2572         case CTL_ENABLE_PORT:
2573         case CTL_DISABLE_PORT:
2574         case CTL_SET_PORT_WWNS: {
2575                 struct ctl_port *port;
2576                 struct ctl_port_entry *entry;
2577
2578                 entry = (struct ctl_port_entry *)addr;
2579                 
2580                 mtx_lock(&softc->ctl_lock);
2581                 STAILQ_FOREACH(port, &softc->port_list, links) {
2582                         int action, done;
2583
2584                         if (port->targ_port < softc->port_min ||
2585                             port->targ_port >= softc->port_max)
2586                                 continue;
2587
2588                         action = 0;
2589                         done = 0;
2590                         if ((entry->port_type == CTL_PORT_NONE)
2591                          && (entry->targ_port == port->targ_port)) {
2592                                 /*
2593                                  * If the user only wants to enable or
2594                                  * disable or set WWNs on a specific port,
2595                                  * do the operation and we're done.
2596                                  */
2597                                 action = 1;
2598                                 done = 1;
2599                         } else if (entry->port_type & port->port_type) {
2600                                 /*
2601                                  * Compare the user's type mask with the
2602                                  * particular frontend type to see if we
2603                                  * have a match.
2604                                  */
2605                                 action = 1;
2606                                 done = 0;
2607
2608                                 /*
2609                                  * Make sure the user isn't trying to set
2610                                  * WWNs on multiple ports at the same time.
2611                                  */
2612                                 if (cmd == CTL_SET_PORT_WWNS) {
2613                                         printf("%s: Can't set WWNs on "
2614                                                "multiple ports\n", __func__);
2615                                         retval = EINVAL;
2616                                         break;
2617                                 }
2618                         }
2619                         if (action == 0)
2620                                 continue;
2621
2622                         /*
2623                          * XXX KDM we have to drop the lock here, because
2624                          * the online/offline operations can potentially
2625                          * block.  We need to reference count the frontends
2626                          * so they can't go away,
2627                          */
2628                         if (cmd == CTL_ENABLE_PORT) {
2629                                 mtx_unlock(&softc->ctl_lock);
2630                                 ctl_port_online(port);
2631                                 mtx_lock(&softc->ctl_lock);
2632                         } else if (cmd == CTL_DISABLE_PORT) {
2633                                 mtx_unlock(&softc->ctl_lock);
2634                                 ctl_port_offline(port);
2635                                 mtx_lock(&softc->ctl_lock);
2636                         } else if (cmd == CTL_SET_PORT_WWNS) {
2637                                 ctl_port_set_wwns(port,
2638                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2639                                     1 : 0, entry->wwnn,
2640                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2641                                     1 : 0, entry->wwpn);
2642                         }
2643                         if (done != 0)
2644                                 break;
2645                 }
2646                 mtx_unlock(&softc->ctl_lock);
2647                 break;
2648         }
2649         case CTL_GET_OOA: {
2650                 struct ctl_ooa *ooa_hdr;
2651                 struct ctl_ooa_entry *entries;
2652                 uint32_t cur_fill_num;
2653
2654                 ooa_hdr = (struct ctl_ooa *)addr;
2655
2656                 if ((ooa_hdr->alloc_len == 0)
2657                  || (ooa_hdr->alloc_num == 0)) {
2658                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2659                                "must be non-zero\n", __func__,
2660                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2661                         retval = EINVAL;
2662                         break;
2663                 }
2664
2665                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2666                     sizeof(struct ctl_ooa_entry))) {
2667                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2668                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2669                                __func__, ooa_hdr->alloc_len,
2670                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2671                         retval = EINVAL;
2672                         break;
2673                 }
2674
2675                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2676                 if (entries == NULL) {
2677                         printf("%s: could not allocate %d bytes for OOA "
2678                                "dump\n", __func__, ooa_hdr->alloc_len);
2679                         retval = ENOMEM;
2680                         break;
2681                 }
2682
2683                 mtx_lock(&softc->ctl_lock);
2684                 if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2685                     (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2686                      softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2687                         mtx_unlock(&softc->ctl_lock);
2688                         free(entries, M_CTL);
2689                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2690                                __func__, (uintmax_t)ooa_hdr->lun_num);
2691                         retval = EINVAL;
2692                         break;
2693                 }
2694
2695                 cur_fill_num = 0;
2696
2697                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2698                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2699                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2700                                     ooa_hdr, entries);
2701                         }
2702                 } else {
2703                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2704                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2705                             entries);
2706                 }
2707                 mtx_unlock(&softc->ctl_lock);
2708
2709                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2710                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2711                         sizeof(struct ctl_ooa_entry);
2712                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2713                 if (retval != 0) {
2714                         printf("%s: error copying out %d bytes for OOA dump\n", 
2715                                __func__, ooa_hdr->fill_len);
2716                 }
2717
2718                 getbinuptime(&ooa_hdr->cur_bt);
2719
2720                 if (cur_fill_num > ooa_hdr->alloc_num) {
2721                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2722                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2723                 } else {
2724                         ooa_hdr->dropped_num = 0;
2725                         ooa_hdr->status = CTL_OOA_OK;
2726                 }
2727
2728                 free(entries, M_CTL);
2729                 break;
2730         }
2731         case CTL_DELAY_IO: {
2732                 struct ctl_io_delay_info *delay_info;
2733
2734                 delay_info = (struct ctl_io_delay_info *)addr;
2735
2736 #ifdef CTL_IO_DELAY
2737                 mtx_lock(&softc->ctl_lock);
2738                 if (delay_info->lun_id >= CTL_MAX_LUNS ||
2739                     (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2740                         mtx_unlock(&softc->ctl_lock);
2741                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2742                         break;
2743                 }
2744                 mtx_lock(&lun->lun_lock);
2745                 mtx_unlock(&softc->ctl_lock);
2746                 delay_info->status = CTL_DELAY_STATUS_OK;
2747                 switch (delay_info->delay_type) {
2748                 case CTL_DELAY_TYPE_CONT:
2749                 case CTL_DELAY_TYPE_ONESHOT:
2750                         break;
2751                 default:
2752                         delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2753                         break;
2754                 }
2755                 switch (delay_info->delay_loc) {
2756                 case CTL_DELAY_LOC_DATAMOVE:
2757                         lun->delay_info.datamove_type = delay_info->delay_type;
2758                         lun->delay_info.datamove_delay = delay_info->delay_secs;
2759                         break;
2760                 case CTL_DELAY_LOC_DONE:
2761                         lun->delay_info.done_type = delay_info->delay_type;
2762                         lun->delay_info.done_delay = delay_info->delay_secs;
2763                         break;
2764                 default:
2765                         delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2766                         break;
2767                 }
2768                 mtx_unlock(&lun->lun_lock);
2769 #else
2770                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2771 #endif /* CTL_IO_DELAY */
2772                 break;
2773         }
2774         case CTL_GETSTATS: {
2775                 struct ctl_stats *stats;
2776                 int i;
2777
2778                 stats = (struct ctl_stats *)addr;
2779
2780                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2781                      stats->alloc_len) {
2782                         stats->status = CTL_SS_NEED_MORE_SPACE;
2783                         stats->num_luns = softc->num_luns;
2784                         break;
2785                 }
2786                 /*
2787                  * XXX KDM no locking here.  If the LUN list changes,
2788                  * things can blow up.
2789                  */
2790                 i = 0;
2791                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2792                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2793                                          sizeof(lun->stats));
2794                         if (retval != 0)
2795                                 break;
2796                 }
2797                 stats->num_luns = softc->num_luns;
2798                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2799                                  softc->num_luns;
2800                 stats->status = CTL_SS_OK;
2801 #ifdef CTL_TIME_IO
2802                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2803 #else
2804                 stats->flags = CTL_STATS_FLAG_NONE;
2805 #endif
2806                 getnanouptime(&stats->timestamp);
2807                 break;
2808         }
2809         case CTL_ERROR_INJECT: {
2810                 struct ctl_error_desc *err_desc, *new_err_desc;
2811
2812                 err_desc = (struct ctl_error_desc *)addr;
2813
2814                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2815                                       M_WAITOK | M_ZERO);
2816                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2817
2818                 mtx_lock(&softc->ctl_lock);
2819                 if (err_desc->lun_id >= CTL_MAX_LUNS ||
2820                     (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2821                         mtx_unlock(&softc->ctl_lock);
2822                         free(new_err_desc, M_CTL);
2823                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2824                                __func__, (uintmax_t)err_desc->lun_id);
2825                         retval = EINVAL;
2826                         break;
2827                 }
2828                 mtx_lock(&lun->lun_lock);
2829                 mtx_unlock(&softc->ctl_lock);
2830
2831                 /*
2832                  * We could do some checking here to verify the validity
2833                  * of the request, but given the complexity of error
2834                  * injection requests, the checking logic would be fairly
2835                  * complex.
2836                  *
2837                  * For now, if the request is invalid, it just won't get
2838                  * executed and might get deleted.
2839                  */
2840                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2841
2842                 /*
2843                  * XXX KDM check to make sure the serial number is unique,
2844                  * in case we somehow manage to wrap.  That shouldn't
2845                  * happen for a very long time, but it's the right thing to
2846                  * do.
2847                  */
2848                 new_err_desc->serial = lun->error_serial;
2849                 err_desc->serial = lun->error_serial;
2850                 lun->error_serial++;
2851
2852                 mtx_unlock(&lun->lun_lock);
2853                 break;
2854         }
2855         case CTL_ERROR_INJECT_DELETE: {
2856                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2857                 int delete_done;
2858
2859                 delete_desc = (struct ctl_error_desc *)addr;
2860                 delete_done = 0;
2861
2862                 mtx_lock(&softc->ctl_lock);
2863                 if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2864                     (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2865                         mtx_unlock(&softc->ctl_lock);
2866                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2867                                __func__, (uintmax_t)delete_desc->lun_id);
2868                         retval = EINVAL;
2869                         break;
2870                 }
2871                 mtx_lock(&lun->lun_lock);
2872                 mtx_unlock(&softc->ctl_lock);
2873                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2874                         if (desc->serial != delete_desc->serial)
2875                                 continue;
2876
2877                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2878                                       links);
2879                         free(desc, M_CTL);
2880                         delete_done = 1;
2881                 }
2882                 mtx_unlock(&lun->lun_lock);
2883                 if (delete_done == 0) {
2884                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2885                                "error serial %ju on LUN %u\n", __func__, 
2886                                delete_desc->serial, delete_desc->lun_id);
2887                         retval = EINVAL;
2888                         break;
2889                 }
2890                 break;
2891         }
2892         case CTL_DUMP_STRUCTS: {
2893                 int j, k;
2894                 struct ctl_port *port;
2895                 struct ctl_frontend *fe;
2896
2897                 mtx_lock(&softc->ctl_lock);
2898                 printf("CTL Persistent Reservation information start:\n");
2899                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2900                         mtx_lock(&lun->lun_lock);
2901                         if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2902                                 mtx_unlock(&lun->lun_lock);
2903                                 continue;
2904                         }
2905
2906                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2907                                 if (lun->pr_keys[j] == NULL)
2908                                         continue;
2909                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2910                                         if (lun->pr_keys[j][k] == 0)
2911                                                 continue;
2912                                         printf("  LUN %ju port %d iid %d key "
2913                                                "%#jx\n", lun->lun, j, k,
2914                                                (uintmax_t)lun->pr_keys[j][k]);
2915                                 }
2916                         }
2917                         mtx_unlock(&lun->lun_lock);
2918                 }
2919                 printf("CTL Persistent Reservation information end\n");
2920                 printf("CTL Ports:\n");
2921                 STAILQ_FOREACH(port, &softc->port_list, links) {
2922                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2923                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2924                                port->frontend->name, port->port_type,
2925                                port->physical_port, port->virtual_port,
2926                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2927                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2928                                 if (port->wwpn_iid[j].in_use == 0 &&
2929                                     port->wwpn_iid[j].wwpn == 0 &&
2930                                     port->wwpn_iid[j].name == NULL)
2931                                         continue;
2932
2933                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2934                                     j, port->wwpn_iid[j].in_use,
2935                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2936                                     port->wwpn_iid[j].name);
2937                         }
2938                 }
2939                 printf("CTL Port information end\n");
2940                 mtx_unlock(&softc->ctl_lock);
2941                 /*
2942                  * XXX KDM calling this without a lock.  We'd likely want
2943                  * to drop the lock before calling the frontend's dump
2944                  * routine anyway.
2945                  */
2946                 printf("CTL Frontends:\n");
2947                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2948                         printf("  Frontend '%s'\n", fe->name);
2949                         if (fe->fe_dump != NULL)
2950                                 fe->fe_dump();
2951                 }
2952                 printf("CTL Frontend information end\n");
2953                 break;
2954         }
2955         case CTL_LUN_REQ: {
2956                 struct ctl_lun_req *lun_req;
2957                 struct ctl_backend_driver *backend;
2958
2959                 lun_req = (struct ctl_lun_req *)addr;
2960
2961                 backend = ctl_backend_find(lun_req->backend);
2962                 if (backend == NULL) {
2963                         lun_req->status = CTL_LUN_ERROR;
2964                         snprintf(lun_req->error_str,
2965                                  sizeof(lun_req->error_str),
2966                                  "Backend \"%s\" not found.",
2967                                  lun_req->backend);
2968                         break;
2969                 }
2970                 if (lun_req->num_be_args > 0) {
2971                         lun_req->kern_be_args = ctl_copyin_args(
2972                                 lun_req->num_be_args,
2973                                 lun_req->be_args,
2974                                 lun_req->error_str,
2975                                 sizeof(lun_req->error_str));
2976                         if (lun_req->kern_be_args == NULL) {
2977                                 lun_req->status = CTL_LUN_ERROR;
2978                                 break;
2979                         }
2980                 }
2981
2982                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2983
2984                 if (lun_req->num_be_args > 0) {
2985                         ctl_copyout_args(lun_req->num_be_args,
2986                                       lun_req->kern_be_args);
2987                         ctl_free_args(lun_req->num_be_args,
2988                                       lun_req->kern_be_args);
2989                 }
2990                 break;
2991         }
2992         case CTL_LUN_LIST: {
2993                 struct sbuf *sb;
2994                 struct ctl_lun_list *list;
2995                 struct ctl_option *opt;
2996
2997                 list = (struct ctl_lun_list *)addr;
2998
2999                 /*
3000                  * Allocate a fixed length sbuf here, based on the length
3001                  * of the user's buffer.  We could allocate an auto-extending
3002                  * buffer, and then tell the user how much larger our
3003                  * amount of data is than his buffer, but that presents
3004                  * some problems:
3005                  *
3006                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3007                  *     we can't hold a lock while calling them with an
3008                  *     auto-extending buffer.
3009                  *
3010                  * 2.  There is not currently a LUN reference counting
3011                  *     mechanism, outside of outstanding transactions on
3012                  *     the LUN's OOA queue.  So a LUN could go away on us
3013                  *     while we're getting the LUN number, backend-specific
3014                  *     information, etc.  Thus, given the way things
3015                  *     currently work, we need to hold the CTL lock while
3016                  *     grabbing LUN information.
3017                  *
3018                  * So, from the user's standpoint, the best thing to do is
3019                  * allocate what he thinks is a reasonable buffer length,
3020                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3021                  * double the buffer length and try again.  (And repeat
3022                  * that until he succeeds.)
3023                  */
3024                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3025                 if (sb == NULL) {
3026                         list->status = CTL_LUN_LIST_ERROR;
3027                         snprintf(list->error_str, sizeof(list->error_str),
3028                                  "Unable to allocate %d bytes for LUN list",
3029                                  list->alloc_len);
3030                         break;
3031                 }
3032
3033                 sbuf_printf(sb, "<ctllunlist>\n");
3034
3035                 mtx_lock(&softc->ctl_lock);
3036                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3037                         mtx_lock(&lun->lun_lock);
3038                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3039                                              (uintmax_t)lun->lun);
3040
3041                         /*
3042                          * Bail out as soon as we see that we've overfilled
3043                          * the buffer.
3044                          */
3045                         if (retval != 0)
3046                                 break;
3047
3048                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3049                                              "</backend_type>\n",
3050                                              (lun->backend == NULL) ?  "none" :
3051                                              lun->backend->name);
3052
3053                         if (retval != 0)
3054                                 break;
3055
3056                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3057                                              lun->be_lun->lun_type);
3058
3059                         if (retval != 0)
3060                                 break;
3061
3062                         if (lun->backend == NULL) {
3063                                 retval = sbuf_printf(sb, "</lun>\n");
3064                                 if (retval != 0)
3065                                         break;
3066                                 continue;
3067                         }
3068
3069                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3070                                              (lun->be_lun->maxlba > 0) ?
3071                                              lun->be_lun->maxlba + 1 : 0);
3072
3073                         if (retval != 0)
3074                                 break;
3075
3076                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3077                                              lun->be_lun->blocksize);
3078
3079                         if (retval != 0)
3080                                 break;
3081
3082                         retval = sbuf_printf(sb, "\t<serial_number>");
3083
3084                         if (retval != 0)
3085                                 break;
3086
3087                         retval = ctl_sbuf_printf_esc(sb,
3088                             lun->be_lun->serial_num,
3089                             sizeof(lun->be_lun->serial_num));
3090
3091                         if (retval != 0)
3092                                 break;
3093
3094                         retval = sbuf_printf(sb, "</serial_number>\n");
3095                 
3096                         if (retval != 0)
3097                                 break;
3098
3099                         retval = sbuf_printf(sb, "\t<device_id>");
3100
3101                         if (retval != 0)
3102                                 break;
3103
3104                         retval = ctl_sbuf_printf_esc(sb,
3105                             lun->be_lun->device_id,
3106                             sizeof(lun->be_lun->device_id));
3107
3108                         if (retval != 0)
3109                                 break;
3110
3111                         retval = sbuf_printf(sb, "</device_id>\n");
3112
3113                         if (retval != 0)
3114                                 break;
3115
3116                         if (lun->backend->lun_info != NULL) {
3117                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3118                                 if (retval != 0)
3119                                         break;
3120                         }
3121                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3122                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3123                                     opt->name, opt->value, opt->name);
3124                                 if (retval != 0)
3125                                         break;
3126                         }
3127
3128                         retval = sbuf_printf(sb, "</lun>\n");
3129
3130                         if (retval != 0)
3131                                 break;
3132                         mtx_unlock(&lun->lun_lock);
3133                 }
3134                 if (lun != NULL)
3135                         mtx_unlock(&lun->lun_lock);
3136                 mtx_unlock(&softc->ctl_lock);
3137
3138                 if ((retval != 0)
3139                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3140                         retval = 0;
3141                         sbuf_delete(sb);
3142                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3143                         snprintf(list->error_str, sizeof(list->error_str),
3144                                  "Out of space, %d bytes is too small",
3145                                  list->alloc_len);
3146                         break;
3147                 }
3148
3149                 sbuf_finish(sb);
3150
3151                 retval = copyout(sbuf_data(sb), list->lun_xml,
3152                                  sbuf_len(sb) + 1);
3153
3154                 list->fill_len = sbuf_len(sb) + 1;
3155                 list->status = CTL_LUN_LIST_OK;
3156                 sbuf_delete(sb);
3157                 break;
3158         }
3159         case CTL_ISCSI: {
3160                 struct ctl_iscsi *ci;
3161                 struct ctl_frontend *fe;
3162
3163                 ci = (struct ctl_iscsi *)addr;
3164
3165                 fe = ctl_frontend_find("iscsi");
3166                 if (fe == NULL) {
3167                         ci->status = CTL_ISCSI_ERROR;
3168                         snprintf(ci->error_str, sizeof(ci->error_str),
3169                             "Frontend \"iscsi\" not found.");
3170                         break;
3171                 }
3172
3173                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3174                 break;
3175         }
3176         case CTL_PORT_REQ: {
3177                 struct ctl_req *req;
3178                 struct ctl_frontend *fe;
3179
3180                 req = (struct ctl_req *)addr;
3181
3182                 fe = ctl_frontend_find(req->driver);
3183                 if (fe == NULL) {
3184                         req->status = CTL_LUN_ERROR;
3185                         snprintf(req->error_str, sizeof(req->error_str),
3186                             "Frontend \"%s\" not found.", req->driver);
3187                         break;
3188                 }
3189                 if (req->num_args > 0) {
3190                         req->kern_args = ctl_copyin_args(req->num_args,
3191                             req->args, req->error_str, sizeof(req->error_str));
3192                         if (req->kern_args == NULL) {
3193                                 req->status = CTL_LUN_ERROR;
3194                                 break;
3195                         }
3196                 }
3197
3198                 if (fe->ioctl)
3199                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3200                 else
3201                         retval = ENODEV;
3202
3203                 if (req->num_args > 0) {
3204                         ctl_copyout_args(req->num_args, req->kern_args);
3205                         ctl_free_args(req->num_args, req->kern_args);
3206                 }
3207                 break;
3208         }
3209         case CTL_PORT_LIST: {
3210                 struct sbuf *sb;
3211                 struct ctl_port *port;
3212                 struct ctl_lun_list *list;
3213                 struct ctl_option *opt;
3214                 int j;
3215                 uint32_t plun;
3216
3217                 list = (struct ctl_lun_list *)addr;
3218
3219                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3220                 if (sb == NULL) {
3221                         list->status = CTL_LUN_LIST_ERROR;
3222                         snprintf(list->error_str, sizeof(list->error_str),
3223                                  "Unable to allocate %d bytes for LUN list",
3224                                  list->alloc_len);
3225                         break;
3226                 }
3227
3228                 sbuf_printf(sb, "<ctlportlist>\n");
3229
3230                 mtx_lock(&softc->ctl_lock);
3231                 STAILQ_FOREACH(port, &softc->port_list, links) {
3232                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3233                                              (uintmax_t)port->targ_port);
3234
3235                         /*
3236                          * Bail out as soon as we see that we've overfilled
3237                          * the buffer.
3238                          */
3239                         if (retval != 0)
3240                                 break;
3241
3242                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3243                             "</frontend_type>\n", port->frontend->name);
3244                         if (retval != 0)
3245                                 break;
3246
3247                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3248                                              port->port_type);
3249                         if (retval != 0)
3250                                 break;
3251
3252                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3253                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3254                         if (retval != 0)
3255                                 break;
3256
3257                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3258                             port->port_name);
3259                         if (retval != 0)
3260                                 break;
3261
3262                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3263                             port->physical_port);
3264                         if (retval != 0)
3265                                 break;
3266
3267                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3268                             port->virtual_port);
3269                         if (retval != 0)
3270                                 break;
3271
3272                         if (port->target_devid != NULL) {
3273                                 sbuf_printf(sb, "\t<target>");
3274                                 ctl_id_sbuf(port->target_devid, sb);
3275                                 sbuf_printf(sb, "</target>\n");
3276                         }
3277
3278                         if (port->port_devid != NULL) {
3279                                 sbuf_printf(sb, "\t<port>");
3280                                 ctl_id_sbuf(port->port_devid, sb);
3281                                 sbuf_printf(sb, "</port>\n");
3282                         }
3283
3284                         if (port->port_info != NULL) {
3285                                 retval = port->port_info(port->onoff_arg, sb);
3286                                 if (retval != 0)
3287                                         break;
3288                         }
3289                         STAILQ_FOREACH(opt, &port->options, links) {
3290                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3291                                     opt->name, opt->value, opt->name);
3292                                 if (retval != 0)
3293                                         break;
3294                         }
3295
3296                         if (port->lun_map != NULL) {
3297                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3298                                 for (j = 0; j < port->lun_map_size; j++) {
3299                                         plun = ctl_lun_map_from_port(port, j);
3300                                         if (plun == UINT32_MAX)
3301                                                 continue;
3302                                         sbuf_printf(sb,
3303                                             "\t<lun id=\"%u\">%u</lun>\n",
3304                                             j, plun);
3305                                 }
3306                         }
3307
3308                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3309                                 if (port->wwpn_iid[j].in_use == 0 ||
3310                                     (port->wwpn_iid[j].wwpn == 0 &&
3311                                      port->wwpn_iid[j].name == NULL))
3312                                         continue;
3313
3314                                 if (port->wwpn_iid[j].name != NULL)
3315                                         retval = sbuf_printf(sb,
3316                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3317                                             j, port->wwpn_iid[j].name);
3318                                 else
3319                                         retval = sbuf_printf(sb,
3320                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3321                                             j, port->wwpn_iid[j].wwpn);
3322                                 if (retval != 0)
3323                                         break;
3324                         }
3325                         if (retval != 0)
3326                                 break;
3327
3328                         retval = sbuf_printf(sb, "</targ_port>\n");
3329                         if (retval != 0)
3330                                 break;
3331                 }
3332                 mtx_unlock(&softc->ctl_lock);
3333
3334                 if ((retval != 0)
3335                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3336                         retval = 0;
3337                         sbuf_delete(sb);
3338                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3339                         snprintf(list->error_str, sizeof(list->error_str),
3340                                  "Out of space, %d bytes is too small",
3341                                  list->alloc_len);
3342                         break;
3343                 }
3344
3345                 sbuf_finish(sb);
3346
3347                 retval = copyout(sbuf_data(sb), list->lun_xml,
3348                                  sbuf_len(sb) + 1);
3349
3350                 list->fill_len = sbuf_len(sb) + 1;
3351                 list->status = CTL_LUN_LIST_OK;
3352                 sbuf_delete(sb);
3353                 break;
3354         }
3355         case CTL_LUN_MAP: {
3356                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3357                 struct ctl_port *port;
3358
3359                 mtx_lock(&softc->ctl_lock);
3360                 if (lm->port < softc->port_min ||
3361                     lm->port >= softc->port_max ||
3362                     (port = softc->ctl_ports[lm->port]) == NULL) {
3363                         mtx_unlock(&softc->ctl_lock);
3364                         return (ENXIO);
3365                 }
3366                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3367                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3368                                 if (ctl_lun_map_to_port(port, lun->lun) ==
3369                                     UINT32_MAX)
3370                                         continue;
3371                                 mtx_lock(&lun->lun_lock);
3372                                 ctl_est_ua_port(lun, lm->port, -1,
3373                                     CTL_UA_LUN_CHANGE);
3374                                 mtx_unlock(&lun->lun_lock);
3375                         }
3376                 }
3377                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3378                 if (lm->plun != UINT32_MAX) {
3379                         if (lm->lun == UINT32_MAX)
3380                                 retval = ctl_lun_map_unset(port, lm->plun);
3381                         else if (lm->lun < CTL_MAX_LUNS &&
3382                             softc->ctl_luns[lm->lun] != NULL)
3383                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3384                         else
3385                                 return (ENXIO);
3386                 } else {
3387                         if (lm->lun == UINT32_MAX)
3388                                 retval = ctl_lun_map_deinit(port);
3389                         else
3390                                 retval = ctl_lun_map_init(port);
3391                 }
3392                 if (port->status & CTL_PORT_STATUS_ONLINE)
3393                         ctl_isc_announce_port(port);
3394                 break;
3395         }
3396         default: {
3397                 /* XXX KDM should we fix this? */
3398 #if 0
3399                 struct ctl_backend_driver *backend;
3400                 unsigned int type;
3401                 int found;
3402
3403                 found = 0;
3404
3405                 /*
3406                  * We encode the backend type as the ioctl type for backend
3407                  * ioctls.  So parse it out here, and then search for a
3408                  * backend of this type.
3409                  */
3410                 type = _IOC_TYPE(cmd);
3411
3412                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3413                         if (backend->type == type) {
3414                                 found = 1;
3415                                 break;
3416                         }
3417                 }
3418                 if (found == 0) {
3419                         printf("ctl: unknown ioctl command %#lx or backend "
3420                                "%d\n", cmd, type);
3421                         retval = EINVAL;
3422                         break;
3423                 }
3424                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3425 #endif
3426                 retval = ENOTTY;
3427                 break;
3428         }
3429         }
3430         return (retval);
3431 }
3432
3433 uint32_t
3434 ctl_get_initindex(struct ctl_nexus *nexus)
3435 {
3436         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3437 }
3438
3439 int
3440 ctl_lun_map_init(struct ctl_port *port)
3441 {
3442         struct ctl_softc *softc = port->ctl_softc;
3443         struct ctl_lun *lun;
3444         int size = ctl_lun_map_size;
3445         uint32_t i;
3446
3447         if (port->lun_map == NULL || port->lun_map_size < size) {
3448                 port->lun_map_size = 0;
3449                 free(port->lun_map, M_CTL);
3450                 port->lun_map = malloc(size * sizeof(uint32_t),
3451                     M_CTL, M_NOWAIT);
3452         }
3453         if (port->lun_map == NULL)
3454                 return (ENOMEM);
3455         for (i = 0; i < size; i++)
3456                 port->lun_map[i] = UINT32_MAX;
3457         port->lun_map_size = size;
3458         if (port->status & CTL_PORT_STATUS_ONLINE) {
3459                 if (port->lun_disable != NULL) {
3460                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3461                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3462                 }
3463                 ctl_isc_announce_port(port);
3464         }
3465         return (0);
3466 }
3467
3468 int
3469 ctl_lun_map_deinit(struct ctl_port *port)
3470 {
3471         struct ctl_softc *softc = port->ctl_softc;
3472         struct ctl_lun *lun;
3473
3474         if (port->lun_map == NULL)
3475                 return (0);
3476         port->lun_map_size = 0;
3477         free(port->lun_map, M_CTL);
3478         port->lun_map = NULL;
3479         if (port->status & CTL_PORT_STATUS_ONLINE) {
3480                 if (port->lun_enable != NULL) {
3481                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3482                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3483                 }
3484                 ctl_isc_announce_port(port);
3485         }
3486         return (0);
3487 }
3488
3489 int
3490 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3491 {
3492         int status;
3493         uint32_t old;
3494
3495         if (port->lun_map == NULL) {
3496                 status = ctl_lun_map_init(port);
3497                 if (status != 0)
3498                         return (status);
3499         }
3500         if (plun >= port->lun_map_size)
3501                 return (EINVAL);
3502         old = port->lun_map[plun];
3503         port->lun_map[plun] = glun;
3504         if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3505                 if (port->lun_enable != NULL)
3506                         port->lun_enable(port->targ_lun_arg, plun);
3507                 ctl_isc_announce_port(port);
3508         }
3509         return (0);
3510 }
3511
3512 int
3513 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3514 {
3515         uint32_t old;
3516
3517         if (port->lun_map == NULL || plun >= port->lun_map_size)
3518                 return (0);
3519         old = port->lun_map[plun];
3520         port->lun_map[plun] = UINT32_MAX;
3521         if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3522                 if (port->lun_disable != NULL)
3523                         port->lun_disable(port->targ_lun_arg, plun);
3524                 ctl_isc_announce_port(port);
3525         }
3526         return (0);
3527 }
3528
3529 uint32_t
3530 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3531 {
3532
3533         if (port == NULL)
3534                 return (UINT32_MAX);
3535         if (port->lun_map == NULL)
3536                 return (lun_id);
3537         if (lun_id > port->lun_map_size)
3538                 return (UINT32_MAX);
3539         return (port->lun_map[lun_id]);
3540 }
3541
3542 uint32_t
3543 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3544 {
3545         uint32_t i;
3546
3547         if (port == NULL)
3548                 return (UINT32_MAX);
3549         if (port->lun_map == NULL)
3550                 return (lun_id);
3551         for (i = 0; i < port->lun_map_size; i++) {
3552                 if (port->lun_map[i] == lun_id)
3553                         return (i);
3554         }
3555         return (UINT32_MAX);
3556 }
3557
3558 uint32_t
3559 ctl_decode_lun(uint64_t encoded)
3560 {
3561         uint8_t lun[8];
3562         uint32_t result = 0xffffffff;
3563
3564         be64enc(lun, encoded);
3565         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3566         case RPL_LUNDATA_ATYP_PERIPH:
3567                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3568                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3569                         result = lun[1];
3570                 break;
3571         case RPL_LUNDATA_ATYP_FLAT:
3572                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3573                     lun[6] == 0 && lun[7] == 0)
3574                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3575                 break;
3576         case RPL_LUNDATA_ATYP_EXTLUN:
3577                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3578                 case 0x02:
3579                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3580                         case 0x00:
3581                                 result = lun[1];
3582                                 break;
3583                         case 0x10:
3584                                 result = (lun[1] << 16) + (lun[2] << 8) +
3585                                     lun[3];
3586                                 break;
3587                         case 0x20:
3588                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3589                                         result = (lun[2] << 24) +
3590                                             (lun[3] << 16) + (lun[4] << 8) +
3591                                             lun[5];
3592                                 break;
3593                         }
3594                         break;
3595                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3596                         result = 0xffffffff;
3597                         break;
3598                 }
3599                 break;
3600         }
3601         return (result);
3602 }
3603
3604 uint64_t
3605 ctl_encode_lun(uint32_t decoded)
3606 {
3607         uint64_t l = decoded;
3608
3609         if (l <= 0xff)
3610                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3611         if (l <= 0x3fff)
3612                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3613         if (l <= 0xffffff)
3614                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3615                     (l << 32));
3616         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3617 }
3618
3619 static struct ctl_port *
3620 ctl_io_port(struct ctl_io_hdr *io_hdr)
3621 {
3622
3623         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3624 }
3625
3626 int
3627 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3628 {
3629         int i;
3630
3631         for (i = first; i < last; i++) {
3632                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3633                         return (i);
3634         }
3635         return (-1);
3636 }
3637
3638 int
3639 ctl_set_mask(uint32_t *mask, uint32_t bit)
3640 {
3641         uint32_t chunk, piece;
3642
3643         chunk = bit >> 5;
3644         piece = bit % (sizeof(uint32_t) * 8);
3645
3646         if ((mask[chunk] & (1 << piece)) != 0)
3647                 return (-1);
3648         else
3649                 mask[chunk] |= (1 << piece);
3650
3651         return (0);
3652 }
3653
3654 int
3655 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3656 {
3657         uint32_t chunk, piece;
3658
3659         chunk = bit >> 5;
3660         piece = bit % (sizeof(uint32_t) * 8);
3661
3662         if ((mask[chunk] & (1 << piece)) == 0)
3663                 return (-1);
3664         else
3665                 mask[chunk] &= ~(1 << piece);
3666
3667         return (0);
3668 }
3669
3670 int
3671 ctl_is_set(uint32_t *mask, uint32_t bit)
3672 {
3673         uint32_t chunk, piece;
3674
3675         chunk = bit >> 5;
3676         piece = bit % (sizeof(uint32_t) * 8);
3677
3678         if ((mask[chunk] & (1 << piece)) == 0)
3679                 return (0);
3680         else
3681                 return (1);
3682 }
3683
3684 static uint64_t
3685 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3686 {
3687         uint64_t *t;
3688
3689         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3690         if (t == NULL)
3691                 return (0);
3692         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3693 }
3694
3695 static void
3696 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3697 {
3698         uint64_t *t;
3699
3700         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3701         if (t == NULL)
3702                 return;
3703         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3704 }
3705
3706 static void
3707 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3708 {
3709         uint64_t *p;
3710         u_int i;
3711
3712         i = residx/CTL_MAX_INIT_PER_PORT;
3713         if (lun->pr_keys[i] != NULL)
3714                 return;
3715         mtx_unlock(&lun->lun_lock);
3716         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3717             M_WAITOK | M_ZERO);
3718         mtx_lock(&lun->lun_lock);
3719         if (lun->pr_keys[i] == NULL)
3720                 lun->pr_keys[i] = p;
3721         else
3722                 free(p, M_CTL);
3723 }
3724
3725 static void
3726 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3727 {
3728         uint64_t *t;
3729
3730         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3731         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3732         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3733 }
3734
3735 /*
3736  * ctl_softc, pool_name, total_ctl_io are passed in.
3737  * npool is passed out.
3738  */
3739 int
3740 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3741                 uint32_t total_ctl_io, void **npool)
3742 {
3743 #ifdef IO_POOLS
3744         struct ctl_io_pool *pool;
3745
3746         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3747                                             M_NOWAIT | M_ZERO);
3748         if (pool == NULL)
3749                 return (ENOMEM);
3750
3751         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3752         pool->ctl_softc = ctl_softc;
3753         pool->zone = uma_zsecond_create(pool->name, NULL,
3754             NULL, NULL, NULL, ctl_softc->io_zone);
3755         /* uma_prealloc(pool->zone, total_ctl_io); */
3756
3757         *npool = pool;
3758 #else
3759         *npool = ctl_softc->io_zone;
3760 #endif
3761         return (0);
3762 }
3763
3764 void
3765 ctl_pool_free(struct ctl_io_pool *pool)
3766 {
3767
3768         if (pool == NULL)
3769                 return;
3770
3771 #ifdef IO_POOLS
3772         uma_zdestroy(pool->zone);
3773         free(pool, M_CTL);
3774 #endif
3775 }
3776
3777 union ctl_io *
3778 ctl_alloc_io(void *pool_ref)
3779 {
3780         union ctl_io *io;
3781 #ifdef IO_POOLS
3782         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3783
3784         io = uma_zalloc(pool->zone, M_WAITOK);
3785 #else
3786         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3787 #endif
3788         if (io != NULL)
3789                 io->io_hdr.pool = pool_ref;
3790         return (io);
3791 }
3792
3793 union ctl_io *
3794 ctl_alloc_io_nowait(void *pool_ref)
3795 {
3796         union ctl_io *io;
3797 #ifdef IO_POOLS
3798         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3799
3800         io = uma_zalloc(pool->zone, M_NOWAIT);
3801 #else
3802         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3803 #endif
3804         if (io != NULL)
3805                 io->io_hdr.pool = pool_ref;
3806         return (io);
3807 }
3808
3809 void
3810 ctl_free_io(union ctl_io *io)
3811 {
3812 #ifdef IO_POOLS
3813         struct ctl_io_pool *pool;
3814 #endif
3815
3816         if (io == NULL)
3817                 return;
3818
3819 #ifdef IO_POOLS
3820         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3821         uma_zfree(pool->zone, io);
3822 #else
3823         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3824 #endif
3825 }
3826
3827 void
3828 ctl_zero_io(union ctl_io *io)
3829 {
3830         void *pool_ref;
3831
3832         if (io == NULL)
3833                 return;
3834
3835         /*
3836          * May need to preserve linked list pointers at some point too.
3837          */
3838         pool_ref = io->io_hdr.pool;
3839         memset(io, 0, sizeof(*io));
3840         io->io_hdr.pool = pool_ref;
3841 }
3842
3843 int
3844 ctl_expand_number(const char *buf, uint64_t *num)
3845 {
3846         char *endptr;
3847         uint64_t number;
3848         unsigned shift;
3849
3850         number = strtoq(buf, &endptr, 0);
3851
3852         switch (tolower((unsigned char)*endptr)) {
3853         case 'e':
3854                 shift = 60;
3855                 break;
3856         case 'p':
3857                 shift = 50;
3858                 break;
3859         case 't':
3860                 shift = 40;
3861                 break;
3862         case 'g':
3863                 shift = 30;
3864                 break;
3865         case 'm':
3866                 shift = 20;
3867                 break;
3868         case 'k':
3869                 shift = 10;
3870                 break;
3871         case 'b':
3872         case '\0': /* No unit. */
3873                 *num = number;
3874                 return (0);
3875         default:
3876                 /* Unrecognized unit. */
3877                 return (-1);
3878         }
3879
3880         if ((number << shift) >> shift != number) {
3881                 /* Overflow */
3882                 return (-1);
3883         }
3884         *num = number << shift;
3885         return (0);
3886 }
3887
3888
3889 /*
3890  * This routine could be used in the future to load default and/or saved
3891  * mode page parameters for a particuar lun.
3892  */
3893 static int
3894 ctl_init_page_index(struct ctl_lun *lun)
3895 {
3896         int i, page_code;
3897         struct ctl_page_index *page_index;
3898         const char *value;
3899         uint64_t ival;
3900
3901         memcpy(&lun->mode_pages.index, page_index_template,
3902                sizeof(page_index_template));
3903
3904         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3905
3906                 page_index = &lun->mode_pages.index[i];
3907                 if (lun->be_lun->lun_type == T_DIRECT &&
3908                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3909                         continue;
3910                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3911                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3912                         continue;
3913                 if (lun->be_lun->lun_type == T_CDROM &&
3914                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3915                         continue;
3916
3917                 page_code = page_index->page_code & SMPH_PC_MASK;
3918                 switch (page_code) {
3919                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3920                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3921                             ("subpage %#x for page %#x is incorrect!",
3922                             page_index->subpage, page_code));
3923                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3924                                &rw_er_page_default,
3925                                sizeof(rw_er_page_default));
3926                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3927                                &rw_er_page_changeable,
3928                                sizeof(rw_er_page_changeable));
3929                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3930                                &rw_er_page_default,
3931                                sizeof(rw_er_page_default));
3932                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3933                                &rw_er_page_default,
3934                                sizeof(rw_er_page_default));
3935                         page_index->page_data =
3936                                 (uint8_t *)lun->mode_pages.rw_er_page;
3937                         break;
3938                 }
3939                 case SMS_FORMAT_DEVICE_PAGE: {
3940                         struct scsi_format_page *format_page;
3941
3942                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3943                             ("subpage %#x for page %#x is incorrect!",
3944                             page_index->subpage, page_code));
3945
3946                         /*
3947                          * Sectors per track are set above.  Bytes per
3948                          * sector need to be set here on a per-LUN basis.
3949                          */
3950                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3951                                &format_page_default,
3952                                sizeof(format_page_default));
3953                         memcpy(&lun->mode_pages.format_page[
3954                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3955                                sizeof(format_page_changeable));
3956                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3957                                &format_page_default,
3958                                sizeof(format_page_default));
3959                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3960                                &format_page_default,
3961                                sizeof(format_page_default));
3962
3963                         format_page = &lun->mode_pages.format_page[
3964                                 CTL_PAGE_CURRENT];
3965                         scsi_ulto2b(lun->be_lun->blocksize,
3966                                     format_page->bytes_per_sector);
3967
3968                         format_page = &lun->mode_pages.format_page[
3969                                 CTL_PAGE_DEFAULT];
3970                         scsi_ulto2b(lun->be_lun->blocksize,
3971                                     format_page->bytes_per_sector);
3972
3973                         format_page = &lun->mode_pages.format_page[
3974                                 CTL_PAGE_SAVED];
3975                         scsi_ulto2b(lun->be_lun->blocksize,
3976                                     format_page->bytes_per_sector);
3977
3978                         page_index->page_data =
3979                                 (uint8_t *)lun->mode_pages.format_page;
3980                         break;
3981                 }
3982                 case SMS_RIGID_DISK_PAGE: {
3983                         struct scsi_rigid_disk_page *rigid_disk_page;
3984                         uint32_t sectors_per_cylinder;
3985                         uint64_t cylinders;
3986 #ifndef __XSCALE__
3987                         int shift;
3988 #endif /* !__XSCALE__ */
3989
3990                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3991                             ("subpage %#x for page %#x is incorrect!",
3992                             page_index->subpage, page_code));
3993
3994                         /*
3995                          * Rotation rate and sectors per track are set
3996                          * above.  We calculate the cylinders here based on
3997                          * capacity.  Due to the number of heads and
3998                          * sectors per track we're using, smaller arrays
3999                          * may turn out to have 0 cylinders.  Linux and
4000                          * FreeBSD don't pay attention to these mode pages
4001                          * to figure out capacity, but Solaris does.  It
4002                          * seems to deal with 0 cylinders just fine, and
4003                          * works out a fake geometry based on the capacity.
4004                          */
4005                         memcpy(&lun->mode_pages.rigid_disk_page[
4006                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4007                                sizeof(rigid_disk_page_default));
4008                         memcpy(&lun->mode_pages.rigid_disk_page[
4009                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4010                                sizeof(rigid_disk_page_changeable));
4011
4012                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4013                                 CTL_DEFAULT_HEADS;
4014
4015                         /*
4016                          * The divide method here will be more accurate,
4017                          * probably, but results in floating point being
4018                          * used in the kernel on i386 (__udivdi3()).  On the
4019                          * XScale, though, __udivdi3() is implemented in
4020                          * software.
4021                          *
4022                          * The shift method for cylinder calculation is
4023                          * accurate if sectors_per_cylinder is a power of
4024                          * 2.  Otherwise it might be slightly off -- you
4025                          * might have a bit of a truncation problem.
4026                          */
4027 #ifdef  __XSCALE__
4028                         cylinders = (lun->be_lun->maxlba + 1) /
4029                                 sectors_per_cylinder;
4030 #else
4031                         for (shift = 31; shift > 0; shift--) {
4032                                 if (sectors_per_cylinder & (1 << shift))
4033                                         break;
4034                         }
4035                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4036 #endif
4037
4038                         /*
4039                          * We've basically got 3 bytes, or 24 bits for the
4040                          * cylinder size in the mode page.  If we're over,
4041                          * just round down to 2^24.
4042                          */
4043                         if (cylinders > 0xffffff)
4044                                 cylinders = 0xffffff;
4045
4046                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4047                                 CTL_PAGE_DEFAULT];
4048                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4049
4050                         if ((value = ctl_get_opt(&lun->be_lun->options,
4051                             "rpm")) != NULL) {
4052                                 scsi_ulto2b(strtol(value, NULL, 0),
4053                                      rigid_disk_page->rotation_rate);
4054                         }
4055
4056                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4057                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4058                                sizeof(rigid_disk_page_default));
4059                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4060                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4061                                sizeof(rigid_disk_page_default));
4062
4063                         page_index->page_data =
4064                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4065                         break;
4066                 }
4067                 case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4068                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4069                             ("subpage %#x for page %#x is incorrect!",
4070                             page_index->subpage, page_code));
4071                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4072                                &verify_er_page_default,
4073                                sizeof(verify_er_page_default));
4074                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4075                                &verify_er_page_changeable,
4076                                sizeof(verify_er_page_changeable));
4077                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4078                                &verify_er_page_default,
4079                                sizeof(verify_er_page_default));
4080                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4081                                &verify_er_page_default,
4082                                sizeof(verify_er_page_default));
4083                         page_index->page_data =
4084                                 (uint8_t *)lun->mode_pages.verify_er_page;
4085                         break;
4086                 }
4087                 case SMS_CACHING_PAGE: {
4088                         struct scsi_caching_page *caching_page;
4089
4090                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4091                             ("subpage %#x for page %#x is incorrect!",
4092                             page_index->subpage, page_code));
4093                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4094                                &caching_page_default,
4095                                sizeof(caching_page_default));
4096                         memcpy(&lun->mode_pages.caching_page[
4097                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4098                                sizeof(caching_page_changeable));
4099                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4100                                &caching_page_default,
4101                                sizeof(caching_page_default));
4102                         caching_page = &lun->mode_pages.caching_page[
4103                             CTL_PAGE_SAVED];
4104                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4105                         if (value != NULL && strcmp(value, "off") == 0)
4106                                 caching_page->flags1 &= ~SCP_WCE;
4107                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4108                         if (value != NULL && strcmp(value, "off") == 0)
4109                                 caching_page->flags1 |= SCP_RCD;
4110                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4111                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4112                                sizeof(caching_page_default));
4113                         page_index->page_data =
4114                                 (uint8_t *)lun->mode_pages.caching_page;
4115                         break;
4116                 }
4117                 case SMS_CONTROL_MODE_PAGE: {
4118                         switch (page_index->subpage) {
4119                         case SMS_SUBPAGE_PAGE_0: {
4120                                 struct scsi_control_page *control_page;
4121
4122                                 memcpy(&lun->mode_pages.control_page[
4123                                     CTL_PAGE_DEFAULT],
4124                                        &control_page_default,
4125                                        sizeof(control_page_default));
4126                                 memcpy(&lun->mode_pages.control_page[
4127                                     CTL_PAGE_CHANGEABLE],
4128                                        &control_page_changeable,
4129                                        sizeof(control_page_changeable));
4130                                 memcpy(&lun->mode_pages.control_page[
4131                                     CTL_PAGE_SAVED],
4132                                        &control_page_default,
4133                                        sizeof(control_page_default));
4134                                 control_page = &lun->mode_pages.control_page[
4135                                     CTL_PAGE_SAVED];
4136                                 value = ctl_get_opt(&lun->be_lun->options,
4137                                     "reordering");
4138                                 if (value != NULL &&
4139                                     strcmp(value, "unrestricted") == 0) {
4140                                         control_page->queue_flags &=
4141                                             ~SCP_QUEUE_ALG_MASK;
4142                                         control_page->queue_flags |=
4143                                             SCP_QUEUE_ALG_UNRESTRICTED;
4144                                 }
4145                                 memcpy(&lun->mode_pages.control_page[
4146                                     CTL_PAGE_CURRENT],
4147                                        &lun->mode_pages.control_page[
4148                                     CTL_PAGE_SAVED],
4149                                        sizeof(control_page_default));
4150                                 page_index->page_data =
4151                                     (uint8_t *)lun->mode_pages.control_page;
4152                                 break;
4153                         }
4154                         case 0x01:
4155                                 memcpy(&lun->mode_pages.control_ext_page[
4156                                     CTL_PAGE_DEFAULT],
4157                                        &control_ext_page_default,
4158                                        sizeof(control_ext_page_default));
4159                                 memcpy(&lun->mode_pages.control_ext_page[
4160                                     CTL_PAGE_CHANGEABLE],
4161                                        &control_ext_page_changeable,
4162                                        sizeof(control_ext_page_changeable));
4163                                 memcpy(&lun->mode_pages.control_ext_page[
4164                                     CTL_PAGE_SAVED],
4165                                        &control_ext_page_default,
4166                                        sizeof(control_ext_page_default));
4167                                 memcpy(&lun->mode_pages.control_ext_page[
4168                                     CTL_PAGE_CURRENT],
4169                                        &lun->mode_pages.control_ext_page[
4170                                     CTL_PAGE_SAVED],
4171                                        sizeof(control_ext_page_default));
4172                                 page_index->page_data =
4173                                     (uint8_t *)lun->mode_pages.control_ext_page;
4174                                 break;
4175                         default:
4176                                 panic("subpage %#x for page %#x is incorrect!",
4177                                       page_index->subpage, page_code);
4178                         }
4179                         break;
4180                 }
4181                 case SMS_INFO_EXCEPTIONS_PAGE: {
4182                         switch (page_index->subpage) {
4183                         case SMS_SUBPAGE_PAGE_0:
4184                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4185                                        &ie_page_default,
4186                                        sizeof(ie_page_default));
4187                                 memcpy(&lun->mode_pages.ie_page[
4188                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4189                                        sizeof(ie_page_changeable));
4190                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4191                                        &ie_page_default,
4192                                        sizeof(ie_page_default));
4193                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4194                                        &ie_page_default,
4195                                        sizeof(ie_page_default));
4196                                 page_index->page_data =
4197                                         (uint8_t *)lun->mode_pages.ie_page;
4198                                 break;
4199                         case 0x02: {
4200                                 struct ctl_logical_block_provisioning_page *page;
4201
4202                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4203                                        &lbp_page_default,
4204                                        sizeof(lbp_page_default));
4205                                 memcpy(&lun->mode_pages.lbp_page[
4206                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4207                                        sizeof(lbp_page_changeable));
4208                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4209                                        &lbp_page_default,
4210                                        sizeof(lbp_page_default));
4211                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4212                                 value = ctl_get_opt(&lun->be_lun->options,
4213                                     "avail-threshold");
4214                                 if (value != NULL &&
4215                                     ctl_expand_number(value, &ival) == 0) {
4216                                         page->descr[0].flags |= SLBPPD_ENABLED |
4217                                             SLBPPD_ARMING_DEC;
4218                                         if (lun->be_lun->blocksize)
4219                                                 ival /= lun->be_lun->blocksize;
4220                                         else
4221                                                 ival /= 512;
4222                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4223                                             page->descr[0].count);
4224                                 }
4225                                 value = ctl_get_opt(&lun->be_lun->options,
4226                                     "used-threshold");
4227                                 if (value != NULL &&
4228                                     ctl_expand_number(value, &ival) == 0) {
4229                                         page->descr[1].flags |= SLBPPD_ENABLED |
4230                                             SLBPPD_ARMING_INC;
4231                                         if (lun->be_lun->blocksize)
4232                                                 ival /= lun->be_lun->blocksize;
4233                                         else
4234                                                 ival /= 512;
4235                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4236                                             page->descr[1].count);
4237                                 }
4238                                 value = ctl_get_opt(&lun->be_lun->options,
4239                                     "pool-avail-threshold");
4240                                 if (value != NULL &&
4241                                     ctl_expand_number(value, &ival) == 0) {
4242                                         page->descr[2].flags |= SLBPPD_ENABLED |
4243                                             SLBPPD_ARMING_DEC;
4244                                         if (lun->be_lun->blocksize)
4245                                                 ival /= lun->be_lun->blocksize;
4246                                         else
4247                                                 ival /= 512;
4248                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4249                                             page->descr[2].count);
4250                                 }
4251                                 value = ctl_get_opt(&lun->be_lun->options,
4252                                     "pool-used-threshold");
4253                                 if (value != NULL &&
4254                                     ctl_expand_number(value, &ival) == 0) {
4255                                         page->descr[3].flags |= SLBPPD_ENABLED |
4256                                             SLBPPD_ARMING_INC;
4257                                         if (lun->be_lun->blocksize)
4258                                                 ival /= lun->be_lun->blocksize;
4259                                         else
4260                                                 ival /= 512;
4261                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4262                                             page->descr[3].count);
4263                                 }
4264                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4265                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4266                                        sizeof(lbp_page_default));
4267                                 page_index->page_data =
4268                                         (uint8_t *)lun->mode_pages.lbp_page;
4269                                 break;
4270                         }
4271                         default:
4272                                 panic("subpage %#x for page %#x is incorrect!",
4273                                       page_index->subpage, page_code);
4274                         }
4275                         break;
4276                 }
4277                 case SMS_CDDVD_CAPS_PAGE:{
4278                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4279                             ("subpage %#x for page %#x is incorrect!",
4280                             page_index->subpage, page_code));
4281                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4282                                &cddvd_page_default,
4283                                sizeof(cddvd_page_default));
4284                         memcpy(&lun->mode_pages.cddvd_page[
4285                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4286                                sizeof(cddvd_page_changeable));
4287                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4288                                &cddvd_page_default,
4289                                sizeof(cddvd_page_default));
4290                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4291                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4292                                sizeof(cddvd_page_default));
4293                         page_index->page_data =
4294                                 (uint8_t *)lun->mode_pages.cddvd_page;
4295                         break;
4296                 }
4297                 default:
4298                         panic("invalid page code value %#x", page_code);
4299                 }
4300         }
4301
4302         return (CTL_RETVAL_COMPLETE);
4303 }
4304
4305 static int
4306 ctl_init_log_page_index(struct ctl_lun *lun)
4307 {
4308         struct ctl_page_index *page_index;
4309         int i, j, k, prev;
4310
4311         memcpy(&lun->log_pages.index, log_page_index_template,
4312                sizeof(log_page_index_template));
4313
4314         prev = -1;
4315         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4316
4317                 page_index = &lun->log_pages.index[i];
4318                 if (lun->be_lun->lun_type == T_DIRECT &&
4319                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4320                         continue;
4321                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4322                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4323                         continue;
4324                 if (lun->be_lun->lun_type == T_CDROM &&
4325                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4326                         continue;
4327
4328                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4329                     lun->backend->lun_attr == NULL)
4330                         continue;
4331
4332                 if (page_index->page_code != prev) {
4333                         lun->log_pages.pages_page[j] = page_index->page_code;
4334                         prev = page_index->page_code;
4335                         j++;
4336                 }
4337                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4338                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4339                 k++;
4340         }
4341         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4342         lun->log_pages.index[0].page_len = j;
4343         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4344         lun->log_pages.index[1].page_len = k * 2;
4345         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4346         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4347         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4348         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4349         lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4350         lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4351
4352         return (CTL_RETVAL_COMPLETE);
4353 }
4354
4355 static int
4356 hex2bin(const char *str, uint8_t *buf, int buf_size)
4357 {
4358         int i;
4359         u_char c;
4360
4361         memset(buf, 0, buf_size);
4362         while (isspace(str[0]))
4363                 str++;
4364         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4365                 str += 2;
4366         buf_size *= 2;
4367         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4368                 while (str[i] == '-')   /* Skip dashes in UUIDs. */
4369                         str++;
4370                 c = str[i];
4371                 if (isdigit(c))
4372                         c -= '0';
4373                 else if (isalpha(c))
4374                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4375                 else
4376                         break;
4377                 if (c >= 16)
4378                         break;
4379                 if ((i & 1) == 0)
4380                         buf[i / 2] |= (c << 4);
4381                 else
4382                         buf[i / 2] |= c;
4383         }
4384         return ((i + 1) / 2);
4385 }
4386
4387 /*
4388  * LUN allocation.
4389  *
4390  * Requirements:
4391  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4392  *   wants us to allocate the LUN and he can block.
4393  * - ctl_softc is always set
4394  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4395  *
4396  * Returns 0 for success, non-zero (errno) for failure.
4397  */
4398 static int
4399 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4400               struct ctl_be_lun *const be_lun)
4401 {
4402         struct ctl_lun *nlun, *lun;
4403         struct scsi_vpd_id_descriptor *desc;
4404         struct scsi_vpd_id_t10 *t10id;
4405         const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4406         int lun_number, i, lun_malloced;
4407         int devidlen, idlen1, idlen2 = 0, len;
4408
4409         if (be_lun == NULL)
4410                 return (EINVAL);
4411
4412         /*
4413          * We currently only support Direct Access or Processor LUN types.
4414          */
4415         switch (be_lun->lun_type) {
4416         case T_DIRECT:
4417         case T_PROCESSOR:
4418         case T_CDROM:
4419                 break;
4420         case T_SEQUENTIAL:
4421         case T_CHANGER:
4422         default:
4423                 be_lun->lun_config_status(be_lun->be_lun,
4424                                           CTL_LUN_CONFIG_FAILURE);
4425                 break;
4426         }
4427         if (ctl_lun == NULL) {
4428                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4429                 lun_malloced = 1;
4430         } else {
4431                 lun_malloced = 0;
4432                 lun = ctl_lun;
4433         }
4434
4435         memset(lun, 0, sizeof(*lun));
4436         if (lun_malloced)
4437                 lun->flags = CTL_LUN_MALLOCED;
4438
4439         /* Generate LUN ID. */
4440         devidlen = max(CTL_DEVID_MIN_LEN,
4441             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4442         idlen1 = sizeof(*t10id) + devidlen;
4443         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4444         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4445         if (scsiname != NULL) {
4446                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4447                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4448         }
4449         eui = ctl_get_opt(&be_lun->options, "eui");
4450         if (eui != NULL) {
4451                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4452         }
4453         naa = ctl_get_opt(&be_lun->options, "naa");
4454         if (naa != NULL) {
4455                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4456         }
4457         uuid = ctl_get_opt(&be_lun->options, "uuid");
4458         if (uuid != NULL) {
4459                 len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4460         }
4461         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4462             M_CTL, M_WAITOK | M_ZERO);
4463         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4464         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4465         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4466         desc->length = idlen1;
4467         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4468         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4469         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4470                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4471         } else {
4472                 strncpy(t10id->vendor, vendor,
4473                     min(sizeof(t10id->vendor), strlen(vendor)));
4474         }
4475         strncpy((char *)t10id->vendor_spec_id,
4476             (char *)be_lun->device_id, devidlen);
4477         if (scsiname != NULL) {
4478                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4479                     desc->length);
4480                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4481                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4482                     SVPD_ID_TYPE_SCSI_NAME;
4483                 desc->length = idlen2;
4484                 strlcpy(desc->identifier, scsiname, idlen2);
4485         }
4486         if (eui != 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_EUI64;
4492                 desc->length = hex2bin(eui, desc->identifier, 16);
4493                 desc->length = desc->length > 12 ? 16 :
4494                     (desc->length > 8 ? 12 : 8);
4495                 len -= 16 - desc->length;
4496         }
4497         if (naa != NULL) {
4498                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4499                     desc->length);
4500                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4501                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4502                     SVPD_ID_TYPE_NAA;
4503                 desc->length = hex2bin(naa, desc->identifier, 16);
4504                 desc->length = desc->length > 8 ? 16 : 8;
4505                 len -= 16 - desc->length;
4506         }
4507         if (uuid != NULL) {
4508                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4509                     desc->length);
4510                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4511                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4512                     SVPD_ID_TYPE_UUID;
4513                 desc->identifier[0] = 0x10;
4514                 hex2bin(uuid, &desc->identifier[2], 16);
4515                 desc->length = 18;
4516         }
4517         lun->lun_devid->len = len;
4518
4519         mtx_lock(&ctl_softc->ctl_lock);
4520         /*
4521          * See if the caller requested a particular LUN number.  If so, see
4522          * if it is available.  Otherwise, allocate the first available LUN.
4523          */
4524         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4525                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4526                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4527                         mtx_unlock(&ctl_softc->ctl_lock);
4528                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4529                                 printf("ctl: requested LUN ID %d is higher "
4530                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4531                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4532                         } else {
4533                                 /*
4534                                  * XXX KDM return an error, or just assign
4535                                  * another LUN ID in this case??
4536                                  */
4537                                 printf("ctl: requested LUN ID %d is already "
4538                                        "in use\n", be_lun->req_lun_id);
4539                         }
4540                         if (lun->flags & CTL_LUN_MALLOCED)
4541                                 free(lun, M_CTL);
4542                         be_lun->lun_config_status(be_lun->be_lun,
4543                                                   CTL_LUN_CONFIG_FAILURE);
4544                         return (ENOSPC);
4545                 }
4546                 lun_number = be_lun->req_lun_id;
4547         } else {
4548                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4549                 if (lun_number == -1) {
4550                         mtx_unlock(&ctl_softc->ctl_lock);
4551                         printf("ctl: can't allocate LUN, out of LUNs\n");
4552                         if (lun->flags & CTL_LUN_MALLOCED)
4553                                 free(lun, M_CTL);
4554                         be_lun->lun_config_status(be_lun->be_lun,
4555                                                   CTL_LUN_CONFIG_FAILURE);
4556                         return (ENOSPC);
4557                 }
4558         }
4559         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4560
4561         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4562         lun->lun = lun_number;
4563         lun->be_lun = be_lun;
4564         /*
4565          * The processor LUN is always enabled.  Disk LUNs come on line
4566          * disabled, and must be enabled by the backend.
4567          */
4568         lun->flags |= CTL_LUN_DISABLED;
4569         lun->backend = be_lun->be;
4570         be_lun->ctl_lun = lun;
4571         be_lun->lun_id = lun_number;
4572         atomic_add_int(&be_lun->be->num_luns, 1);
4573         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4574                 lun->flags |= CTL_LUN_EJECTED;
4575         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4576                 lun->flags |= CTL_LUN_NO_MEDIA;
4577         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4578                 lun->flags |= CTL_LUN_STOPPED;
4579
4580         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4581                 lun->flags |= CTL_LUN_PRIMARY_SC;
4582
4583         value = ctl_get_opt(&be_lun->options, "removable");
4584         if (value != NULL) {
4585                 if (strcmp(value, "on") == 0)
4586                         lun->flags |= CTL_LUN_REMOVABLE;
4587         } else if (be_lun->lun_type == T_CDROM)
4588                 lun->flags |= CTL_LUN_REMOVABLE;
4589
4590         lun->ctl_softc = ctl_softc;
4591 #ifdef CTL_TIME_IO
4592         lun->last_busy = getsbinuptime();
4593 #endif
4594         TAILQ_INIT(&lun->ooa_queue);
4595         TAILQ_INIT(&lun->blocked_queue);
4596         STAILQ_INIT(&lun->error_list);
4597         lun->ie_reported = 1;
4598         callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4599         ctl_tpc_lun_init(lun);
4600
4601         /*
4602          * Initialize the mode and log page index.
4603          */
4604         ctl_init_page_index(lun);
4605         ctl_init_log_page_index(lun);
4606
4607         /*
4608          * Now, before we insert this lun on the lun list, set the lun
4609          * inventory changed UA for all other luns.
4610          */
4611         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4612                 mtx_lock(&nlun->lun_lock);
4613                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4614                 mtx_unlock(&nlun->lun_lock);
4615         }
4616
4617         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4618
4619         ctl_softc->ctl_luns[lun_number] = lun;
4620
4621         ctl_softc->num_luns++;
4622
4623         /* Setup statistics gathering */
4624         lun->stats.device_type = be_lun->lun_type;
4625         lun->stats.lun_number = lun_number;
4626         lun->stats.blocksize = be_lun->blocksize;
4627         if (be_lun->blocksize == 0)
4628                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4629         for (i = 0;i < CTL_MAX_PORTS;i++)
4630                 lun->stats.ports[i].targ_port = i;
4631
4632         mtx_unlock(&ctl_softc->ctl_lock);
4633
4634         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4635         return (0);
4636 }
4637
4638 /*
4639  * Delete a LUN.
4640  * Assumptions:
4641  * - LUN has already been marked invalid and any pending I/O has been taken
4642  *   care of.
4643  */
4644 static int
4645 ctl_free_lun(struct ctl_lun *lun)
4646 {
4647         struct ctl_softc *softc;
4648         struct ctl_lun *nlun;
4649         int i;
4650
4651         softc = lun->ctl_softc;
4652
4653         mtx_assert(&softc->ctl_lock, MA_OWNED);
4654
4655         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4656
4657         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4658
4659         softc->ctl_luns[lun->lun] = NULL;
4660
4661         if (!TAILQ_EMPTY(&lun->ooa_queue))
4662                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4663
4664         softc->num_luns--;
4665
4666         /*
4667          * Tell the backend to free resources, if this LUN has a backend.
4668          */
4669         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4670         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4671
4672         lun->ie_reportcnt = UINT32_MAX;
4673         callout_drain(&lun->ie_callout);
4674
4675         ctl_tpc_lun_shutdown(lun);
4676         mtx_destroy(&lun->lun_lock);
4677         free(lun->lun_devid, M_CTL);
4678         for (i = 0; i < CTL_MAX_PORTS; i++)
4679                 free(lun->pending_ua[i], M_CTL);
4680         for (i = 0; i < CTL_MAX_PORTS; i++)
4681                 free(lun->pr_keys[i], M_CTL);
4682         free(lun->write_buffer, M_CTL);
4683         if (lun->flags & CTL_LUN_MALLOCED)
4684                 free(lun, M_CTL);
4685
4686         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4687                 mtx_lock(&nlun->lun_lock);
4688                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4689                 mtx_unlock(&nlun->lun_lock);
4690         }
4691
4692         return (0);
4693 }
4694
4695 static void
4696 ctl_create_lun(struct ctl_be_lun *be_lun)
4697 {
4698
4699         /*
4700          * ctl_alloc_lun() should handle all potential failure cases.
4701          */
4702         ctl_alloc_lun(control_softc, NULL, be_lun);
4703 }
4704
4705 int
4706 ctl_add_lun(struct ctl_be_lun *be_lun)
4707 {
4708         struct ctl_softc *softc = control_softc;
4709
4710         mtx_lock(&softc->ctl_lock);
4711         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4712         mtx_unlock(&softc->ctl_lock);
4713         wakeup(&softc->pending_lun_queue);
4714
4715         return (0);
4716 }
4717
4718 int
4719 ctl_enable_lun(struct ctl_be_lun *be_lun)
4720 {
4721         struct ctl_softc *softc;
4722         struct ctl_port *port, *nport;
4723         struct ctl_lun *lun;
4724         int retval;
4725
4726         lun = (struct ctl_lun *)be_lun->ctl_lun;
4727         softc = lun->ctl_softc;
4728
4729         mtx_lock(&softc->ctl_lock);
4730         mtx_lock(&lun->lun_lock);
4731         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4732                 /*
4733                  * eh?  Why did we get called if the LUN is already
4734                  * enabled?
4735                  */
4736                 mtx_unlock(&lun->lun_lock);
4737                 mtx_unlock(&softc->ctl_lock);
4738                 return (0);
4739         }
4740         lun->flags &= ~CTL_LUN_DISABLED;
4741         mtx_unlock(&lun->lun_lock);
4742
4743         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4744                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4745                     port->lun_map != NULL || port->lun_enable == NULL)
4746                         continue;
4747
4748                 /*
4749                  * Drop the lock while we call the FETD's enable routine.
4750                  * This can lead to a callback into CTL (at least in the
4751                  * case of the internal initiator frontend.
4752                  */
4753                 mtx_unlock(&softc->ctl_lock);
4754                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4755                 mtx_lock(&softc->ctl_lock);
4756                 if (retval != 0) {
4757                         printf("%s: FETD %s port %d returned error "
4758                                "%d for lun_enable on lun %jd\n",
4759                                __func__, port->port_name, port->targ_port,
4760                                retval, (intmax_t)lun->lun);
4761                 }
4762         }
4763
4764         mtx_unlock(&softc->ctl_lock);
4765         ctl_isc_announce_lun(lun);
4766
4767         return (0);
4768 }
4769
4770 int
4771 ctl_disable_lun(struct ctl_be_lun *be_lun)
4772 {
4773         struct ctl_softc *softc;
4774         struct ctl_port *port;
4775         struct ctl_lun *lun;
4776         int retval;
4777
4778         lun = (struct ctl_lun *)be_lun->ctl_lun;
4779         softc = lun->ctl_softc;
4780
4781         mtx_lock(&softc->ctl_lock);
4782         mtx_lock(&lun->lun_lock);
4783         if (lun->flags & CTL_LUN_DISABLED) {
4784                 mtx_unlock(&lun->lun_lock);
4785                 mtx_unlock(&softc->ctl_lock);
4786                 return (0);
4787         }
4788         lun->flags |= CTL_LUN_DISABLED;
4789         mtx_unlock(&lun->lun_lock);
4790
4791         STAILQ_FOREACH(port, &softc->port_list, links) {
4792                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4793                     port->lun_map != NULL || port->lun_disable == NULL)
4794                         continue;
4795
4796                 /*
4797                  * Drop the lock before we call the frontend's disable
4798                  * routine, to avoid lock order reversals.
4799                  *
4800                  * XXX KDM what happens if the frontend list changes while
4801                  * we're traversing it?  It's unlikely, but should be handled.
4802                  */
4803                 mtx_unlock(&softc->ctl_lock);
4804                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4805                 mtx_lock(&softc->ctl_lock);
4806                 if (retval != 0) {
4807                         printf("%s: FETD %s port %d returned error "
4808                                "%d for lun_disable on lun %jd\n",
4809                                __func__, port->port_name, port->targ_port,
4810                                retval, (intmax_t)lun->lun);
4811                 }
4812         }
4813
4814         mtx_unlock(&softc->ctl_lock);
4815         ctl_isc_announce_lun(lun);
4816
4817         return (0);
4818 }
4819
4820 int
4821 ctl_start_lun(struct ctl_be_lun *be_lun)
4822 {
4823         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4824
4825         mtx_lock(&lun->lun_lock);
4826         lun->flags &= ~CTL_LUN_STOPPED;
4827         mtx_unlock(&lun->lun_lock);
4828         return (0);
4829 }
4830
4831 int
4832 ctl_stop_lun(struct ctl_be_lun *be_lun)
4833 {
4834         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4835
4836         mtx_lock(&lun->lun_lock);
4837         lun->flags |= CTL_LUN_STOPPED;
4838         mtx_unlock(&lun->lun_lock);
4839         return (0);
4840 }
4841
4842 int
4843 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4844 {
4845         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4846
4847         mtx_lock(&lun->lun_lock);
4848         lun->flags |= CTL_LUN_NO_MEDIA;
4849         mtx_unlock(&lun->lun_lock);
4850         return (0);
4851 }
4852
4853 int
4854 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4855 {
4856         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4857         union ctl_ha_msg msg;
4858
4859         mtx_lock(&lun->lun_lock);
4860         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4861         if (lun->flags & CTL_LUN_REMOVABLE)
4862                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4863         mtx_unlock(&lun->lun_lock);
4864         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4865             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4866                 bzero(&msg.ua, sizeof(msg.ua));
4867                 msg.hdr.msg_type = CTL_MSG_UA;
4868                 msg.hdr.nexus.initid = -1;
4869                 msg.hdr.nexus.targ_port = -1;
4870                 msg.hdr.nexus.targ_lun = lun->lun;
4871                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4872                 msg.ua.ua_all = 1;
4873                 msg.ua.ua_set = 1;
4874                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4875                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4876                     M_WAITOK);
4877         }
4878         return (0);
4879 }
4880
4881 int
4882 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4883 {
4884         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4885
4886         mtx_lock(&lun->lun_lock);
4887         lun->flags |= CTL_LUN_EJECTED;
4888         mtx_unlock(&lun->lun_lock);
4889         return (0);
4890 }
4891
4892 int
4893 ctl_lun_primary(struct ctl_be_lun *be_lun)
4894 {
4895         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4896
4897         mtx_lock(&lun->lun_lock);
4898         lun->flags |= CTL_LUN_PRIMARY_SC;
4899         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4900         mtx_unlock(&lun->lun_lock);
4901         ctl_isc_announce_lun(lun);
4902         return (0);
4903 }
4904
4905 int
4906 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4907 {
4908         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4909
4910         mtx_lock(&lun->lun_lock);
4911         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4912         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4913         mtx_unlock(&lun->lun_lock);
4914         ctl_isc_announce_lun(lun);
4915         return (0);
4916 }
4917
4918 int
4919 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4920 {
4921         struct ctl_softc *softc;
4922         struct ctl_lun *lun;
4923
4924         lun = (struct ctl_lun *)be_lun->ctl_lun;
4925         softc = lun->ctl_softc;
4926
4927         mtx_lock(&lun->lun_lock);
4928
4929         /*
4930          * The LUN needs to be disabled before it can be marked invalid.
4931          */
4932         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4933                 mtx_unlock(&lun->lun_lock);
4934                 return (-1);
4935         }
4936         /*
4937          * Mark the LUN invalid.
4938          */
4939         lun->flags |= CTL_LUN_INVALID;
4940
4941         /*
4942          * If there is nothing in the OOA queue, go ahead and free the LUN.
4943          * If we have something in the OOA queue, we'll free it when the
4944          * last I/O completes.
4945          */
4946         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4947                 mtx_unlock(&lun->lun_lock);
4948                 mtx_lock(&softc->ctl_lock);
4949                 ctl_free_lun(lun);
4950                 mtx_unlock(&softc->ctl_lock);
4951         } else
4952                 mtx_unlock(&lun->lun_lock);
4953
4954         return (0);
4955 }
4956
4957 void
4958 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4959 {
4960         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4961         union ctl_ha_msg msg;
4962
4963         mtx_lock(&lun->lun_lock);
4964         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4965         mtx_unlock(&lun->lun_lock);
4966         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4967                 /* Send msg to other side. */
4968                 bzero(&msg.ua, sizeof(msg.ua));
4969                 msg.hdr.msg_type = CTL_MSG_UA;
4970                 msg.hdr.nexus.initid = -1;
4971                 msg.hdr.nexus.targ_port = -1;
4972                 msg.hdr.nexus.targ_lun = lun->lun;
4973                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4974                 msg.ua.ua_all = 1;
4975                 msg.ua.ua_set = 1;
4976                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4977                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4978                     M_WAITOK);
4979         }
4980 }
4981
4982 /*
4983  * Backend "memory move is complete" callback for requests that never
4984  * make it down to say RAIDCore's configuration code.
4985  */
4986 int
4987 ctl_config_move_done(union ctl_io *io)
4988 {
4989         int retval;
4990
4991         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4992         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4993             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4994
4995         if ((io->io_hdr.port_status != 0) &&
4996             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4997              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4998                 /*
4999                  * For hardware error sense keys, the sense key
5000                  * specific value is defined to be a retry count,
5001                  * but we use it to pass back an internal FETD
5002                  * error code.  XXX KDM  Hopefully the FETD is only
5003                  * using 16 bits for an error code, since that's
5004                  * all the space we have in the sks field.
5005                  */
5006                 ctl_set_internal_failure(&io->scsiio,
5007                                          /*sks_valid*/ 1,
5008                                          /*retry_count*/
5009                                          io->io_hdr.port_status);
5010         }
5011
5012         if (ctl_debug & CTL_DEBUG_CDB_DATA)
5013                 ctl_data_print(io);
5014         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5015             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5016              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5017             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5018                 /*
5019                  * XXX KDM just assuming a single pointer here, and not a
5020                  * S/G list.  If we start using S/G lists for config data,
5021                  * we'll need to know how to clean them up here as well.
5022                  */
5023                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5024                         free(io->scsiio.kern_data_ptr, M_CTL);
5025                 ctl_done(io);
5026                 retval = CTL_RETVAL_COMPLETE;
5027         } else {
5028                 /*
5029                  * XXX KDM now we need to continue data movement.  Some
5030                  * options:
5031                  * - call ctl_scsiio() again?  We don't do this for data
5032                  *   writes, because for those at least we know ahead of
5033                  *   time where the write will go and how long it is.  For
5034                  *   config writes, though, that information is largely
5035                  *   contained within the write itself, thus we need to
5036                  *   parse out the data again.
5037                  *
5038                  * - Call some other function once the data is in?
5039                  */
5040
5041                 /*
5042                  * XXX KDM call ctl_scsiio() again for now, and check flag
5043                  * bits to see whether we're allocated or not.
5044                  */
5045                 retval = ctl_scsiio(&io->scsiio);
5046         }
5047         return (retval);
5048 }
5049
5050 /*
5051  * This gets called by a backend driver when it is done with a
5052  * data_submit method.
5053  */
5054 void
5055 ctl_data_submit_done(union ctl_io *io)
5056 {
5057         /*
5058          * If the IO_CONT flag is set, we need to call the supplied
5059          * function to continue processing the I/O, instead of completing
5060          * the I/O just yet.
5061          *
5062          * If there is an error, though, we don't want to keep processing.
5063          * Instead, just send status back to the initiator.
5064          */
5065         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5066             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5067             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5068              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5069                 io->scsiio.io_cont(io);
5070                 return;
5071         }
5072         ctl_done(io);
5073 }
5074
5075 /*
5076  * This gets called by a backend driver when it is done with a
5077  * configuration write.
5078  */
5079 void
5080 ctl_config_write_done(union ctl_io *io)
5081 {
5082         uint8_t *buf;
5083
5084         /*
5085          * If the IO_CONT flag is set, we need to call the supplied
5086          * function to continue processing the I/O, instead of completing
5087          * the I/O just yet.
5088          *
5089          * If there is an error, though, we don't want to keep processing.
5090          * Instead, just send status back to the initiator.
5091          */
5092         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5093             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5094             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5095              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5096                 io->scsiio.io_cont(io);
5097                 return;
5098         }
5099         /*
5100          * Since a configuration write can be done for commands that actually
5101          * have data allocated, like write buffer, and commands that have
5102          * no data, like start/stop unit, we need to check here.
5103          */
5104         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5105                 buf = io->scsiio.kern_data_ptr;
5106         else
5107                 buf = NULL;
5108         ctl_done(io);
5109         if (buf)
5110                 free(buf, M_CTL);
5111 }
5112
5113 void
5114 ctl_config_read_done(union ctl_io *io)
5115 {
5116         uint8_t *buf;
5117
5118         /*
5119          * If there is some error -- we are done, skip data transfer.
5120          */
5121         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5122             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5123              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5124                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5125                         buf = io->scsiio.kern_data_ptr;
5126                 else
5127                         buf = NULL;
5128                 ctl_done(io);
5129                 if (buf)
5130                         free(buf, M_CTL);
5131                 return;
5132         }
5133
5134         /*
5135          * If the IO_CONT flag is set, we need to call the supplied
5136          * function to continue processing the I/O, instead of completing
5137          * the I/O just yet.
5138          */
5139         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5140                 io->scsiio.io_cont(io);
5141                 return;
5142         }
5143
5144         ctl_datamove(io);
5145 }
5146
5147 /*
5148  * SCSI release command.
5149  */
5150 int
5151 ctl_scsi_release(struct ctl_scsiio *ctsio)
5152 {
5153         struct ctl_lun *lun;
5154         uint32_t residx;
5155
5156         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5157
5158         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5159         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5160
5161         /*
5162          * XXX KDM right now, we only support LUN reservation.  We don't
5163          * support 3rd party reservations, or extent reservations, which
5164          * might actually need the parameter list.  If we've gotten this
5165          * far, we've got a LUN reservation.  Anything else got kicked out
5166          * above.  So, according to SPC, ignore the length.
5167          */
5168
5169         mtx_lock(&lun->lun_lock);
5170
5171         /*
5172          * According to SPC, it is not an error for an intiator to attempt
5173          * to release a reservation on a LUN that isn't reserved, or that
5174          * is reserved by another initiator.  The reservation can only be
5175          * released, though, by the initiator who made it or by one of
5176          * several reset type events.
5177          */
5178         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5179                         lun->flags &= ~CTL_LUN_RESERVED;
5180
5181         mtx_unlock(&lun->lun_lock);
5182
5183         ctl_set_success(ctsio);
5184         ctl_done((union ctl_io *)ctsio);
5185         return (CTL_RETVAL_COMPLETE);
5186 }
5187
5188 int
5189 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5190 {
5191         struct ctl_lun *lun;
5192         uint32_t residx;
5193
5194         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5195
5196         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5197         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5198
5199         /*
5200          * XXX KDM right now, we only support LUN reservation.  We don't
5201          * support 3rd party reservations, or extent reservations, which
5202          * might actually need the parameter list.  If we've gotten this
5203          * far, we've got a LUN reservation.  Anything else got kicked out
5204          * above.  So, according to SPC, ignore the length.
5205          */
5206
5207         mtx_lock(&lun->lun_lock);
5208         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5209                 ctl_set_reservation_conflict(ctsio);
5210                 goto bailout;
5211         }
5212
5213         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5214         if (lun->flags & CTL_LUN_PR_RESERVED) {
5215                 ctl_set_success(ctsio);
5216                 goto bailout;
5217         }
5218
5219         lun->flags |= CTL_LUN_RESERVED;
5220         lun->res_idx = residx;
5221         ctl_set_success(ctsio);
5222
5223 bailout:
5224         mtx_unlock(&lun->lun_lock);
5225         ctl_done((union ctl_io *)ctsio);
5226         return (CTL_RETVAL_COMPLETE);
5227 }
5228
5229 int
5230 ctl_start_stop(struct ctl_scsiio *ctsio)
5231 {
5232         struct scsi_start_stop_unit *cdb;
5233         struct ctl_lun *lun;
5234         int retval;
5235
5236         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5237
5238         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5239         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5240
5241         if ((cdb->how & SSS_PC_MASK) == 0) {
5242                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5243                     (cdb->how & SSS_START) == 0) {
5244                         uint32_t residx;
5245
5246                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5247                         if (ctl_get_prkey(lun, residx) == 0 ||
5248                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5249
5250                                 ctl_set_reservation_conflict(ctsio);
5251                                 ctl_done((union ctl_io *)ctsio);
5252                                 return (CTL_RETVAL_COMPLETE);
5253                         }
5254                 }
5255
5256                 if ((cdb->how & SSS_LOEJ) &&
5257                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5258                         ctl_set_invalid_field(ctsio,
5259                                               /*sks_valid*/ 1,
5260                                               /*command*/ 1,
5261                                               /*field*/ 4,
5262                                               /*bit_valid*/ 1,
5263                                               /*bit*/ 1);
5264                         ctl_done((union ctl_io *)ctsio);
5265                         return (CTL_RETVAL_COMPLETE);
5266                 }
5267
5268                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5269                     lun->prevent_count > 0) {
5270                         /* "Medium removal prevented" */
5271                         ctl_set_sense(ctsio, /*current_error*/ 1,
5272                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5273                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5274                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5275                         ctl_done((union ctl_io *)ctsio);
5276                         return (CTL_RETVAL_COMPLETE);
5277                 }
5278         }
5279
5280         retval = lun->backend->config_write((union ctl_io *)ctsio);
5281         return (retval);
5282 }
5283
5284 int
5285 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5286 {
5287         struct ctl_lun *lun;
5288         struct scsi_prevent *cdb;
5289         int retval;
5290         uint32_t initidx;
5291
5292         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5293
5294         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5295         cdb = (struct scsi_prevent *)ctsio->cdb;
5296
5297         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5298                 ctl_set_invalid_opcode(ctsio);
5299                 ctl_done((union ctl_io *)ctsio);
5300                 return (CTL_RETVAL_COMPLETE);
5301         }
5302
5303         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5304         mtx_lock(&lun->lun_lock);
5305         if ((cdb->how & PR_PREVENT) &&
5306             ctl_is_set(lun->prevent, initidx) == 0) {
5307                 ctl_set_mask(lun->prevent, initidx);
5308                 lun->prevent_count++;
5309         } else if ((cdb->how & PR_PREVENT) == 0 &&
5310             ctl_is_set(lun->prevent, initidx)) {
5311                 ctl_clear_mask(lun->prevent, initidx);
5312                 lun->prevent_count--;
5313         }
5314         mtx_unlock(&lun->lun_lock);
5315         retval = lun->backend->config_write((union ctl_io *)ctsio);
5316         return (retval);
5317 }
5318
5319 /*
5320  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5321  * we don't really do anything with the LBA and length fields if the user
5322  * passes them in.  Instead we'll just flush out the cache for the entire
5323  * LUN.
5324  */
5325 int
5326 ctl_sync_cache(struct ctl_scsiio *ctsio)
5327 {
5328         struct ctl_lun *lun;
5329         struct ctl_softc *softc;
5330         struct ctl_lba_len_flags *lbalen;
5331         uint64_t starting_lba;
5332         uint32_t block_count;
5333         int retval;
5334         uint8_t byte2;
5335
5336         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5337
5338         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5339         softc = lun->ctl_softc;
5340         retval = 0;
5341
5342         switch (ctsio->cdb[0]) {
5343         case SYNCHRONIZE_CACHE: {
5344                 struct scsi_sync_cache *cdb;
5345                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5346
5347                 starting_lba = scsi_4btoul(cdb->begin_lba);
5348                 block_count = scsi_2btoul(cdb->lb_count);
5349                 byte2 = cdb->byte2;
5350                 break;
5351         }
5352         case SYNCHRONIZE_CACHE_16: {
5353                 struct scsi_sync_cache_16 *cdb;
5354                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5355
5356                 starting_lba = scsi_8btou64(cdb->begin_lba);
5357                 block_count = scsi_4btoul(cdb->lb_count);
5358                 byte2 = cdb->byte2;
5359                 break;
5360         }
5361         default:
5362                 ctl_set_invalid_opcode(ctsio);
5363                 ctl_done((union ctl_io *)ctsio);
5364                 goto bailout;
5365                 break; /* NOTREACHED */
5366         }
5367
5368         /*
5369          * We check the LBA and length, but don't do anything with them.
5370          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5371          * get flushed.  This check will just help satisfy anyone who wants
5372          * to see an error for an out of range LBA.
5373          */
5374         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5375                 ctl_set_lba_out_of_range(ctsio,
5376                     MAX(starting_lba, lun->be_lun->maxlba + 1));
5377                 ctl_done((union ctl_io *)ctsio);
5378                 goto bailout;
5379         }
5380
5381         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5382         lbalen->lba = starting_lba;
5383         lbalen->len = block_count;
5384         lbalen->flags = byte2;
5385         retval = lun->backend->config_write((union ctl_io *)ctsio);
5386
5387 bailout:
5388         return (retval);
5389 }
5390
5391 int
5392 ctl_format(struct ctl_scsiio *ctsio)
5393 {
5394         struct scsi_format *cdb;
5395         struct ctl_lun *lun;
5396         int length, defect_list_len;
5397
5398         CTL_DEBUG_PRINT(("ctl_format\n"));
5399
5400         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5401
5402         cdb = (struct scsi_format *)ctsio->cdb;
5403
5404         length = 0;
5405         if (cdb->byte2 & SF_FMTDATA) {
5406                 if (cdb->byte2 & SF_LONGLIST)
5407                         length = sizeof(struct scsi_format_header_long);
5408                 else
5409                         length = sizeof(struct scsi_format_header_short);
5410         }
5411
5412         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5413          && (length > 0)) {
5414                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5415                 ctsio->kern_data_len = length;
5416                 ctsio->kern_total_len = length;
5417                 ctsio->kern_data_resid = 0;
5418                 ctsio->kern_rel_offset = 0;
5419                 ctsio->kern_sg_entries = 0;
5420                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5421                 ctsio->be_move_done = ctl_config_move_done;
5422                 ctl_datamove((union ctl_io *)ctsio);
5423
5424                 return (CTL_RETVAL_COMPLETE);
5425         }
5426
5427         defect_list_len = 0;
5428
5429         if (cdb->byte2 & SF_FMTDATA) {
5430                 if (cdb->byte2 & SF_LONGLIST) {
5431                         struct scsi_format_header_long *header;
5432
5433                         header = (struct scsi_format_header_long *)
5434                                 ctsio->kern_data_ptr;
5435
5436                         defect_list_len = scsi_4btoul(header->defect_list_len);
5437                         if (defect_list_len != 0) {
5438                                 ctl_set_invalid_field(ctsio,
5439                                                       /*sks_valid*/ 1,
5440                                                       /*command*/ 0,
5441                                                       /*field*/ 2,
5442                                                       /*bit_valid*/ 0,
5443                                                       /*bit*/ 0);
5444                                 goto bailout;
5445                         }
5446                 } else {
5447                         struct scsi_format_header_short *header;
5448
5449                         header = (struct scsi_format_header_short *)
5450                                 ctsio->kern_data_ptr;
5451
5452                         defect_list_len = scsi_2btoul(header->defect_list_len);
5453                         if (defect_list_len != 0) {
5454                                 ctl_set_invalid_field(ctsio,
5455                                                       /*sks_valid*/ 1,
5456                                                       /*command*/ 0,
5457                                                       /*field*/ 2,
5458                                                       /*bit_valid*/ 0,
5459                                                       /*bit*/ 0);
5460                                 goto bailout;
5461                         }
5462                 }
5463         }
5464
5465         ctl_set_success(ctsio);
5466 bailout:
5467
5468         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5469                 free(ctsio->kern_data_ptr, M_CTL);
5470                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5471         }
5472
5473         ctl_done((union ctl_io *)ctsio);
5474         return (CTL_RETVAL_COMPLETE);
5475 }
5476
5477 int
5478 ctl_read_buffer(struct ctl_scsiio *ctsio)
5479 {
5480         struct ctl_lun *lun;
5481         uint64_t buffer_offset;
5482         uint32_t len;
5483         uint8_t byte2;
5484         static uint8_t descr[4];
5485         static uint8_t echo_descr[4] = { 0 };
5486
5487         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5488         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5489         switch (ctsio->cdb[0]) {
5490         case READ_BUFFER: {
5491                 struct scsi_read_buffer *cdb;
5492
5493                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5494                 buffer_offset = scsi_3btoul(cdb->offset);
5495                 len = scsi_3btoul(cdb->length);
5496                 byte2 = cdb->byte2;
5497                 break;
5498         }
5499         case READ_BUFFER_16: {
5500                 struct scsi_read_buffer_16 *cdb;
5501
5502                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5503                 buffer_offset = scsi_8btou64(cdb->offset);
5504                 len = scsi_4btoul(cdb->length);
5505                 byte2 = cdb->byte2;
5506                 break;
5507         }
5508         default: /* This shouldn't happen. */
5509                 ctl_set_invalid_opcode(ctsio);
5510                 ctl_done((union ctl_io *)ctsio);
5511                 return (CTL_RETVAL_COMPLETE);
5512         }
5513
5514         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5515             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5516                 ctl_set_invalid_field(ctsio,
5517                                       /*sks_valid*/ 1,
5518                                       /*command*/ 1,
5519                                       /*field*/ 6,
5520                                       /*bit_valid*/ 0,
5521                                       /*bit*/ 0);
5522                 ctl_done((union ctl_io *)ctsio);
5523                 return (CTL_RETVAL_COMPLETE);
5524         }
5525
5526         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5527                 descr[0] = 0;
5528                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5529                 ctsio->kern_data_ptr = descr;
5530                 len = min(len, sizeof(descr));
5531         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5532                 ctsio->kern_data_ptr = echo_descr;
5533                 len = min(len, sizeof(echo_descr));
5534         } else {
5535                 if (lun->write_buffer == NULL) {
5536                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5537                             M_CTL, M_WAITOK);
5538                 }
5539                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5540         }
5541         ctsio->kern_data_len = len;
5542         ctsio->kern_total_len = len;
5543         ctsio->kern_data_resid = 0;
5544         ctsio->kern_rel_offset = 0;
5545         ctsio->kern_sg_entries = 0;
5546         ctl_set_success(ctsio);
5547         ctsio->be_move_done = ctl_config_move_done;
5548         ctl_datamove((union ctl_io *)ctsio);
5549         return (CTL_RETVAL_COMPLETE);
5550 }
5551
5552 int
5553 ctl_write_buffer(struct ctl_scsiio *ctsio)
5554 {
5555         struct scsi_write_buffer *cdb;
5556         struct ctl_lun *lun;
5557         int buffer_offset, len;
5558
5559         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5560
5561         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5562         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5563
5564         len = scsi_3btoul(cdb->length);
5565         buffer_offset = scsi_3btoul(cdb->offset);
5566
5567         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5568                 ctl_set_invalid_field(ctsio,
5569                                       /*sks_valid*/ 1,
5570                                       /*command*/ 1,
5571                                       /*field*/ 6,
5572                                       /*bit_valid*/ 0,
5573                                       /*bit*/ 0);
5574                 ctl_done((union ctl_io *)ctsio);
5575                 return (CTL_RETVAL_COMPLETE);
5576         }
5577
5578         /*
5579          * If we've got a kernel request that hasn't been malloced yet,
5580          * malloc it and tell the caller the data buffer is here.
5581          */
5582         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5583                 if (lun->write_buffer == NULL) {
5584                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5585                             M_CTL, M_WAITOK);
5586                 }
5587                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5588                 ctsio->kern_data_len = len;
5589                 ctsio->kern_total_len = len;
5590                 ctsio->kern_data_resid = 0;
5591                 ctsio->kern_rel_offset = 0;
5592                 ctsio->kern_sg_entries = 0;
5593                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5594                 ctsio->be_move_done = ctl_config_move_done;
5595                 ctl_datamove((union ctl_io *)ctsio);
5596
5597                 return (CTL_RETVAL_COMPLETE);
5598         }
5599
5600         ctl_set_success(ctsio);
5601         ctl_done((union ctl_io *)ctsio);
5602         return (CTL_RETVAL_COMPLETE);
5603 }
5604
5605 int
5606 ctl_write_same(struct ctl_scsiio *ctsio)
5607 {
5608         struct ctl_lun *lun;
5609         struct ctl_lba_len_flags *lbalen;
5610         uint64_t lba;
5611         uint32_t num_blocks;
5612         int len, retval;
5613         uint8_t byte2;
5614
5615         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5616
5617         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5618
5619         switch (ctsio->cdb[0]) {
5620         case WRITE_SAME_10: {
5621                 struct scsi_write_same_10 *cdb;
5622
5623                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5624
5625                 lba = scsi_4btoul(cdb->addr);
5626                 num_blocks = scsi_2btoul(cdb->length);
5627                 byte2 = cdb->byte2;
5628                 break;
5629         }
5630         case WRITE_SAME_16: {
5631                 struct scsi_write_same_16 *cdb;
5632
5633                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5634
5635                 lba = scsi_8btou64(cdb->addr);
5636                 num_blocks = scsi_4btoul(cdb->length);
5637                 byte2 = cdb->byte2;
5638                 break;
5639         }
5640         default:
5641                 /*
5642                  * We got a command we don't support.  This shouldn't
5643                  * happen, commands should be filtered out above us.
5644                  */
5645                 ctl_set_invalid_opcode(ctsio);
5646                 ctl_done((union ctl_io *)ctsio);
5647
5648                 return (CTL_RETVAL_COMPLETE);
5649                 break; /* NOTREACHED */
5650         }
5651
5652         /* ANCHOR flag can be used only together with UNMAP */
5653         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5654                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5655                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5656                 ctl_done((union ctl_io *)ctsio);
5657                 return (CTL_RETVAL_COMPLETE);
5658         }
5659
5660         /*
5661          * The first check is to make sure we're in bounds, the second
5662          * check is to catch wrap-around problems.  If the lba + num blocks
5663          * is less than the lba, then we've wrapped around and the block
5664          * range is invalid anyway.
5665          */
5666         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5667          || ((lba + num_blocks) < lba)) {
5668                 ctl_set_lba_out_of_range(ctsio,
5669                     MAX(lba, lun->be_lun->maxlba + 1));
5670                 ctl_done((union ctl_io *)ctsio);
5671                 return (CTL_RETVAL_COMPLETE);
5672         }
5673
5674         /* Zero number of blocks means "to the last logical block" */
5675         if (num_blocks == 0) {
5676                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5677                         ctl_set_invalid_field(ctsio,
5678                                               /*sks_valid*/ 0,
5679                                               /*command*/ 1,
5680                                               /*field*/ 0,
5681                                               /*bit_valid*/ 0,
5682                                               /*bit*/ 0);
5683                         ctl_done((union ctl_io *)ctsio);
5684                         return (CTL_RETVAL_COMPLETE);
5685                 }
5686                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5687         }
5688
5689         len = lun->be_lun->blocksize;
5690
5691         /*
5692          * If we've got a kernel request that hasn't been malloced yet,
5693          * malloc it and tell the caller the data buffer is here.
5694          */
5695         if ((byte2 & SWS_NDOB) == 0 &&
5696             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5697                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5698                 ctsio->kern_data_len = len;
5699                 ctsio->kern_total_len = len;
5700                 ctsio->kern_data_resid = 0;
5701                 ctsio->kern_rel_offset = 0;
5702                 ctsio->kern_sg_entries = 0;
5703                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5704                 ctsio->be_move_done = ctl_config_move_done;
5705                 ctl_datamove((union ctl_io *)ctsio);
5706
5707                 return (CTL_RETVAL_COMPLETE);
5708         }
5709
5710         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5711         lbalen->lba = lba;
5712         lbalen->len = num_blocks;
5713         lbalen->flags = byte2;
5714         retval = lun->backend->config_write((union ctl_io *)ctsio);
5715
5716         return (retval);
5717 }
5718
5719 int
5720 ctl_unmap(struct ctl_scsiio *ctsio)
5721 {
5722         struct ctl_lun *lun;
5723         struct scsi_unmap *cdb;
5724         struct ctl_ptr_len_flags *ptrlen;
5725         struct scsi_unmap_header *hdr;
5726         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5727         uint64_t lba;
5728         uint32_t num_blocks;
5729         int len, retval;
5730         uint8_t byte2;
5731
5732         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5733
5734         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5735         cdb = (struct scsi_unmap *)ctsio->cdb;
5736
5737         len = scsi_2btoul(cdb->length);
5738         byte2 = cdb->byte2;
5739
5740         /*
5741          * If we've got a kernel request that hasn't been malloced yet,
5742          * malloc it and tell the caller the data buffer is here.
5743          */
5744         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5745                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5746                 ctsio->kern_data_len = len;
5747                 ctsio->kern_total_len = len;
5748                 ctsio->kern_data_resid = 0;
5749                 ctsio->kern_rel_offset = 0;
5750                 ctsio->kern_sg_entries = 0;
5751                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5752                 ctsio->be_move_done = ctl_config_move_done;
5753                 ctl_datamove((union ctl_io *)ctsio);
5754
5755                 return (CTL_RETVAL_COMPLETE);
5756         }
5757
5758         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5759         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5760         if (len < sizeof (*hdr) ||
5761             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5762             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5763             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5764                 ctl_set_invalid_field(ctsio,
5765                                       /*sks_valid*/ 0,
5766                                       /*command*/ 0,
5767                                       /*field*/ 0,
5768                                       /*bit_valid*/ 0,
5769                                       /*bit*/ 0);
5770                 goto done;
5771         }
5772         len = scsi_2btoul(hdr->desc_length);
5773         buf = (struct scsi_unmap_desc *)(hdr + 1);
5774         end = buf + len / sizeof(*buf);
5775
5776         endnz = buf;
5777         for (range = buf; range < end; range++) {
5778                 lba = scsi_8btou64(range->lba);
5779                 num_blocks = scsi_4btoul(range->length);
5780                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5781                  || ((lba + num_blocks) < lba)) {
5782                         ctl_set_lba_out_of_range(ctsio,
5783                             MAX(lba, lun->be_lun->maxlba + 1));
5784                         ctl_done((union ctl_io *)ctsio);
5785                         return (CTL_RETVAL_COMPLETE);
5786                 }
5787                 if (num_blocks != 0)
5788                         endnz = range + 1;
5789         }
5790
5791         /*
5792          * Block backend can not handle zero last range.
5793          * Filter it out and return if there is nothing left.
5794          */
5795         len = (uint8_t *)endnz - (uint8_t *)buf;
5796         if (len == 0) {
5797                 ctl_set_success(ctsio);
5798                 goto done;
5799         }
5800
5801         mtx_lock(&lun->lun_lock);
5802         ptrlen = (struct ctl_ptr_len_flags *)
5803             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5804         ptrlen->ptr = (void *)buf;
5805         ptrlen->len = len;
5806         ptrlen->flags = byte2;
5807         ctl_check_blocked(lun);
5808         mtx_unlock(&lun->lun_lock);
5809
5810         retval = lun->backend->config_write((union ctl_io *)ctsio);
5811         return (retval);
5812
5813 done:
5814         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5815                 free(ctsio->kern_data_ptr, M_CTL);
5816                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5817         }
5818         ctl_done((union ctl_io *)ctsio);
5819         return (CTL_RETVAL_COMPLETE);
5820 }
5821
5822 int
5823 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5824                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5825 {
5826         struct ctl_lun *lun;
5827         uint8_t *current_cp;
5828         int set_ua;
5829         uint32_t initidx;
5830
5831         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5832         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5833         set_ua = 0;
5834
5835         current_cp = (page_index->page_data + (page_index->page_len *
5836             CTL_PAGE_CURRENT));
5837
5838         mtx_lock(&lun->lun_lock);
5839         if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5840                 memcpy(current_cp, page_ptr, page_index->page_len);
5841                 set_ua = 1;
5842         }
5843         if (set_ua != 0)
5844                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5845         mtx_unlock(&lun->lun_lock);
5846         if (set_ua) {
5847                 ctl_isc_announce_mode(lun,
5848                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5849                     page_index->page_code, page_index->subpage);
5850         }
5851         return (CTL_RETVAL_COMPLETE);
5852 }
5853
5854 static void
5855 ctl_ie_timer(void *arg)
5856 {
5857         struct ctl_lun *lun = arg;
5858         uint64_t t;
5859
5860         if (lun->ie_asc == 0)
5861                 return;
5862
5863         if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5864                 ctl_est_ua_all(lun, -1, CTL_UA_IE);
5865         else
5866                 lun->ie_reported = 0;
5867
5868         if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5869                 lun->ie_reportcnt++;
5870                 t = scsi_4btoul(lun->MODE_IE.interval_timer);
5871                 if (t == 0 || t == UINT32_MAX)
5872                         t = 3000;  /* 5 min */
5873                 callout_schedule(&lun->ie_callout, t * hz / 10);
5874         }
5875 }
5876
5877 int
5878 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5879                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5880 {
5881         struct scsi_info_exceptions_page *pg;
5882         struct ctl_lun *lun;
5883         uint64_t t;
5884
5885         (void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5886
5887         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5888         pg = (struct scsi_info_exceptions_page *)page_ptr;
5889         mtx_lock(&lun->lun_lock);
5890         if (pg->info_flags & SIEP_FLAGS_TEST) {
5891                 lun->ie_asc = 0x5d;
5892                 lun->ie_ascq = 0xff;
5893                 if (pg->mrie == SIEP_MRIE_UA) {
5894                         ctl_est_ua_all(lun, -1, CTL_UA_IE);
5895                         lun->ie_reported = 1;
5896                 } else {
5897                         ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5898                         lun->ie_reported = -1;
5899                 }
5900                 lun->ie_reportcnt = 1;
5901                 if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5902                         lun->ie_reportcnt++;
5903                         t = scsi_4btoul(pg->interval_timer);
5904                         if (t == 0 || t == UINT32_MAX)
5905                                 t = 3000;  /* 5 min */
5906                         callout_reset(&lun->ie_callout, t * hz / 10,
5907                             ctl_ie_timer, lun);
5908                 }
5909         } else {
5910                 lun->ie_asc = 0;
5911                 lun->ie_ascq = 0;
5912                 lun->ie_reported = 1;
5913                 ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5914                 lun->ie_reportcnt = UINT32_MAX;
5915                 callout_stop(&lun->ie_callout);
5916         }
5917         mtx_unlock(&lun->lun_lock);
5918         return (CTL_RETVAL_COMPLETE);
5919 }
5920
5921 static int
5922 ctl_do_mode_select(union ctl_io *io)
5923 {
5924         struct scsi_mode_page_header *page_header;
5925         struct ctl_page_index *page_index;
5926         struct ctl_scsiio *ctsio;
5927         int page_len, page_len_offset, page_len_size;
5928         union ctl_modepage_info *modepage_info;
5929         struct ctl_lun *lun;
5930         uint16_t *len_left, *len_used;
5931         int retval, i;
5932
5933         ctsio = &io->scsiio;
5934         page_index = NULL;
5935         page_len = 0;
5936         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5937
5938         modepage_info = (union ctl_modepage_info *)
5939                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5940         len_left = &modepage_info->header.len_left;
5941         len_used = &modepage_info->header.len_used;
5942
5943 do_next_page:
5944
5945         page_header = (struct scsi_mode_page_header *)
5946                 (ctsio->kern_data_ptr + *len_used);
5947
5948         if (*len_left == 0) {
5949                 free(ctsio->kern_data_ptr, M_CTL);
5950                 ctl_set_success(ctsio);
5951                 ctl_done((union ctl_io *)ctsio);
5952                 return (CTL_RETVAL_COMPLETE);
5953         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5954
5955                 free(ctsio->kern_data_ptr, M_CTL);
5956                 ctl_set_param_len_error(ctsio);
5957                 ctl_done((union ctl_io *)ctsio);
5958                 return (CTL_RETVAL_COMPLETE);
5959
5960         } else if ((page_header->page_code & SMPH_SPF)
5961                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5962
5963                 free(ctsio->kern_data_ptr, M_CTL);
5964                 ctl_set_param_len_error(ctsio);
5965                 ctl_done((union ctl_io *)ctsio);
5966                 return (CTL_RETVAL_COMPLETE);
5967         }
5968
5969
5970         /*
5971          * XXX KDM should we do something with the block descriptor?
5972          */
5973         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5974                 page_index = &lun->mode_pages.index[i];
5975                 if (lun->be_lun->lun_type == T_DIRECT &&
5976                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5977                         continue;
5978                 if (lun->be_lun->lun_type == T_PROCESSOR &&
5979                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5980                         continue;
5981                 if (lun->be_lun->lun_type == T_CDROM &&
5982                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5983                         continue;
5984
5985                 if ((page_index->page_code & SMPH_PC_MASK) !=
5986                     (page_header->page_code & SMPH_PC_MASK))
5987                         continue;
5988
5989                 /*
5990                  * If neither page has a subpage code, then we've got a
5991                  * match.
5992                  */
5993                 if (((page_index->page_code & SMPH_SPF) == 0)
5994                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5995                         page_len = page_header->page_length;
5996                         break;
5997                 }
5998
5999                 /*
6000                  * If both pages have subpages, then the subpage numbers
6001                  * have to match.
6002                  */
6003                 if ((page_index->page_code & SMPH_SPF)
6004                   && (page_header->page_code & SMPH_SPF)) {
6005                         struct scsi_mode_page_header_sp *sph;
6006
6007                         sph = (struct scsi_mode_page_header_sp *)page_header;
6008                         if (page_index->subpage == sph->subpage) {
6009                                 page_len = scsi_2btoul(sph->page_length);
6010                                 break;
6011                         }
6012                 }
6013         }
6014
6015         /*
6016          * If we couldn't find the page, or if we don't have a mode select
6017          * handler for it, send back an error to the user.
6018          */
6019         if ((i >= CTL_NUM_MODE_PAGES)
6020          || (page_index->select_handler == NULL)) {
6021                 ctl_set_invalid_field(ctsio,
6022                                       /*sks_valid*/ 1,
6023                                       /*command*/ 0,
6024                                       /*field*/ *len_used,
6025                                       /*bit_valid*/ 0,
6026                                       /*bit*/ 0);
6027                 free(ctsio->kern_data_ptr, M_CTL);
6028                 ctl_done((union ctl_io *)ctsio);
6029                 return (CTL_RETVAL_COMPLETE);
6030         }
6031
6032         if (page_index->page_code & SMPH_SPF) {
6033                 page_len_offset = 2;
6034                 page_len_size = 2;
6035         } else {
6036                 page_len_size = 1;
6037                 page_len_offset = 1;
6038         }
6039
6040         /*
6041          * If the length the initiator gives us isn't the one we specify in
6042          * the mode page header, or if they didn't specify enough data in
6043          * the CDB to avoid truncating this page, kick out the request.
6044          */
6045         if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6046                 ctl_set_invalid_field(ctsio,
6047                                       /*sks_valid*/ 1,
6048                                       /*command*/ 0,
6049                                       /*field*/ *len_used + page_len_offset,
6050                                       /*bit_valid*/ 0,
6051                                       /*bit*/ 0);
6052                 free(ctsio->kern_data_ptr, M_CTL);
6053                 ctl_done((union ctl_io *)ctsio);
6054                 return (CTL_RETVAL_COMPLETE);
6055         }
6056         if (*len_left < page_index->page_len) {
6057                 free(ctsio->kern_data_ptr, M_CTL);
6058                 ctl_set_param_len_error(ctsio);
6059                 ctl_done((union ctl_io *)ctsio);
6060                 return (CTL_RETVAL_COMPLETE);
6061         }
6062
6063         /*
6064          * Run through the mode page, checking to make sure that the bits
6065          * the user changed are actually legal for him to change.
6066          */
6067         for (i = 0; i < page_index->page_len; i++) {
6068                 uint8_t *user_byte, *change_mask, *current_byte;
6069                 int bad_bit;
6070                 int j;
6071
6072                 user_byte = (uint8_t *)page_header + i;
6073                 change_mask = page_index->page_data +
6074                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6075                 current_byte = page_index->page_data +
6076                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6077
6078                 /*
6079                  * Check to see whether the user set any bits in this byte
6080                  * that he is not allowed to set.
6081                  */
6082                 if ((*user_byte & ~(*change_mask)) ==
6083                     (*current_byte & ~(*change_mask)))
6084                         continue;
6085
6086                 /*
6087                  * Go through bit by bit to determine which one is illegal.
6088                  */
6089                 bad_bit = 0;
6090                 for (j = 7; j >= 0; j--) {
6091                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6092                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6093                                 bad_bit = i;
6094                                 break;
6095                         }
6096                 }
6097                 ctl_set_invalid_field(ctsio,
6098                                       /*sks_valid*/ 1,
6099                                       /*command*/ 0,
6100                                       /*field*/ *len_used + i,
6101                                       /*bit_valid*/ 1,
6102                                       /*bit*/ bad_bit);
6103                 free(ctsio->kern_data_ptr, M_CTL);
6104                 ctl_done((union ctl_io *)ctsio);
6105                 return (CTL_RETVAL_COMPLETE);
6106         }
6107
6108         /*
6109          * Decrement these before we call the page handler, since we may
6110          * end up getting called back one way or another before the handler
6111          * returns to this context.
6112          */
6113         *len_left -= page_index->page_len;
6114         *len_used += page_index->page_len;
6115
6116         retval = page_index->select_handler(ctsio, page_index,
6117                                             (uint8_t *)page_header);
6118
6119         /*
6120          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6121          * wait until this queued command completes to finish processing
6122          * the mode page.  If it returns anything other than
6123          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6124          * already set the sense information, freed the data pointer, and
6125          * completed the io for us.
6126          */
6127         if (retval != CTL_RETVAL_COMPLETE)
6128                 goto bailout_no_done;
6129
6130         /*
6131          * If the initiator sent us more than one page, parse the next one.
6132          */
6133         if (*len_left > 0)
6134                 goto do_next_page;
6135
6136         ctl_set_success(ctsio);
6137         free(ctsio->kern_data_ptr, M_CTL);
6138         ctl_done((union ctl_io *)ctsio);
6139
6140 bailout_no_done:
6141
6142         return (CTL_RETVAL_COMPLETE);
6143
6144 }
6145
6146 int
6147 ctl_mode_select(struct ctl_scsiio *ctsio)
6148 {
6149         struct ctl_lun *lun;
6150         union ctl_modepage_info *modepage_info;
6151         int bd_len, i, header_size, param_len, pf, rtd, sp;
6152         uint32_t initidx;
6153
6154         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6155         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6156         switch (ctsio->cdb[0]) {
6157         case MODE_SELECT_6: {
6158                 struct scsi_mode_select_6 *cdb;
6159
6160                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6161
6162                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6163                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6164                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6165                 param_len = cdb->length;
6166                 header_size = sizeof(struct scsi_mode_header_6);
6167                 break;
6168         }
6169         case MODE_SELECT_10: {
6170                 struct scsi_mode_select_10 *cdb;
6171
6172                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6173
6174                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6175                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6176                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6177                 param_len = scsi_2btoul(cdb->length);
6178                 header_size = sizeof(struct scsi_mode_header_10);
6179                 break;
6180         }
6181         default:
6182                 ctl_set_invalid_opcode(ctsio);
6183                 ctl_done((union ctl_io *)ctsio);
6184                 return (CTL_RETVAL_COMPLETE);
6185         }
6186
6187         if (rtd) {
6188                 if (param_len != 0) {
6189                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6190                             /*command*/ 1, /*field*/ 0,
6191                             /*bit_valid*/ 0, /*bit*/ 0);
6192                         ctl_done((union ctl_io *)ctsio);
6193                         return (CTL_RETVAL_COMPLETE);
6194                 }
6195
6196                 /* Revert to defaults. */
6197                 ctl_init_page_index(lun);
6198                 mtx_lock(&lun->lun_lock);
6199                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6200                 mtx_unlock(&lun->lun_lock);
6201                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6202                         ctl_isc_announce_mode(lun, -1,
6203                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6204                             lun->mode_pages.index[i].subpage);
6205                 }
6206                 ctl_set_success(ctsio);
6207                 ctl_done((union ctl_io *)ctsio);
6208                 return (CTL_RETVAL_COMPLETE);
6209         }
6210
6211         /*
6212          * From SPC-3:
6213          * "A parameter list length of zero indicates that the Data-Out Buffer
6214          * shall be empty. This condition shall not be considered as an error."
6215          */
6216         if (param_len == 0) {
6217                 ctl_set_success(ctsio);
6218                 ctl_done((union ctl_io *)ctsio);
6219                 return (CTL_RETVAL_COMPLETE);
6220         }
6221
6222         /*
6223          * Since we'll hit this the first time through, prior to
6224          * allocation, we don't need to free a data buffer here.
6225          */
6226         if (param_len < header_size) {
6227                 ctl_set_param_len_error(ctsio);
6228                 ctl_done((union ctl_io *)ctsio);
6229                 return (CTL_RETVAL_COMPLETE);
6230         }
6231
6232         /*
6233          * Allocate the data buffer and grab the user's data.  In theory,
6234          * we shouldn't have to sanity check the parameter list length here
6235          * because the maximum size is 64K.  We should be able to malloc
6236          * that much without too many problems.
6237          */
6238         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6239                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6240                 ctsio->kern_data_len = param_len;
6241                 ctsio->kern_total_len = param_len;
6242                 ctsio->kern_data_resid = 0;
6243                 ctsio->kern_rel_offset = 0;
6244                 ctsio->kern_sg_entries = 0;
6245                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6246                 ctsio->be_move_done = ctl_config_move_done;
6247                 ctl_datamove((union ctl_io *)ctsio);
6248
6249                 return (CTL_RETVAL_COMPLETE);
6250         }
6251
6252         switch (ctsio->cdb[0]) {
6253         case MODE_SELECT_6: {
6254                 struct scsi_mode_header_6 *mh6;
6255
6256                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6257                 bd_len = mh6->blk_desc_len;
6258                 break;
6259         }
6260         case MODE_SELECT_10: {
6261                 struct scsi_mode_header_10 *mh10;
6262
6263                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6264                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6265                 break;
6266         }
6267         default:
6268                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6269         }
6270
6271         if (param_len < (header_size + bd_len)) {
6272                 free(ctsio->kern_data_ptr, M_CTL);
6273                 ctl_set_param_len_error(ctsio);
6274                 ctl_done((union ctl_io *)ctsio);
6275                 return (CTL_RETVAL_COMPLETE);
6276         }
6277
6278         /*
6279          * Set the IO_CONT flag, so that if this I/O gets passed to
6280          * ctl_config_write_done(), it'll get passed back to
6281          * ctl_do_mode_select() for further processing, or completion if
6282          * we're all done.
6283          */
6284         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6285         ctsio->io_cont = ctl_do_mode_select;
6286
6287         modepage_info = (union ctl_modepage_info *)
6288                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6289         memset(modepage_info, 0, sizeof(*modepage_info));
6290         modepage_info->header.len_left = param_len - header_size - bd_len;
6291         modepage_info->header.len_used = header_size + bd_len;
6292
6293         return (ctl_do_mode_select((union ctl_io *)ctsio));
6294 }
6295
6296 int
6297 ctl_mode_sense(struct ctl_scsiio *ctsio)
6298 {
6299         struct ctl_lun *lun;
6300         int pc, page_code, dbd, llba, subpage;
6301         int alloc_len, page_len, header_len, total_len;
6302         struct scsi_mode_block_descr *block_desc;
6303         struct ctl_page_index *page_index;
6304
6305         dbd = 0;
6306         llba = 0;
6307         block_desc = NULL;
6308
6309         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6310
6311         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6312         switch (ctsio->cdb[0]) {
6313         case MODE_SENSE_6: {
6314                 struct scsi_mode_sense_6 *cdb;
6315
6316                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6317
6318                 header_len = sizeof(struct scsi_mode_hdr_6);
6319                 if (cdb->byte2 & SMS_DBD)
6320                         dbd = 1;
6321                 else
6322                         header_len += sizeof(struct scsi_mode_block_descr);
6323
6324                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6325                 page_code = cdb->page & SMS_PAGE_CODE;
6326                 subpage = cdb->subpage;
6327                 alloc_len = cdb->length;
6328                 break;
6329         }
6330         case MODE_SENSE_10: {
6331                 struct scsi_mode_sense_10 *cdb;
6332
6333                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6334
6335                 header_len = sizeof(struct scsi_mode_hdr_10);
6336
6337                 if (cdb->byte2 & SMS_DBD)
6338                         dbd = 1;
6339                 else
6340                         header_len += sizeof(struct scsi_mode_block_descr);
6341                 if (cdb->byte2 & SMS10_LLBAA)
6342                         llba = 1;
6343                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6344                 page_code = cdb->page & SMS_PAGE_CODE;
6345                 subpage = cdb->subpage;
6346                 alloc_len = scsi_2btoul(cdb->length);
6347                 break;
6348         }
6349         default:
6350                 ctl_set_invalid_opcode(ctsio);
6351                 ctl_done((union ctl_io *)ctsio);
6352                 return (CTL_RETVAL_COMPLETE);
6353                 break; /* NOTREACHED */
6354         }
6355
6356         /*
6357          * We have to make a first pass through to calculate the size of
6358          * the pages that match the user's query.  Then we allocate enough
6359          * memory to hold it, and actually copy the data into the buffer.
6360          */
6361         switch (page_code) {
6362         case SMS_ALL_PAGES_PAGE: {
6363                 u_int i;
6364
6365                 page_len = 0;
6366
6367                 /*
6368                  * At the moment, values other than 0 and 0xff here are
6369                  * reserved according to SPC-3.
6370                  */
6371                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6372                  && (subpage != SMS_SUBPAGE_ALL)) {
6373                         ctl_set_invalid_field(ctsio,
6374                                               /*sks_valid*/ 1,
6375                                               /*command*/ 1,
6376                                               /*field*/ 3,
6377                                               /*bit_valid*/ 0,
6378                                               /*bit*/ 0);
6379                         ctl_done((union ctl_io *)ctsio);
6380                         return (CTL_RETVAL_COMPLETE);
6381                 }
6382
6383                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6384                         page_index = &lun->mode_pages.index[i];
6385
6386                         /* Make sure the page is supported for this dev type */
6387                         if (lun->be_lun->lun_type == T_DIRECT &&
6388                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6389                                 continue;
6390                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6391                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6392                                 continue;
6393                         if (lun->be_lun->lun_type == T_CDROM &&
6394                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6395                                 continue;
6396
6397                         /*
6398                          * We don't use this subpage if the user didn't
6399                          * request all subpages.
6400                          */
6401                         if ((page_index->subpage != 0)
6402                          && (subpage == SMS_SUBPAGE_PAGE_0))
6403                                 continue;
6404
6405 #if 0
6406                         printf("found page %#x len %d\n",
6407                                page_index->page_code & SMPH_PC_MASK,
6408                                page_index->page_len);
6409 #endif
6410                         page_len += page_index->page_len;
6411                 }
6412                 break;
6413         }
6414         default: {
6415                 u_int i;
6416
6417                 page_len = 0;
6418
6419                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6420                         page_index = &lun->mode_pages.index[i];
6421
6422                         /* Make sure the page is supported for this dev type */
6423                         if (lun->be_lun->lun_type == T_DIRECT &&
6424                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6425                                 continue;
6426                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6427                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6428                                 continue;
6429                         if (lun->be_lun->lun_type == T_CDROM &&
6430                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6431                                 continue;
6432
6433                         /* Look for the right page code */
6434                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6435                                 continue;
6436
6437                         /* Look for the right subpage or the subpage wildcard*/
6438                         if ((page_index->subpage != subpage)
6439                          && (subpage != SMS_SUBPAGE_ALL))
6440                                 continue;
6441
6442 #if 0
6443                         printf("found page %#x len %d\n",
6444                                page_index->page_code & SMPH_PC_MASK,
6445                                page_index->page_len);
6446 #endif
6447
6448                         page_len += page_index->page_len;
6449                 }
6450
6451                 if (page_len == 0) {
6452                         ctl_set_invalid_field(ctsio,
6453                                               /*sks_valid*/ 1,
6454                                               /*command*/ 1,
6455                                               /*field*/ 2,
6456                                               /*bit_valid*/ 1,
6457                                               /*bit*/ 5);
6458                         ctl_done((union ctl_io *)ctsio);
6459                         return (CTL_RETVAL_COMPLETE);
6460                 }
6461                 break;
6462         }
6463         }
6464
6465         total_len = header_len + page_len;
6466 #if 0
6467         printf("header_len = %d, page_len = %d, total_len = %d\n",
6468                header_len, page_len, total_len);
6469 #endif
6470
6471         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6472         ctsio->kern_sg_entries = 0;
6473         ctsio->kern_data_resid = 0;
6474         ctsio->kern_rel_offset = 0;
6475         if (total_len < alloc_len) {
6476                 ctsio->residual = alloc_len - total_len;
6477                 ctsio->kern_data_len = total_len;
6478                 ctsio->kern_total_len = total_len;
6479         } else {
6480                 ctsio->residual = 0;
6481                 ctsio->kern_data_len = alloc_len;
6482                 ctsio->kern_total_len = alloc_len;
6483         }
6484
6485         switch (ctsio->cdb[0]) {
6486         case MODE_SENSE_6: {
6487                 struct scsi_mode_hdr_6 *header;
6488
6489                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6490
6491                 header->datalen = MIN(total_len - 1, 254);
6492                 if (lun->be_lun->lun_type == T_DIRECT) {
6493                         header->dev_specific = 0x10; /* DPOFUA */
6494                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6495                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6496                                 header->dev_specific |= 0x80; /* WP */
6497                 }
6498                 if (dbd)
6499                         header->block_descr_len = 0;
6500                 else
6501                         header->block_descr_len =
6502                                 sizeof(struct scsi_mode_block_descr);
6503                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6504                 break;
6505         }
6506         case MODE_SENSE_10: {
6507                 struct scsi_mode_hdr_10 *header;
6508                 int datalen;
6509
6510                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6511
6512                 datalen = MIN(total_len - 2, 65533);
6513                 scsi_ulto2b(datalen, header->datalen);
6514                 if (lun->be_lun->lun_type == T_DIRECT) {
6515                         header->dev_specific = 0x10; /* DPOFUA */
6516                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6517                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6518                                 header->dev_specific |= 0x80; /* WP */
6519                 }
6520                 if (dbd)
6521                         scsi_ulto2b(0, header->block_descr_len);
6522                 else
6523                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6524                                     header->block_descr_len);
6525                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6526                 break;
6527         }
6528         default:
6529                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6530         }
6531
6532         /*
6533          * If we've got a disk, use its blocksize in the block
6534          * descriptor.  Otherwise, just set it to 0.
6535          */
6536         if (dbd == 0) {
6537                 if (lun->be_lun->lun_type == T_DIRECT)
6538                         scsi_ulto3b(lun->be_lun->blocksize,
6539                                     block_desc->block_len);
6540                 else
6541                         scsi_ulto3b(0, block_desc->block_len);
6542         }
6543
6544         switch (page_code) {
6545         case SMS_ALL_PAGES_PAGE: {
6546                 int i, data_used;
6547
6548                 data_used = header_len;
6549                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6550                         struct ctl_page_index *page_index;
6551
6552                         page_index = &lun->mode_pages.index[i];
6553                         if (lun->be_lun->lun_type == T_DIRECT &&
6554                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6555                                 continue;
6556                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6557                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6558                                 continue;
6559                         if (lun->be_lun->lun_type == T_CDROM &&
6560                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6561                                 continue;
6562
6563                         /*
6564                          * We don't use this subpage if the user didn't
6565                          * request all subpages.  We already checked (above)
6566                          * to make sure the user only specified a subpage
6567                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6568                          */
6569                         if ((page_index->subpage != 0)
6570                          && (subpage == SMS_SUBPAGE_PAGE_0))
6571                                 continue;
6572
6573                         /*
6574                          * Call the handler, if it exists, to update the
6575                          * page to the latest values.
6576                          */
6577                         if (page_index->sense_handler != NULL)
6578                                 page_index->sense_handler(ctsio, page_index,pc);
6579
6580                         memcpy(ctsio->kern_data_ptr + data_used,
6581                                page_index->page_data +
6582                                (page_index->page_len * pc),
6583                                page_index->page_len);
6584                         data_used += page_index->page_len;
6585                 }
6586                 break;
6587         }
6588         default: {
6589                 int i, data_used;
6590
6591                 data_used = header_len;
6592
6593                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6594                         struct ctl_page_index *page_index;
6595
6596                         page_index = &lun->mode_pages.index[i];
6597
6598                         /* Look for the right page code */
6599                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6600                                 continue;
6601
6602                         /* Look for the right subpage or the subpage wildcard*/
6603                         if ((page_index->subpage != subpage)
6604                          && (subpage != SMS_SUBPAGE_ALL))
6605                                 continue;
6606
6607                         /* Make sure the page is supported for this dev type */
6608                         if (lun->be_lun->lun_type == T_DIRECT &&
6609                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6610                                 continue;
6611                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6612                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6613                                 continue;
6614                         if (lun->be_lun->lun_type == T_CDROM &&
6615                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6616                                 continue;
6617
6618                         /*
6619                          * Call the handler, if it exists, to update the
6620                          * page to the latest values.
6621                          */
6622                         if (page_index->sense_handler != NULL)
6623                                 page_index->sense_handler(ctsio, page_index,pc);
6624
6625                         memcpy(ctsio->kern_data_ptr + data_used,
6626                                page_index->page_data +
6627                                (page_index->page_len * pc),
6628                                page_index->page_len);
6629                         data_used += page_index->page_len;
6630                 }
6631                 break;
6632         }
6633         }
6634
6635         ctl_set_success(ctsio);
6636         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6637         ctsio->be_move_done = ctl_config_move_done;
6638         ctl_datamove((union ctl_io *)ctsio);
6639         return (CTL_RETVAL_COMPLETE);
6640 }
6641
6642 int
6643 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6644                                struct ctl_page_index *page_index,
6645                                int pc)
6646 {
6647         struct ctl_lun *lun;
6648         struct scsi_log_param_header *phdr;
6649         uint8_t *data;
6650         uint64_t val;
6651
6652         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6653         data = page_index->page_data;
6654
6655         if (lun->backend->lun_attr != NULL &&
6656             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6657              != UINT64_MAX) {
6658                 phdr = (struct scsi_log_param_header *)data;
6659                 scsi_ulto2b(0x0001, 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         if (lun->backend->lun_attr != NULL &&
6669             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6670              != UINT64_MAX) {
6671                 phdr = (struct scsi_log_param_header *)data;
6672                 scsi_ulto2b(0x0002, phdr->param_code);
6673                 phdr->param_control = SLP_LBIN | SLP_LP;
6674                 phdr->param_len = 8;
6675                 data = (uint8_t *)(phdr + 1);
6676                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6677                 data[4] = 0x01; /* per-LUN */
6678                 data += phdr->param_len;
6679         }
6680
6681         if (lun->backend->lun_attr != NULL &&
6682             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6683              != UINT64_MAX) {
6684                 phdr = (struct scsi_log_param_header *)data;
6685                 scsi_ulto2b(0x00f1, phdr->param_code);
6686                 phdr->param_control = SLP_LBIN | SLP_LP;
6687                 phdr->param_len = 8;
6688                 data = (uint8_t *)(phdr + 1);
6689                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6690                 data[4] = 0x02; /* per-pool */
6691                 data += phdr->param_len;
6692         }
6693
6694         if (lun->backend->lun_attr != NULL &&
6695             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6696              != UINT64_MAX) {
6697                 phdr = (struct scsi_log_param_header *)data;
6698                 scsi_ulto2b(0x00f2, phdr->param_code);
6699                 phdr->param_control = SLP_LBIN | SLP_LP;
6700                 phdr->param_len = 8;
6701                 data = (uint8_t *)(phdr + 1);
6702                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6703                 data[4] = 0x02; /* per-pool */
6704                 data += phdr->param_len;
6705         }
6706
6707         page_index->page_len = data - page_index->page_data;
6708         return (0);
6709 }
6710
6711 int
6712 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6713                                struct ctl_page_index *page_index,
6714                                int pc)
6715 {
6716         struct ctl_lun *lun;
6717         struct stat_page *data;
6718         uint64_t rn, wn, rb, wb;
6719         struct bintime rt, wt;
6720         int i;
6721
6722         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6723         data = (struct stat_page *)page_index->page_data;
6724
6725         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6726         data->sap.hdr.param_control = SLP_LBIN;
6727         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6728             sizeof(struct scsi_log_param_header);
6729         rn = wn = rb = wb = 0;
6730         bintime_clear(&rt);
6731         bintime_clear(&wt);
6732         for (i = 0; i < CTL_MAX_PORTS; i++) {
6733                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6734                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6735                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6736                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6737                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6738                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6739         }
6740         scsi_u64to8b(rn, data->sap.read_num);
6741         scsi_u64to8b(wn, data->sap.write_num);
6742         if (lun->stats.blocksize > 0) {
6743                 scsi_u64to8b(wb / lun->stats.blocksize,
6744                     data->sap.recvieved_lba);
6745                 scsi_u64to8b(rb / lun->stats.blocksize,
6746                     data->sap.transmitted_lba);
6747         }
6748         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6749             data->sap.read_int);
6750         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6751             data->sap.write_int);
6752         scsi_u64to8b(0, data->sap.weighted_num);
6753         scsi_u64to8b(0, data->sap.weighted_int);
6754         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6755         data->it.hdr.param_control = SLP_LBIN;
6756         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6757             sizeof(struct scsi_log_param_header);
6758 #ifdef CTL_TIME_IO
6759         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6760 #endif
6761         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6762         data->it.hdr.param_control = SLP_LBIN;
6763         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6764             sizeof(struct scsi_log_param_header);
6765         scsi_ulto4b(3, data->ti.exponent);
6766         scsi_ulto4b(1, data->ti.integer);
6767         return (0);
6768 }
6769
6770 int
6771 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6772                                struct ctl_page_index *page_index,
6773                                int pc)
6774 {
6775         struct ctl_lun *lun;
6776         struct scsi_log_informational_exceptions *data;
6777
6778         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6779         data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6780
6781         scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6782         data->hdr.param_control = SLP_LBIN;
6783         data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6784             sizeof(struct scsi_log_param_header);
6785         data->ie_asc = lun->ie_asc;
6786         data->ie_ascq = lun->ie_ascq;
6787         data->temperature = 0xff;
6788         return (0);
6789 }
6790
6791 int
6792 ctl_log_sense(struct ctl_scsiio *ctsio)
6793 {
6794         struct ctl_lun *lun;
6795         int i, pc, page_code, subpage;
6796         int alloc_len, total_len;
6797         struct ctl_page_index *page_index;
6798         struct scsi_log_sense *cdb;
6799         struct scsi_log_header *header;
6800
6801         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6802
6803         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6804         cdb = (struct scsi_log_sense *)ctsio->cdb;
6805         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6806         page_code = cdb->page & SLS_PAGE_CODE;
6807         subpage = cdb->subpage;
6808         alloc_len = scsi_2btoul(cdb->length);
6809
6810         page_index = NULL;
6811         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6812                 page_index = &lun->log_pages.index[i];
6813
6814                 /* Look for the right page code */
6815                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6816                         continue;
6817
6818                 /* Look for the right subpage or the subpage wildcard*/
6819                 if (page_index->subpage != subpage)
6820                         continue;
6821
6822                 break;
6823         }
6824         if (i >= CTL_NUM_LOG_PAGES) {
6825                 ctl_set_invalid_field(ctsio,
6826                                       /*sks_valid*/ 1,
6827                                       /*command*/ 1,
6828                                       /*field*/ 2,
6829                                       /*bit_valid*/ 0,
6830                                       /*bit*/ 0);
6831                 ctl_done((union ctl_io *)ctsio);
6832                 return (CTL_RETVAL_COMPLETE);
6833         }
6834
6835         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6836
6837         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6838         ctsio->kern_sg_entries = 0;
6839         ctsio->kern_data_resid = 0;
6840         ctsio->kern_rel_offset = 0;
6841         if (total_len < alloc_len) {
6842                 ctsio->residual = alloc_len - total_len;
6843                 ctsio->kern_data_len = total_len;
6844                 ctsio->kern_total_len = total_len;
6845         } else {
6846                 ctsio->residual = 0;
6847                 ctsio->kern_data_len = alloc_len;
6848                 ctsio->kern_total_len = alloc_len;
6849         }
6850
6851         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6852         header->page = page_index->page_code;
6853         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6854                 header->page |= SL_DS;
6855         if (page_index->subpage) {
6856                 header->page |= SL_SPF;
6857                 header->subpage = page_index->subpage;
6858         }
6859         scsi_ulto2b(page_index->page_len, header->datalen);
6860
6861         /*
6862          * Call the handler, if it exists, to update the
6863          * page to the latest values.
6864          */
6865         if (page_index->sense_handler != NULL)
6866                 page_index->sense_handler(ctsio, page_index, pc);
6867
6868         memcpy(header + 1, page_index->page_data, page_index->page_len);
6869
6870         ctl_set_success(ctsio);
6871         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6872         ctsio->be_move_done = ctl_config_move_done;
6873         ctl_datamove((union ctl_io *)ctsio);
6874         return (CTL_RETVAL_COMPLETE);
6875 }
6876
6877 int
6878 ctl_read_capacity(struct ctl_scsiio *ctsio)
6879 {
6880         struct scsi_read_capacity *cdb;
6881         struct scsi_read_capacity_data *data;
6882         struct ctl_lun *lun;
6883         uint32_t lba;
6884
6885         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6886
6887         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6888
6889         lba = scsi_4btoul(cdb->addr);
6890         if (((cdb->pmi & SRC_PMI) == 0)
6891          && (lba != 0)) {
6892                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6893                                       /*sks_valid*/ 1,
6894                                       /*command*/ 1,
6895                                       /*field*/ 2,
6896                                       /*bit_valid*/ 0,
6897                                       /*bit*/ 0);
6898                 ctl_done((union ctl_io *)ctsio);
6899                 return (CTL_RETVAL_COMPLETE);
6900         }
6901
6902         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6903
6904         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6905         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6906         ctsio->residual = 0;
6907         ctsio->kern_data_len = sizeof(*data);
6908         ctsio->kern_total_len = sizeof(*data);
6909         ctsio->kern_data_resid = 0;
6910         ctsio->kern_rel_offset = 0;
6911         ctsio->kern_sg_entries = 0;
6912
6913         /*
6914          * If the maximum LBA is greater than 0xfffffffe, the user must
6915          * issue a SERVICE ACTION IN (16) command, with the read capacity
6916          * serivce action set.
6917          */
6918         if (lun->be_lun->maxlba > 0xfffffffe)
6919                 scsi_ulto4b(0xffffffff, data->addr);
6920         else
6921                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6922
6923         /*
6924          * XXX KDM this may not be 512 bytes...
6925          */
6926         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6927
6928         ctl_set_success(ctsio);
6929         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6930         ctsio->be_move_done = ctl_config_move_done;
6931         ctl_datamove((union ctl_io *)ctsio);
6932         return (CTL_RETVAL_COMPLETE);
6933 }
6934
6935 int
6936 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6937 {
6938         struct scsi_read_capacity_16 *cdb;
6939         struct scsi_read_capacity_data_long *data;
6940         struct ctl_lun *lun;
6941         uint64_t lba;
6942         uint32_t alloc_len;
6943
6944         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6945
6946         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6947
6948         alloc_len = scsi_4btoul(cdb->alloc_len);
6949         lba = scsi_8btou64(cdb->addr);
6950
6951         if ((cdb->reladr & SRC16_PMI)
6952          && (lba != 0)) {
6953                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6954                                       /*sks_valid*/ 1,
6955                                       /*command*/ 1,
6956                                       /*field*/ 2,
6957                                       /*bit_valid*/ 0,
6958                                       /*bit*/ 0);
6959                 ctl_done((union ctl_io *)ctsio);
6960                 return (CTL_RETVAL_COMPLETE);
6961         }
6962
6963         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6964
6965         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6966         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6967
6968         if (sizeof(*data) < alloc_len) {
6969                 ctsio->residual = alloc_len - sizeof(*data);
6970                 ctsio->kern_data_len = sizeof(*data);
6971                 ctsio->kern_total_len = sizeof(*data);
6972         } else {
6973                 ctsio->residual = 0;
6974                 ctsio->kern_data_len = alloc_len;
6975                 ctsio->kern_total_len = alloc_len;
6976         }
6977         ctsio->kern_data_resid = 0;
6978         ctsio->kern_rel_offset = 0;
6979         ctsio->kern_sg_entries = 0;
6980
6981         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6982         /* XXX KDM this may not be 512 bytes... */
6983         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6984         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6985         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6986         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6987                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6988
6989         ctl_set_success(ctsio);
6990         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6991         ctsio->be_move_done = ctl_config_move_done;
6992         ctl_datamove((union ctl_io *)ctsio);
6993         return (CTL_RETVAL_COMPLETE);
6994 }
6995
6996 int
6997 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6998 {
6999         struct scsi_get_lba_status *cdb;
7000         struct scsi_get_lba_status_data *data;
7001         struct ctl_lun *lun;
7002         struct ctl_lba_len_flags *lbalen;
7003         uint64_t lba;
7004         uint32_t alloc_len, total_len;
7005         int retval;
7006
7007         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7008
7009         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7010         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7011         lba = scsi_8btou64(cdb->addr);
7012         alloc_len = scsi_4btoul(cdb->alloc_len);
7013
7014         if (lba > lun->be_lun->maxlba) {
7015                 ctl_set_lba_out_of_range(ctsio, lba);
7016                 ctl_done((union ctl_io *)ctsio);
7017                 return (CTL_RETVAL_COMPLETE);
7018         }
7019
7020         total_len = sizeof(*data) + sizeof(data->descr[0]);
7021         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7022         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7023
7024         if (total_len < alloc_len) {
7025                 ctsio->residual = alloc_len - total_len;
7026                 ctsio->kern_data_len = total_len;
7027                 ctsio->kern_total_len = total_len;
7028         } else {
7029                 ctsio->residual = 0;
7030                 ctsio->kern_data_len = alloc_len;
7031                 ctsio->kern_total_len = alloc_len;
7032         }
7033         ctsio->kern_data_resid = 0;
7034         ctsio->kern_rel_offset = 0;
7035         ctsio->kern_sg_entries = 0;
7036
7037         /* Fill dummy data in case backend can't tell anything. */
7038         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7039         scsi_u64to8b(lba, data->descr[0].addr);
7040         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7041             data->descr[0].length);
7042         data->descr[0].status = 0; /* Mapped or unknown. */
7043
7044         ctl_set_success(ctsio);
7045         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7046         ctsio->be_move_done = ctl_config_move_done;
7047
7048         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7049         lbalen->lba = lba;
7050         lbalen->len = total_len;
7051         lbalen->flags = 0;
7052         retval = lun->backend->config_read((union ctl_io *)ctsio);
7053         return (CTL_RETVAL_COMPLETE);
7054 }
7055
7056 int
7057 ctl_read_defect(struct ctl_scsiio *ctsio)
7058 {
7059         struct scsi_read_defect_data_10 *ccb10;
7060         struct scsi_read_defect_data_12 *ccb12;
7061         struct scsi_read_defect_data_hdr_10 *data10;
7062         struct scsi_read_defect_data_hdr_12 *data12;
7063         uint32_t alloc_len, data_len;
7064         uint8_t format;
7065
7066         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7067
7068         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7069                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7070                 format = ccb10->format;
7071                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7072                 data_len = sizeof(*data10);
7073         } else {
7074                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7075                 format = ccb12->format;
7076                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7077                 data_len = sizeof(*data12);
7078         }
7079         if (alloc_len == 0) {
7080                 ctl_set_success(ctsio);
7081                 ctl_done((union ctl_io *)ctsio);
7082                 return (CTL_RETVAL_COMPLETE);
7083         }
7084
7085         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7086         if (data_len < alloc_len) {
7087                 ctsio->residual = alloc_len - data_len;
7088                 ctsio->kern_data_len = data_len;
7089                 ctsio->kern_total_len = data_len;
7090         } else {
7091                 ctsio->residual = 0;
7092                 ctsio->kern_data_len = alloc_len;
7093                 ctsio->kern_total_len = alloc_len;
7094         }
7095         ctsio->kern_data_resid = 0;
7096         ctsio->kern_rel_offset = 0;
7097         ctsio->kern_sg_entries = 0;
7098
7099         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7100                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7101                     ctsio->kern_data_ptr;
7102                 data10->format = format;
7103                 scsi_ulto2b(0, data10->length);
7104         } else {
7105                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7106                     ctsio->kern_data_ptr;
7107                 data12->format = format;
7108                 scsi_ulto2b(0, data12->generation);
7109                 scsi_ulto4b(0, data12->length);
7110         }
7111
7112         ctl_set_success(ctsio);
7113         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7114         ctsio->be_move_done = ctl_config_move_done;
7115         ctl_datamove((union ctl_io *)ctsio);
7116         return (CTL_RETVAL_COMPLETE);
7117 }
7118
7119 int
7120 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7121 {
7122         struct scsi_maintenance_in *cdb;
7123         int retval;
7124         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7125         int num_ha_groups, num_target_ports, shared_group;
7126         struct ctl_lun *lun;
7127         struct ctl_softc *softc;
7128         struct ctl_port *port;
7129         struct scsi_target_group_data *rtg_ptr;
7130         struct scsi_target_group_data_extended *rtg_ext_ptr;
7131         struct scsi_target_port_group_descriptor *tpg_desc;
7132
7133         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7134
7135         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7136         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7137         softc = lun->ctl_softc;
7138
7139         retval = CTL_RETVAL_COMPLETE;
7140
7141         switch (cdb->byte2 & STG_PDF_MASK) {
7142         case STG_PDF_LENGTH:
7143                 ext = 0;
7144                 break;
7145         case STG_PDF_EXTENDED:
7146                 ext = 1;
7147                 break;
7148         default:
7149                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7150                                       /*sks_valid*/ 1,
7151                                       /*command*/ 1,
7152                                       /*field*/ 2,
7153                                       /*bit_valid*/ 1,
7154                                       /*bit*/ 5);
7155                 ctl_done((union ctl_io *)ctsio);
7156                 return(retval);
7157         }
7158
7159         num_target_ports = 0;
7160         shared_group = (softc->is_single != 0);
7161         mtx_lock(&softc->ctl_lock);
7162         STAILQ_FOREACH(port, &softc->port_list, links) {
7163                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7164                         continue;
7165                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7166                         continue;
7167                 num_target_ports++;
7168                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7169                         shared_group = 1;
7170         }
7171         mtx_unlock(&softc->ctl_lock);
7172         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7173
7174         if (ext)
7175                 total_len = sizeof(struct scsi_target_group_data_extended);
7176         else
7177                 total_len = sizeof(struct scsi_target_group_data);
7178         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7179                 (shared_group + num_ha_groups) +
7180             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7181
7182         alloc_len = scsi_4btoul(cdb->length);
7183
7184         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7185
7186         ctsio->kern_sg_entries = 0;
7187
7188         if (total_len < alloc_len) {
7189                 ctsio->residual = alloc_len - total_len;
7190                 ctsio->kern_data_len = total_len;
7191                 ctsio->kern_total_len = total_len;
7192         } else {
7193                 ctsio->residual = 0;
7194                 ctsio->kern_data_len = alloc_len;
7195                 ctsio->kern_total_len = alloc_len;
7196         }
7197         ctsio->kern_data_resid = 0;
7198         ctsio->kern_rel_offset = 0;
7199
7200         if (ext) {
7201                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7202                     ctsio->kern_data_ptr;
7203                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7204                 rtg_ext_ptr->format_type = 0x10;
7205                 rtg_ext_ptr->implicit_transition_time = 0;
7206                 tpg_desc = &rtg_ext_ptr->groups[0];
7207         } else {
7208                 rtg_ptr = (struct scsi_target_group_data *)
7209                     ctsio->kern_data_ptr;
7210                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7211                 tpg_desc = &rtg_ptr->groups[0];
7212         }
7213
7214         mtx_lock(&softc->ctl_lock);
7215         pg = softc->port_min / softc->port_cnt;
7216         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7217                 /* Some shelf is known to be primary. */
7218                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7219                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7220                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7221                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7222                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7223                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7224                 else
7225                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7226                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7227                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7228                 } else {
7229                         ts = os;
7230                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7231                 }
7232         } else {
7233                 /* No known primary shelf. */
7234                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7235                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7236                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7237                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7238                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7239                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7240                 } else {
7241                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7242                 }
7243         }
7244         if (shared_group) {
7245                 tpg_desc->pref_state = ts;
7246                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7247                     TPG_U_SUP | TPG_T_SUP;
7248                 scsi_ulto2b(1, tpg_desc->target_port_group);
7249                 tpg_desc->status = TPG_IMPLICIT;
7250                 pc = 0;
7251                 STAILQ_FOREACH(port, &softc->port_list, links) {
7252                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7253                                 continue;
7254                         if (!softc->is_single &&
7255                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7256                                 continue;
7257                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7258                                 continue;
7259                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7260                             relative_target_port_identifier);
7261                         pc++;
7262                 }
7263                 tpg_desc->target_port_count = pc;
7264                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7265                     &tpg_desc->descriptors[pc];
7266         }
7267         for (g = 0; g < num_ha_groups; g++) {
7268                 tpg_desc->pref_state = (g == pg) ? ts : os;
7269                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7270                     TPG_U_SUP | TPG_T_SUP;
7271                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7272                 tpg_desc->status = TPG_IMPLICIT;
7273                 pc = 0;
7274                 STAILQ_FOREACH(port, &softc->port_list, links) {
7275                         if (port->targ_port < g * softc->port_cnt ||
7276                             port->targ_port >= (g + 1) * softc->port_cnt)
7277                                 continue;
7278                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7279                                 continue;
7280                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7281                                 continue;
7282                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7283                                 continue;
7284                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7285                             relative_target_port_identifier);
7286                         pc++;
7287                 }
7288                 tpg_desc->target_port_count = pc;
7289                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7290                     &tpg_desc->descriptors[pc];
7291         }
7292         mtx_unlock(&softc->ctl_lock);
7293
7294         ctl_set_success(ctsio);
7295         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7296         ctsio->be_move_done = ctl_config_move_done;
7297         ctl_datamove((union ctl_io *)ctsio);
7298         return(retval);
7299 }
7300
7301 int
7302 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7303 {
7304         struct ctl_lun *lun;
7305         struct scsi_report_supported_opcodes *cdb;
7306         const struct ctl_cmd_entry *entry, *sentry;
7307         struct scsi_report_supported_opcodes_all *all;
7308         struct scsi_report_supported_opcodes_descr *descr;
7309         struct scsi_report_supported_opcodes_one *one;
7310         int retval;
7311         int alloc_len, total_len;
7312         int opcode, service_action, i, j, num;
7313
7314         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7315
7316         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7317         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7318
7319         retval = CTL_RETVAL_COMPLETE;
7320
7321         opcode = cdb->requested_opcode;
7322         service_action = scsi_2btoul(cdb->requested_service_action);
7323         switch (cdb->options & RSO_OPTIONS_MASK) {
7324         case RSO_OPTIONS_ALL:
7325                 num = 0;
7326                 for (i = 0; i < 256; i++) {
7327                         entry = &ctl_cmd_table[i];
7328                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7329                                 for (j = 0; j < 32; j++) {
7330                                         sentry = &((const struct ctl_cmd_entry *)
7331                                             entry->execute)[j];
7332                                         if (ctl_cmd_applicable(
7333                                             lun->be_lun->lun_type, sentry))
7334                                                 num++;
7335                                 }
7336                         } else {
7337                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7338                                     entry))
7339                                         num++;
7340                         }
7341                 }
7342                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7343                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7344                 break;
7345         case RSO_OPTIONS_OC:
7346                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7347                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7348                                               /*sks_valid*/ 1,
7349                                               /*command*/ 1,
7350                                               /*field*/ 2,
7351                                               /*bit_valid*/ 1,
7352                                               /*bit*/ 2);
7353                         ctl_done((union ctl_io *)ctsio);
7354                         return (CTL_RETVAL_COMPLETE);
7355                 }
7356                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7357                 break;
7358         case RSO_OPTIONS_OC_SA:
7359                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7360                     service_action >= 32) {
7361                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7362                                               /*sks_valid*/ 1,
7363                                               /*command*/ 1,
7364                                               /*field*/ 2,
7365                                               /*bit_valid*/ 1,
7366                                               /*bit*/ 2);
7367                         ctl_done((union ctl_io *)ctsio);
7368                         return (CTL_RETVAL_COMPLETE);
7369                 }
7370                 /* FALLTHROUGH */
7371         case RSO_OPTIONS_OC_ASA:
7372                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7373                 break;
7374         default:
7375                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7376                                       /*sks_valid*/ 1,
7377                                       /*command*/ 1,
7378                                       /*field*/ 2,
7379                                       /*bit_valid*/ 1,
7380                                       /*bit*/ 2);
7381                 ctl_done((union ctl_io *)ctsio);
7382                 return (CTL_RETVAL_COMPLETE);
7383         }
7384
7385         alloc_len = scsi_4btoul(cdb->length);
7386
7387         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7388
7389         ctsio->kern_sg_entries = 0;
7390
7391         if (total_len < alloc_len) {
7392                 ctsio->residual = alloc_len - total_len;
7393                 ctsio->kern_data_len = total_len;
7394                 ctsio->kern_total_len = total_len;
7395         } else {
7396                 ctsio->residual = 0;
7397                 ctsio->kern_data_len = alloc_len;
7398                 ctsio->kern_total_len = alloc_len;
7399         }
7400         ctsio->kern_data_resid = 0;
7401         ctsio->kern_rel_offset = 0;
7402
7403         switch (cdb->options & RSO_OPTIONS_MASK) {
7404         case RSO_OPTIONS_ALL:
7405                 all = (struct scsi_report_supported_opcodes_all *)
7406                     ctsio->kern_data_ptr;
7407                 num = 0;
7408                 for (i = 0; i < 256; i++) {
7409                         entry = &ctl_cmd_table[i];
7410                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7411                                 for (j = 0; j < 32; j++) {
7412                                         sentry = &((const struct ctl_cmd_entry *)
7413                                             entry->execute)[j];
7414                                         if (!ctl_cmd_applicable(
7415                                             lun->be_lun->lun_type, sentry))
7416                                                 continue;
7417                                         descr = &all->descr[num++];
7418                                         descr->opcode = i;
7419                                         scsi_ulto2b(j, descr->service_action);
7420                                         descr->flags = RSO_SERVACTV;
7421                                         scsi_ulto2b(sentry->length,
7422                                             descr->cdb_length);
7423                                 }
7424                         } else {
7425                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7426                                     entry))
7427                                         continue;
7428                                 descr = &all->descr[num++];
7429                                 descr->opcode = i;
7430                                 scsi_ulto2b(0, descr->service_action);
7431                                 descr->flags = 0;
7432                                 scsi_ulto2b(entry->length, descr->cdb_length);
7433                         }
7434                 }
7435                 scsi_ulto4b(
7436                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7437                     all->length);
7438                 break;
7439         case RSO_OPTIONS_OC:
7440                 one = (struct scsi_report_supported_opcodes_one *)
7441                     ctsio->kern_data_ptr;
7442                 entry = &ctl_cmd_table[opcode];
7443                 goto fill_one;
7444         case RSO_OPTIONS_OC_SA:
7445                 one = (struct scsi_report_supported_opcodes_one *)
7446                     ctsio->kern_data_ptr;
7447                 entry = &ctl_cmd_table[opcode];
7448                 entry = &((const struct ctl_cmd_entry *)
7449                     entry->execute)[service_action];
7450 fill_one:
7451                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7452                         one->support = 3;
7453                         scsi_ulto2b(entry->length, one->cdb_length);
7454                         one->cdb_usage[0] = opcode;
7455                         memcpy(&one->cdb_usage[1], entry->usage,
7456                             entry->length - 1);
7457                 } else
7458                         one->support = 1;
7459                 break;
7460         case RSO_OPTIONS_OC_ASA:
7461                 one = (struct scsi_report_supported_opcodes_one *)
7462                     ctsio->kern_data_ptr;
7463                 entry = &ctl_cmd_table[opcode];
7464                 if (entry->flags & CTL_CMD_FLAG_SA5) {
7465                         entry = &((const struct ctl_cmd_entry *)
7466                             entry->execute)[service_action];
7467                 } else if (service_action != 0) {
7468                         one->support = 1;
7469                         break;
7470                 }
7471                 goto fill_one;
7472         }
7473
7474         ctl_set_success(ctsio);
7475         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7476         ctsio->be_move_done = ctl_config_move_done;
7477         ctl_datamove((union ctl_io *)ctsio);
7478         return(retval);
7479 }
7480
7481 int
7482 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7483 {
7484         struct scsi_report_supported_tmf *cdb;
7485         struct scsi_report_supported_tmf_ext_data *data;
7486         int retval;
7487         int alloc_len, total_len;
7488
7489         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7490
7491         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7492
7493         retval = CTL_RETVAL_COMPLETE;
7494
7495         if (cdb->options & RST_REPD)
7496                 total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7497         else
7498                 total_len = sizeof(struct scsi_report_supported_tmf_data);
7499         alloc_len = scsi_4btoul(cdb->length);
7500
7501         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7502
7503         ctsio->kern_sg_entries = 0;
7504
7505         if (total_len < alloc_len) {
7506                 ctsio->residual = alloc_len - total_len;
7507                 ctsio->kern_data_len = total_len;
7508                 ctsio->kern_total_len = total_len;
7509         } else {
7510                 ctsio->residual = 0;
7511                 ctsio->kern_data_len = alloc_len;
7512                 ctsio->kern_total_len = alloc_len;
7513         }
7514         ctsio->kern_data_resid = 0;
7515         ctsio->kern_rel_offset = 0;
7516
7517         data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7518         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7519             RST_TRS;
7520         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7521         data->length = total_len - 4;
7522
7523         ctl_set_success(ctsio);
7524         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7525         ctsio->be_move_done = ctl_config_move_done;
7526         ctl_datamove((union ctl_io *)ctsio);
7527         return (retval);
7528 }
7529
7530 int
7531 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7532 {
7533         struct scsi_report_timestamp *cdb;
7534         struct scsi_report_timestamp_data *data;
7535         struct timeval tv;
7536         int64_t timestamp;
7537         int retval;
7538         int alloc_len, total_len;
7539
7540         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7541
7542         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7543
7544         retval = CTL_RETVAL_COMPLETE;
7545
7546         total_len = sizeof(struct scsi_report_timestamp_data);
7547         alloc_len = scsi_4btoul(cdb->length);
7548
7549         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7550
7551         ctsio->kern_sg_entries = 0;
7552
7553         if (total_len < alloc_len) {
7554                 ctsio->residual = alloc_len - total_len;
7555                 ctsio->kern_data_len = total_len;
7556                 ctsio->kern_total_len = total_len;
7557         } else {
7558                 ctsio->residual = 0;
7559                 ctsio->kern_data_len = alloc_len;
7560                 ctsio->kern_total_len = alloc_len;
7561         }
7562         ctsio->kern_data_resid = 0;
7563         ctsio->kern_rel_offset = 0;
7564
7565         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7566         scsi_ulto2b(sizeof(*data) - 2, data->length);
7567         data->origin = RTS_ORIG_OUTSIDE;
7568         getmicrotime(&tv);
7569         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7570         scsi_ulto4b(timestamp >> 16, data->timestamp);
7571         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7572
7573         ctl_set_success(ctsio);
7574         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7575         ctsio->be_move_done = ctl_config_move_done;
7576         ctl_datamove((union ctl_io *)ctsio);
7577         return (retval);
7578 }
7579
7580 int
7581 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7582 {
7583         struct scsi_per_res_in *cdb;
7584         int alloc_len, total_len = 0;
7585         /* struct scsi_per_res_in_rsrv in_data; */
7586         struct ctl_lun *lun;
7587         struct ctl_softc *softc;
7588         uint64_t key;
7589
7590         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7591
7592         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7593
7594         alloc_len = scsi_2btoul(cdb->length);
7595
7596         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7597         softc = lun->ctl_softc;
7598
7599 retry:
7600         mtx_lock(&lun->lun_lock);
7601         switch (cdb->action) {
7602         case SPRI_RK: /* read keys */
7603                 total_len = sizeof(struct scsi_per_res_in_keys) +
7604                         lun->pr_key_count *
7605                         sizeof(struct scsi_per_res_key);
7606                 break;
7607         case SPRI_RR: /* read reservation */
7608                 if (lun->flags & CTL_LUN_PR_RESERVED)
7609                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7610                 else
7611                         total_len = sizeof(struct scsi_per_res_in_header);
7612                 break;
7613         case SPRI_RC: /* report capabilities */
7614                 total_len = sizeof(struct scsi_per_res_cap);
7615                 break;
7616         case SPRI_RS: /* read full status */
7617                 total_len = sizeof(struct scsi_per_res_in_header) +
7618                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7619                     lun->pr_key_count;
7620                 break;
7621         default:
7622                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7623         }
7624         mtx_unlock(&lun->lun_lock);
7625
7626         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7627
7628         if (total_len < alloc_len) {
7629                 ctsio->residual = alloc_len - total_len;
7630                 ctsio->kern_data_len = total_len;
7631                 ctsio->kern_total_len = total_len;
7632         } else {
7633                 ctsio->residual = 0;
7634                 ctsio->kern_data_len = alloc_len;
7635                 ctsio->kern_total_len = alloc_len;
7636         }
7637
7638         ctsio->kern_data_resid = 0;
7639         ctsio->kern_rel_offset = 0;
7640         ctsio->kern_sg_entries = 0;
7641
7642         mtx_lock(&lun->lun_lock);
7643         switch (cdb->action) {
7644         case SPRI_RK: { // read keys
7645         struct scsi_per_res_in_keys *res_keys;
7646                 int i, key_count;
7647
7648                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7649
7650                 /*
7651                  * We had to drop the lock to allocate our buffer, which
7652                  * leaves time for someone to come in with another
7653                  * persistent reservation.  (That is unlikely, though,
7654                  * since this should be the only persistent reservation
7655                  * command active right now.)
7656                  */
7657                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7658                     (lun->pr_key_count *
7659                      sizeof(struct scsi_per_res_key)))){
7660                         mtx_unlock(&lun->lun_lock);
7661                         free(ctsio->kern_data_ptr, M_CTL);
7662                         printf("%s: reservation length changed, retrying\n",
7663                                __func__);
7664                         goto retry;
7665                 }
7666
7667                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7668
7669                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7670                              lun->pr_key_count, res_keys->header.length);
7671
7672                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7673                         if ((key = ctl_get_prkey(lun, i)) == 0)
7674                                 continue;
7675
7676                         /*
7677                          * We used lun->pr_key_count to calculate the
7678                          * size to allocate.  If it turns out the number of
7679                          * initiators with the registered flag set is
7680                          * larger than that (i.e. they haven't been kept in
7681                          * sync), we've got a problem.
7682                          */
7683                         if (key_count >= lun->pr_key_count) {
7684                                 key_count++;
7685                                 continue;
7686                         }
7687                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7688                         key_count++;
7689                 }
7690                 break;
7691         }
7692         case SPRI_RR: { // read reservation
7693                 struct scsi_per_res_in_rsrv *res;
7694                 int tmp_len, header_only;
7695
7696                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7697
7698                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7699
7700                 if (lun->flags & CTL_LUN_PR_RESERVED)
7701                 {
7702                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7703                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7704                                     res->header.length);
7705                         header_only = 0;
7706                 } else {
7707                         tmp_len = sizeof(struct scsi_per_res_in_header);
7708                         scsi_ulto4b(0, res->header.length);
7709                         header_only = 1;
7710                 }
7711
7712                 /*
7713                  * We had to drop the lock to allocate our buffer, which
7714                  * leaves time for someone to come in with another
7715                  * persistent reservation.  (That is unlikely, though,
7716                  * since this should be the only persistent reservation
7717                  * command active right now.)
7718                  */
7719                 if (tmp_len != total_len) {
7720                         mtx_unlock(&lun->lun_lock);
7721                         free(ctsio->kern_data_ptr, M_CTL);
7722                         printf("%s: reservation status changed, retrying\n",
7723                                __func__);
7724                         goto retry;
7725                 }
7726
7727                 /*
7728                  * No reservation held, so we're done.
7729                  */
7730                 if (header_only != 0)
7731                         break;
7732
7733                 /*
7734                  * If the registration is an All Registrants type, the key
7735                  * is 0, since it doesn't really matter.
7736                  */
7737                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7738                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7739                             res->data.reservation);
7740                 }
7741                 res->data.scopetype = lun->pr_res_type;
7742                 break;
7743         }
7744         case SPRI_RC:     //report capabilities
7745         {
7746                 struct scsi_per_res_cap *res_cap;
7747                 uint16_t type_mask;
7748
7749                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7750                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7751                 res_cap->flags1 = SPRI_CRH;
7752                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7753                 type_mask = SPRI_TM_WR_EX_AR |
7754                             SPRI_TM_EX_AC_RO |
7755                             SPRI_TM_WR_EX_RO |
7756                             SPRI_TM_EX_AC |
7757                             SPRI_TM_WR_EX |
7758                             SPRI_TM_EX_AC_AR;
7759                 scsi_ulto2b(type_mask, res_cap->type_mask);
7760                 break;
7761         }
7762         case SPRI_RS: { // read full status
7763                 struct scsi_per_res_in_full *res_status;
7764                 struct scsi_per_res_in_full_desc *res_desc;
7765                 struct ctl_port *port;
7766                 int i, len;
7767
7768                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7769
7770                 /*
7771                  * We had to drop the lock to allocate our buffer, which
7772                  * leaves time for someone to come in with another
7773                  * persistent reservation.  (That is unlikely, though,
7774                  * since this should be the only persistent reservation
7775                  * command active right now.)
7776                  */
7777                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7778                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7779                      lun->pr_key_count)){
7780                         mtx_unlock(&lun->lun_lock);
7781                         free(ctsio->kern_data_ptr, M_CTL);
7782                         printf("%s: reservation length changed, retrying\n",
7783                                __func__);
7784                         goto retry;
7785                 }
7786
7787                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7788
7789                 res_desc = &res_status->desc[0];
7790                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7791                         if ((key = ctl_get_prkey(lun, i)) == 0)
7792                                 continue;
7793
7794                         scsi_u64to8b(key, res_desc->res_key.key);
7795                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7796                             (lun->pr_res_idx == i ||
7797                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7798                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7799                                 res_desc->scopetype = lun->pr_res_type;
7800                         }
7801                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7802                             res_desc->rel_trgt_port_id);
7803                         len = 0;
7804                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7805                         if (port != NULL)
7806                                 len = ctl_create_iid(port,
7807                                     i % CTL_MAX_INIT_PER_PORT,
7808                                     res_desc->transport_id);
7809                         scsi_ulto4b(len, res_desc->additional_length);
7810                         res_desc = (struct scsi_per_res_in_full_desc *)
7811                             &res_desc->transport_id[len];
7812                 }
7813                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7814                     res_status->header.length);
7815                 break;
7816         }
7817         default:
7818                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7819         }
7820         mtx_unlock(&lun->lun_lock);
7821
7822         ctl_set_success(ctsio);
7823         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7824         ctsio->be_move_done = ctl_config_move_done;
7825         ctl_datamove((union ctl_io *)ctsio);
7826         return (CTL_RETVAL_COMPLETE);
7827 }
7828
7829 /*
7830  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7831  * it should return.
7832  */
7833 static int
7834 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7835                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7836                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7837                 struct scsi_per_res_out_parms* param)
7838 {
7839         union ctl_ha_msg persis_io;
7840         int i;
7841
7842         mtx_lock(&lun->lun_lock);
7843         if (sa_res_key == 0) {
7844                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7845                         /* validate scope and type */
7846                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7847                              SPR_LU_SCOPE) {
7848                                 mtx_unlock(&lun->lun_lock);
7849                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7850                                                       /*sks_valid*/ 1,
7851                                                       /*command*/ 1,
7852                                                       /*field*/ 2,
7853                                                       /*bit_valid*/ 1,
7854                                                       /*bit*/ 4);
7855                                 ctl_done((union ctl_io *)ctsio);
7856                                 return (1);
7857                         }
7858
7859                         if (type>8 || type==2 || type==4 || type==0) {
7860                                 mtx_unlock(&lun->lun_lock);
7861                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7862                                                       /*sks_valid*/ 1,
7863                                                       /*command*/ 1,
7864                                                       /*field*/ 2,
7865                                                       /*bit_valid*/ 1,
7866                                                       /*bit*/ 0);
7867                                 ctl_done((union ctl_io *)ctsio);
7868                                 return (1);
7869                         }
7870
7871                         /*
7872                          * Unregister everybody else and build UA for
7873                          * them
7874                          */
7875                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7876                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7877                                         continue;
7878
7879                                 ctl_clr_prkey(lun, i);
7880                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7881                         }
7882                         lun->pr_key_count = 1;
7883                         lun->pr_res_type = type;
7884                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7885                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7886                                 lun->pr_res_idx = residx;
7887                         lun->pr_generation++;
7888                         mtx_unlock(&lun->lun_lock);
7889
7890                         /* send msg to other side */
7891                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7892                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7893                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7894                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7895                         persis_io.pr.pr_info.res_type = type;
7896                         memcpy(persis_io.pr.pr_info.sa_res_key,
7897                                param->serv_act_res_key,
7898                                sizeof(param->serv_act_res_key));
7899                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7900                             sizeof(persis_io.pr), M_WAITOK);
7901                 } else {
7902                         /* not all registrants */
7903                         mtx_unlock(&lun->lun_lock);
7904                         free(ctsio->kern_data_ptr, M_CTL);
7905                         ctl_set_invalid_field(ctsio,
7906                                               /*sks_valid*/ 1,
7907                                               /*command*/ 0,
7908                                               /*field*/ 8,
7909                                               /*bit_valid*/ 0,
7910                                               /*bit*/ 0);
7911                         ctl_done((union ctl_io *)ctsio);
7912                         return (1);
7913                 }
7914         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7915                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7916                 int found = 0;
7917
7918                 if (res_key == sa_res_key) {
7919                         /* special case */
7920                         /*
7921                          * The spec implies this is not good but doesn't
7922                          * say what to do. There are two choices either
7923                          * generate a res conflict or check condition
7924                          * with illegal field in parameter data. Since
7925                          * that is what is done when the sa_res_key is
7926                          * zero I'll take that approach since this has
7927                          * to do with the sa_res_key.
7928                          */
7929                         mtx_unlock(&lun->lun_lock);
7930                         free(ctsio->kern_data_ptr, M_CTL);
7931                         ctl_set_invalid_field(ctsio,
7932                                               /*sks_valid*/ 1,
7933                                               /*command*/ 0,
7934                                               /*field*/ 8,
7935                                               /*bit_valid*/ 0,
7936                                               /*bit*/ 0);
7937                         ctl_done((union ctl_io *)ctsio);
7938                         return (1);
7939                 }
7940
7941                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7942                         if (ctl_get_prkey(lun, i) != sa_res_key)
7943                                 continue;
7944
7945                         found = 1;
7946                         ctl_clr_prkey(lun, i);
7947                         lun->pr_key_count--;
7948                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7949                 }
7950                 if (!found) {
7951                         mtx_unlock(&lun->lun_lock);
7952                         free(ctsio->kern_data_ptr, M_CTL);
7953                         ctl_set_reservation_conflict(ctsio);
7954                         ctl_done((union ctl_io *)ctsio);
7955                         return (CTL_RETVAL_COMPLETE);
7956                 }
7957                 lun->pr_generation++;
7958                 mtx_unlock(&lun->lun_lock);
7959
7960                 /* send msg to other side */
7961                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7962                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7963                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7964                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7965                 persis_io.pr.pr_info.res_type = type;
7966                 memcpy(persis_io.pr.pr_info.sa_res_key,
7967                        param->serv_act_res_key,
7968                        sizeof(param->serv_act_res_key));
7969                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7970                     sizeof(persis_io.pr), M_WAITOK);
7971         } else {
7972                 /* Reserved but not all registrants */
7973                 /* sa_res_key is res holder */
7974                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7975                         /* validate scope and type */
7976                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7977                              SPR_LU_SCOPE) {
7978                                 mtx_unlock(&lun->lun_lock);
7979                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7980                                                       /*sks_valid*/ 1,
7981                                                       /*command*/ 1,
7982                                                       /*field*/ 2,
7983                                                       /*bit_valid*/ 1,
7984                                                       /*bit*/ 4);
7985                                 ctl_done((union ctl_io *)ctsio);
7986                                 return (1);
7987                         }
7988
7989                         if (type>8 || type==2 || type==4 || type==0) {
7990                                 mtx_unlock(&lun->lun_lock);
7991                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7992                                                       /*sks_valid*/ 1,
7993                                                       /*command*/ 1,
7994                                                       /*field*/ 2,
7995                                                       /*bit_valid*/ 1,
7996                                                       /*bit*/ 0);
7997                                 ctl_done((union ctl_io *)ctsio);
7998                                 return (1);
7999                         }
8000
8001                         /*
8002                          * Do the following:
8003                          * if sa_res_key != res_key remove all
8004                          * registrants w/sa_res_key and generate UA
8005                          * for these registrants(Registrations
8006                          * Preempted) if it wasn't an exclusive
8007                          * reservation generate UA(Reservations
8008                          * Preempted) for all other registered nexuses
8009                          * if the type has changed. Establish the new
8010                          * reservation and holder. If res_key and
8011                          * sa_res_key are the same do the above
8012                          * except don't unregister the res holder.
8013                          */
8014
8015                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8016                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8017                                         continue;
8018
8019                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8020                                         ctl_clr_prkey(lun, i);
8021                                         lun->pr_key_count--;
8022                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8023                                 } else if (type != lun->pr_res_type &&
8024                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8025                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8026                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8027                                 }
8028                         }
8029                         lun->pr_res_type = type;
8030                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8031                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8032                                 lun->pr_res_idx = residx;
8033                         else
8034                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8035                         lun->pr_generation++;
8036                         mtx_unlock(&lun->lun_lock);
8037
8038                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8039                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8040                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8041                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8042                         persis_io.pr.pr_info.res_type = type;
8043                         memcpy(persis_io.pr.pr_info.sa_res_key,
8044                                param->serv_act_res_key,
8045                                sizeof(param->serv_act_res_key));
8046                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8047                             sizeof(persis_io.pr), M_WAITOK);
8048                 } else {
8049                         /*
8050                          * sa_res_key is not the res holder just
8051                          * remove registrants
8052                          */
8053                         int found=0;
8054
8055                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8056                                 if (sa_res_key != ctl_get_prkey(lun, i))
8057                                         continue;
8058
8059                                 found = 1;
8060                                 ctl_clr_prkey(lun, i);
8061                                 lun->pr_key_count--;
8062                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8063                         }
8064
8065                         if (!found) {
8066                                 mtx_unlock(&lun->lun_lock);
8067                                 free(ctsio->kern_data_ptr, M_CTL);
8068                                 ctl_set_reservation_conflict(ctsio);
8069                                 ctl_done((union ctl_io *)ctsio);
8070                                 return (1);
8071                         }
8072                         lun->pr_generation++;
8073                         mtx_unlock(&lun->lun_lock);
8074
8075                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8076                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8077                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8078                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8079                         persis_io.pr.pr_info.res_type = type;
8080                         memcpy(persis_io.pr.pr_info.sa_res_key,
8081                                param->serv_act_res_key,
8082                                sizeof(param->serv_act_res_key));
8083                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8084                             sizeof(persis_io.pr), M_WAITOK);
8085                 }
8086         }
8087         return (0);
8088 }
8089
8090 static void
8091 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8092 {
8093         uint64_t sa_res_key;
8094         int i;
8095
8096         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8097
8098         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8099          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8100          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8101                 if (sa_res_key == 0) {
8102                         /*
8103                          * Unregister everybody else and build UA for
8104                          * them
8105                          */
8106                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8107                                 if (i == msg->pr.pr_info.residx ||
8108                                     ctl_get_prkey(lun, i) == 0)
8109                                         continue;
8110
8111                                 ctl_clr_prkey(lun, i);
8112                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8113                         }
8114
8115                         lun->pr_key_count = 1;
8116                         lun->pr_res_type = msg->pr.pr_info.res_type;
8117                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8118                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8119                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8120                 } else {
8121                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8122                                 if (sa_res_key == ctl_get_prkey(lun, i))
8123                                         continue;
8124
8125                                 ctl_clr_prkey(lun, i);
8126                                 lun->pr_key_count--;
8127                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8128                         }
8129                 }
8130         } else {
8131                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8132                         if (i == msg->pr.pr_info.residx ||
8133                             ctl_get_prkey(lun, i) == 0)
8134                                 continue;
8135
8136                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8137                                 ctl_clr_prkey(lun, i);
8138                                 lun->pr_key_count--;
8139                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8140                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8141                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8142                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8143                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8144                         }
8145                 }
8146                 lun->pr_res_type = msg->pr.pr_info.res_type;
8147                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8148                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8149                         lun->pr_res_idx = msg->pr.pr_info.residx;
8150                 else
8151                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8152         }
8153         lun->pr_generation++;
8154
8155 }
8156
8157
8158 int
8159 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8160 {
8161         int retval;
8162         u_int32_t param_len;
8163         struct scsi_per_res_out *cdb;
8164         struct ctl_lun *lun;
8165         struct scsi_per_res_out_parms* param;
8166         struct ctl_softc *softc;
8167         uint32_t residx;
8168         uint64_t res_key, sa_res_key, key;
8169         uint8_t type;
8170         union ctl_ha_msg persis_io;
8171         int    i;
8172
8173         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8174
8175         retval = CTL_RETVAL_COMPLETE;
8176
8177         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8178         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8179         softc = lun->ctl_softc;
8180
8181         /*
8182          * We only support whole-LUN scope.  The scope & type are ignored for
8183          * register, register and ignore existing key and clear.
8184          * We sometimes ignore scope and type on preempts too!!
8185          * Verify reservation type here as well.
8186          */
8187         type = cdb->scope_type & SPR_TYPE_MASK;
8188         if ((cdb->action == SPRO_RESERVE)
8189          || (cdb->action == SPRO_RELEASE)) {
8190                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8191                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8192                                               /*sks_valid*/ 1,
8193                                               /*command*/ 1,
8194                                               /*field*/ 2,
8195                                               /*bit_valid*/ 1,
8196                                               /*bit*/ 4);
8197                         ctl_done((union ctl_io *)ctsio);
8198                         return (CTL_RETVAL_COMPLETE);
8199                 }
8200
8201                 if (type>8 || type==2 || type==4 || type==0) {
8202                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8203                                               /*sks_valid*/ 1,
8204                                               /*command*/ 1,
8205                                               /*field*/ 2,
8206                                               /*bit_valid*/ 1,
8207                                               /*bit*/ 0);
8208                         ctl_done((union ctl_io *)ctsio);
8209                         return (CTL_RETVAL_COMPLETE);
8210                 }
8211         }
8212
8213         param_len = scsi_4btoul(cdb->length);
8214
8215         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8216                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8217                 ctsio->kern_data_len = param_len;
8218                 ctsio->kern_total_len = param_len;
8219                 ctsio->kern_data_resid = 0;
8220                 ctsio->kern_rel_offset = 0;
8221                 ctsio->kern_sg_entries = 0;
8222                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8223                 ctsio->be_move_done = ctl_config_move_done;
8224                 ctl_datamove((union ctl_io *)ctsio);
8225
8226                 return (CTL_RETVAL_COMPLETE);
8227         }
8228
8229         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8230
8231         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8232         res_key = scsi_8btou64(param->res_key.key);
8233         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8234
8235         /*
8236          * Validate the reservation key here except for SPRO_REG_IGNO
8237          * This must be done for all other service actions
8238          */
8239         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8240                 mtx_lock(&lun->lun_lock);
8241                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8242                         if (res_key != key) {
8243                                 /*
8244                                  * The current key passed in doesn't match
8245                                  * the one the initiator previously
8246                                  * registered.
8247                                  */
8248                                 mtx_unlock(&lun->lun_lock);
8249                                 free(ctsio->kern_data_ptr, M_CTL);
8250                                 ctl_set_reservation_conflict(ctsio);
8251                                 ctl_done((union ctl_io *)ctsio);
8252                                 return (CTL_RETVAL_COMPLETE);
8253                         }
8254                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8255                         /*
8256                          * We are not registered
8257                          */
8258                         mtx_unlock(&lun->lun_lock);
8259                         free(ctsio->kern_data_ptr, M_CTL);
8260                         ctl_set_reservation_conflict(ctsio);
8261                         ctl_done((union ctl_io *)ctsio);
8262                         return (CTL_RETVAL_COMPLETE);
8263                 } else if (res_key != 0) {
8264                         /*
8265                          * We are not registered and trying to register but
8266                          * the register key isn't zero.
8267                          */
8268                         mtx_unlock(&lun->lun_lock);
8269                         free(ctsio->kern_data_ptr, M_CTL);
8270                         ctl_set_reservation_conflict(ctsio);
8271                         ctl_done((union ctl_io *)ctsio);
8272                         return (CTL_RETVAL_COMPLETE);
8273                 }
8274                 mtx_unlock(&lun->lun_lock);
8275         }
8276
8277         switch (cdb->action & SPRO_ACTION_MASK) {
8278         case SPRO_REGISTER:
8279         case SPRO_REG_IGNO: {
8280
8281 #if 0
8282                 printf("Registration received\n");
8283 #endif
8284
8285                 /*
8286                  * We don't support any of these options, as we report in
8287                  * the read capabilities request (see
8288                  * ctl_persistent_reserve_in(), above).
8289                  */
8290                 if ((param->flags & SPR_SPEC_I_PT)
8291                  || (param->flags & SPR_ALL_TG_PT)
8292                  || (param->flags & SPR_APTPL)) {
8293                         int bit_ptr;
8294
8295                         if (param->flags & SPR_APTPL)
8296                                 bit_ptr = 0;
8297                         else if (param->flags & SPR_ALL_TG_PT)
8298                                 bit_ptr = 2;
8299                         else /* SPR_SPEC_I_PT */
8300                                 bit_ptr = 3;
8301
8302                         free(ctsio->kern_data_ptr, M_CTL);
8303                         ctl_set_invalid_field(ctsio,
8304                                               /*sks_valid*/ 1,
8305                                               /*command*/ 0,
8306                                               /*field*/ 20,
8307                                               /*bit_valid*/ 1,
8308                                               /*bit*/ bit_ptr);
8309                         ctl_done((union ctl_io *)ctsio);
8310                         return (CTL_RETVAL_COMPLETE);
8311                 }
8312
8313                 mtx_lock(&lun->lun_lock);
8314
8315                 /*
8316                  * The initiator wants to clear the
8317                  * key/unregister.
8318                  */
8319                 if (sa_res_key == 0) {
8320                         if ((res_key == 0
8321                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8322                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8323                           && ctl_get_prkey(lun, residx) == 0)) {
8324                                 mtx_unlock(&lun->lun_lock);
8325                                 goto done;
8326                         }
8327
8328                         ctl_clr_prkey(lun, residx);
8329                         lun->pr_key_count--;
8330
8331                         if (residx == lun->pr_res_idx) {
8332                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8333                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8334
8335                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8336                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8337                                     lun->pr_key_count) {
8338                                         /*
8339                                          * If the reservation is a registrants
8340                                          * only type we need to generate a UA
8341                                          * for other registered inits.  The
8342                                          * sense code should be RESERVATIONS
8343                                          * RELEASED
8344                                          */
8345
8346                                         for (i = softc->init_min; i < softc->init_max; i++){
8347                                                 if (ctl_get_prkey(lun, i) == 0)
8348                                                         continue;
8349                                                 ctl_est_ua(lun, i,
8350                                                     CTL_UA_RES_RELEASE);
8351                                         }
8352                                 }
8353                                 lun->pr_res_type = 0;
8354                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8355                                 if (lun->pr_key_count==0) {
8356                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8357                                         lun->pr_res_type = 0;
8358                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8359                                 }
8360                         }
8361                         lun->pr_generation++;
8362                         mtx_unlock(&lun->lun_lock);
8363
8364                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8365                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8366                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8367                         persis_io.pr.pr_info.residx = residx;
8368                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8369                             sizeof(persis_io.pr), M_WAITOK);
8370                 } else /* sa_res_key != 0 */ {
8371
8372                         /*
8373                          * If we aren't registered currently then increment
8374                          * the key count and set the registered flag.
8375                          */
8376                         ctl_alloc_prkey(lun, residx);
8377                         if (ctl_get_prkey(lun, residx) == 0)
8378                                 lun->pr_key_count++;
8379                         ctl_set_prkey(lun, residx, sa_res_key);
8380                         lun->pr_generation++;
8381                         mtx_unlock(&lun->lun_lock);
8382
8383                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8384                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8385                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8386                         persis_io.pr.pr_info.residx = residx;
8387                         memcpy(persis_io.pr.pr_info.sa_res_key,
8388                                param->serv_act_res_key,
8389                                sizeof(param->serv_act_res_key));
8390                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8391                             sizeof(persis_io.pr), M_WAITOK);
8392                 }
8393
8394                 break;
8395         }
8396         case SPRO_RESERVE:
8397 #if 0
8398                 printf("Reserve executed type %d\n", type);
8399 #endif
8400                 mtx_lock(&lun->lun_lock);
8401                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8402                         /*
8403                          * if this isn't the reservation holder and it's
8404                          * not a "all registrants" type or if the type is
8405                          * different then we have a conflict
8406                          */
8407                         if ((lun->pr_res_idx != residx
8408                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8409                          || lun->pr_res_type != type) {
8410                                 mtx_unlock(&lun->lun_lock);
8411                                 free(ctsio->kern_data_ptr, M_CTL);
8412                                 ctl_set_reservation_conflict(ctsio);
8413                                 ctl_done((union ctl_io *)ctsio);
8414                                 return (CTL_RETVAL_COMPLETE);
8415                         }
8416                         mtx_unlock(&lun->lun_lock);
8417                 } else /* create a reservation */ {
8418                         /*
8419                          * If it's not an "all registrants" type record
8420                          * reservation holder
8421                          */
8422                         if (type != SPR_TYPE_WR_EX_AR
8423                          && type != SPR_TYPE_EX_AC_AR)
8424                                 lun->pr_res_idx = residx; /* Res holder */
8425                         else
8426                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8427
8428                         lun->flags |= CTL_LUN_PR_RESERVED;
8429                         lun->pr_res_type = type;
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_RESERVE;
8437                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8438                         persis_io.pr.pr_info.res_type = type;
8439                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8440                             sizeof(persis_io.pr), M_WAITOK);
8441                 }
8442                 break;
8443
8444         case SPRO_RELEASE:
8445                 mtx_lock(&lun->lun_lock);
8446                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8447                         /* No reservation exists return good status */
8448                         mtx_unlock(&lun->lun_lock);
8449                         goto done;
8450                 }
8451                 /*
8452                  * Is this nexus a reservation holder?
8453                  */
8454                 if (lun->pr_res_idx != residx
8455                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8456                         /*
8457                          * not a res holder return good status but
8458                          * do nothing
8459                          */
8460                         mtx_unlock(&lun->lun_lock);
8461                         goto done;
8462                 }
8463
8464                 if (lun->pr_res_type != type) {
8465                         mtx_unlock(&lun->lun_lock);
8466                         free(ctsio->kern_data_ptr, M_CTL);
8467                         ctl_set_illegal_pr_release(ctsio);
8468                         ctl_done((union ctl_io *)ctsio);
8469                         return (CTL_RETVAL_COMPLETE);
8470                 }
8471
8472                 /* okay to release */
8473                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8474                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8475                 lun->pr_res_type = 0;
8476
8477                 /*
8478                  * If this isn't an exclusive access reservation and NUAR
8479                  * is not set, generate UA for all other registrants.
8480                  */
8481                 if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8482                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8483                         for (i = softc->init_min; i < softc->init_max; i++) {
8484                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8485                                         continue;
8486                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8487                         }
8488                 }
8489                 mtx_unlock(&lun->lun_lock);
8490
8491                 /* Send msg to other side */
8492                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8493                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8494                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8495                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8496                      sizeof(persis_io.pr), M_WAITOK);
8497                 break;
8498
8499         case SPRO_CLEAR:
8500                 /* send msg to other side */
8501
8502                 mtx_lock(&lun->lun_lock);
8503                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8504                 lun->pr_res_type = 0;
8505                 lun->pr_key_count = 0;
8506                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8507
8508                 ctl_clr_prkey(lun, residx);
8509                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8510                         if (ctl_get_prkey(lun, i) != 0) {
8511                                 ctl_clr_prkey(lun, i);
8512                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8513                         }
8514                 lun->pr_generation++;
8515                 mtx_unlock(&lun->lun_lock);
8516
8517                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8518                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8519                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8520                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8521                      sizeof(persis_io.pr), M_WAITOK);
8522                 break;
8523
8524         case SPRO_PREEMPT:
8525         case SPRO_PRE_ABO: {
8526                 int nretval;
8527
8528                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8529                                           residx, ctsio, cdb, param);
8530                 if (nretval != 0)
8531                         return (CTL_RETVAL_COMPLETE);
8532                 break;
8533         }
8534         default:
8535                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8536         }
8537
8538 done:
8539         free(ctsio->kern_data_ptr, M_CTL);
8540         ctl_set_success(ctsio);
8541         ctl_done((union ctl_io *)ctsio);
8542
8543         return (retval);
8544 }
8545
8546 /*
8547  * This routine is for handling a message from the other SC pertaining to
8548  * persistent reserve out. All the error checking will have been done
8549  * so only perorming the action need be done here to keep the two
8550  * in sync.
8551  */
8552 static void
8553 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8554 {
8555         struct ctl_softc *softc = control_softc;
8556         struct ctl_lun *lun;
8557         int i;
8558         uint32_t residx, targ_lun;
8559
8560         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8561         mtx_lock(&softc->ctl_lock);
8562         if (targ_lun >= CTL_MAX_LUNS ||
8563             (lun = softc->ctl_luns[targ_lun]) == NULL) {
8564                 mtx_unlock(&softc->ctl_lock);
8565                 return;
8566         }
8567         mtx_lock(&lun->lun_lock);
8568         mtx_unlock(&softc->ctl_lock);
8569         if (lun->flags & CTL_LUN_DISABLED) {
8570                 mtx_unlock(&lun->lun_lock);
8571                 return;
8572         }
8573         residx = ctl_get_initindex(&msg->hdr.nexus);
8574         switch(msg->pr.pr_info.action) {
8575         case CTL_PR_REG_KEY:
8576                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8577                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8578                         lun->pr_key_count++;
8579                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8580                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8581                 lun->pr_generation++;
8582                 break;
8583
8584         case CTL_PR_UNREG_KEY:
8585                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8586                 lun->pr_key_count--;
8587
8588                 /* XXX Need to see if the reservation has been released */
8589                 /* if so do we need to generate UA? */
8590                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8591                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8592                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8593
8594                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8595                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8596                             lun->pr_key_count) {
8597                                 /*
8598                                  * If the reservation is a registrants
8599                                  * only type we need to generate a UA
8600                                  * for other registered inits.  The
8601                                  * sense code should be RESERVATIONS
8602                                  * RELEASED
8603                                  */
8604
8605                                 for (i = softc->init_min; i < softc->init_max; i++) {
8606                                         if (ctl_get_prkey(lun, i) == 0)
8607                                                 continue;
8608
8609                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8610                                 }
8611                         }
8612                         lun->pr_res_type = 0;
8613                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8614                         if (lun->pr_key_count==0) {
8615                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8616                                 lun->pr_res_type = 0;
8617                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8618                         }
8619                 }
8620                 lun->pr_generation++;
8621                 break;
8622
8623         case CTL_PR_RESERVE:
8624                 lun->flags |= CTL_LUN_PR_RESERVED;
8625                 lun->pr_res_type = msg->pr.pr_info.res_type;
8626                 lun->pr_res_idx = msg->pr.pr_info.residx;
8627
8628                 break;
8629
8630         case CTL_PR_RELEASE:
8631                 /*
8632                  * If this isn't an exclusive access reservation and NUAR
8633                  * is not set, generate UA for all other registrants.
8634                  */
8635                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8636                     lun->pr_res_type != SPR_TYPE_WR_EX &&
8637                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8638                         for (i = softc->init_min; i < softc->init_max; i++)
8639                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8640                                         continue;
8641                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8642                 }
8643
8644                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8645                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8646                 lun->pr_res_type = 0;
8647                 break;
8648
8649         case CTL_PR_PREEMPT:
8650                 ctl_pro_preempt_other(lun, msg);
8651                 break;
8652         case CTL_PR_CLEAR:
8653                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8654                 lun->pr_res_type = 0;
8655                 lun->pr_key_count = 0;
8656                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8657
8658                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8659                         if (ctl_get_prkey(lun, i) == 0)
8660                                 continue;
8661                         ctl_clr_prkey(lun, i);
8662                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8663                 }
8664                 lun->pr_generation++;
8665                 break;
8666         }
8667
8668         mtx_unlock(&lun->lun_lock);
8669 }
8670
8671 int
8672 ctl_read_write(struct ctl_scsiio *ctsio)
8673 {
8674         struct ctl_lun *lun;
8675         struct ctl_lba_len_flags *lbalen;
8676         uint64_t lba;
8677         uint32_t num_blocks;
8678         int flags, retval;
8679         int isread;
8680
8681         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8682
8683         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8684
8685         flags = 0;
8686         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8687               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8688         switch (ctsio->cdb[0]) {
8689         case READ_6:
8690         case WRITE_6: {
8691                 struct scsi_rw_6 *cdb;
8692
8693                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8694
8695                 lba = scsi_3btoul(cdb->addr);
8696                 /* only 5 bits are valid in the most significant address byte */
8697                 lba &= 0x1fffff;
8698                 num_blocks = cdb->length;
8699                 /*
8700                  * This is correct according to SBC-2.
8701                  */
8702                 if (num_blocks == 0)
8703                         num_blocks = 256;
8704                 break;
8705         }
8706         case READ_10:
8707         case WRITE_10: {
8708                 struct scsi_rw_10 *cdb;
8709
8710                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8711                 if (cdb->byte2 & SRW10_FUA)
8712                         flags |= CTL_LLF_FUA;
8713                 if (cdb->byte2 & SRW10_DPO)
8714                         flags |= CTL_LLF_DPO;
8715                 lba = scsi_4btoul(cdb->addr);
8716                 num_blocks = scsi_2btoul(cdb->length);
8717                 break;
8718         }
8719         case WRITE_VERIFY_10: {
8720                 struct scsi_write_verify_10 *cdb;
8721
8722                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8723                 flags |= CTL_LLF_FUA;
8724                 if (cdb->byte2 & SWV_DPO)
8725                         flags |= CTL_LLF_DPO;
8726                 lba = scsi_4btoul(cdb->addr);
8727                 num_blocks = scsi_2btoul(cdb->length);
8728                 break;
8729         }
8730         case READ_12:
8731         case WRITE_12: {
8732                 struct scsi_rw_12 *cdb;
8733
8734                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8735                 if (cdb->byte2 & SRW12_FUA)
8736                         flags |= CTL_LLF_FUA;
8737                 if (cdb->byte2 & SRW12_DPO)
8738                         flags |= CTL_LLF_DPO;
8739                 lba = scsi_4btoul(cdb->addr);
8740                 num_blocks = scsi_4btoul(cdb->length);
8741                 break;
8742         }
8743         case WRITE_VERIFY_12: {
8744                 struct scsi_write_verify_12 *cdb;
8745
8746                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8747                 flags |= CTL_LLF_FUA;
8748                 if (cdb->byte2 & SWV_DPO)
8749                         flags |= CTL_LLF_DPO;
8750                 lba = scsi_4btoul(cdb->addr);
8751                 num_blocks = scsi_4btoul(cdb->length);
8752                 break;
8753         }
8754         case READ_16:
8755         case WRITE_16: {
8756                 struct scsi_rw_16 *cdb;
8757
8758                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8759                 if (cdb->byte2 & SRW12_FUA)
8760                         flags |= CTL_LLF_FUA;
8761                 if (cdb->byte2 & SRW12_DPO)
8762                         flags |= CTL_LLF_DPO;
8763                 lba = scsi_8btou64(cdb->addr);
8764                 num_blocks = scsi_4btoul(cdb->length);
8765                 break;
8766         }
8767         case WRITE_ATOMIC_16: {
8768                 struct scsi_write_atomic_16 *cdb;
8769
8770                 if (lun->be_lun->atomicblock == 0) {
8771                         ctl_set_invalid_opcode(ctsio);
8772                         ctl_done((union ctl_io *)ctsio);
8773                         return (CTL_RETVAL_COMPLETE);
8774                 }
8775
8776                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8777                 if (cdb->byte2 & SRW12_FUA)
8778                         flags |= CTL_LLF_FUA;
8779                 if (cdb->byte2 & SRW12_DPO)
8780                         flags |= CTL_LLF_DPO;
8781                 lba = scsi_8btou64(cdb->addr);
8782                 num_blocks = scsi_2btoul(cdb->length);
8783                 if (num_blocks > lun->be_lun->atomicblock) {
8784                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8785                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8786                             /*bit*/ 0);
8787                         ctl_done((union ctl_io *)ctsio);
8788                         return (CTL_RETVAL_COMPLETE);
8789                 }
8790                 break;
8791         }
8792         case WRITE_VERIFY_16: {
8793                 struct scsi_write_verify_16 *cdb;
8794
8795                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8796                 flags |= CTL_LLF_FUA;
8797                 if (cdb->byte2 & SWV_DPO)
8798                         flags |= CTL_LLF_DPO;
8799                 lba = scsi_8btou64(cdb->addr);
8800                 num_blocks = scsi_4btoul(cdb->length);
8801                 break;
8802         }
8803         default:
8804                 /*
8805                  * We got a command we don't support.  This shouldn't
8806                  * happen, commands should be filtered out above us.
8807                  */
8808                 ctl_set_invalid_opcode(ctsio);
8809                 ctl_done((union ctl_io *)ctsio);
8810
8811                 return (CTL_RETVAL_COMPLETE);
8812                 break; /* NOTREACHED */
8813         }
8814
8815         /*
8816          * The first check is to make sure we're in bounds, the second
8817          * check is to catch wrap-around problems.  If the lba + num blocks
8818          * is less than the lba, then we've wrapped around and the block
8819          * range is invalid anyway.
8820          */
8821         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8822          || ((lba + num_blocks) < lba)) {
8823                 ctl_set_lba_out_of_range(ctsio,
8824                     MAX(lba, lun->be_lun->maxlba + 1));
8825                 ctl_done((union ctl_io *)ctsio);
8826                 return (CTL_RETVAL_COMPLETE);
8827         }
8828
8829         /*
8830          * According to SBC-3, a transfer length of 0 is not an error.
8831          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8832          * translates to 256 blocks for those commands.
8833          */
8834         if (num_blocks == 0) {
8835                 ctl_set_success(ctsio);
8836                 ctl_done((union ctl_io *)ctsio);
8837                 return (CTL_RETVAL_COMPLETE);
8838         }
8839
8840         /* Set FUA and/or DPO if caches are disabled. */
8841         if (isread) {
8842                 if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8843                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8844         } else {
8845                 if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8846                         flags |= CTL_LLF_FUA;
8847         }
8848
8849         lbalen = (struct ctl_lba_len_flags *)
8850             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8851         lbalen->lba = lba;
8852         lbalen->len = num_blocks;
8853         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8854
8855         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8856         ctsio->kern_rel_offset = 0;
8857
8858         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8859
8860         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8861         return (retval);
8862 }
8863
8864 static int
8865 ctl_cnw_cont(union ctl_io *io)
8866 {
8867         struct ctl_scsiio *ctsio;
8868         struct ctl_lun *lun;
8869         struct ctl_lba_len_flags *lbalen;
8870         int retval;
8871
8872         ctsio = &io->scsiio;
8873         ctsio->io_hdr.status = CTL_STATUS_NONE;
8874         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8875         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8876         lbalen = (struct ctl_lba_len_flags *)
8877             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8878         lbalen->flags &= ~CTL_LLF_COMPARE;
8879         lbalen->flags |= CTL_LLF_WRITE;
8880
8881         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8882         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8883         return (retval);
8884 }
8885
8886 int
8887 ctl_cnw(struct ctl_scsiio *ctsio)
8888 {
8889         struct ctl_lun *lun;
8890         struct ctl_lba_len_flags *lbalen;
8891         uint64_t lba;
8892         uint32_t num_blocks;
8893         int flags, retval;
8894
8895         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8896
8897         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8898
8899         flags = 0;
8900         switch (ctsio->cdb[0]) {
8901         case COMPARE_AND_WRITE: {
8902                 struct scsi_compare_and_write *cdb;
8903
8904                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8905                 if (cdb->byte2 & SRW10_FUA)
8906                         flags |= CTL_LLF_FUA;
8907                 if (cdb->byte2 & SRW10_DPO)
8908                         flags |= CTL_LLF_DPO;
8909                 lba = scsi_8btou64(cdb->addr);
8910                 num_blocks = cdb->length;
8911                 break;
8912         }
8913         default:
8914                 /*
8915                  * We got a command we don't support.  This shouldn't
8916                  * happen, commands should be filtered out above us.
8917                  */
8918                 ctl_set_invalid_opcode(ctsio);
8919                 ctl_done((union ctl_io *)ctsio);
8920
8921                 return (CTL_RETVAL_COMPLETE);
8922                 break; /* NOTREACHED */
8923         }
8924
8925         /*
8926          * The first check is to make sure we're in bounds, the second
8927          * check is to catch wrap-around problems.  If the lba + num blocks
8928          * is less than the lba, then we've wrapped around and the block
8929          * range is invalid anyway.
8930          */
8931         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8932          || ((lba + num_blocks) < lba)) {
8933                 ctl_set_lba_out_of_range(ctsio,
8934                     MAX(lba, lun->be_lun->maxlba + 1));
8935                 ctl_done((union ctl_io *)ctsio);
8936                 return (CTL_RETVAL_COMPLETE);
8937         }
8938
8939         /*
8940          * According to SBC-3, a transfer length of 0 is not an error.
8941          */
8942         if (num_blocks == 0) {
8943                 ctl_set_success(ctsio);
8944                 ctl_done((union ctl_io *)ctsio);
8945                 return (CTL_RETVAL_COMPLETE);
8946         }
8947
8948         /* Set FUA if write cache is disabled. */
8949         if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8950                 flags |= CTL_LLF_FUA;
8951
8952         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8953         ctsio->kern_rel_offset = 0;
8954
8955         /*
8956          * Set the IO_CONT flag, so that if this I/O gets passed to
8957          * ctl_data_submit_done(), it'll get passed back to
8958          * ctl_ctl_cnw_cont() for further processing.
8959          */
8960         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8961         ctsio->io_cont = ctl_cnw_cont;
8962
8963         lbalen = (struct ctl_lba_len_flags *)
8964             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8965         lbalen->lba = lba;
8966         lbalen->len = num_blocks;
8967         lbalen->flags = CTL_LLF_COMPARE | flags;
8968
8969         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8970         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8971         return (retval);
8972 }
8973
8974 int
8975 ctl_verify(struct ctl_scsiio *ctsio)
8976 {
8977         struct ctl_lun *lun;
8978         struct ctl_lba_len_flags *lbalen;
8979         uint64_t lba;
8980         uint32_t num_blocks;
8981         int bytchk, flags;
8982         int retval;
8983
8984         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8985
8986         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8987
8988         bytchk = 0;
8989         flags = CTL_LLF_FUA;
8990         switch (ctsio->cdb[0]) {
8991         case VERIFY_10: {
8992                 struct scsi_verify_10 *cdb;
8993
8994                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8995                 if (cdb->byte2 & SVFY_BYTCHK)
8996                         bytchk = 1;
8997                 if (cdb->byte2 & SVFY_DPO)
8998                         flags |= CTL_LLF_DPO;
8999                 lba = scsi_4btoul(cdb->addr);
9000                 num_blocks = scsi_2btoul(cdb->length);
9001                 break;
9002         }
9003         case VERIFY_12: {
9004                 struct scsi_verify_12 *cdb;
9005
9006                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9007                 if (cdb->byte2 & SVFY_BYTCHK)
9008                         bytchk = 1;
9009                 if (cdb->byte2 & SVFY_DPO)
9010                         flags |= CTL_LLF_DPO;
9011                 lba = scsi_4btoul(cdb->addr);
9012                 num_blocks = scsi_4btoul(cdb->length);
9013                 break;
9014         }
9015         case VERIFY_16: {
9016                 struct scsi_rw_16 *cdb;
9017
9018                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9019                 if (cdb->byte2 & SVFY_BYTCHK)
9020                         bytchk = 1;
9021                 if (cdb->byte2 & SVFY_DPO)
9022                         flags |= CTL_LLF_DPO;
9023                 lba = scsi_8btou64(cdb->addr);
9024                 num_blocks = scsi_4btoul(cdb->length);
9025                 break;
9026         }
9027         default:
9028                 /*
9029                  * We got a command we don't support.  This shouldn't
9030                  * happen, commands should be filtered out above us.
9031                  */
9032                 ctl_set_invalid_opcode(ctsio);
9033                 ctl_done((union ctl_io *)ctsio);
9034                 return (CTL_RETVAL_COMPLETE);
9035         }
9036
9037         /*
9038          * The first check is to make sure we're in bounds, the second
9039          * check is to catch wrap-around problems.  If the lba + num blocks
9040          * is less than the lba, then we've wrapped around and the block
9041          * range is invalid anyway.
9042          */
9043         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9044          || ((lba + num_blocks) < lba)) {
9045                 ctl_set_lba_out_of_range(ctsio,
9046                     MAX(lba, lun->be_lun->maxlba + 1));
9047                 ctl_done((union ctl_io *)ctsio);
9048                 return (CTL_RETVAL_COMPLETE);
9049         }
9050
9051         /*
9052          * According to SBC-3, a transfer length of 0 is not an error.
9053          */
9054         if (num_blocks == 0) {
9055                 ctl_set_success(ctsio);
9056                 ctl_done((union ctl_io *)ctsio);
9057                 return (CTL_RETVAL_COMPLETE);
9058         }
9059
9060         lbalen = (struct ctl_lba_len_flags *)
9061             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9062         lbalen->lba = lba;
9063         lbalen->len = num_blocks;
9064         if (bytchk) {
9065                 lbalen->flags = CTL_LLF_COMPARE | flags;
9066                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9067         } else {
9068                 lbalen->flags = CTL_LLF_VERIFY | flags;
9069                 ctsio->kern_total_len = 0;
9070         }
9071         ctsio->kern_rel_offset = 0;
9072
9073         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9074         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9075         return (retval);
9076 }
9077
9078 int
9079 ctl_report_luns(struct ctl_scsiio *ctsio)
9080 {
9081         struct ctl_softc *softc;
9082         struct scsi_report_luns *cdb;
9083         struct scsi_report_luns_data *lun_data;
9084         struct ctl_lun *lun, *request_lun;
9085         struct ctl_port *port;
9086         int num_filled, num_luns, num_port_luns, retval;
9087         uint32_t alloc_len, lun_datalen;
9088         uint32_t initidx, targ_lun_id, lun_id;
9089
9090         retval = CTL_RETVAL_COMPLETE;
9091         cdb = (struct scsi_report_luns *)ctsio->cdb;
9092         port = ctl_io_port(&ctsio->io_hdr);
9093         softc = port->ctl_softc;
9094
9095         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9096
9097         num_luns = 0;
9098         num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9099         mtx_lock(&softc->ctl_lock);
9100         for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9101                 if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9102                         num_luns++;
9103         }
9104         mtx_unlock(&softc->ctl_lock);
9105
9106         switch (cdb->select_report) {
9107         case RPL_REPORT_DEFAULT:
9108         case RPL_REPORT_ALL:
9109         case RPL_REPORT_NONSUBSID:
9110                 break;
9111         case RPL_REPORT_WELLKNOWN:
9112         case RPL_REPORT_ADMIN:
9113         case RPL_REPORT_CONGLOM:
9114                 num_luns = 0;
9115                 break;
9116         default:
9117                 ctl_set_invalid_field(ctsio,
9118                                       /*sks_valid*/ 1,
9119                                       /*command*/ 1,
9120                                       /*field*/ 2,
9121                                       /*bit_valid*/ 0,
9122                                       /*bit*/ 0);
9123                 ctl_done((union ctl_io *)ctsio);
9124                 return (retval);
9125                 break; /* NOTREACHED */
9126         }
9127
9128         alloc_len = scsi_4btoul(cdb->length);
9129         /*
9130          * The initiator has to allocate at least 16 bytes for this request,
9131          * so he can at least get the header and the first LUN.  Otherwise
9132          * we reject the request (per SPC-3 rev 14, section 6.21).
9133          */
9134         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9135             sizeof(struct scsi_report_luns_lundata))) {
9136                 ctl_set_invalid_field(ctsio,
9137                                       /*sks_valid*/ 1,
9138                                       /*command*/ 1,
9139                                       /*field*/ 6,
9140                                       /*bit_valid*/ 0,
9141                                       /*bit*/ 0);
9142                 ctl_done((union ctl_io *)ctsio);
9143                 return (retval);
9144         }
9145
9146         request_lun = (struct ctl_lun *)
9147                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9148
9149         lun_datalen = sizeof(*lun_data) +
9150                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9151
9152         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9153         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9154         ctsio->kern_sg_entries = 0;
9155
9156         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9157
9158         mtx_lock(&softc->ctl_lock);
9159         for (targ_lun_id = 0, num_filled = 0;
9160             targ_lun_id < num_port_luns && num_filled < num_luns;
9161             targ_lun_id++) {
9162                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9163                 if (lun_id == UINT32_MAX)
9164                         continue;
9165                 lun = softc->ctl_luns[lun_id];
9166                 if (lun == NULL)
9167                         continue;
9168
9169                 be64enc(lun_data->luns[num_filled++].lundata,
9170                     ctl_encode_lun(targ_lun_id));
9171
9172                 /*
9173                  * According to SPC-3, rev 14 section 6.21:
9174                  *
9175                  * "The execution of a REPORT LUNS command to any valid and
9176                  * installed logical unit shall clear the REPORTED LUNS DATA
9177                  * HAS CHANGED unit attention condition for all logical
9178                  * units of that target with respect to the requesting
9179                  * initiator. A valid and installed logical unit is one
9180                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9181                  * INQUIRY data (see 6.4.2)."
9182                  *
9183                  * If request_lun is NULL, the LUN this report luns command
9184                  * was issued to is either disabled or doesn't exist. In that
9185                  * case, we shouldn't clear any pending lun change unit
9186                  * attention.
9187                  */
9188                 if (request_lun != NULL) {
9189                         mtx_lock(&lun->lun_lock);
9190                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9191                         mtx_unlock(&lun->lun_lock);
9192                 }
9193         }
9194         mtx_unlock(&softc->ctl_lock);
9195
9196         /*
9197          * It's quite possible that we've returned fewer LUNs than we allocated
9198          * space for.  Trim it.
9199          */
9200         lun_datalen = sizeof(*lun_data) +
9201                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9202
9203         if (lun_datalen < alloc_len) {
9204                 ctsio->residual = alloc_len - lun_datalen;
9205                 ctsio->kern_data_len = lun_datalen;
9206                 ctsio->kern_total_len = lun_datalen;
9207         } else {
9208                 ctsio->residual = 0;
9209                 ctsio->kern_data_len = alloc_len;
9210                 ctsio->kern_total_len = alloc_len;
9211         }
9212         ctsio->kern_data_resid = 0;
9213         ctsio->kern_rel_offset = 0;
9214         ctsio->kern_sg_entries = 0;
9215
9216         /*
9217          * We set this to the actual data length, regardless of how much
9218          * space we actually have to return results.  If the user looks at
9219          * this value, he'll know whether or not he allocated enough space
9220          * and reissue the command if necessary.  We don't support well
9221          * known logical units, so if the user asks for that, return none.
9222          */
9223         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9224
9225         /*
9226          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9227          * this request.
9228          */
9229         ctl_set_success(ctsio);
9230         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9231         ctsio->be_move_done = ctl_config_move_done;
9232         ctl_datamove((union ctl_io *)ctsio);
9233         return (retval);
9234 }
9235
9236 int
9237 ctl_request_sense(struct ctl_scsiio *ctsio)
9238 {
9239         struct scsi_request_sense *cdb;
9240         struct scsi_sense_data *sense_ptr;
9241         struct ctl_softc *softc;
9242         struct ctl_lun *lun;
9243         uint32_t initidx;
9244         int have_error;
9245         u_int sense_len = SSD_FULL_SIZE;
9246         scsi_sense_data_type sense_format;
9247         ctl_ua_type ua_type;
9248         uint8_t asc = 0, ascq = 0;
9249
9250         cdb = (struct scsi_request_sense *)ctsio->cdb;
9251
9252         softc = control_softc;
9253         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9254
9255         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9256
9257         /*
9258          * Determine which sense format the user wants.
9259          */
9260         if (cdb->byte2 & SRS_DESC)
9261                 sense_format = SSD_TYPE_DESC;
9262         else
9263                 sense_format = SSD_TYPE_FIXED;
9264
9265         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9266         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9267         ctsio->kern_sg_entries = 0;
9268
9269         /*
9270          * struct scsi_sense_data, which is currently set to 256 bytes, is
9271          * larger than the largest allowed value for the length field in the
9272          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9273          */
9274         ctsio->residual = 0;
9275         ctsio->kern_data_len = cdb->length;
9276         ctsio->kern_total_len = cdb->length;
9277
9278         ctsio->kern_data_resid = 0;
9279         ctsio->kern_rel_offset = 0;
9280         ctsio->kern_sg_entries = 0;
9281
9282         /*
9283          * If we don't have a LUN, we don't have any pending sense.
9284          */
9285         if (lun == NULL ||
9286             ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9287              softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9288                 /* "Logical unit not supported" */
9289                 ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9290                     /*current_error*/ 1,
9291                     /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9292                     /*asc*/ 0x25,
9293                     /*ascq*/ 0x00,
9294                     SSD_ELEM_NONE);
9295                 goto send;
9296         }
9297
9298         have_error = 0;
9299         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9300         /*
9301          * Check for pending sense, and then for pending unit attentions.
9302          * Pending sense gets returned first, then pending unit attentions.
9303          */
9304         mtx_lock(&lun->lun_lock);
9305 #ifdef CTL_WITH_CA
9306         if (ctl_is_set(lun->have_ca, initidx)) {
9307                 scsi_sense_data_type stored_format;
9308
9309                 /*
9310                  * Check to see which sense format was used for the stored
9311                  * sense data.
9312                  */
9313                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9314
9315                 /*
9316                  * If the user requested a different sense format than the
9317                  * one we stored, then we need to convert it to the other
9318                  * format.  If we're going from descriptor to fixed format
9319                  * sense data, we may lose things in translation, depending
9320                  * on what options were used.
9321                  *
9322                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9323                  * for some reason we'll just copy it out as-is.
9324                  */
9325                 if ((stored_format == SSD_TYPE_FIXED)
9326                  && (sense_format == SSD_TYPE_DESC))
9327                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9328                             &lun->pending_sense[initidx],
9329                             (struct scsi_sense_data_desc *)sense_ptr);
9330                 else if ((stored_format == SSD_TYPE_DESC)
9331                       && (sense_format == SSD_TYPE_FIXED))
9332                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9333                             &lun->pending_sense[initidx],
9334                             (struct scsi_sense_data_fixed *)sense_ptr);
9335                 else
9336                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9337                                MIN(sizeof(*sense_ptr),
9338                                sizeof(lun->pending_sense[initidx])));
9339
9340                 ctl_clear_mask(lun->have_ca, initidx);
9341                 have_error = 1;
9342         } else
9343 #endif
9344         if (have_error == 0) {
9345                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9346                     sense_format);
9347                 if (ua_type != CTL_UA_NONE)
9348                         have_error = 1;
9349         }
9350         if (have_error == 0) {
9351                 /*
9352                  * Report informational exception if have one and allowed.
9353                  */
9354                 if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9355                         asc = lun->ie_asc;
9356                         ascq = lun->ie_ascq;
9357                 }
9358                 ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9359                     /*current_error*/ 1,
9360                     /*sense_key*/ SSD_KEY_NO_SENSE,
9361                     /*asc*/ asc,
9362                     /*ascq*/ ascq,
9363                     SSD_ELEM_NONE);
9364         }
9365         mtx_unlock(&lun->lun_lock);
9366
9367 send:
9368         /*
9369          * We report the SCSI status as OK, since the status of the command
9370          * itself is OK.  We're reporting sense as parameter data.
9371          */
9372         ctl_set_success(ctsio);
9373         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9374         ctsio->be_move_done = ctl_config_move_done;
9375         ctl_datamove((union ctl_io *)ctsio);
9376         return (CTL_RETVAL_COMPLETE);
9377 }
9378
9379 int
9380 ctl_tur(struct ctl_scsiio *ctsio)
9381 {
9382
9383         CTL_DEBUG_PRINT(("ctl_tur\n"));
9384
9385         ctl_set_success(ctsio);
9386         ctl_done((union ctl_io *)ctsio);
9387
9388         return (CTL_RETVAL_COMPLETE);
9389 }
9390
9391 /*
9392  * SCSI VPD page 0x00, the Supported VPD Pages page.
9393  */
9394 static int
9395 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9396 {
9397         struct scsi_vpd_supported_pages *pages;
9398         int sup_page_size;
9399         struct ctl_lun *lun;
9400         int p;
9401
9402         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9403
9404         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9405             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9406         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9407         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9408         ctsio->kern_sg_entries = 0;
9409
9410         if (sup_page_size < alloc_len) {
9411                 ctsio->residual = alloc_len - sup_page_size;
9412                 ctsio->kern_data_len = sup_page_size;
9413                 ctsio->kern_total_len = sup_page_size;
9414         } else {
9415                 ctsio->residual = 0;
9416                 ctsio->kern_data_len = alloc_len;
9417                 ctsio->kern_total_len = alloc_len;
9418         }
9419         ctsio->kern_data_resid = 0;
9420         ctsio->kern_rel_offset = 0;
9421         ctsio->kern_sg_entries = 0;
9422
9423         /*
9424          * The control device is always connected.  The disk device, on the
9425          * other hand, may not be online all the time.  Need to change this
9426          * to figure out whether the disk device is actually online or not.
9427          */
9428         if (lun != NULL)
9429                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9430                                 lun->be_lun->lun_type;
9431         else
9432                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9433
9434         p = 0;
9435         /* Supported VPD pages */
9436         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9437         /* Serial Number */
9438         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9439         /* Device Identification */
9440         pages->page_list[p++] = SVPD_DEVICE_ID;
9441         /* Extended INQUIRY Data */
9442         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9443         /* Mode Page Policy */
9444         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9445         /* SCSI Ports */
9446         pages->page_list[p++] = SVPD_SCSI_PORTS;
9447         /* Third-party Copy */
9448         pages->page_list[p++] = SVPD_SCSI_TPC;
9449         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9450                 /* Block limits */
9451                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9452                 /* Block Device Characteristics */
9453                 pages->page_list[p++] = SVPD_BDC;
9454                 /* Logical Block Provisioning */
9455                 pages->page_list[p++] = SVPD_LBP;
9456         }
9457         pages->length = p;
9458
9459         ctl_set_success(ctsio);
9460         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9461         ctsio->be_move_done = ctl_config_move_done;
9462         ctl_datamove((union ctl_io *)ctsio);
9463         return (CTL_RETVAL_COMPLETE);
9464 }
9465
9466 /*
9467  * SCSI VPD page 0x80, the Unit Serial Number page.
9468  */
9469 static int
9470 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9471 {
9472         struct scsi_vpd_unit_serial_number *sn_ptr;
9473         struct ctl_lun *lun;
9474         int data_len;
9475
9476         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9477
9478         data_len = 4 + CTL_SN_LEN;
9479         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9480         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9481         if (data_len < alloc_len) {
9482                 ctsio->residual = alloc_len - data_len;
9483                 ctsio->kern_data_len = data_len;
9484                 ctsio->kern_total_len = data_len;
9485         } else {
9486                 ctsio->residual = 0;
9487                 ctsio->kern_data_len = alloc_len;
9488                 ctsio->kern_total_len = alloc_len;
9489         }
9490         ctsio->kern_data_resid = 0;
9491         ctsio->kern_rel_offset = 0;
9492         ctsio->kern_sg_entries = 0;
9493
9494         /*
9495          * The control device is always connected.  The disk device, on the
9496          * other hand, may not be online all the time.  Need to change this
9497          * to figure out whether the disk device is actually online or not.
9498          */
9499         if (lun != NULL)
9500                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9501                                   lun->be_lun->lun_type;
9502         else
9503                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9504
9505         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9506         sn_ptr->length = CTL_SN_LEN;
9507         /*
9508          * If we don't have a LUN, we just leave the serial number as
9509          * all spaces.
9510          */
9511         if (lun != NULL) {
9512                 strncpy((char *)sn_ptr->serial_num,
9513                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9514         } else
9515                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9516
9517         ctl_set_success(ctsio);
9518         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9519         ctsio->be_move_done = ctl_config_move_done;
9520         ctl_datamove((union ctl_io *)ctsio);
9521         return (CTL_RETVAL_COMPLETE);
9522 }
9523
9524
9525 /*
9526  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9527  */
9528 static int
9529 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9530 {
9531         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9532         struct ctl_lun *lun;
9533         int data_len;
9534
9535         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9536
9537         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9538         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9539         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9540         ctsio->kern_sg_entries = 0;
9541
9542         if (data_len < alloc_len) {
9543                 ctsio->residual = alloc_len - data_len;
9544                 ctsio->kern_data_len = data_len;
9545                 ctsio->kern_total_len = data_len;
9546         } else {
9547                 ctsio->residual = 0;
9548                 ctsio->kern_data_len = alloc_len;
9549                 ctsio->kern_total_len = alloc_len;
9550         }
9551         ctsio->kern_data_resid = 0;
9552         ctsio->kern_rel_offset = 0;
9553         ctsio->kern_sg_entries = 0;
9554
9555         /*
9556          * The control device is always connected.  The disk device, on the
9557          * other hand, may not be online all the time.
9558          */
9559         if (lun != NULL)
9560                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9561                                      lun->be_lun->lun_type;
9562         else
9563                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9564         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9565         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9566         /*
9567          * We support head of queue, ordered and simple tags.
9568          */
9569         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9570         /*
9571          * Volatile cache supported.
9572          */
9573         eid_ptr->flags3 = SVPD_EID_V_SUP;
9574
9575         /*
9576          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9577          * attention for a particular IT nexus on all LUNs once we report
9578          * it to that nexus once.  This bit is required as of SPC-4.
9579          */
9580         eid_ptr->flags4 = SVPD_EID_LUICLR;
9581
9582         /*
9583          * We support revert to defaults (RTD) bit in MODE SELECT.
9584          */
9585         eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9586
9587         /*
9588          * XXX KDM in order to correctly answer this, we would need
9589          * information from the SIM to determine how much sense data it
9590          * can send.  So this would really be a path inquiry field, most
9591          * likely.  This can be set to a maximum of 252 according to SPC-4,
9592          * but the hardware may or may not be able to support that much.
9593          * 0 just means that the maximum sense data length is not reported.
9594          */
9595         eid_ptr->max_sense_length = 0;
9596
9597         ctl_set_success(ctsio);
9598         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9599         ctsio->be_move_done = ctl_config_move_done;
9600         ctl_datamove((union ctl_io *)ctsio);
9601         return (CTL_RETVAL_COMPLETE);
9602 }
9603
9604 static int
9605 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9606 {
9607         struct scsi_vpd_mode_page_policy *mpp_ptr;
9608         struct ctl_lun *lun;
9609         int data_len;
9610
9611         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9612
9613         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9614             sizeof(struct scsi_vpd_mode_page_policy_descr);
9615
9616         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9617         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9618         ctsio->kern_sg_entries = 0;
9619
9620         if (data_len < alloc_len) {
9621                 ctsio->residual = alloc_len - data_len;
9622                 ctsio->kern_data_len = data_len;
9623                 ctsio->kern_total_len = data_len;
9624         } else {
9625                 ctsio->residual = 0;
9626                 ctsio->kern_data_len = alloc_len;
9627                 ctsio->kern_total_len = alloc_len;
9628         }
9629         ctsio->kern_data_resid = 0;
9630         ctsio->kern_rel_offset = 0;
9631         ctsio->kern_sg_entries = 0;
9632
9633         /*
9634          * The control device is always connected.  The disk device, on the
9635          * other hand, may not be online all the time.
9636          */
9637         if (lun != NULL)
9638                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9639                                      lun->be_lun->lun_type;
9640         else
9641                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9642         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9643         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9644         mpp_ptr->descr[0].page_code = 0x3f;
9645         mpp_ptr->descr[0].subpage_code = 0xff;
9646         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9647
9648         ctl_set_success(ctsio);
9649         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9650         ctsio->be_move_done = ctl_config_move_done;
9651         ctl_datamove((union ctl_io *)ctsio);
9652         return (CTL_RETVAL_COMPLETE);
9653 }
9654
9655 /*
9656  * SCSI VPD page 0x83, the Device Identification page.
9657  */
9658 static int
9659 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9660 {
9661         struct scsi_vpd_device_id *devid_ptr;
9662         struct scsi_vpd_id_descriptor *desc;
9663         struct ctl_softc *softc;
9664         struct ctl_lun *lun;
9665         struct ctl_port *port;
9666         int data_len, g;
9667         uint8_t proto;
9668
9669         softc = control_softc;
9670
9671         port = ctl_io_port(&ctsio->io_hdr);
9672         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9673
9674         data_len = sizeof(struct scsi_vpd_device_id) +
9675             sizeof(struct scsi_vpd_id_descriptor) +
9676                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9677             sizeof(struct scsi_vpd_id_descriptor) +
9678                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9679         if (lun && lun->lun_devid)
9680                 data_len += lun->lun_devid->len;
9681         if (port && port->port_devid)
9682                 data_len += port->port_devid->len;
9683         if (port && port->target_devid)
9684                 data_len += port->target_devid->len;
9685
9686         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9687         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9688         ctsio->kern_sg_entries = 0;
9689
9690         if (data_len < alloc_len) {
9691                 ctsio->residual = alloc_len - data_len;
9692                 ctsio->kern_data_len = data_len;
9693                 ctsio->kern_total_len = data_len;
9694         } else {
9695                 ctsio->residual = 0;
9696                 ctsio->kern_data_len = alloc_len;
9697                 ctsio->kern_total_len = alloc_len;
9698         }
9699         ctsio->kern_data_resid = 0;
9700         ctsio->kern_rel_offset = 0;
9701         ctsio->kern_sg_entries = 0;
9702
9703         /*
9704          * The control device is always connected.  The disk device, on the
9705          * other hand, may not be online all the time.
9706          */
9707         if (lun != NULL)
9708                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9709                                      lun->be_lun->lun_type;
9710         else
9711                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9712         devid_ptr->page_code = SVPD_DEVICE_ID;
9713         scsi_ulto2b(data_len - 4, devid_ptr->length);
9714
9715         if (port && port->port_type == CTL_PORT_FC)
9716                 proto = SCSI_PROTO_FC << 4;
9717         else if (port && port->port_type == CTL_PORT_ISCSI)
9718                 proto = SCSI_PROTO_ISCSI << 4;
9719         else
9720                 proto = SCSI_PROTO_SPI << 4;
9721         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9722
9723         /*
9724          * We're using a LUN association here.  i.e., this device ID is a
9725          * per-LUN identifier.
9726          */
9727         if (lun && lun->lun_devid) {
9728                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9729                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9730                     lun->lun_devid->len);
9731         }
9732
9733         /*
9734          * This is for the WWPN which is a port association.
9735          */
9736         if (port && port->port_devid) {
9737                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9738                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9739                     port->port_devid->len);
9740         }
9741
9742         /*
9743          * This is for the Relative Target Port(type 4h) identifier
9744          */
9745         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9746         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9747             SVPD_ID_TYPE_RELTARG;
9748         desc->length = 4;
9749         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9750         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9751             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9752
9753         /*
9754          * This is for the Target Port Group(type 5h) identifier
9755          */
9756         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9757         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9758             SVPD_ID_TYPE_TPORTGRP;
9759         desc->length = 4;
9760         if (softc->is_single ||
9761             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9762                 g = 1;
9763         else
9764                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9765         scsi_ulto2b(g, &desc->identifier[2]);
9766         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9767             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9768
9769         /*
9770          * This is for the Target identifier
9771          */
9772         if (port && port->target_devid) {
9773                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9774         }
9775
9776         ctl_set_success(ctsio);
9777         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9778         ctsio->be_move_done = ctl_config_move_done;
9779         ctl_datamove((union ctl_io *)ctsio);
9780         return (CTL_RETVAL_COMPLETE);
9781 }
9782
9783 static int
9784 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9785 {
9786         struct ctl_softc *softc = control_softc;
9787         struct scsi_vpd_scsi_ports *sp;
9788         struct scsi_vpd_port_designation *pd;
9789         struct scsi_vpd_port_designation_cont *pdc;
9790         struct ctl_lun *lun;
9791         struct ctl_port *port;
9792         int data_len, num_target_ports, iid_len, id_len;
9793
9794         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9795
9796         num_target_ports = 0;
9797         iid_len = 0;
9798         id_len = 0;
9799         mtx_lock(&softc->ctl_lock);
9800         STAILQ_FOREACH(port, &softc->port_list, links) {
9801                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9802                         continue;
9803                 if (lun != NULL &&
9804                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9805                         continue;
9806                 num_target_ports++;
9807                 if (port->init_devid)
9808                         iid_len += port->init_devid->len;
9809                 if (port->port_devid)
9810                         id_len += port->port_devid->len;
9811         }
9812         mtx_unlock(&softc->ctl_lock);
9813
9814         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9815             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9816              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9817         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9818         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9819         ctsio->kern_sg_entries = 0;
9820
9821         if (data_len < alloc_len) {
9822                 ctsio->residual = alloc_len - data_len;
9823                 ctsio->kern_data_len = data_len;
9824                 ctsio->kern_total_len = data_len;
9825         } else {
9826                 ctsio->residual = 0;
9827                 ctsio->kern_data_len = alloc_len;
9828                 ctsio->kern_total_len = alloc_len;
9829         }
9830         ctsio->kern_data_resid = 0;
9831         ctsio->kern_rel_offset = 0;
9832         ctsio->kern_sg_entries = 0;
9833
9834         /*
9835          * The control device is always connected.  The disk device, on the
9836          * other hand, may not be online all the time.  Need to change this
9837          * to figure out whether the disk device is actually online or not.
9838          */
9839         if (lun != NULL)
9840                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9841                                   lun->be_lun->lun_type;
9842         else
9843                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9844
9845         sp->page_code = SVPD_SCSI_PORTS;
9846         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9847             sp->page_length);
9848         pd = &sp->design[0];
9849
9850         mtx_lock(&softc->ctl_lock);
9851         STAILQ_FOREACH(port, &softc->port_list, links) {
9852                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9853                         continue;
9854                 if (lun != NULL &&
9855                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9856                         continue;
9857                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9858                 if (port->init_devid) {
9859                         iid_len = port->init_devid->len;
9860                         memcpy(pd->initiator_transportid,
9861                             port->init_devid->data, port->init_devid->len);
9862                 } else
9863                         iid_len = 0;
9864                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9865                 pdc = (struct scsi_vpd_port_designation_cont *)
9866                     (&pd->initiator_transportid[iid_len]);
9867                 if (port->port_devid) {
9868                         id_len = port->port_devid->len;
9869                         memcpy(pdc->target_port_descriptors,
9870                             port->port_devid->data, port->port_devid->len);
9871                 } else
9872                         id_len = 0;
9873                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9874                 pd = (struct scsi_vpd_port_designation *)
9875                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9876         }
9877         mtx_unlock(&softc->ctl_lock);
9878
9879         ctl_set_success(ctsio);
9880         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9881         ctsio->be_move_done = ctl_config_move_done;
9882         ctl_datamove((union ctl_io *)ctsio);
9883         return (CTL_RETVAL_COMPLETE);
9884 }
9885
9886 static int
9887 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9888 {
9889         struct scsi_vpd_block_limits *bl_ptr;
9890         struct ctl_lun *lun;
9891         uint64_t ival;
9892
9893         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9894
9895         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9896         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9897         ctsio->kern_sg_entries = 0;
9898
9899         if (sizeof(*bl_ptr) < alloc_len) {
9900                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9901                 ctsio->kern_data_len = sizeof(*bl_ptr);
9902                 ctsio->kern_total_len = sizeof(*bl_ptr);
9903         } else {
9904                 ctsio->residual = 0;
9905                 ctsio->kern_data_len = alloc_len;
9906                 ctsio->kern_total_len = alloc_len;
9907         }
9908         ctsio->kern_data_resid = 0;
9909         ctsio->kern_rel_offset = 0;
9910         ctsio->kern_sg_entries = 0;
9911
9912         /*
9913          * The control device is always connected.  The disk device, on the
9914          * other hand, may not be online all the time.  Need to change this
9915          * to figure out whether the disk device is actually online or not.
9916          */
9917         if (lun != NULL)
9918                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9919                                   lun->be_lun->lun_type;
9920         else
9921                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9922
9923         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9924         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9925         bl_ptr->max_cmp_write_len = 0xff;
9926         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9927         if (lun != NULL) {
9928                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9929                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9930                         ival = 0xffffffff;
9931                         ctl_get_opt_number(&lun->be_lun->options,
9932                             "unmap_max_lba", &ival);
9933                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9934                         ival = 0xffffffff;
9935                         ctl_get_opt_number(&lun->be_lun->options,
9936                             "unmap_max_descr", &ival);
9937                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9938                         if (lun->be_lun->ublockexp != 0) {
9939                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9940                                     bl_ptr->opt_unmap_grain);
9941                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9942                                     bl_ptr->unmap_grain_align);
9943                         }
9944                 }
9945                 scsi_ulto4b(lun->be_lun->atomicblock,
9946                     bl_ptr->max_atomic_transfer_length);
9947                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9948                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9949                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9950                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9951                 ival = UINT64_MAX;
9952                 ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9953                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9954         }
9955
9956         ctl_set_success(ctsio);
9957         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9958         ctsio->be_move_done = ctl_config_move_done;
9959         ctl_datamove((union ctl_io *)ctsio);
9960         return (CTL_RETVAL_COMPLETE);
9961 }
9962
9963 static int
9964 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9965 {
9966         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9967         struct ctl_lun *lun;
9968         const char *value;
9969         u_int i;
9970
9971         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9972
9973         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9974         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9975         ctsio->kern_sg_entries = 0;
9976
9977         if (sizeof(*bdc_ptr) < alloc_len) {
9978                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9979                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9980                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9981         } else {
9982                 ctsio->residual = 0;
9983                 ctsio->kern_data_len = alloc_len;
9984                 ctsio->kern_total_len = alloc_len;
9985         }
9986         ctsio->kern_data_resid = 0;
9987         ctsio->kern_rel_offset = 0;
9988         ctsio->kern_sg_entries = 0;
9989
9990         /*
9991          * The control device is always connected.  The disk device, on the
9992          * other hand, may not be online all the time.  Need to change this
9993          * to figure out whether the disk device is actually online or not.
9994          */
9995         if (lun != NULL)
9996                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9997                                   lun->be_lun->lun_type;
9998         else
9999                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10000         bdc_ptr->page_code = SVPD_BDC;
10001         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10002         if (lun != NULL &&
10003             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10004                 i = strtol(value, NULL, 0);
10005         else
10006                 i = CTL_DEFAULT_ROTATION_RATE;
10007         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10008         if (lun != NULL &&
10009             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10010                 i = strtol(value, NULL, 0);
10011         else
10012                 i = 0;
10013         bdc_ptr->wab_wac_ff = (i & 0x0f);
10014         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10015
10016         ctl_set_success(ctsio);
10017         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10018         ctsio->be_move_done = ctl_config_move_done;
10019         ctl_datamove((union ctl_io *)ctsio);
10020         return (CTL_RETVAL_COMPLETE);
10021 }
10022
10023 static int
10024 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10025 {
10026         struct scsi_vpd_logical_block_prov *lbp_ptr;
10027         struct ctl_lun *lun;
10028         const char *value;
10029
10030         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10031
10032         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10033         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10034         ctsio->kern_sg_entries = 0;
10035
10036         if (sizeof(*lbp_ptr) < alloc_len) {
10037                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10038                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10039                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10040         } else {
10041                 ctsio->residual = 0;
10042                 ctsio->kern_data_len = alloc_len;
10043                 ctsio->kern_total_len = alloc_len;
10044         }
10045         ctsio->kern_data_resid = 0;
10046         ctsio->kern_rel_offset = 0;
10047         ctsio->kern_sg_entries = 0;
10048
10049         /*
10050          * The control device is always connected.  The disk device, on the
10051          * other hand, may not be online all the time.  Need to change this
10052          * to figure out whether the disk device is actually online or not.
10053          */
10054         if (lun != NULL)
10055                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10056                                   lun->be_lun->lun_type;
10057         else
10058                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10059
10060         lbp_ptr->page_code = SVPD_LBP;
10061         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10062         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10063         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10064                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10065                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10066                 value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10067                 if (value != NULL) {
10068                         if (strcmp(value, "resource") == 0)
10069                                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10070                         else if (strcmp(value, "thin") == 0)
10071                                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10072                 } else
10073                         lbp_ptr->prov_type = SVPD_LBP_THIN;
10074         }
10075
10076         ctl_set_success(ctsio);
10077         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10078         ctsio->be_move_done = ctl_config_move_done;
10079         ctl_datamove((union ctl_io *)ctsio);
10080         return (CTL_RETVAL_COMPLETE);
10081 }
10082
10083 /*
10084  * INQUIRY with the EVPD bit set.
10085  */
10086 static int
10087 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10088 {
10089         struct ctl_lun *lun;
10090         struct scsi_inquiry *cdb;
10091         int alloc_len, retval;
10092
10093         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10094         cdb = (struct scsi_inquiry *)ctsio->cdb;
10095         alloc_len = scsi_2btoul(cdb->length);
10096
10097         switch (cdb->page_code) {
10098         case SVPD_SUPPORTED_PAGES:
10099                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10100                 break;
10101         case SVPD_UNIT_SERIAL_NUMBER:
10102                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10103                 break;
10104         case SVPD_DEVICE_ID:
10105                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10106                 break;
10107         case SVPD_EXTENDED_INQUIRY_DATA:
10108                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10109                 break;
10110         case SVPD_MODE_PAGE_POLICY:
10111                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10112                 break;
10113         case SVPD_SCSI_PORTS:
10114                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10115                 break;
10116         case SVPD_SCSI_TPC:
10117                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10118                 break;
10119         case SVPD_BLOCK_LIMITS:
10120                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10121                         goto err;
10122                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10123                 break;
10124         case SVPD_BDC:
10125                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10126                         goto err;
10127                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10128                 break;
10129         case SVPD_LBP:
10130                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10131                         goto err;
10132                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10133                 break;
10134         default:
10135 err:
10136                 ctl_set_invalid_field(ctsio,
10137                                       /*sks_valid*/ 1,
10138                                       /*command*/ 1,
10139                                       /*field*/ 2,
10140                                       /*bit_valid*/ 0,
10141                                       /*bit*/ 0);
10142                 ctl_done((union ctl_io *)ctsio);
10143                 retval = CTL_RETVAL_COMPLETE;
10144                 break;
10145         }
10146
10147         return (retval);
10148 }
10149
10150 /*
10151  * Standard INQUIRY data.
10152  */
10153 static int
10154 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10155 {
10156         struct scsi_inquiry_data *inq_ptr;
10157         struct scsi_inquiry *cdb;
10158         struct ctl_softc *softc = control_softc;
10159         struct ctl_port *port;
10160         struct ctl_lun *lun;
10161         char *val;
10162         uint32_t alloc_len, data_len;
10163         ctl_port_type port_type;
10164
10165         port = ctl_io_port(&ctsio->io_hdr);
10166         port_type = port->port_type;
10167         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10168                 port_type = CTL_PORT_SCSI;
10169
10170         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10171         cdb = (struct scsi_inquiry *)ctsio->cdb;
10172         alloc_len = scsi_2btoul(cdb->length);
10173
10174         /*
10175          * We malloc the full inquiry data size here and fill it
10176          * in.  If the user only asks for less, we'll give him
10177          * that much.
10178          */
10179         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10180         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10181         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10182         ctsio->kern_sg_entries = 0;
10183         ctsio->kern_data_resid = 0;
10184         ctsio->kern_rel_offset = 0;
10185
10186         if (data_len < alloc_len) {
10187                 ctsio->residual = alloc_len - data_len;
10188                 ctsio->kern_data_len = data_len;
10189                 ctsio->kern_total_len = data_len;
10190         } else {
10191                 ctsio->residual = 0;
10192                 ctsio->kern_data_len = alloc_len;
10193                 ctsio->kern_total_len = alloc_len;
10194         }
10195
10196         if (lun != NULL) {
10197                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10198                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10199                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10200                             lun->be_lun->lun_type;
10201                 } else {
10202                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10203                             lun->be_lun->lun_type;
10204                 }
10205                 if (lun->flags & CTL_LUN_REMOVABLE)
10206                         inq_ptr->dev_qual2 |= SID_RMB;
10207         } else
10208                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10209
10210         /* RMB in byte 2 is 0 */
10211         inq_ptr->version = SCSI_REV_SPC5;
10212
10213         /*
10214          * According to SAM-3, even if a device only supports a single
10215          * level of LUN addressing, it should still set the HISUP bit:
10216          *
10217          * 4.9.1 Logical unit numbers overview
10218          *
10219          * All logical unit number formats described in this standard are
10220          * hierarchical in structure even when only a single level in that
10221          * hierarchy is used. The HISUP bit shall be set to one in the
10222          * standard INQUIRY data (see SPC-2) when any logical unit number
10223          * format described in this standard is used.  Non-hierarchical
10224          * formats are outside the scope of this standard.
10225          *
10226          * Therefore we set the HiSup bit here.
10227          *
10228          * The response format is 2, per SPC-3.
10229          */
10230         inq_ptr->response_format = SID_HiSup | 2;
10231
10232         inq_ptr->additional_length = data_len -
10233             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10234         CTL_DEBUG_PRINT(("additional_length = %d\n",
10235                          inq_ptr->additional_length));
10236
10237         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10238         if (port_type == CTL_PORT_SCSI)
10239                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10240         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10241         inq_ptr->flags = SID_CmdQue;
10242         if (port_type == CTL_PORT_SCSI)
10243                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10244
10245         /*
10246          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10247          * We have 8 bytes for the vendor name, and 16 bytes for the device
10248          * name and 4 bytes for the revision.
10249          */
10250         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10251             "vendor")) == NULL) {
10252                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10253         } else {
10254                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10255                 strncpy(inq_ptr->vendor, val,
10256                     min(sizeof(inq_ptr->vendor), strlen(val)));
10257         }
10258         if (lun == NULL) {
10259                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10260                     sizeof(inq_ptr->product));
10261         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10262                 switch (lun->be_lun->lun_type) {
10263                 case T_DIRECT:
10264                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10265                             sizeof(inq_ptr->product));
10266                         break;
10267                 case T_PROCESSOR:
10268                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10269                             sizeof(inq_ptr->product));
10270                         break;
10271                 case T_CDROM:
10272                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10273                             sizeof(inq_ptr->product));
10274                         break;
10275                 default:
10276                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10277                             sizeof(inq_ptr->product));
10278                         break;
10279                 }
10280         } else {
10281                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10282                 strncpy(inq_ptr->product, val,
10283                     min(sizeof(inq_ptr->product), strlen(val)));
10284         }
10285
10286         /*
10287          * XXX make this a macro somewhere so it automatically gets
10288          * incremented when we make changes.
10289          */
10290         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10291             "revision")) == NULL) {
10292                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10293         } else {
10294                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10295                 strncpy(inq_ptr->revision, val,
10296                     min(sizeof(inq_ptr->revision), strlen(val)));
10297         }
10298
10299         /*
10300          * For parallel SCSI, we support double transition and single
10301          * transition clocking.  We also support QAS (Quick Arbitration
10302          * and Selection) and Information Unit transfers on both the
10303          * control and array devices.
10304          */
10305         if (port_type == CTL_PORT_SCSI)
10306                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10307                                     SID_SPI_IUS;
10308
10309         /* SAM-6 (no version claimed) */
10310         scsi_ulto2b(0x00C0, inq_ptr->version1);
10311         /* SPC-5 (no version claimed) */
10312         scsi_ulto2b(0x05C0, inq_ptr->version2);
10313         if (port_type == CTL_PORT_FC) {
10314                 /* FCP-2 ANSI INCITS.350:2003 */
10315                 scsi_ulto2b(0x0917, inq_ptr->version3);
10316         } else if (port_type == CTL_PORT_SCSI) {
10317                 /* SPI-4 ANSI INCITS.362:200x */
10318                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10319         } else if (port_type == CTL_PORT_ISCSI) {
10320                 /* iSCSI (no version claimed) */
10321                 scsi_ulto2b(0x0960, inq_ptr->version3);
10322         } else if (port_type == CTL_PORT_SAS) {
10323                 /* SAS (no version claimed) */
10324                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10325         }
10326
10327         if (lun == NULL) {
10328                 /* SBC-4 (no version claimed) */
10329                 scsi_ulto2b(0x0600, inq_ptr->version4);
10330         } else {
10331                 switch (lun->be_lun->lun_type) {
10332                 case T_DIRECT:
10333                         /* SBC-4 (no version claimed) */
10334                         scsi_ulto2b(0x0600, inq_ptr->version4);
10335                         break;
10336                 case T_PROCESSOR:
10337                         break;
10338                 case T_CDROM:
10339                         /* MMC-6 (no version claimed) */
10340                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10341                         break;
10342                 default:
10343                         break;
10344                 }
10345         }
10346
10347         ctl_set_success(ctsio);
10348         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10349         ctsio->be_move_done = ctl_config_move_done;
10350         ctl_datamove((union ctl_io *)ctsio);
10351         return (CTL_RETVAL_COMPLETE);
10352 }
10353
10354 int
10355 ctl_inquiry(struct ctl_scsiio *ctsio)
10356 {
10357         struct scsi_inquiry *cdb;
10358         int retval;
10359
10360         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10361
10362         cdb = (struct scsi_inquiry *)ctsio->cdb;
10363         if (cdb->byte2 & SI_EVPD)
10364                 retval = ctl_inquiry_evpd(ctsio);
10365         else if (cdb->page_code == 0)
10366                 retval = ctl_inquiry_std(ctsio);
10367         else {
10368                 ctl_set_invalid_field(ctsio,
10369                                       /*sks_valid*/ 1,
10370                                       /*command*/ 1,
10371                                       /*field*/ 2,
10372                                       /*bit_valid*/ 0,
10373                                       /*bit*/ 0);
10374                 ctl_done((union ctl_io *)ctsio);
10375                 return (CTL_RETVAL_COMPLETE);
10376         }
10377
10378         return (retval);
10379 }
10380
10381 int
10382 ctl_get_config(struct ctl_scsiio *ctsio)
10383 {
10384         struct scsi_get_config_header *hdr;
10385         struct scsi_get_config_feature *feature;
10386         struct scsi_get_config *cdb;
10387         struct ctl_lun *lun;
10388         uint32_t alloc_len, data_len;
10389         int rt, starting;
10390
10391         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10392         cdb = (struct scsi_get_config *)ctsio->cdb;
10393         rt = (cdb->rt & SGC_RT_MASK);
10394         starting = scsi_2btoul(cdb->starting_feature);
10395         alloc_len = scsi_2btoul(cdb->length);
10396
10397         data_len = sizeof(struct scsi_get_config_header) +
10398             sizeof(struct scsi_get_config_feature) + 8 +
10399             sizeof(struct scsi_get_config_feature) + 8 +
10400             sizeof(struct scsi_get_config_feature) + 4 +
10401             sizeof(struct scsi_get_config_feature) + 4 +
10402             sizeof(struct scsi_get_config_feature) + 8 +
10403             sizeof(struct scsi_get_config_feature) +
10404             sizeof(struct scsi_get_config_feature) + 4 +
10405             sizeof(struct scsi_get_config_feature) + 4 +
10406             sizeof(struct scsi_get_config_feature) + 4 +
10407             sizeof(struct scsi_get_config_feature) + 4 +
10408             sizeof(struct scsi_get_config_feature) + 4 +
10409             sizeof(struct scsi_get_config_feature) + 4;
10410         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10411         ctsio->kern_sg_entries = 0;
10412         ctsio->kern_data_resid = 0;
10413         ctsio->kern_rel_offset = 0;
10414
10415         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10416         if (lun->flags & CTL_LUN_NO_MEDIA)
10417                 scsi_ulto2b(0x0000, hdr->current_profile);
10418         else
10419                 scsi_ulto2b(0x0010, hdr->current_profile);
10420         feature = (struct scsi_get_config_feature *)(hdr + 1);
10421
10422         if (starting > 0x003b)
10423                 goto done;
10424         if (starting > 0x003a)
10425                 goto f3b;
10426         if (starting > 0x002b)
10427                 goto f3a;
10428         if (starting > 0x002a)
10429                 goto f2b;
10430         if (starting > 0x001f)
10431                 goto f2a;
10432         if (starting > 0x001e)
10433                 goto f1f;
10434         if (starting > 0x001d)
10435                 goto f1e;
10436         if (starting > 0x0010)
10437                 goto f1d;
10438         if (starting > 0x0003)
10439                 goto f10;
10440         if (starting > 0x0002)
10441                 goto f3;
10442         if (starting > 0x0001)
10443                 goto f2;
10444         if (starting > 0x0000)
10445                 goto f1;
10446
10447         /* Profile List */
10448         scsi_ulto2b(0x0000, feature->feature_code);
10449         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10450         feature->add_length = 8;
10451         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10452         feature->feature_data[2] = 0x00;
10453         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10454         feature->feature_data[6] = 0x01;
10455         feature = (struct scsi_get_config_feature *)
10456             &feature->feature_data[feature->add_length];
10457
10458 f1:     /* Core */
10459         scsi_ulto2b(0x0001, feature->feature_code);
10460         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10461         feature->add_length = 8;
10462         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10463         feature->feature_data[4] = 0x03;
10464         feature = (struct scsi_get_config_feature *)
10465             &feature->feature_data[feature->add_length];
10466
10467 f2:     /* Morphing */
10468         scsi_ulto2b(0x0002, feature->feature_code);
10469         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10470         feature->add_length = 4;
10471         feature->feature_data[0] = 0x02;
10472         feature = (struct scsi_get_config_feature *)
10473             &feature->feature_data[feature->add_length];
10474
10475 f3:     /* Removable Medium */
10476         scsi_ulto2b(0x0003, feature->feature_code);
10477         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10478         feature->add_length = 4;
10479         feature->feature_data[0] = 0x39;
10480         feature = (struct scsi_get_config_feature *)
10481             &feature->feature_data[feature->add_length];
10482
10483         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10484                 goto done;
10485
10486 f10:    /* Random Read */
10487         scsi_ulto2b(0x0010, feature->feature_code);
10488         feature->flags = 0x00;
10489         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10490                 feature->flags |= SGC_F_CURRENT;
10491         feature->add_length = 8;
10492         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10493         scsi_ulto2b(1, &feature->feature_data[4]);
10494         feature->feature_data[6] = 0x00;
10495         feature = (struct scsi_get_config_feature *)
10496             &feature->feature_data[feature->add_length];
10497
10498 f1d:    /* Multi-Read */
10499         scsi_ulto2b(0x001D, feature->feature_code);
10500         feature->flags = 0x00;
10501         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10502                 feature->flags |= SGC_F_CURRENT;
10503         feature->add_length = 0;
10504         feature = (struct scsi_get_config_feature *)
10505             &feature->feature_data[feature->add_length];
10506
10507 f1e:    /* CD Read */
10508         scsi_ulto2b(0x001E, feature->feature_code);
10509         feature->flags = 0x00;
10510         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10511                 feature->flags |= SGC_F_CURRENT;
10512         feature->add_length = 4;
10513         feature->feature_data[0] = 0x00;
10514         feature = (struct scsi_get_config_feature *)
10515             &feature->feature_data[feature->add_length];
10516
10517 f1f:    /* DVD Read */
10518         scsi_ulto2b(0x001F, feature->feature_code);
10519         feature->flags = 0x08;
10520         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10521                 feature->flags |= SGC_F_CURRENT;
10522         feature->add_length = 4;
10523         feature->feature_data[0] = 0x01;
10524         feature->feature_data[2] = 0x03;
10525         feature = (struct scsi_get_config_feature *)
10526             &feature->feature_data[feature->add_length];
10527
10528 f2a:    /* DVD+RW */
10529         scsi_ulto2b(0x002A, feature->feature_code);
10530         feature->flags = 0x04;
10531         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10532                 feature->flags |= SGC_F_CURRENT;
10533         feature->add_length = 4;
10534         feature->feature_data[0] = 0x00;
10535         feature->feature_data[1] = 0x00;
10536         feature = (struct scsi_get_config_feature *)
10537             &feature->feature_data[feature->add_length];
10538
10539 f2b:    /* DVD+R */
10540         scsi_ulto2b(0x002B, feature->feature_code);
10541         feature->flags = 0x00;
10542         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10543                 feature->flags |= SGC_F_CURRENT;
10544         feature->add_length = 4;
10545         feature->feature_data[0] = 0x00;
10546         feature = (struct scsi_get_config_feature *)
10547             &feature->feature_data[feature->add_length];
10548
10549 f3a:    /* DVD+RW Dual Layer */
10550         scsi_ulto2b(0x003A, feature->feature_code);
10551         feature->flags = 0x00;
10552         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10553                 feature->flags |= SGC_F_CURRENT;
10554         feature->add_length = 4;
10555         feature->feature_data[0] = 0x00;
10556         feature->feature_data[1] = 0x00;
10557         feature = (struct scsi_get_config_feature *)
10558             &feature->feature_data[feature->add_length];
10559
10560 f3b:    /* DVD+R Dual Layer */
10561         scsi_ulto2b(0x003B, feature->feature_code);
10562         feature->flags = 0x00;
10563         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10564                 feature->flags |= SGC_F_CURRENT;
10565         feature->add_length = 4;
10566         feature->feature_data[0] = 0x00;
10567         feature = (struct scsi_get_config_feature *)
10568             &feature->feature_data[feature->add_length];
10569
10570 done:
10571         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10572         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10573                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10574                 if (scsi_2btoul(feature->feature_code) == starting)
10575                         feature = (struct scsi_get_config_feature *)
10576                             &feature->feature_data[feature->add_length];
10577                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10578         }
10579         scsi_ulto4b(data_len - 4, hdr->data_length);
10580         if (data_len < alloc_len) {
10581                 ctsio->residual = alloc_len - data_len;
10582                 ctsio->kern_data_len = data_len;
10583                 ctsio->kern_total_len = data_len;
10584         } else {
10585                 ctsio->residual = 0;
10586                 ctsio->kern_data_len = alloc_len;
10587                 ctsio->kern_total_len = alloc_len;
10588         }
10589
10590         ctl_set_success(ctsio);
10591         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10592         ctsio->be_move_done = ctl_config_move_done;
10593         ctl_datamove((union ctl_io *)ctsio);
10594         return (CTL_RETVAL_COMPLETE);
10595 }
10596
10597 int
10598 ctl_get_event_status(struct ctl_scsiio *ctsio)
10599 {
10600         struct scsi_get_event_status_header *hdr;
10601         struct scsi_get_event_status *cdb;
10602         struct ctl_lun *lun;
10603         uint32_t alloc_len, data_len;
10604         int notif_class;
10605
10606         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10607         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10608         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10609                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10610                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10611                 ctl_done((union ctl_io *)ctsio);
10612                 return (CTL_RETVAL_COMPLETE);
10613         }
10614         notif_class = cdb->notif_class;
10615         alloc_len = scsi_2btoul(cdb->length);
10616
10617         data_len = sizeof(struct scsi_get_event_status_header);
10618         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10619         ctsio->kern_sg_entries = 0;
10620         ctsio->kern_data_resid = 0;
10621         ctsio->kern_rel_offset = 0;
10622
10623         if (data_len < alloc_len) {
10624                 ctsio->residual = alloc_len - data_len;
10625                 ctsio->kern_data_len = data_len;
10626                 ctsio->kern_total_len = data_len;
10627         } else {
10628                 ctsio->residual = 0;
10629                 ctsio->kern_data_len = alloc_len;
10630                 ctsio->kern_total_len = alloc_len;
10631         }
10632
10633         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10634         scsi_ulto2b(0, hdr->descr_length);
10635         hdr->nea_class = SGESN_NEA;
10636         hdr->supported_class = 0;
10637
10638         ctl_set_success(ctsio);
10639         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10640         ctsio->be_move_done = ctl_config_move_done;
10641         ctl_datamove((union ctl_io *)ctsio);
10642         return (CTL_RETVAL_COMPLETE);
10643 }
10644
10645 int
10646 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10647 {
10648         struct scsi_mechanism_status_header *hdr;
10649         struct scsi_mechanism_status *cdb;
10650         struct ctl_lun *lun;
10651         uint32_t alloc_len, data_len;
10652
10653         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10654         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10655         alloc_len = scsi_2btoul(cdb->length);
10656
10657         data_len = sizeof(struct scsi_mechanism_status_header);
10658         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10659         ctsio->kern_sg_entries = 0;
10660         ctsio->kern_data_resid = 0;
10661         ctsio->kern_rel_offset = 0;
10662
10663         if (data_len < alloc_len) {
10664                 ctsio->residual = alloc_len - data_len;
10665                 ctsio->kern_data_len = data_len;
10666                 ctsio->kern_total_len = data_len;
10667         } else {
10668                 ctsio->residual = 0;
10669                 ctsio->kern_data_len = alloc_len;
10670                 ctsio->kern_total_len = alloc_len;
10671         }
10672
10673         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10674         hdr->state1 = 0x00;
10675         hdr->state2 = 0xe0;
10676         scsi_ulto3b(0, hdr->lba);
10677         hdr->slots_num = 0;
10678         scsi_ulto2b(0, hdr->slots_length);
10679
10680         ctl_set_success(ctsio);
10681         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10682         ctsio->be_move_done = ctl_config_move_done;
10683         ctl_datamove((union ctl_io *)ctsio);
10684         return (CTL_RETVAL_COMPLETE);
10685 }
10686
10687 static void
10688 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10689 {
10690
10691         lba += 150;
10692         buf[0] = 0;
10693         buf[1] = bin2bcd((lba / 75) / 60);
10694         buf[2] = bin2bcd((lba / 75) % 60);
10695         buf[3] = bin2bcd(lba % 75);
10696 }
10697
10698 int
10699 ctl_read_toc(struct ctl_scsiio *ctsio)
10700 {
10701         struct scsi_read_toc_hdr *hdr;
10702         struct scsi_read_toc_type01_descr *descr;
10703         struct scsi_read_toc *cdb;
10704         struct ctl_lun *lun;
10705         uint32_t alloc_len, data_len;
10706         int format, msf;
10707
10708         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10709         cdb = (struct scsi_read_toc *)ctsio->cdb;
10710         msf = (cdb->byte2 & CD_MSF) != 0;
10711         format = cdb->format;
10712         alloc_len = scsi_2btoul(cdb->data_len);
10713
10714         data_len = sizeof(struct scsi_read_toc_hdr);
10715         if (format == 0)
10716                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10717         else
10718                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10719         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10720         ctsio->kern_sg_entries = 0;
10721         ctsio->kern_data_resid = 0;
10722         ctsio->kern_rel_offset = 0;
10723
10724         if (data_len < alloc_len) {
10725                 ctsio->residual = alloc_len - data_len;
10726                 ctsio->kern_data_len = data_len;
10727                 ctsio->kern_total_len = data_len;
10728         } else {
10729                 ctsio->residual = 0;
10730                 ctsio->kern_data_len = alloc_len;
10731                 ctsio->kern_total_len = alloc_len;
10732         }
10733
10734         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10735         if (format == 0) {
10736                 scsi_ulto2b(0x12, hdr->data_length);
10737                 hdr->first = 1;
10738                 hdr->last = 1;
10739                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10740                 descr->addr_ctl = 0x14;
10741                 descr->track_number = 1;
10742                 if (msf)
10743                         ctl_ultomsf(0, descr->track_start);
10744                 else
10745                         scsi_ulto4b(0, descr->track_start);
10746                 descr++;
10747                 descr->addr_ctl = 0x14;
10748                 descr->track_number = 0xaa;
10749                 if (msf)
10750                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10751                 else
10752                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10753         } else {
10754                 scsi_ulto2b(0x0a, hdr->data_length);
10755                 hdr->first = 1;
10756                 hdr->last = 1;
10757                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10758                 descr->addr_ctl = 0x14;
10759                 descr->track_number = 1;
10760                 if (msf)
10761                         ctl_ultomsf(0, descr->track_start);
10762                 else
10763                         scsi_ulto4b(0, descr->track_start);
10764         }
10765
10766         ctl_set_success(ctsio);
10767         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10768         ctsio->be_move_done = ctl_config_move_done;
10769         ctl_datamove((union ctl_io *)ctsio);
10770         return (CTL_RETVAL_COMPLETE);
10771 }
10772
10773 /*
10774  * For known CDB types, parse the LBA and length.
10775  */
10776 static int
10777 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10778 {
10779         if (io->io_hdr.io_type != CTL_IO_SCSI)
10780                 return (1);
10781
10782         switch (io->scsiio.cdb[0]) {
10783         case COMPARE_AND_WRITE: {
10784                 struct scsi_compare_and_write *cdb;
10785
10786                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10787
10788                 *lba = scsi_8btou64(cdb->addr);
10789                 *len = cdb->length;
10790                 break;
10791         }
10792         case READ_6:
10793         case WRITE_6: {
10794                 struct scsi_rw_6 *cdb;
10795
10796                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10797
10798                 *lba = scsi_3btoul(cdb->addr);
10799                 /* only 5 bits are valid in the most significant address byte */
10800                 *lba &= 0x1fffff;
10801                 *len = cdb->length;
10802                 break;
10803         }
10804         case READ_10:
10805         case WRITE_10: {
10806                 struct scsi_rw_10 *cdb;
10807
10808                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10809
10810                 *lba = scsi_4btoul(cdb->addr);
10811                 *len = scsi_2btoul(cdb->length);
10812                 break;
10813         }
10814         case WRITE_VERIFY_10: {
10815                 struct scsi_write_verify_10 *cdb;
10816
10817                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10818
10819                 *lba = scsi_4btoul(cdb->addr);
10820                 *len = scsi_2btoul(cdb->length);
10821                 break;
10822         }
10823         case READ_12:
10824         case WRITE_12: {
10825                 struct scsi_rw_12 *cdb;
10826
10827                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10828
10829                 *lba = scsi_4btoul(cdb->addr);
10830                 *len = scsi_4btoul(cdb->length);
10831                 break;
10832         }
10833         case WRITE_VERIFY_12: {
10834                 struct scsi_write_verify_12 *cdb;
10835
10836                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10837
10838                 *lba = scsi_4btoul(cdb->addr);
10839                 *len = scsi_4btoul(cdb->length);
10840                 break;
10841         }
10842         case READ_16:
10843         case WRITE_16: {
10844                 struct scsi_rw_16 *cdb;
10845
10846                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10847
10848                 *lba = scsi_8btou64(cdb->addr);
10849                 *len = scsi_4btoul(cdb->length);
10850                 break;
10851         }
10852         case WRITE_ATOMIC_16: {
10853                 struct scsi_write_atomic_16 *cdb;
10854
10855                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10856
10857                 *lba = scsi_8btou64(cdb->addr);
10858                 *len = scsi_2btoul(cdb->length);
10859                 break;
10860         }
10861         case WRITE_VERIFY_16: {
10862                 struct scsi_write_verify_16 *cdb;
10863
10864                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10865
10866                 *lba = scsi_8btou64(cdb->addr);
10867                 *len = scsi_4btoul(cdb->length);
10868                 break;
10869         }
10870         case WRITE_SAME_10: {
10871                 struct scsi_write_same_10 *cdb;
10872
10873                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10874
10875                 *lba = scsi_4btoul(cdb->addr);
10876                 *len = scsi_2btoul(cdb->length);
10877                 break;
10878         }
10879         case WRITE_SAME_16: {
10880                 struct scsi_write_same_16 *cdb;
10881
10882                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10883
10884                 *lba = scsi_8btou64(cdb->addr);
10885                 *len = scsi_4btoul(cdb->length);
10886                 break;
10887         }
10888         case VERIFY_10: {
10889                 struct scsi_verify_10 *cdb;
10890
10891                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10892
10893                 *lba = scsi_4btoul(cdb->addr);
10894                 *len = scsi_2btoul(cdb->length);
10895                 break;
10896         }
10897         case VERIFY_12: {
10898                 struct scsi_verify_12 *cdb;
10899
10900                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10901
10902                 *lba = scsi_4btoul(cdb->addr);
10903                 *len = scsi_4btoul(cdb->length);
10904                 break;
10905         }
10906         case VERIFY_16: {
10907                 struct scsi_verify_16 *cdb;
10908
10909                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10910
10911                 *lba = scsi_8btou64(cdb->addr);
10912                 *len = scsi_4btoul(cdb->length);
10913                 break;
10914         }
10915         case UNMAP: {
10916                 *lba = 0;
10917                 *len = UINT64_MAX;
10918                 break;
10919         }
10920         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10921                 struct scsi_get_lba_status *cdb;
10922
10923                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10924                 *lba = scsi_8btou64(cdb->addr);
10925                 *len = UINT32_MAX;
10926                 break;
10927         }
10928         default:
10929                 return (1);
10930                 break; /* NOTREACHED */
10931         }
10932
10933         return (0);
10934 }
10935
10936 static ctl_action
10937 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10938     bool seq)
10939 {
10940         uint64_t endlba1, endlba2;
10941
10942         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10943         endlba2 = lba2 + len2 - 1;
10944
10945         if ((endlba1 < lba2) || (endlba2 < lba1))
10946                 return (CTL_ACTION_PASS);
10947         else
10948                 return (CTL_ACTION_BLOCK);
10949 }
10950
10951 static int
10952 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10953 {
10954         struct ctl_ptr_len_flags *ptrlen;
10955         struct scsi_unmap_desc *buf, *end, *range;
10956         uint64_t lba;
10957         uint32_t len;
10958
10959         /* If not UNMAP -- go other way. */
10960         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10961             io->scsiio.cdb[0] != UNMAP)
10962                 return (CTL_ACTION_ERROR);
10963
10964         /* If UNMAP without data -- block and wait for data. */
10965         ptrlen = (struct ctl_ptr_len_flags *)
10966             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10967         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10968             ptrlen->ptr == NULL)
10969                 return (CTL_ACTION_BLOCK);
10970
10971         /* UNMAP with data -- check for collision. */
10972         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10973         end = buf + ptrlen->len / sizeof(*buf);
10974         for (range = buf; range < end; range++) {
10975                 lba = scsi_8btou64(range->lba);
10976                 len = scsi_4btoul(range->length);
10977                 if ((lba < lba2 + len2) && (lba + len > lba2))
10978                         return (CTL_ACTION_BLOCK);
10979         }
10980         return (CTL_ACTION_PASS);
10981 }
10982
10983 static ctl_action
10984 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10985 {
10986         uint64_t lba1, lba2;
10987         uint64_t len1, len2;
10988         int retval;
10989
10990         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10991                 return (CTL_ACTION_ERROR);
10992
10993         retval = ctl_extent_check_unmap(io1, lba2, len2);
10994         if (retval != CTL_ACTION_ERROR)
10995                 return (retval);
10996
10997         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10998                 return (CTL_ACTION_ERROR);
10999
11000         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11001                 seq = FALSE;
11002         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11003 }
11004
11005 static ctl_action
11006 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
11007 {
11008         uint64_t lba1, lba2;
11009         uint64_t len1, len2;
11010
11011         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11012                 return (CTL_ACTION_PASS);
11013         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11014                 return (CTL_ACTION_ERROR);
11015         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11016                 return (CTL_ACTION_ERROR);
11017
11018         if (lba1 + len1 == lba2)
11019                 return (CTL_ACTION_BLOCK);
11020         return (CTL_ACTION_PASS);
11021 }
11022
11023 static ctl_action
11024 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11025     union ctl_io *ooa_io)
11026 {
11027         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11028         const ctl_serialize_action *serialize_row;
11029
11030         /*
11031          * The initiator attempted multiple untagged commands at the same
11032          * time.  Can't do that.
11033          */
11034         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11035          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11036          && ((pending_io->io_hdr.nexus.targ_port ==
11037               ooa_io->io_hdr.nexus.targ_port)
11038           && (pending_io->io_hdr.nexus.initid ==
11039               ooa_io->io_hdr.nexus.initid))
11040          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11041               CTL_FLAG_STATUS_SENT)) == 0))
11042                 return (CTL_ACTION_OVERLAP);
11043
11044         /*
11045          * The initiator attempted to send multiple tagged commands with
11046          * the same ID.  (It's fine if different initiators have the same
11047          * tag ID.)
11048          *
11049          * Even if all of those conditions are true, we don't kill the I/O
11050          * if the command ahead of us has been aborted.  We won't end up
11051          * sending it to the FETD, and it's perfectly legal to resend a
11052          * command with the same tag number as long as the previous
11053          * instance of this tag number has been aborted somehow.
11054          */
11055         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11056          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11057          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11058          && ((pending_io->io_hdr.nexus.targ_port ==
11059               ooa_io->io_hdr.nexus.targ_port)
11060           && (pending_io->io_hdr.nexus.initid ==
11061               ooa_io->io_hdr.nexus.initid))
11062          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11063               CTL_FLAG_STATUS_SENT)) == 0))
11064                 return (CTL_ACTION_OVERLAP_TAG);
11065
11066         /*
11067          * If we get a head of queue tag, SAM-3 says that we should
11068          * immediately execute it.
11069          *
11070          * What happens if this command would normally block for some other
11071          * reason?  e.g. a request sense with a head of queue tag
11072          * immediately after a write.  Normally that would block, but this
11073          * will result in its getting executed immediately...
11074          *
11075          * We currently return "pass" instead of "skip", so we'll end up
11076          * going through the rest of the queue to check for overlapped tags.
11077          *
11078          * XXX KDM check for other types of blockage first??
11079          */
11080         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11081                 return (CTL_ACTION_PASS);
11082
11083         /*
11084          * Ordered tags have to block until all items ahead of them
11085          * have completed.  If we get called with an ordered tag, we always
11086          * block, if something else is ahead of us in the queue.
11087          */
11088         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11089                 return (CTL_ACTION_BLOCK);
11090
11091         /*
11092          * Simple tags get blocked until all head of queue and ordered tags
11093          * ahead of them have completed.  I'm lumping untagged commands in
11094          * with simple tags here.  XXX KDM is that the right thing to do?
11095          */
11096         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11097           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11098          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11099           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11100                 return (CTL_ACTION_BLOCK);
11101
11102         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11103         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11104             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11105              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11106              pending_io->scsiio.cdb[1], pending_io));
11107         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11108         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11109                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11110         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11111             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11112              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11113              ooa_io->scsiio.cdb[1], ooa_io));
11114
11115         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11116
11117         switch (serialize_row[pending_entry->seridx]) {
11118         case CTL_SER_BLOCK:
11119                 return (CTL_ACTION_BLOCK);
11120         case CTL_SER_EXTENT:
11121                 return (ctl_extent_check(ooa_io, pending_io,
11122                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11123         case CTL_SER_EXTENTOPT:
11124                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11125                     SCP_QUEUE_ALG_UNRESTRICTED)
11126                         return (ctl_extent_check(ooa_io, pending_io,
11127                             (lun->be_lun &&
11128                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11129                 return (CTL_ACTION_PASS);
11130         case CTL_SER_EXTENTSEQ:
11131                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11132                         return (ctl_extent_check_seq(ooa_io, pending_io));
11133                 return (CTL_ACTION_PASS);
11134         case CTL_SER_PASS:
11135                 return (CTL_ACTION_PASS);
11136         case CTL_SER_BLOCKOPT:
11137                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11138                     SCP_QUEUE_ALG_UNRESTRICTED)
11139                         return (CTL_ACTION_BLOCK);
11140                 return (CTL_ACTION_PASS);
11141         case CTL_SER_SKIP:
11142                 return (CTL_ACTION_SKIP);
11143         default:
11144                 panic("%s: Invalid serialization value %d for %d => %d",
11145                     __func__, serialize_row[pending_entry->seridx],
11146                     pending_entry->seridx, ooa_entry->seridx);
11147         }
11148
11149         return (CTL_ACTION_ERROR);
11150 }
11151
11152 /*
11153  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11154  * Assumptions:
11155  * - pending_io is generally either incoming, or on the blocked queue
11156  * - starting I/O is the I/O we want to start the check with.
11157  */
11158 static ctl_action
11159 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11160               union ctl_io *starting_io)
11161 {
11162         union ctl_io *ooa_io;
11163         ctl_action action;
11164
11165         mtx_assert(&lun->lun_lock, MA_OWNED);
11166
11167         /*
11168          * Run back along the OOA queue, starting with the current
11169          * blocked I/O and going through every I/O before it on the
11170          * queue.  If starting_io is NULL, we'll just end up returning
11171          * CTL_ACTION_PASS.
11172          */
11173         for (ooa_io = starting_io; ooa_io != NULL;
11174              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11175              ooa_links)){
11176
11177                 /*
11178                  * This routine just checks to see whether
11179                  * cur_blocked is blocked by ooa_io, which is ahead
11180                  * of it in the queue.  It doesn't queue/dequeue
11181                  * cur_blocked.
11182                  */
11183                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11184                 switch (action) {
11185                 case CTL_ACTION_BLOCK:
11186                 case CTL_ACTION_OVERLAP:
11187                 case CTL_ACTION_OVERLAP_TAG:
11188                 case CTL_ACTION_SKIP:
11189                 case CTL_ACTION_ERROR:
11190                         return (action);
11191                         break; /* NOTREACHED */
11192                 case CTL_ACTION_PASS:
11193                         break;
11194                 default:
11195                         panic("%s: Invalid action %d\n", __func__, action);
11196                 }
11197         }
11198
11199         return (CTL_ACTION_PASS);
11200 }
11201
11202 /*
11203  * Assumptions:
11204  * - An I/O has just completed, and has been removed from the per-LUN OOA
11205  *   queue, so some items on the blocked queue may now be unblocked.
11206  */
11207 static int
11208 ctl_check_blocked(struct ctl_lun *lun)
11209 {
11210         struct ctl_softc *softc = lun->ctl_softc;
11211         union ctl_io *cur_blocked, *next_blocked;
11212
11213         mtx_assert(&lun->lun_lock, MA_OWNED);
11214
11215         /*
11216          * Run forward from the head of the blocked queue, checking each
11217          * entry against the I/Os prior to it on the OOA queue to see if
11218          * there is still any blockage.
11219          *
11220          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11221          * with our removing a variable on it while it is traversing the
11222          * list.
11223          */
11224         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11225              cur_blocked != NULL; cur_blocked = next_blocked) {
11226                 union ctl_io *prev_ooa;
11227                 ctl_action action;
11228
11229                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11230                                                           blocked_links);
11231
11232                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11233                                                       ctl_ooaq, ooa_links);
11234
11235                 /*
11236                  * If cur_blocked happens to be the first item in the OOA
11237                  * queue now, prev_ooa will be NULL, and the action
11238                  * returned will just be CTL_ACTION_PASS.
11239                  */
11240                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11241
11242                 switch (action) {
11243                 case CTL_ACTION_BLOCK:
11244                         /* Nothing to do here, still blocked */
11245                         break;
11246                 case CTL_ACTION_OVERLAP:
11247                 case CTL_ACTION_OVERLAP_TAG:
11248                         /*
11249                          * This shouldn't happen!  In theory we've already
11250                          * checked this command for overlap...
11251                          */
11252                         break;
11253                 case CTL_ACTION_PASS:
11254                 case CTL_ACTION_SKIP: {
11255                         const struct ctl_cmd_entry *entry;
11256
11257                         /*
11258                          * The skip case shouldn't happen, this transaction
11259                          * should have never made it onto the blocked queue.
11260                          */
11261                         /*
11262                          * This I/O is no longer blocked, we can remove it
11263                          * from the blocked queue.  Since this is a TAILQ
11264                          * (doubly linked list), we can do O(1) removals
11265                          * from any place on the list.
11266                          */
11267                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11268                                      blocked_links);
11269                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11270
11271                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11272                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11273                                 /*
11274                                  * Need to send IO back to original side to
11275                                  * run
11276                                  */
11277                                 union ctl_ha_msg msg_info;
11278
11279                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11280                                 msg_info.hdr.original_sc =
11281                                         cur_blocked->io_hdr.original_sc;
11282                                 msg_info.hdr.serializing_sc = cur_blocked;
11283                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11284                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11285                                     sizeof(msg_info.hdr), M_NOWAIT);
11286                                 break;
11287                         }
11288                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11289
11290                         /*
11291                          * Check this I/O for LUN state changes that may
11292                          * have happened while this command was blocked.
11293                          * The LUN state may have been changed by a command
11294                          * ahead of us in the queue, so we need to re-check
11295                          * for any states that can be caused by SCSI
11296                          * commands.
11297                          */
11298                         if (ctl_scsiio_lun_check(lun, entry,
11299                                                  &cur_blocked->scsiio) == 0) {
11300                                 cur_blocked->io_hdr.flags |=
11301                                                       CTL_FLAG_IS_WAS_ON_RTR;
11302                                 ctl_enqueue_rtr(cur_blocked);
11303                         } else
11304                                 ctl_done(cur_blocked);
11305                         break;
11306                 }
11307                 default:
11308                         /*
11309                          * This probably shouldn't happen -- we shouldn't
11310                          * get CTL_ACTION_ERROR, or anything else.
11311                          */
11312                         break;
11313                 }
11314         }
11315
11316         return (CTL_RETVAL_COMPLETE);
11317 }
11318
11319 /*
11320  * This routine (with one exception) checks LUN flags that can be set by
11321  * commands ahead of us in the OOA queue.  These flags have to be checked
11322  * when a command initially comes in, and when we pull a command off the
11323  * blocked queue and are preparing to execute it.  The reason we have to
11324  * check these flags for commands on the blocked queue is that the LUN
11325  * state may have been changed by a command ahead of us while we're on the
11326  * blocked queue.
11327  *
11328  * Ordering is somewhat important with these checks, so please pay
11329  * careful attention to the placement of any new checks.
11330  */
11331 static int
11332 ctl_scsiio_lun_check(struct ctl_lun *lun,
11333     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11334 {
11335         struct ctl_softc *softc = lun->ctl_softc;
11336         int retval;
11337         uint32_t residx;
11338
11339         retval = 0;
11340
11341         mtx_assert(&lun->lun_lock, MA_OWNED);
11342
11343         /*
11344          * If this shelf is a secondary shelf controller, we may have to
11345          * reject some commands disallowed by HA mode and link state.
11346          */
11347         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11348                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11349                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11350                         ctl_set_lun_unavail(ctsio);
11351                         retval = 1;
11352                         goto bailout;
11353                 }
11354                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11355                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11356                         ctl_set_lun_transit(ctsio);
11357                         retval = 1;
11358                         goto bailout;
11359                 }
11360                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11361                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11362                         ctl_set_lun_standby(ctsio);
11363                         retval = 1;
11364                         goto bailout;
11365                 }
11366
11367                 /* The rest of checks are only done on executing side */
11368                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11369                         goto bailout;
11370         }
11371
11372         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11373                 if (lun->be_lun &&
11374                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11375                         ctl_set_hw_write_protected(ctsio);
11376                         retval = 1;
11377                         goto bailout;
11378                 }
11379                 if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11380                         ctl_set_sense(ctsio, /*current_error*/ 1,
11381                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11382                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11383                         retval = 1;
11384                         goto bailout;
11385                 }
11386         }
11387
11388         /*
11389          * Check for a reservation conflict.  If this command isn't allowed
11390          * even on reserved LUNs, and if this initiator isn't the one who
11391          * reserved us, reject the command with a reservation conflict.
11392          */
11393         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11394         if ((lun->flags & CTL_LUN_RESERVED)
11395          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11396                 if (lun->res_idx != residx) {
11397                         ctl_set_reservation_conflict(ctsio);
11398                         retval = 1;
11399                         goto bailout;
11400                 }
11401         }
11402
11403         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11404             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11405                 /* No reservation or command is allowed. */;
11406         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11407             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11408              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11409              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11410                 /* The command is allowed for Write Exclusive resv. */;
11411         } else {
11412                 /*
11413                  * if we aren't registered or it's a res holder type
11414                  * reservation and this isn't the res holder then set a
11415                  * conflict.
11416                  */
11417                 if (ctl_get_prkey(lun, residx) == 0 ||
11418                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11419                         ctl_set_reservation_conflict(ctsio);
11420                         retval = 1;
11421                         goto bailout;
11422                 }
11423         }
11424
11425         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11426                 if (lun->flags & CTL_LUN_EJECTED)
11427                         ctl_set_lun_ejected(ctsio);
11428                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11429                         if (lun->flags & CTL_LUN_REMOVABLE)
11430                                 ctl_set_lun_no_media(ctsio);
11431                         else
11432                                 ctl_set_lun_int_reqd(ctsio);
11433                 } else if (lun->flags & CTL_LUN_STOPPED)
11434                         ctl_set_lun_stopped(ctsio);
11435                 else
11436                         goto bailout;
11437                 retval = 1;
11438                 goto bailout;
11439         }
11440
11441 bailout:
11442         return (retval);
11443 }
11444
11445 static void
11446 ctl_failover_io(union ctl_io *io, int have_lock)
11447 {
11448         ctl_set_busy(&io->scsiio);
11449         ctl_done(io);
11450 }
11451
11452 static void
11453 ctl_failover_lun(union ctl_io *rio)
11454 {
11455         struct ctl_softc *softc = control_softc;
11456         struct ctl_lun *lun;
11457         struct ctl_io_hdr *io, *next_io;
11458         uint32_t targ_lun;
11459
11460         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11461         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11462
11463         /* Find and lock the LUN. */
11464         mtx_lock(&softc->ctl_lock);
11465         if (targ_lun > CTL_MAX_LUNS ||
11466             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11467                 mtx_unlock(&softc->ctl_lock);
11468                 return;
11469         }
11470         mtx_lock(&lun->lun_lock);
11471         mtx_unlock(&softc->ctl_lock);
11472         if (lun->flags & CTL_LUN_DISABLED) {
11473                 mtx_unlock(&lun->lun_lock);
11474                 return;
11475         }
11476
11477         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11478                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11479                         /* We are master */
11480                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11481                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11482                                         io->flags |= CTL_FLAG_ABORT;
11483                                         io->flags |= CTL_FLAG_FAILOVER;
11484                                 } else { /* This can be only due to DATAMOVE */
11485                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11486                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11487                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11488                                         io->port_status = 31340;
11489                                         ctl_enqueue_isc((union ctl_io *)io);
11490                                 }
11491                         }
11492                         /* We are slave */
11493                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11494                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11495                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11496                                         io->flags |= CTL_FLAG_FAILOVER;
11497                                 } else {
11498                                         ctl_set_busy(&((union ctl_io *)io)->
11499                                             scsiio);
11500                                         ctl_done((union ctl_io *)io);
11501                                 }
11502                         }
11503                 }
11504         } else { /* SERIALIZE modes */
11505                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11506                     next_io) {
11507                         /* We are master */
11508                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11509                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11510                                     blocked_links);
11511                                 io->flags &= ~CTL_FLAG_BLOCKED;
11512                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11513                                 ctl_free_io((union ctl_io *)io);
11514                         }
11515                 }
11516                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11517                         /* We are master */
11518                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11519                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11520                                 ctl_free_io((union ctl_io *)io);
11521                         }
11522                         /* We are slave */
11523                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11524                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11525                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11526                                         ctl_set_busy(&((union ctl_io *)io)->
11527                                             scsiio);
11528                                         ctl_done((union ctl_io *)io);
11529                                 }
11530                         }
11531                 }
11532                 ctl_check_blocked(lun);
11533         }
11534         mtx_unlock(&lun->lun_lock);
11535 }
11536
11537 static int
11538 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11539 {
11540         struct ctl_lun *lun;
11541         const struct ctl_cmd_entry *entry;
11542         uint32_t initidx, targ_lun;
11543         int retval = 0;
11544
11545         lun = NULL;
11546         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11547         if (targ_lun < CTL_MAX_LUNS)
11548                 lun = softc->ctl_luns[targ_lun];
11549         if (lun) {
11550                 /*
11551                  * If the LUN is invalid, pretend that it doesn't exist.
11552                  * It will go away as soon as all pending I/O has been
11553                  * completed.
11554                  */
11555                 mtx_lock(&lun->lun_lock);
11556                 if (lun->flags & CTL_LUN_DISABLED) {
11557                         mtx_unlock(&lun->lun_lock);
11558                         lun = NULL;
11559                 }
11560         }
11561         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11562         if (lun) {
11563                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11564                     lun->be_lun;
11565
11566                 /*
11567                  * Every I/O goes into the OOA queue for a particular LUN,
11568                  * and stays there until completion.
11569                  */
11570 #ifdef CTL_TIME_IO
11571                 if (TAILQ_EMPTY(&lun->ooa_queue))
11572                         lun->idle_time += getsbinuptime() - lun->last_busy;
11573 #endif
11574                 TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11575         }
11576
11577         /* Get command entry and return error if it is unsuppotyed. */
11578         entry = ctl_validate_command(ctsio);
11579         if (entry == NULL) {
11580                 if (lun)
11581                         mtx_unlock(&lun->lun_lock);
11582                 return (retval);
11583         }
11584
11585         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11586         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11587
11588         /*
11589          * Check to see whether we can send this command to LUNs that don't
11590          * exist.  This should pretty much only be the case for inquiry
11591          * and request sense.  Further checks, below, really require having
11592          * a LUN, so we can't really check the command anymore.  Just put
11593          * it on the rtr queue.
11594          */
11595         if (lun == NULL) {
11596                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11597                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11598                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11599                         return (retval);
11600                 }
11601
11602                 ctl_set_unsupported_lun(ctsio);
11603                 ctl_done((union ctl_io *)ctsio);
11604                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11605                 return (retval);
11606         } else {
11607                 /*
11608                  * Make sure we support this particular command on this LUN.
11609                  * e.g., we don't support writes to the control LUN.
11610                  */
11611                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11612                         mtx_unlock(&lun->lun_lock);
11613                         ctl_set_invalid_opcode(ctsio);
11614                         ctl_done((union ctl_io *)ctsio);
11615                         return (retval);
11616                 }
11617         }
11618
11619         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11620
11621 #ifdef CTL_WITH_CA
11622         /*
11623          * If we've got a request sense, it'll clear the contingent
11624          * allegiance condition.  Otherwise, if we have a CA condition for
11625          * this initiator, clear it, because it sent down a command other
11626          * than request sense.
11627          */
11628         if ((ctsio->cdb[0] != REQUEST_SENSE)
11629          && (ctl_is_set(lun->have_ca, initidx)))
11630                 ctl_clear_mask(lun->have_ca, initidx);
11631 #endif
11632
11633         /*
11634          * If the command has this flag set, it handles its own unit
11635          * attention reporting, we shouldn't do anything.  Otherwise we
11636          * check for any pending unit attentions, and send them back to the
11637          * initiator.  We only do this when a command initially comes in,
11638          * not when we pull it off the blocked queue.
11639          *
11640          * According to SAM-3, section 5.3.2, the order that things get
11641          * presented back to the host is basically unit attentions caused
11642          * by some sort of reset event, busy status, reservation conflicts
11643          * or task set full, and finally any other status.
11644          *
11645          * One issue here is that some of the unit attentions we report
11646          * don't fall into the "reset" category (e.g. "reported luns data
11647          * has changed").  So reporting it here, before the reservation
11648          * check, may be technically wrong.  I guess the only thing to do
11649          * would be to check for and report the reset events here, and then
11650          * check for the other unit attention types after we check for a
11651          * reservation conflict.
11652          *
11653          * XXX KDM need to fix this
11654          */
11655         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11656                 ctl_ua_type ua_type;
11657                 u_int sense_len = 0;
11658
11659                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11660                     &sense_len, SSD_TYPE_NONE);
11661                 if (ua_type != CTL_UA_NONE) {
11662                         mtx_unlock(&lun->lun_lock);
11663                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11664                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11665                         ctsio->sense_len = sense_len;
11666                         ctl_done((union ctl_io *)ctsio);
11667                         return (retval);
11668                 }
11669         }
11670
11671
11672         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11673                 mtx_unlock(&lun->lun_lock);
11674                 ctl_done((union ctl_io *)ctsio);
11675                 return (retval);
11676         }
11677
11678         /*
11679          * XXX CHD this is where we want to send IO to other side if
11680          * this LUN is secondary on this SC. We will need to make a copy
11681          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11682          * the copy we send as FROM_OTHER.
11683          * We also need to stuff the address of the original IO so we can
11684          * find it easily. Something similar will need be done on the other
11685          * side so when we are done we can find the copy.
11686          */
11687         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11688             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11689             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11690                 union ctl_ha_msg msg_info;
11691                 int isc_retval;
11692
11693                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11694                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11695                 mtx_unlock(&lun->lun_lock);
11696
11697                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11698                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11699                 msg_info.hdr.serializing_sc = NULL;
11700                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11701                 msg_info.scsi.tag_num = ctsio->tag_num;
11702                 msg_info.scsi.tag_type = ctsio->tag_type;
11703                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11704                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11705
11706                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11707                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11708                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11709                         ctl_set_busy(ctsio);
11710                         ctl_done((union ctl_io *)ctsio);
11711                         return (retval);
11712                 }
11713                 return (retval);
11714         }
11715
11716         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11717                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11718                               ctl_ooaq, ooa_links))) {
11719         case CTL_ACTION_BLOCK:
11720                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11721                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11722                                   blocked_links);
11723                 mtx_unlock(&lun->lun_lock);
11724                 return (retval);
11725         case CTL_ACTION_PASS:
11726         case CTL_ACTION_SKIP:
11727                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11728                 mtx_unlock(&lun->lun_lock);
11729                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11730                 break;
11731         case CTL_ACTION_OVERLAP:
11732                 mtx_unlock(&lun->lun_lock);
11733                 ctl_set_overlapped_cmd(ctsio);
11734                 ctl_done((union ctl_io *)ctsio);
11735                 break;
11736         case CTL_ACTION_OVERLAP_TAG:
11737                 mtx_unlock(&lun->lun_lock);
11738                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11739                 ctl_done((union ctl_io *)ctsio);
11740                 break;
11741         case CTL_ACTION_ERROR:
11742         default:
11743                 mtx_unlock(&lun->lun_lock);
11744                 ctl_set_internal_failure(ctsio,
11745                                          /*sks_valid*/ 0,
11746                                          /*retry_count*/ 0);
11747                 ctl_done((union ctl_io *)ctsio);
11748                 break;
11749         }
11750         return (retval);
11751 }
11752
11753 const struct ctl_cmd_entry *
11754 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11755 {
11756         const struct ctl_cmd_entry *entry;
11757         int service_action;
11758
11759         entry = &ctl_cmd_table[ctsio->cdb[0]];
11760         if (sa)
11761                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11762         if (entry->flags & CTL_CMD_FLAG_SA5) {
11763                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11764                 entry = &((const struct ctl_cmd_entry *)
11765                     entry->execute)[service_action];
11766         }
11767         return (entry);
11768 }
11769
11770 const struct ctl_cmd_entry *
11771 ctl_validate_command(struct ctl_scsiio *ctsio)
11772 {
11773         const struct ctl_cmd_entry *entry;
11774         int i, sa;
11775         uint8_t diff;
11776
11777         entry = ctl_get_cmd_entry(ctsio, &sa);
11778         if (entry->execute == NULL) {
11779                 if (sa)
11780                         ctl_set_invalid_field(ctsio,
11781                                               /*sks_valid*/ 1,
11782                                               /*command*/ 1,
11783                                               /*field*/ 1,
11784                                               /*bit_valid*/ 1,
11785                                               /*bit*/ 4);
11786                 else
11787                         ctl_set_invalid_opcode(ctsio);
11788                 ctl_done((union ctl_io *)ctsio);
11789                 return (NULL);
11790         }
11791         KASSERT(entry->length > 0,
11792             ("Not defined length for command 0x%02x/0x%02x",
11793              ctsio->cdb[0], ctsio->cdb[1]));
11794         for (i = 1; i < entry->length; i++) {
11795                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11796                 if (diff == 0)
11797                         continue;
11798                 ctl_set_invalid_field(ctsio,
11799                                       /*sks_valid*/ 1,
11800                                       /*command*/ 1,
11801                                       /*field*/ i,
11802                                       /*bit_valid*/ 1,
11803                                       /*bit*/ fls(diff) - 1);
11804                 ctl_done((union ctl_io *)ctsio);
11805                 return (NULL);
11806         }
11807         return (entry);
11808 }
11809
11810 static int
11811 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11812 {
11813
11814         switch (lun_type) {
11815         case T_DIRECT:
11816                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11817                         return (0);
11818                 break;
11819         case T_PROCESSOR:
11820                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11821                         return (0);
11822                 break;
11823         case T_CDROM:
11824                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11825                         return (0);
11826                 break;
11827         default:
11828                 return (0);
11829         }
11830         return (1);
11831 }
11832
11833 static int
11834 ctl_scsiio(struct ctl_scsiio *ctsio)
11835 {
11836         int retval;
11837         const struct ctl_cmd_entry *entry;
11838
11839         retval = CTL_RETVAL_COMPLETE;
11840
11841         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11842
11843         entry = ctl_get_cmd_entry(ctsio, NULL);
11844
11845         /*
11846          * If this I/O has been aborted, just send it straight to
11847          * ctl_done() without executing it.
11848          */
11849         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11850                 ctl_done((union ctl_io *)ctsio);
11851                 goto bailout;
11852         }
11853
11854         /*
11855          * All the checks should have been handled by ctl_scsiio_precheck().
11856          * We should be clear now to just execute the I/O.
11857          */
11858         retval = entry->execute(ctsio);
11859
11860 bailout:
11861         return (retval);
11862 }
11863
11864 /*
11865  * Since we only implement one target right now, a bus reset simply resets
11866  * our single target.
11867  */
11868 static int
11869 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11870 {
11871         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11872 }
11873
11874 static int
11875 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11876                  ctl_ua_type ua_type)
11877 {
11878         struct ctl_port *port;
11879         struct ctl_lun *lun;
11880         int retval;
11881
11882         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11883                 union ctl_ha_msg msg_info;
11884
11885                 msg_info.hdr.nexus = io->io_hdr.nexus;
11886                 if (ua_type==CTL_UA_TARG_RESET)
11887                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11888                 else
11889                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11890                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11891                 msg_info.hdr.original_sc = NULL;
11892                 msg_info.hdr.serializing_sc = NULL;
11893                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11894                     sizeof(msg_info.task), M_WAITOK);
11895         }
11896         retval = 0;
11897
11898         mtx_lock(&softc->ctl_lock);
11899         port = ctl_io_port(&io->io_hdr);
11900         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11901                 if (port != NULL &&
11902                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11903                         continue;
11904                 retval += ctl_do_lun_reset(lun, io, ua_type);
11905         }
11906         mtx_unlock(&softc->ctl_lock);
11907         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11908         return (retval);
11909 }
11910
11911 /*
11912  * The LUN should always be set.  The I/O is optional, and is used to
11913  * distinguish between I/Os sent by this initiator, and by other
11914  * initiators.  We set unit attention for initiators other than this one.
11915  * SAM-3 is vague on this point.  It does say that a unit attention should
11916  * be established for other initiators when a LUN is reset (see section
11917  * 5.7.3), but it doesn't specifically say that the unit attention should
11918  * be established for this particular initiator when a LUN is reset.  Here
11919  * is the relevant text, from SAM-3 rev 8:
11920  *
11921  * 5.7.2 When a SCSI initiator port aborts its own tasks
11922  *
11923  * When a SCSI initiator port causes its own task(s) to be aborted, no
11924  * notification that the task(s) have been aborted shall be returned to
11925  * the SCSI initiator port other than the completion response for the
11926  * command or task management function action that caused the task(s) to
11927  * be aborted and notification(s) associated with related effects of the
11928  * action (e.g., a reset unit attention condition).
11929  *
11930  * XXX KDM for now, we're setting unit attention for all initiators.
11931  */
11932 static int
11933 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11934 {
11935         union ctl_io *xio;
11936 #if 0
11937         uint32_t initidx;
11938 #endif
11939         int i;
11940
11941         mtx_lock(&lun->lun_lock);
11942         /*
11943          * Run through the OOA queue and abort each I/O.
11944          */
11945         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11946              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11947                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11948         }
11949
11950         /*
11951          * This version sets unit attention for every
11952          */
11953 #if 0
11954         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11955         ctl_est_ua_all(lun, initidx, ua_type);
11956 #else
11957         ctl_est_ua_all(lun, -1, ua_type);
11958 #endif
11959
11960         /*
11961          * A reset (any kind, really) clears reservations established with
11962          * RESERVE/RELEASE.  It does not clear reservations established
11963          * with PERSISTENT RESERVE OUT, but we don't support that at the
11964          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11965          * reservations made with the RESERVE/RELEASE commands, because
11966          * those commands are obsolete in SPC-3.
11967          */
11968         lun->flags &= ~CTL_LUN_RESERVED;
11969
11970 #ifdef CTL_WITH_CA
11971         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11972                 ctl_clear_mask(lun->have_ca, i);
11973 #endif
11974         lun->prevent_count = 0;
11975         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11976                 ctl_clear_mask(lun->prevent, i);
11977         mtx_unlock(&lun->lun_lock);
11978
11979         return (0);
11980 }
11981
11982 static int
11983 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11984 {
11985         struct ctl_lun *lun;
11986         uint32_t targ_lun;
11987         int retval;
11988
11989         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11990         mtx_lock(&softc->ctl_lock);
11991         if (targ_lun >= CTL_MAX_LUNS ||
11992             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11993                 mtx_unlock(&softc->ctl_lock);
11994                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11995                 return (1);
11996         }
11997         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11998         mtx_unlock(&softc->ctl_lock);
11999         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12000
12001         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
12002                 union ctl_ha_msg msg_info;
12003
12004                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12005                 msg_info.hdr.nexus = io->io_hdr.nexus;
12006                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
12007                 msg_info.hdr.original_sc = NULL;
12008                 msg_info.hdr.serializing_sc = NULL;
12009                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12010                     sizeof(msg_info.task), M_WAITOK);
12011         }
12012         return (retval);
12013 }
12014
12015 static void
12016 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12017     int other_sc)
12018 {
12019         union ctl_io *xio;
12020
12021         mtx_assert(&lun->lun_lock, MA_OWNED);
12022
12023         /*
12024          * Run through the OOA queue and attempt to find the given I/O.
12025          * The target port, initiator ID, tag type and tag number have to
12026          * match the values that we got from the initiator.  If we have an
12027          * untagged command to abort, simply abort the first untagged command
12028          * we come to.  We only allow one untagged command at a time of course.
12029          */
12030         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12031              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12032
12033                 if ((targ_port == UINT32_MAX ||
12034                      targ_port == xio->io_hdr.nexus.targ_port) &&
12035                     (init_id == UINT32_MAX ||
12036                      init_id == xio->io_hdr.nexus.initid)) {
12037                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12038                             init_id != xio->io_hdr.nexus.initid)
12039                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12040                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12041                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12042                                 union ctl_ha_msg msg_info;
12043
12044                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12045                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12046                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12047                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12048                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12049                                 msg_info.hdr.original_sc = NULL;
12050                                 msg_info.hdr.serializing_sc = NULL;
12051                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12052                                     sizeof(msg_info.task), M_NOWAIT);
12053                         }
12054                 }
12055         }
12056 }
12057
12058 static int
12059 ctl_abort_task_set(union ctl_io *io)
12060 {
12061         struct ctl_softc *softc = control_softc;
12062         struct ctl_lun *lun;
12063         uint32_t targ_lun;
12064
12065         /*
12066          * Look up the LUN.
12067          */
12068         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12069         mtx_lock(&softc->ctl_lock);
12070         if (targ_lun >= CTL_MAX_LUNS ||
12071             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12072                 mtx_unlock(&softc->ctl_lock);
12073                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12074                 return (1);
12075         }
12076
12077         mtx_lock(&lun->lun_lock);
12078         mtx_unlock(&softc->ctl_lock);
12079         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12080                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12081                     io->io_hdr.nexus.initid,
12082                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12083         } else { /* CTL_TASK_CLEAR_TASK_SET */
12084                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12085                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12086         }
12087         mtx_unlock(&lun->lun_lock);
12088         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12089         return (0);
12090 }
12091
12092 static int
12093 ctl_i_t_nexus_reset(union ctl_io *io)
12094 {
12095         struct ctl_softc *softc = control_softc;
12096         struct ctl_lun *lun;
12097         uint32_t initidx;
12098
12099         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12100                 union ctl_ha_msg msg_info;
12101
12102                 msg_info.hdr.nexus = io->io_hdr.nexus;
12103                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12104                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12105                 msg_info.hdr.original_sc = NULL;
12106                 msg_info.hdr.serializing_sc = NULL;
12107                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12108                     sizeof(msg_info.task), M_WAITOK);
12109         }
12110
12111         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12112         mtx_lock(&softc->ctl_lock);
12113         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12114                 mtx_lock(&lun->lun_lock);
12115                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12116                     io->io_hdr.nexus.initid, 1);
12117 #ifdef CTL_WITH_CA
12118                 ctl_clear_mask(lun->have_ca, initidx);
12119 #endif
12120                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12121                         lun->flags &= ~CTL_LUN_RESERVED;
12122                 if (ctl_is_set(lun->prevent, initidx)) {
12123                         ctl_clear_mask(lun->prevent, initidx);
12124                         lun->prevent_count--;
12125                 }
12126                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12127                 mtx_unlock(&lun->lun_lock);
12128         }
12129         mtx_unlock(&softc->ctl_lock);
12130         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12131         return (0);
12132 }
12133
12134 static int
12135 ctl_abort_task(union ctl_io *io)
12136 {
12137         union ctl_io *xio;
12138         struct ctl_lun *lun;
12139         struct ctl_softc *softc;
12140 #if 0
12141         struct sbuf sb;
12142         char printbuf[128];
12143 #endif
12144         int found;
12145         uint32_t targ_lun;
12146
12147         softc = control_softc;
12148         found = 0;
12149
12150         /*
12151          * Look up the LUN.
12152          */
12153         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12154         mtx_lock(&softc->ctl_lock);
12155         if (targ_lun >= CTL_MAX_LUNS ||
12156             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12157                 mtx_unlock(&softc->ctl_lock);
12158                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12159                 return (1);
12160         }
12161
12162 #if 0
12163         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12164                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12165 #endif
12166
12167         mtx_lock(&lun->lun_lock);
12168         mtx_unlock(&softc->ctl_lock);
12169         /*
12170          * Run through the OOA queue and attempt to find the given I/O.
12171          * The target port, initiator ID, tag type and tag number have to
12172          * match the values that we got from the initiator.  If we have an
12173          * untagged command to abort, simply abort the first untagged command
12174          * we come to.  We only allow one untagged command at a time of course.
12175          */
12176         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12177              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12178 #if 0
12179                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12180
12181                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12182                             lun->lun, xio->scsiio.tag_num,
12183                             xio->scsiio.tag_type,
12184                             (xio->io_hdr.blocked_links.tqe_prev
12185                             == NULL) ? "" : " BLOCKED",
12186                             (xio->io_hdr.flags &
12187                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12188                             (xio->io_hdr.flags &
12189                             CTL_FLAG_ABORT) ? " ABORT" : "",
12190                             (xio->io_hdr.flags &
12191                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12192                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12193                 sbuf_finish(&sb);
12194                 printf("%s\n", sbuf_data(&sb));
12195 #endif
12196
12197                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12198                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12199                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12200                         continue;
12201
12202                 /*
12203                  * If the abort says that the task is untagged, the
12204                  * task in the queue must be untagged.  Otherwise,
12205                  * we just check to see whether the tag numbers
12206                  * match.  This is because the QLogic firmware
12207                  * doesn't pass back the tag type in an abort
12208                  * request.
12209                  */
12210 #if 0
12211                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12212                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12213                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12214 #endif
12215                 /*
12216                  * XXX KDM we've got problems with FC, because it
12217                  * doesn't send down a tag type with aborts.  So we
12218                  * can only really go by the tag number...
12219                  * This may cause problems with parallel SCSI.
12220                  * Need to figure that out!!
12221                  */
12222                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12223                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12224                         found = 1;
12225                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12226                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12227                                 union ctl_ha_msg msg_info;
12228
12229                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12230                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12231                                 msg_info.task.tag_num = io->taskio.tag_num;
12232                                 msg_info.task.tag_type = io->taskio.tag_type;
12233                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12234                                 msg_info.hdr.original_sc = NULL;
12235                                 msg_info.hdr.serializing_sc = NULL;
12236 #if 0
12237                                 printf("Sent Abort to other side\n");
12238 #endif
12239                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12240                                     sizeof(msg_info.task), M_NOWAIT);
12241                         }
12242 #if 0
12243                         printf("ctl_abort_task: found I/O to abort\n");
12244 #endif
12245                 }
12246         }
12247         mtx_unlock(&lun->lun_lock);
12248
12249         if (found == 0) {
12250                 /*
12251                  * This isn't really an error.  It's entirely possible for
12252                  * the abort and command completion to cross on the wire.
12253                  * This is more of an informative/diagnostic error.
12254                  */
12255 #if 0
12256                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12257                        "%u:%u:%u tag %d type %d\n",
12258                        io->io_hdr.nexus.initid,
12259                        io->io_hdr.nexus.targ_port,
12260                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12261                        io->taskio.tag_type);
12262 #endif
12263         }
12264         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12265         return (0);
12266 }
12267
12268 static int
12269 ctl_query_task(union ctl_io *io, int task_set)
12270 {
12271         union ctl_io *xio;
12272         struct ctl_lun *lun;
12273         struct ctl_softc *softc;
12274         int found = 0;
12275         uint32_t targ_lun;
12276
12277         softc = control_softc;
12278         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12279         mtx_lock(&softc->ctl_lock);
12280         if (targ_lun >= CTL_MAX_LUNS ||
12281             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12282                 mtx_unlock(&softc->ctl_lock);
12283                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12284                 return (1);
12285         }
12286         mtx_lock(&lun->lun_lock);
12287         mtx_unlock(&softc->ctl_lock);
12288         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12289              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12290
12291                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12292                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12293                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12294                         continue;
12295
12296                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12297                         found = 1;
12298                         break;
12299                 }
12300         }
12301         mtx_unlock(&lun->lun_lock);
12302         if (found)
12303                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12304         else
12305                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12306         return (0);
12307 }
12308
12309 static int
12310 ctl_query_async_event(union ctl_io *io)
12311 {
12312         struct ctl_lun *lun;
12313         struct ctl_softc *softc;
12314         ctl_ua_type ua;
12315         uint32_t targ_lun, initidx;
12316
12317         softc = control_softc;
12318         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12319         mtx_lock(&softc->ctl_lock);
12320         if (targ_lun >= CTL_MAX_LUNS ||
12321             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12322                 mtx_unlock(&softc->ctl_lock);
12323                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12324                 return (1);
12325         }
12326         mtx_lock(&lun->lun_lock);
12327         mtx_unlock(&softc->ctl_lock);
12328         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12329         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12330         mtx_unlock(&lun->lun_lock);
12331         if (ua != CTL_UA_NONE)
12332                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12333         else
12334                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12335         return (0);
12336 }
12337
12338 static void
12339 ctl_run_task(union ctl_io *io)
12340 {
12341         struct ctl_softc *softc = control_softc;
12342         int retval = 1;
12343
12344         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12345         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12346             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12347         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12348         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12349         switch (io->taskio.task_action) {
12350         case CTL_TASK_ABORT_TASK:
12351                 retval = ctl_abort_task(io);
12352                 break;
12353         case CTL_TASK_ABORT_TASK_SET:
12354         case CTL_TASK_CLEAR_TASK_SET:
12355                 retval = ctl_abort_task_set(io);
12356                 break;
12357         case CTL_TASK_CLEAR_ACA:
12358                 break;
12359         case CTL_TASK_I_T_NEXUS_RESET:
12360                 retval = ctl_i_t_nexus_reset(io);
12361                 break;
12362         case CTL_TASK_LUN_RESET:
12363                 retval = ctl_lun_reset(softc, io);
12364                 break;
12365         case CTL_TASK_TARGET_RESET:
12366                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12367                 break;
12368         case CTL_TASK_BUS_RESET:
12369                 retval = ctl_bus_reset(softc, io);
12370                 break;
12371         case CTL_TASK_PORT_LOGIN:
12372                 break;
12373         case CTL_TASK_PORT_LOGOUT:
12374                 break;
12375         case CTL_TASK_QUERY_TASK:
12376                 retval = ctl_query_task(io, 0);
12377                 break;
12378         case CTL_TASK_QUERY_TASK_SET:
12379                 retval = ctl_query_task(io, 1);
12380                 break;
12381         case CTL_TASK_QUERY_ASYNC_EVENT:
12382                 retval = ctl_query_async_event(io);
12383                 break;
12384         default:
12385                 printf("%s: got unknown task management event %d\n",
12386                        __func__, io->taskio.task_action);
12387                 break;
12388         }
12389         if (retval == 0)
12390                 io->io_hdr.status = CTL_SUCCESS;
12391         else
12392                 io->io_hdr.status = CTL_ERROR;
12393         ctl_done(io);
12394 }
12395
12396 /*
12397  * For HA operation.  Handle commands that come in from the other
12398  * controller.
12399  */
12400 static void
12401 ctl_handle_isc(union ctl_io *io)
12402 {
12403         struct ctl_softc *softc = control_softc;
12404         struct ctl_lun *lun;
12405         const struct ctl_cmd_entry *entry;
12406         uint32_t targ_lun;
12407
12408         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12409         switch (io->io_hdr.msg_type) {
12410         case CTL_MSG_SERIALIZE:
12411                 ctl_serialize_other_sc_cmd(&io->scsiio);
12412                 break;
12413         case CTL_MSG_R2R:               /* Only used in SER_ONLY mode. */
12414                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12415                 if (targ_lun >= CTL_MAX_LUNS ||
12416                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12417                         ctl_done(io);
12418                         break;
12419                 }
12420                 mtx_lock(&lun->lun_lock);
12421                 if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12422                         mtx_unlock(&lun->lun_lock);
12423                         ctl_done(io);
12424                         break;
12425                 }
12426                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12427                 mtx_unlock(&lun->lun_lock);
12428                 ctl_enqueue_rtr(io);
12429                 break;
12430         case CTL_MSG_FINISH_IO:
12431                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12432                         ctl_done(io);
12433                         break;
12434                 }
12435                 if (targ_lun >= CTL_MAX_LUNS ||
12436                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12437                         ctl_free_io(io);
12438                         break;
12439                 }
12440                 mtx_lock(&lun->lun_lock);
12441                 TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12442                 ctl_check_blocked(lun);
12443                 mtx_unlock(&lun->lun_lock);
12444                 ctl_free_io(io);
12445                 break;
12446         case CTL_MSG_PERS_ACTION:
12447                 ctl_hndl_per_res_out_on_other_sc(
12448                         (union ctl_ha_msg *)&io->presio.pr_msg);
12449                 ctl_free_io(io);
12450                 break;
12451         case CTL_MSG_BAD_JUJU:
12452                 ctl_done(io);
12453                 break;
12454         case CTL_MSG_DATAMOVE:          /* Only used in XFER mode */
12455                 ctl_datamove_remote(io);
12456                 break;
12457         case CTL_MSG_DATAMOVE_DONE:     /* Only used in XFER mode */
12458                 io->scsiio.be_move_done(io);
12459                 break;
12460         case CTL_MSG_FAILOVER:
12461                 ctl_failover_lun(io);
12462                 ctl_free_io(io);
12463                 break;
12464         default:
12465                 printf("%s: Invalid message type %d\n",
12466                        __func__, io->io_hdr.msg_type);
12467                 ctl_free_io(io);
12468                 break;
12469         }
12470
12471 }
12472
12473
12474 /*
12475  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12476  * there is no match.
12477  */
12478 static ctl_lun_error_pattern
12479 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12480 {
12481         const struct ctl_cmd_entry *entry;
12482         ctl_lun_error_pattern filtered_pattern, pattern;
12483
12484         pattern = desc->error_pattern;
12485
12486         /*
12487          * XXX KDM we need more data passed into this function to match a
12488          * custom pattern, and we actually need to implement custom pattern
12489          * matching.
12490          */
12491         if (pattern & CTL_LUN_PAT_CMD)
12492                 return (CTL_LUN_PAT_CMD);
12493
12494         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12495                 return (CTL_LUN_PAT_ANY);
12496
12497         entry = ctl_get_cmd_entry(ctsio, NULL);
12498
12499         filtered_pattern = entry->pattern & pattern;
12500
12501         /*
12502          * If the user requested specific flags in the pattern (e.g.
12503          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12504          * flags.
12505          *
12506          * If the user did not specify any flags, it doesn't matter whether
12507          * or not the command supports the flags.
12508          */
12509         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12510              (pattern & ~CTL_LUN_PAT_MASK))
12511                 return (CTL_LUN_PAT_NONE);
12512
12513         /*
12514          * If the user asked for a range check, see if the requested LBA
12515          * range overlaps with this command's LBA range.
12516          */
12517         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12518                 uint64_t lba1;
12519                 uint64_t len1;
12520                 ctl_action action;
12521                 int retval;
12522
12523                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12524                 if (retval != 0)
12525                         return (CTL_LUN_PAT_NONE);
12526
12527                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12528                                               desc->lba_range.len, FALSE);
12529                 /*
12530                  * A "pass" means that the LBA ranges don't overlap, so
12531                  * this doesn't match the user's range criteria.
12532                  */
12533                 if (action == CTL_ACTION_PASS)
12534                         return (CTL_LUN_PAT_NONE);
12535         }
12536
12537         return (filtered_pattern);
12538 }
12539
12540 static void
12541 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12542 {
12543         struct ctl_error_desc *desc, *desc2;
12544
12545         mtx_assert(&lun->lun_lock, MA_OWNED);
12546
12547         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12548                 ctl_lun_error_pattern pattern;
12549                 /*
12550                  * Check to see whether this particular command matches
12551                  * the pattern in the descriptor.
12552                  */
12553                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12554                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12555                         continue;
12556
12557                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12558                 case CTL_LUN_INJ_ABORTED:
12559                         ctl_set_aborted(&io->scsiio);
12560                         break;
12561                 case CTL_LUN_INJ_MEDIUM_ERR:
12562                         ctl_set_medium_error(&io->scsiio,
12563                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12564                              CTL_FLAG_DATA_OUT);
12565                         break;
12566                 case CTL_LUN_INJ_UA:
12567                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12568                          * OCCURRED */
12569                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12570                         break;
12571                 case CTL_LUN_INJ_CUSTOM:
12572                         /*
12573                          * We're assuming the user knows what he is doing.
12574                          * Just copy the sense information without doing
12575                          * checks.
12576                          */
12577                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12578                               MIN(sizeof(desc->custom_sense),
12579                                   sizeof(io->scsiio.sense_data)));
12580                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12581                         io->scsiio.sense_len = SSD_FULL_SIZE;
12582                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12583                         break;
12584                 case CTL_LUN_INJ_NONE:
12585                 default:
12586                         /*
12587                          * If this is an error injection type we don't know
12588                          * about, clear the continuous flag (if it is set)
12589                          * so it will get deleted below.
12590                          */
12591                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12592                         break;
12593                 }
12594                 /*
12595                  * By default, each error injection action is a one-shot
12596                  */
12597                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12598                         continue;
12599
12600                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12601
12602                 free(desc, M_CTL);
12603         }
12604 }
12605
12606 #ifdef CTL_IO_DELAY
12607 static void
12608 ctl_datamove_timer_wakeup(void *arg)
12609 {
12610         union ctl_io *io;
12611
12612         io = (union ctl_io *)arg;
12613
12614         ctl_datamove(io);
12615 }
12616 #endif /* CTL_IO_DELAY */
12617
12618 void
12619 ctl_datamove(union ctl_io *io)
12620 {
12621         struct ctl_lun *lun;
12622         void (*fe_datamove)(union ctl_io *io);
12623
12624         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12625
12626         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12627
12628         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12629 #ifdef CTL_TIME_IO
12630         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12631                 char str[256];
12632                 char path_str[64];
12633                 struct sbuf sb;
12634
12635                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12636                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12637
12638                 sbuf_cat(&sb, path_str);
12639                 switch (io->io_hdr.io_type) {
12640                 case CTL_IO_SCSI:
12641                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12642                         sbuf_printf(&sb, "\n");
12643                         sbuf_cat(&sb, path_str);
12644                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12645                                     io->scsiio.tag_num, io->scsiio.tag_type);
12646                         break;
12647                 case CTL_IO_TASK:
12648                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12649                                     "Tag Type: %d\n", io->taskio.task_action,
12650                                     io->taskio.tag_num, io->taskio.tag_type);
12651                         break;
12652                 default:
12653                         panic("%s: Invalid CTL I/O type %d\n",
12654                             __func__, io->io_hdr.io_type);
12655                 }
12656                 sbuf_cat(&sb, path_str);
12657                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12658                             (intmax_t)time_uptime - io->io_hdr.start_time);
12659                 sbuf_finish(&sb);
12660                 printf("%s", sbuf_data(&sb));
12661         }
12662 #endif /* CTL_TIME_IO */
12663
12664 #ifdef CTL_IO_DELAY
12665         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12666                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12667         } else {
12668                 if ((lun != NULL)
12669                  && (lun->delay_info.datamove_delay > 0)) {
12670
12671                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12672                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12673                         callout_reset(&io->io_hdr.delay_callout,
12674                                       lun->delay_info.datamove_delay * hz,
12675                                       ctl_datamove_timer_wakeup, io);
12676                         if (lun->delay_info.datamove_type ==
12677                             CTL_DELAY_TYPE_ONESHOT)
12678                                 lun->delay_info.datamove_delay = 0;
12679                         return;
12680                 }
12681         }
12682 #endif
12683
12684         /*
12685          * This command has been aborted.  Set the port status, so we fail
12686          * the data move.
12687          */
12688         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12689                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12690                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12691                        io->io_hdr.nexus.targ_port,
12692                        io->io_hdr.nexus.targ_lun);
12693                 io->io_hdr.port_status = 31337;
12694                 /*
12695                  * Note that the backend, in this case, will get the
12696                  * callback in its context.  In other cases it may get
12697                  * called in the frontend's interrupt thread context.
12698                  */
12699                 io->scsiio.be_move_done(io);
12700                 return;
12701         }
12702
12703         /* Don't confuse frontend with zero length data move. */
12704         if (io->scsiio.kern_data_len == 0) {
12705                 io->scsiio.be_move_done(io);
12706                 return;
12707         }
12708
12709         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12710         fe_datamove(io);
12711 }
12712
12713 static void
12714 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12715 {
12716         union ctl_ha_msg msg;
12717 #ifdef CTL_TIME_IO
12718         struct bintime cur_bt;
12719 #endif
12720
12721         memset(&msg, 0, sizeof(msg));
12722         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12723         msg.hdr.original_sc = io;
12724         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12725         msg.hdr.nexus = io->io_hdr.nexus;
12726         msg.hdr.status = io->io_hdr.status;
12727         msg.scsi.tag_num = io->scsiio.tag_num;
12728         msg.scsi.tag_type = io->scsiio.tag_type;
12729         msg.scsi.scsi_status = io->scsiio.scsi_status;
12730         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12731                io->scsiio.sense_len);
12732         msg.scsi.sense_len = io->scsiio.sense_len;
12733         msg.scsi.sense_residual = io->scsiio.sense_residual;
12734         msg.scsi.fetd_status = io->io_hdr.port_status;
12735         msg.scsi.residual = io->scsiio.residual;
12736         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12737         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12738                 ctl_failover_io(io, /*have_lock*/ have_lock);
12739                 return;
12740         }
12741         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12742             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12743             msg.scsi.sense_len, M_WAITOK);
12744
12745 #ifdef CTL_TIME_IO
12746         getbinuptime(&cur_bt);
12747         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12748         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12749 #endif
12750         io->io_hdr.num_dmas++;
12751 }
12752
12753 /*
12754  * The DMA to the remote side is done, now we need to tell the other side
12755  * we're done so it can continue with its data movement.
12756  */
12757 static void
12758 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12759 {
12760         union ctl_io *io;
12761         uint32_t i;
12762
12763         io = rq->context;
12764
12765         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12766                 printf("%s: ISC DMA write failed with error %d", __func__,
12767                        rq->ret);
12768                 ctl_set_internal_failure(&io->scsiio,
12769                                          /*sks_valid*/ 1,
12770                                          /*retry_count*/ rq->ret);
12771         }
12772
12773         ctl_dt_req_free(rq);
12774
12775         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12776                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12777         free(io->io_hdr.remote_sglist, M_CTL);
12778         io->io_hdr.remote_sglist = NULL;
12779         io->io_hdr.local_sglist = NULL;
12780
12781         /*
12782          * The data is in local and remote memory, so now we need to send
12783          * status (good or back) back to the other side.
12784          */
12785         ctl_send_datamove_done(io, /*have_lock*/ 0);
12786 }
12787
12788 /*
12789  * We've moved the data from the host/controller into local memory.  Now we
12790  * need to push it over to the remote controller's memory.
12791  */
12792 static int
12793 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12794 {
12795         int retval;
12796
12797         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12798                                           ctl_datamove_remote_write_cb);
12799         return (retval);
12800 }
12801
12802 static void
12803 ctl_datamove_remote_write(union ctl_io *io)
12804 {
12805         int retval;
12806         void (*fe_datamove)(union ctl_io *io);
12807
12808         /*
12809          * - Get the data from the host/HBA into local memory.
12810          * - DMA memory from the local controller to the remote controller.
12811          * - Send status back to the remote controller.
12812          */
12813
12814         retval = ctl_datamove_remote_sgl_setup(io);
12815         if (retval != 0)
12816                 return;
12817
12818         /* Switch the pointer over so the FETD knows what to do */
12819         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12820
12821         /*
12822          * Use a custom move done callback, since we need to send completion
12823          * back to the other controller, not to the backend on this side.
12824          */
12825         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12826
12827         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12828         fe_datamove(io);
12829 }
12830
12831 static int
12832 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12833 {
12834 #if 0
12835         char str[256];
12836         char path_str[64];
12837         struct sbuf sb;
12838 #endif
12839         uint32_t i;
12840
12841         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12842                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12843         free(io->io_hdr.remote_sglist, M_CTL);
12844         io->io_hdr.remote_sglist = NULL;
12845         io->io_hdr.local_sglist = NULL;
12846
12847 #if 0
12848         scsi_path_string(io, path_str, sizeof(path_str));
12849         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12850         sbuf_cat(&sb, path_str);
12851         scsi_command_string(&io->scsiio, NULL, &sb);
12852         sbuf_printf(&sb, "\n");
12853         sbuf_cat(&sb, path_str);
12854         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12855                     io->scsiio.tag_num, io->scsiio.tag_type);
12856         sbuf_cat(&sb, path_str);
12857         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12858                     io->io_hdr.flags, io->io_hdr.status);
12859         sbuf_finish(&sb);
12860         printk("%s", sbuf_data(&sb));
12861 #endif
12862
12863
12864         /*
12865          * The read is done, now we need to send status (good or bad) back
12866          * to the other side.
12867          */
12868         ctl_send_datamove_done(io, /*have_lock*/ 0);
12869
12870         return (0);
12871 }
12872
12873 static void
12874 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12875 {
12876         union ctl_io *io;
12877         void (*fe_datamove)(union ctl_io *io);
12878
12879         io = rq->context;
12880
12881         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12882                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12883                        rq->ret);
12884                 ctl_set_internal_failure(&io->scsiio,
12885                                          /*sks_valid*/ 1,
12886                                          /*retry_count*/ rq->ret);
12887         }
12888
12889         ctl_dt_req_free(rq);
12890
12891         /* Switch the pointer over so the FETD knows what to do */
12892         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12893
12894         /*
12895          * Use a custom move done callback, since we need to send completion
12896          * back to the other controller, not to the backend on this side.
12897          */
12898         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12899
12900         /* XXX KDM add checks like the ones in ctl_datamove? */
12901
12902         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12903         fe_datamove(io);
12904 }
12905
12906 static int
12907 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12908 {
12909         struct ctl_sg_entry *local_sglist;
12910         uint32_t len_to_go;
12911         int retval;
12912         int i;
12913
12914         retval = 0;
12915         local_sglist = io->io_hdr.local_sglist;
12916         len_to_go = io->scsiio.kern_data_len;
12917
12918         /*
12919          * The difficult thing here is that the size of the various
12920          * S/G segments may be different than the size from the
12921          * remote controller.  That'll make it harder when DMAing
12922          * the data back to the other side.
12923          */
12924         for (i = 0; len_to_go > 0; i++) {
12925                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12926                 local_sglist[i].addr =
12927                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12928
12929                 len_to_go -= local_sglist[i].len;
12930         }
12931         /*
12932          * Reset the number of S/G entries accordingly.  The original
12933          * number of S/G entries is available in rem_sg_entries.
12934          */
12935         io->scsiio.kern_sg_entries = i;
12936
12937 #if 0
12938         printf("%s: kern_sg_entries = %d\n", __func__,
12939                io->scsiio.kern_sg_entries);
12940         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12941                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12942                        local_sglist[i].addr, local_sglist[i].len);
12943 #endif
12944
12945         return (retval);
12946 }
12947
12948 static int
12949 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12950                          ctl_ha_dt_cb callback)
12951 {
12952         struct ctl_ha_dt_req *rq;
12953         struct ctl_sg_entry *remote_sglist, *local_sglist;
12954         uint32_t local_used, remote_used, total_used;
12955         int i, j, isc_ret;
12956
12957         rq = ctl_dt_req_alloc();
12958
12959         /*
12960          * If we failed to allocate the request, and if the DMA didn't fail
12961          * anyway, set busy status.  This is just a resource allocation
12962          * failure.
12963          */
12964         if ((rq == NULL)
12965          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12966              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12967                 ctl_set_busy(&io->scsiio);
12968
12969         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12970             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12971
12972                 if (rq != NULL)
12973                         ctl_dt_req_free(rq);
12974
12975                 /*
12976                  * The data move failed.  We need to return status back
12977                  * to the other controller.  No point in trying to DMA
12978                  * data to the remote controller.
12979                  */
12980
12981                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12982
12983                 return (1);
12984         }
12985
12986         local_sglist = io->io_hdr.local_sglist;
12987         remote_sglist = io->io_hdr.remote_sglist;
12988         local_used = 0;
12989         remote_used = 0;
12990         total_used = 0;
12991
12992         /*
12993          * Pull/push the data over the wire from/to the other controller.
12994          * This takes into account the possibility that the local and
12995          * remote sglists may not be identical in terms of the size of
12996          * the elements and the number of elements.
12997          *
12998          * One fundamental assumption here is that the length allocated for
12999          * both the local and remote sglists is identical.  Otherwise, we've
13000          * essentially got a coding error of some sort.
13001          */
13002         isc_ret = CTL_HA_STATUS_SUCCESS;
13003         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13004                 uint32_t cur_len;
13005                 uint8_t *tmp_ptr;
13006
13007                 rq->command = command;
13008                 rq->context = io;
13009
13010                 /*
13011                  * Both pointers should be aligned.  But it is possible
13012                  * that the allocation length is not.  They should both
13013                  * also have enough slack left over at the end, though,
13014                  * to round up to the next 8 byte boundary.
13015                  */
13016                 cur_len = MIN(local_sglist[i].len - local_used,
13017                               remote_sglist[j].len - remote_used);
13018                 rq->size = cur_len;
13019
13020                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13021                 tmp_ptr += local_used;
13022
13023 #if 0
13024                 /* Use physical addresses when talking to ISC hardware */
13025                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13026                         /* XXX KDM use busdma */
13027                         rq->local = vtophys(tmp_ptr);
13028                 } else
13029                         rq->local = tmp_ptr;
13030 #else
13031                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13032                     ("HA does not support BUS_ADDR"));
13033                 rq->local = tmp_ptr;
13034 #endif
13035
13036                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13037                 tmp_ptr += remote_used;
13038                 rq->remote = tmp_ptr;
13039
13040                 rq->callback = NULL;
13041
13042                 local_used += cur_len;
13043                 if (local_used >= local_sglist[i].len) {
13044                         i++;
13045                         local_used = 0;
13046                 }
13047
13048                 remote_used += cur_len;
13049                 if (remote_used >= remote_sglist[j].len) {
13050                         j++;
13051                         remote_used = 0;
13052                 }
13053                 total_used += cur_len;
13054
13055                 if (total_used >= io->scsiio.kern_data_len)
13056                         rq->callback = callback;
13057
13058 #if 0
13059                 printf("%s: %s: local %p remote %p size %d\n", __func__,
13060                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13061                        rq->local, rq->remote, rq->size);
13062 #endif
13063
13064                 isc_ret = ctl_dt_single(rq);
13065                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
13066                         break;
13067         }
13068         if (isc_ret != CTL_HA_STATUS_WAIT) {
13069                 rq->ret = isc_ret;
13070                 callback(rq);
13071         }
13072
13073         return (0);
13074 }
13075
13076 static void
13077 ctl_datamove_remote_read(union ctl_io *io)
13078 {
13079         int retval;
13080         uint32_t i;
13081
13082         /*
13083          * This will send an error to the other controller in the case of a
13084          * failure.
13085          */
13086         retval = ctl_datamove_remote_sgl_setup(io);
13087         if (retval != 0)
13088                 return;
13089
13090         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13091                                           ctl_datamove_remote_read_cb);
13092         if (retval != 0) {
13093                 /*
13094                  * Make sure we free memory if there was an error..  The
13095                  * ctl_datamove_remote_xfer() function will send the
13096                  * datamove done message, or call the callback with an
13097                  * error if there is a problem.
13098                  */
13099                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13100                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13101                 free(io->io_hdr.remote_sglist, M_CTL);
13102                 io->io_hdr.remote_sglist = NULL;
13103                 io->io_hdr.local_sglist = NULL;
13104         }
13105 }
13106
13107 /*
13108  * Process a datamove request from the other controller.  This is used for
13109  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13110  * first.  Once that is complete, the data gets DMAed into the remote
13111  * controller's memory.  For reads, we DMA from the remote controller's
13112  * memory into our memory first, and then move it out to the FETD.
13113  */
13114 static void
13115 ctl_datamove_remote(union ctl_io *io)
13116 {
13117
13118         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13119
13120         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13121                 ctl_failover_io(io, /*have_lock*/ 0);
13122                 return;
13123         }
13124
13125         /*
13126          * Note that we look for an aborted I/O here, but don't do some of
13127          * the other checks that ctl_datamove() normally does.
13128          * We don't need to run the datamove delay code, since that should
13129          * have been done if need be on the other controller.
13130          */
13131         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13132                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13133                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13134                        io->io_hdr.nexus.targ_port,
13135                        io->io_hdr.nexus.targ_lun);
13136                 io->io_hdr.port_status = 31338;
13137                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13138                 return;
13139         }
13140
13141         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13142                 ctl_datamove_remote_write(io);
13143         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13144                 ctl_datamove_remote_read(io);
13145         else {
13146                 io->io_hdr.port_status = 31339;
13147                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13148         }
13149 }
13150
13151 static void
13152 ctl_process_done(union ctl_io *io)
13153 {
13154         struct ctl_lun *lun;
13155         struct ctl_softc *softc = control_softc;
13156         void (*fe_done)(union ctl_io *io);
13157         union ctl_ha_msg msg;
13158         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13159
13160         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13161         fe_done = softc->ctl_ports[targ_port]->fe_done;
13162
13163 #ifdef CTL_TIME_IO
13164         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13165                 char str[256];
13166                 char path_str[64];
13167                 struct sbuf sb;
13168
13169                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13170                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13171
13172                 sbuf_cat(&sb, path_str);
13173                 switch (io->io_hdr.io_type) {
13174                 case CTL_IO_SCSI:
13175                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13176                         sbuf_printf(&sb, "\n");
13177                         sbuf_cat(&sb, path_str);
13178                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13179                                     io->scsiio.tag_num, io->scsiio.tag_type);
13180                         break;
13181                 case CTL_IO_TASK:
13182                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13183                                     "Tag Type: %d\n", io->taskio.task_action,
13184                                     io->taskio.tag_num, io->taskio.tag_type);
13185                         break;
13186                 default:
13187                         panic("%s: Invalid CTL I/O type %d\n",
13188                             __func__, io->io_hdr.io_type);
13189                 }
13190                 sbuf_cat(&sb, path_str);
13191                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13192                             (intmax_t)time_uptime - io->io_hdr.start_time);
13193                 sbuf_finish(&sb);
13194                 printf("%s", sbuf_data(&sb));
13195         }
13196 #endif /* CTL_TIME_IO */
13197
13198         switch (io->io_hdr.io_type) {
13199         case CTL_IO_SCSI:
13200                 break;
13201         case CTL_IO_TASK:
13202                 if (ctl_debug & CTL_DEBUG_INFO)
13203                         ctl_io_error_print(io, NULL);
13204                 fe_done(io);
13205                 return;
13206         default:
13207                 panic("%s: Invalid CTL I/O type %d\n",
13208                     __func__, io->io_hdr.io_type);
13209         }
13210
13211         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13212         if (lun == NULL) {
13213                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13214                                  io->io_hdr.nexus.targ_mapped_lun));
13215                 goto bailout;
13216         }
13217
13218         mtx_lock(&lun->lun_lock);
13219
13220         /*
13221          * Check to see if we have any informational exception and status
13222          * of this command can be modified to report it in form of either
13223          * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13224          */
13225         if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13226             io->io_hdr.status == CTL_SUCCESS &&
13227             (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13228                 uint8_t mrie = lun->MODE_IE.mrie;
13229                 uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13230                     (lun->MODE_VER.byte3 & SMS_VER_PER));
13231                 if (((mrie == SIEP_MRIE_REC_COND && per) ||
13232                      mrie == SIEP_MRIE_REC_UNCOND ||
13233                      mrie == SIEP_MRIE_NO_SENSE) &&
13234                     (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13235                      CTL_CMD_FLAG_NO_SENSE) == 0) {
13236                         ctl_set_sense(&io->scsiio,
13237                               /*current_error*/ 1,
13238                               /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13239                                 SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13240                               /*asc*/ lun->ie_asc,
13241                               /*ascq*/ lun->ie_ascq,
13242                               SSD_ELEM_NONE);
13243                         lun->ie_reported = 1;
13244                 }
13245         } else if (lun->ie_reported < 0)
13246                 lun->ie_reported = 0;
13247
13248         /*
13249          * Check to see if we have any errors to inject here.  We only
13250          * inject errors for commands that don't already have errors set.
13251          */
13252         if (!STAILQ_EMPTY(&lun->error_list) &&
13253             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13254             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13255                 ctl_inject_error(lun, io);
13256
13257         /*
13258          * XXX KDM how do we treat commands that aren't completed
13259          * successfully?
13260          *
13261          * XXX KDM should we also track I/O latency?
13262          */
13263         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13264             io->io_hdr.io_type == CTL_IO_SCSI) {
13265 #ifdef CTL_TIME_IO
13266                 struct bintime cur_bt;
13267 #endif
13268                 int type;
13269
13270                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13271                     CTL_FLAG_DATA_IN)
13272                         type = CTL_STATS_READ;
13273                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13274                     CTL_FLAG_DATA_OUT)
13275                         type = CTL_STATS_WRITE;
13276                 else
13277                         type = CTL_STATS_NO_IO;
13278
13279                 lun->stats.ports[targ_port].bytes[type] +=
13280                     io->scsiio.kern_total_len;
13281                 lun->stats.ports[targ_port].operations[type]++;
13282 #ifdef CTL_TIME_IO
13283                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13284                    &io->io_hdr.dma_bt);
13285                 getbinuptime(&cur_bt);
13286                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13287                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13288 #endif
13289                 lun->stats.ports[targ_port].num_dmas[type] +=
13290                     io->io_hdr.num_dmas;
13291         }
13292
13293         /*
13294          * Remove this from the OOA queue.
13295          */
13296         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13297 #ifdef CTL_TIME_IO
13298         if (TAILQ_EMPTY(&lun->ooa_queue))
13299                 lun->last_busy = getsbinuptime();
13300 #endif
13301
13302         /*
13303          * Run through the blocked queue on this LUN and see if anything
13304          * has become unblocked, now that this transaction is done.
13305          */
13306         ctl_check_blocked(lun);
13307
13308         /*
13309          * If the LUN has been invalidated, free it if there is nothing
13310          * left on its OOA queue.
13311          */
13312         if ((lun->flags & CTL_LUN_INVALID)
13313          && TAILQ_EMPTY(&lun->ooa_queue)) {
13314                 mtx_unlock(&lun->lun_lock);
13315                 mtx_lock(&softc->ctl_lock);
13316                 ctl_free_lun(lun);
13317                 mtx_unlock(&softc->ctl_lock);
13318         } else
13319                 mtx_unlock(&lun->lun_lock);
13320
13321 bailout:
13322
13323         /*
13324          * If this command has been aborted, make sure we set the status
13325          * properly.  The FETD is responsible for freeing the I/O and doing
13326          * whatever it needs to do to clean up its state.
13327          */
13328         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13329                 ctl_set_task_aborted(&io->scsiio);
13330
13331         /*
13332          * If enabled, print command error status.
13333          */
13334         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13335             (ctl_debug & CTL_DEBUG_INFO) != 0)
13336                 ctl_io_error_print(io, NULL);
13337
13338         /*
13339          * Tell the FETD or the other shelf controller we're done with this
13340          * command.  Note that only SCSI commands get to this point.  Task
13341          * management commands are completed above.
13342          */
13343         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13344             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13345                 memset(&msg, 0, sizeof(msg));
13346                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13347                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13348                 msg.hdr.nexus = io->io_hdr.nexus;
13349                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13350                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13351                     M_WAITOK);
13352         }
13353
13354         fe_done(io);
13355 }
13356
13357 #ifdef CTL_WITH_CA
13358 /*
13359  * Front end should call this if it doesn't do autosense.  When the request
13360  * sense comes back in from the initiator, we'll dequeue this and send it.
13361  */
13362 int
13363 ctl_queue_sense(union ctl_io *io)
13364 {
13365         struct ctl_lun *lun;
13366         struct ctl_port *port;
13367         struct ctl_softc *softc;
13368         uint32_t initidx, targ_lun;
13369
13370         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13371
13372         softc = control_softc;
13373         port = ctl_io_port(&ctsio->io_hdr);
13374         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13375
13376         /*
13377          * LUN lookup will likely move to the ctl_work_thread() once we
13378          * have our new queueing infrastructure (that doesn't put things on
13379          * a per-LUN queue initially).  That is so that we can handle
13380          * things like an INQUIRY to a LUN that we don't have enabled.  We
13381          * can't deal with that right now.
13382          * If we don't have a LUN for this, just toss the sense information.
13383          */
13384         mtx_lock(&softc->ctl_lock);
13385         if (targ_lun >= CTL_MAX_LUNS ||
13386             (lun = softc->ctl_luns[targ_lun]) == NULL) {
13387                 mtx_unlock(&softc->ctl_lock);
13388                 goto bailout;
13389         }
13390         mtx_lock(&lun->lun_lock);
13391         mtx_unlock(&softc->ctl_lock);
13392
13393         /*
13394          * Already have CA set for this LUN...toss the sense information.
13395          */
13396         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13397         if (ctl_is_set(lun->have_ca, initidx)) {
13398                 mtx_unlock(&lun->lun_lock);
13399                 goto bailout;
13400         }
13401
13402         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13403                MIN(sizeof(lun->pending_sense[initidx]),
13404                sizeof(io->scsiio.sense_data)));
13405         ctl_set_mask(lun->have_ca, initidx);
13406         mtx_unlock(&lun->lun_lock);
13407
13408 bailout:
13409         ctl_free_io(io);
13410         return (CTL_RETVAL_COMPLETE);
13411 }
13412 #endif
13413
13414 /*
13415  * Primary command inlet from frontend ports.  All SCSI and task I/O
13416  * requests must go through this function.
13417  */
13418 int
13419 ctl_queue(union ctl_io *io)
13420 {
13421         struct ctl_port *port;
13422
13423         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13424
13425 #ifdef CTL_TIME_IO
13426         io->io_hdr.start_time = time_uptime;
13427         getbinuptime(&io->io_hdr.start_bt);
13428 #endif /* CTL_TIME_IO */
13429
13430         /* Map FE-specific LUN ID into global one. */
13431         port = ctl_io_port(&io->io_hdr);
13432         io->io_hdr.nexus.targ_mapped_lun =
13433             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13434
13435         switch (io->io_hdr.io_type) {
13436         case CTL_IO_SCSI:
13437         case CTL_IO_TASK:
13438                 if (ctl_debug & CTL_DEBUG_CDB)
13439                         ctl_io_print(io);
13440                 ctl_enqueue_incoming(io);
13441                 break;
13442         default:
13443                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13444                 return (EINVAL);
13445         }
13446
13447         return (CTL_RETVAL_COMPLETE);
13448 }
13449
13450 #ifdef CTL_IO_DELAY
13451 static void
13452 ctl_done_timer_wakeup(void *arg)
13453 {
13454         union ctl_io *io;
13455
13456         io = (union ctl_io *)arg;
13457         ctl_done(io);
13458 }
13459 #endif /* CTL_IO_DELAY */
13460
13461 void
13462 ctl_serseq_done(union ctl_io *io)
13463 {
13464         struct ctl_lun *lun;
13465
13466         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13467         if (lun->be_lun == NULL ||
13468             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13469                 return;
13470         mtx_lock(&lun->lun_lock);
13471         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13472         ctl_check_blocked(lun);
13473         mtx_unlock(&lun->lun_lock);
13474 }
13475
13476 void
13477 ctl_done(union ctl_io *io)
13478 {
13479
13480         /*
13481          * Enable this to catch duplicate completion issues.
13482          */
13483 #if 0
13484         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13485                 printf("%s: type %d msg %d cdb %x iptl: "
13486                        "%u:%u:%u tag 0x%04x "
13487                        "flag %#x status %x\n",
13488                         __func__,
13489                         io->io_hdr.io_type,
13490                         io->io_hdr.msg_type,
13491                         io->scsiio.cdb[0],
13492                         io->io_hdr.nexus.initid,
13493                         io->io_hdr.nexus.targ_port,
13494                         io->io_hdr.nexus.targ_lun,
13495                         (io->io_hdr.io_type ==
13496                         CTL_IO_TASK) ?
13497                         io->taskio.tag_num :
13498                         io->scsiio.tag_num,
13499                         io->io_hdr.flags,
13500                         io->io_hdr.status);
13501         } else
13502                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13503 #endif
13504
13505         /*
13506          * This is an internal copy of an I/O, and should not go through
13507          * the normal done processing logic.
13508          */
13509         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13510                 return;
13511
13512 #ifdef CTL_IO_DELAY
13513         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13514                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13515         } else {
13516                 struct ctl_lun *lun;
13517
13518                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13519
13520                 if ((lun != NULL)
13521                  && (lun->delay_info.done_delay > 0)) {
13522
13523                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13524                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13525                         callout_reset(&io->io_hdr.delay_callout,
13526                                       lun->delay_info.done_delay * hz,
13527                                       ctl_done_timer_wakeup, io);
13528                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13529                                 lun->delay_info.done_delay = 0;
13530                         return;
13531                 }
13532         }
13533 #endif /* CTL_IO_DELAY */
13534
13535         ctl_enqueue_done(io);
13536 }
13537
13538 static void
13539 ctl_work_thread(void *arg)
13540 {
13541         struct ctl_thread *thr = (struct ctl_thread *)arg;
13542         struct ctl_softc *softc = thr->ctl_softc;
13543         union ctl_io *io;
13544         int retval;
13545
13546         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13547
13548         for (;;) {
13549                 /*
13550                  * We handle the queues in this order:
13551                  * - ISC
13552                  * - done queue (to free up resources, unblock other commands)
13553                  * - RtR queue
13554                  * - incoming queue
13555                  *
13556                  * If those queues are empty, we break out of the loop and
13557                  * go to sleep.
13558                  */
13559                 mtx_lock(&thr->queue_lock);
13560                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13561                 if (io != NULL) {
13562                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13563                         mtx_unlock(&thr->queue_lock);
13564                         ctl_handle_isc(io);
13565                         continue;
13566                 }
13567                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13568                 if (io != NULL) {
13569                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13570                         /* clear any blocked commands, call fe_done */
13571                         mtx_unlock(&thr->queue_lock);
13572                         ctl_process_done(io);
13573                         continue;
13574                 }
13575                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13576                 if (io != NULL) {
13577                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13578                         mtx_unlock(&thr->queue_lock);
13579                         if (io->io_hdr.io_type == CTL_IO_TASK)
13580                                 ctl_run_task(io);
13581                         else
13582                                 ctl_scsiio_precheck(softc, &io->scsiio);
13583                         continue;
13584                 }
13585                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13586                 if (io != NULL) {
13587                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13588                         mtx_unlock(&thr->queue_lock);
13589                         retval = ctl_scsiio(&io->scsiio);
13590                         if (retval != CTL_RETVAL_COMPLETE)
13591                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13592                         continue;
13593                 }
13594
13595                 /* Sleep until we have something to do. */
13596                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13597         }
13598 }
13599
13600 static void
13601 ctl_lun_thread(void *arg)
13602 {
13603         struct ctl_softc *softc = (struct ctl_softc *)arg;
13604         struct ctl_be_lun *be_lun;
13605
13606         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13607
13608         for (;;) {
13609                 mtx_lock(&softc->ctl_lock);
13610                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13611                 if (be_lun != NULL) {
13612                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13613                         mtx_unlock(&softc->ctl_lock);
13614                         ctl_create_lun(be_lun);
13615                         continue;
13616                 }
13617
13618                 /* Sleep until we have something to do. */
13619                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13620                     PDROP | PRIBIO, "-", 0);
13621         }
13622 }
13623
13624 static void
13625 ctl_thresh_thread(void *arg)
13626 {
13627         struct ctl_softc *softc = (struct ctl_softc *)arg;
13628         struct ctl_lun *lun;
13629         struct ctl_logical_block_provisioning_page *page;
13630         const char *attr;
13631         union ctl_ha_msg msg;
13632         uint64_t thres, val;
13633         int i, e, set;
13634
13635         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13636
13637         for (;;) {
13638                 mtx_lock(&softc->ctl_lock);
13639                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13640                         if ((lun->flags & CTL_LUN_DISABLED) ||
13641                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13642                             lun->backend->lun_attr == NULL)
13643                                 continue;
13644                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13645                             softc->ha_mode == CTL_HA_MODE_XFER)
13646                                 continue;
13647                         if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13648                                 continue;
13649                         e = 0;
13650                         page = &lun->MODE_LBP;
13651                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13652                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13653                                         continue;
13654                                 thres = scsi_4btoul(page->descr[i].count);
13655                                 thres <<= CTL_LBP_EXPONENT;
13656                                 switch (page->descr[i].resource) {
13657                                 case 0x01:
13658                                         attr = "blocksavail";
13659                                         break;
13660                                 case 0x02:
13661                                         attr = "blocksused";
13662                                         break;
13663                                 case 0xf1:
13664                                         attr = "poolblocksavail";
13665                                         break;
13666                                 case 0xf2:
13667                                         attr = "poolblocksused";
13668                                         break;
13669                                 default:
13670                                         continue;
13671                                 }
13672                                 mtx_unlock(&softc->ctl_lock); // XXX
13673                                 val = lun->backend->lun_attr(
13674                                     lun->be_lun->be_lun, attr);
13675                                 mtx_lock(&softc->ctl_lock);
13676                                 if (val == UINT64_MAX)
13677                                         continue;
13678                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13679                                     == SLBPPD_ARMING_INC)
13680                                         e = (val >= thres);
13681                                 else
13682                                         e = (val <= thres);
13683                                 if (e)
13684                                         break;
13685                         }
13686                         mtx_lock(&lun->lun_lock);
13687                         if (e) {
13688                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13689                                     (uint8_t *)page, lun->ua_tpt_info);
13690                                 if (lun->lasttpt == 0 ||
13691                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13692                                         lun->lasttpt = time_uptime;
13693                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13694                                         set = 1;
13695                                 } else
13696                                         set = 0;
13697                         } else {
13698                                 lun->lasttpt = 0;
13699                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13700                                 set = -1;
13701                         }
13702                         mtx_unlock(&lun->lun_lock);
13703                         if (set != 0 &&
13704                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13705                                 /* Send msg to other side. */
13706                                 bzero(&msg.ua, sizeof(msg.ua));
13707                                 msg.hdr.msg_type = CTL_MSG_UA;
13708                                 msg.hdr.nexus.initid = -1;
13709                                 msg.hdr.nexus.targ_port = -1;
13710                                 msg.hdr.nexus.targ_lun = lun->lun;
13711                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13712                                 msg.ua.ua_all = 1;
13713                                 msg.ua.ua_set = (set > 0);
13714                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13715                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13716                                 mtx_unlock(&softc->ctl_lock); // XXX
13717                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13718                                     sizeof(msg.ua), M_WAITOK);
13719                                 mtx_lock(&softc->ctl_lock);
13720                         }
13721                 }
13722                 mtx_unlock(&softc->ctl_lock);
13723                 pause("-", CTL_LBP_PERIOD * hz);
13724         }
13725 }
13726
13727 static void
13728 ctl_enqueue_incoming(union ctl_io *io)
13729 {
13730         struct ctl_softc *softc = control_softc;
13731         struct ctl_thread *thr;
13732         u_int idx;
13733
13734         idx = (io->io_hdr.nexus.targ_port * 127 +
13735                io->io_hdr.nexus.initid) % worker_threads;
13736         thr = &softc->threads[idx];
13737         mtx_lock(&thr->queue_lock);
13738         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13739         mtx_unlock(&thr->queue_lock);
13740         wakeup(thr);
13741 }
13742
13743 static void
13744 ctl_enqueue_rtr(union ctl_io *io)
13745 {
13746         struct ctl_softc *softc = control_softc;
13747         struct ctl_thread *thr;
13748
13749         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13750         mtx_lock(&thr->queue_lock);
13751         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13752         mtx_unlock(&thr->queue_lock);
13753         wakeup(thr);
13754 }
13755
13756 static void
13757 ctl_enqueue_done(union ctl_io *io)
13758 {
13759         struct ctl_softc *softc = control_softc;
13760         struct ctl_thread *thr;
13761
13762         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13763         mtx_lock(&thr->queue_lock);
13764         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13765         mtx_unlock(&thr->queue_lock);
13766         wakeup(thr);
13767 }
13768
13769 static void
13770 ctl_enqueue_isc(union ctl_io *io)
13771 {
13772         struct ctl_softc *softc = control_softc;
13773         struct ctl_thread *thr;
13774
13775         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13776         mtx_lock(&thr->queue_lock);
13777         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13778         mtx_unlock(&thr->queue_lock);
13779         wakeup(thr);
13780 }
13781
13782 /*
13783  *  vim: ts=8
13784  */