]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r310778, r310782: Improve use of I/O's private area.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42
43 #define _CTL_C
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_cd.h>
73 #include <cam/scsi/scsi_da.h>
74 #include <cam/ctl/ctl_io.h>
75 #include <cam/ctl/ctl.h>
76 #include <cam/ctl/ctl_frontend.h>
77 #include <cam/ctl/ctl_util.h>
78 #include <cam/ctl/ctl_backend.h>
79 #include <cam/ctl/ctl_ioctl.h>
80 #include <cam/ctl/ctl_ha.h>
81 #include <cam/ctl/ctl_private.h>
82 #include <cam/ctl/ctl_debug.h>
83 #include <cam/ctl/ctl_scsi_all.h>
84 #include <cam/ctl/ctl_error.h>
85
86 struct ctl_softc *control_softc = NULL;
87
88 /*
89  * Template mode pages.
90  */
91
92 /*
93  * Note that these are default values only.  The actual values will be
94  * filled in when the user does a mode sense.
95  */
96 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
97         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100         /*read_retry_count*/0,
101         /*correction_span*/0,
102         /*head_offset_count*/0,
103         /*data_strobe_offset_cnt*/0,
104         /*byte8*/SMS_RWER_LBPERE,
105         /*write_retry_count*/0,
106         /*reserved2*/0,
107         /*recovery_time_limit*/{0, 0},
108 };
109
110 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113         /*byte3*/SMS_RWER_PER,
114         /*read_retry_count*/0,
115         /*correction_span*/0,
116         /*head_offset_count*/0,
117         /*data_strobe_offset_cnt*/0,
118         /*byte8*/SMS_RWER_LBPERE,
119         /*write_retry_count*/0,
120         /*reserved2*/0,
121         /*recovery_time_limit*/{0, 0},
122 };
123
124 const static struct scsi_format_page format_page_default = {
125         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
126         /*page_length*/sizeof(struct scsi_format_page) - 2,
127         /*tracks_per_zone*/ {0, 0},
128         /*alt_sectors_per_zone*/ {0, 0},
129         /*alt_tracks_per_zone*/ {0, 0},
130         /*alt_tracks_per_lun*/ {0, 0},
131         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133         /*bytes_per_sector*/ {0, 0},
134         /*interleave*/ {0, 0},
135         /*track_skew*/ {0, 0},
136         /*cylinder_skew*/ {0, 0},
137         /*flags*/ SFP_HSEC,
138         /*reserved*/ {0, 0, 0}
139 };
140
141 const static struct scsi_format_page format_page_changeable = {
142         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
143         /*page_length*/sizeof(struct scsi_format_page) - 2,
144         /*tracks_per_zone*/ {0, 0},
145         /*alt_sectors_per_zone*/ {0, 0},
146         /*alt_tracks_per_zone*/ {0, 0},
147         /*alt_tracks_per_lun*/ {0, 0},
148         /*sectors_per_track*/ {0, 0},
149         /*bytes_per_sector*/ {0, 0},
150         /*interleave*/ {0, 0},
151         /*track_skew*/ {0, 0},
152         /*cylinder_skew*/ {0, 0},
153         /*flags*/ 0,
154         /*reserved*/ {0, 0, 0}
155 };
156
157 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158         /*page_code*/SMS_RIGID_DISK_PAGE,
159         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160         /*cylinders*/ {0, 0, 0},
161         /*heads*/ CTL_DEFAULT_HEADS,
162         /*start_write_precomp*/ {0, 0, 0},
163         /*start_reduced_current*/ {0, 0, 0},
164         /*step_rate*/ {0, 0},
165         /*landing_zone_cylinder*/ {0, 0, 0},
166         /*rpl*/ SRDP_RPL_DISABLED,
167         /*rotational_offset*/ 0,
168         /*reserved1*/ 0,
169         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170                            CTL_DEFAULT_ROTATION_RATE & 0xff},
171         /*reserved2*/ {0, 0}
172 };
173
174 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175         /*page_code*/SMS_RIGID_DISK_PAGE,
176         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177         /*cylinders*/ {0, 0, 0},
178         /*heads*/ 0,
179         /*start_write_precomp*/ {0, 0, 0},
180         /*start_reduced_current*/ {0, 0, 0},
181         /*step_rate*/ {0, 0},
182         /*landing_zone_cylinder*/ {0, 0, 0},
183         /*rpl*/ 0,
184         /*rotational_offset*/ 0,
185         /*reserved1*/ 0,
186         /*rotation_rate*/ {0, 0},
187         /*reserved2*/ {0, 0}
188 };
189
190 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193         /*byte3*/0,
194         /*read_retry_count*/0,
195         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
196         /*recovery_time_limit*/{0, 0},
197 };
198
199 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200         /*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201         /*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202         /*byte3*/SMS_VER_PER,
203         /*read_retry_count*/0,
204         /*reserved*/{ 0, 0, 0, 0, 0, 0 },
205         /*recovery_time_limit*/{0, 0},
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
265
266 const static struct scsi_control_ext_page control_ext_page_default = {
267         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268         /*subpage_code*/0x01,
269         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270         /*flags*/0,
271         /*prio*/0,
272         /*max_sense*/0
273 };
274
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277         /*subpage_code*/0x01,
278         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279         /*flags*/0,
280         /*prio*/0,
281         /*max_sense*/0xff
282 };
283
284 const static struct scsi_info_exceptions_page ie_page_default = {
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287         /*info_flags*/SIEP_FLAGS_EWASC,
288         /*mrie*/SIEP_MRIE_NO,
289         /*interval_timer*/{0, 0, 0, 0},
290         /*report_count*/{0, 0, 0, 1}
291 };
292
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296         /*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297             SIEP_FLAGS_LOGERR,
298         /*mrie*/0x0f,
299         /*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300         /*report_count*/{0xff, 0xff, 0xff, 0xff}
301 };
302
303 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307         /*subpage_code*/0x02,
308         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309         /*flags*/0,
310         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311         /*descr*/{}},
312         {{/*flags*/0,
313           /*resource*/0x01,
314           /*reserved*/{0, 0},
315           /*count*/{0, 0, 0, 0}},
316          {/*flags*/0,
317           /*resource*/0x02,
318           /*reserved*/{0, 0},
319           /*count*/{0, 0, 0, 0}},
320          {/*flags*/0,
321           /*resource*/0xf1,
322           /*reserved*/{0, 0},
323           /*count*/{0, 0, 0, 0}},
324          {/*flags*/0,
325           /*resource*/0xf2,
326           /*reserved*/{0, 0},
327           /*count*/{0, 0, 0, 0}}
328         }
329 };
330
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333         /*subpage_code*/0x02,
334         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335         /*flags*/SLBPP_SITUA,
336         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337         /*descr*/{}},
338         {{/*flags*/0,
339           /*resource*/0,
340           /*reserved*/{0, 0},
341           /*count*/{0, 0, 0, 0}},
342          {/*flags*/0,
343           /*resource*/0,
344           /*reserved*/{0, 0},
345           /*count*/{0, 0, 0, 0}},
346          {/*flags*/0,
347           /*resource*/0,
348           /*reserved*/{0, 0},
349           /*count*/{0, 0, 0, 0}},
350          {/*flags*/0,
351           /*resource*/0,
352           /*reserved*/{0, 0},
353           /*count*/{0, 0, 0, 0}}
354         }
355 };
356
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358         /*page_code*/SMS_CDDVD_CAPS_PAGE,
359         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360         /*caps1*/0x3f,
361         /*caps2*/0x00,
362         /*caps3*/0xf0,
363         /*caps4*/0x00,
364         /*caps5*/0x29,
365         /*caps6*/0x00,
366         /*obsolete*/{0, 0},
367         /*nvol_levels*/{0, 0},
368         /*buffer_size*/{8, 0},
369         /*obsolete2*/{0, 0},
370         /*reserved*/0,
371         /*digital*/0,
372         /*obsolete3*/0,
373         /*copy_management*/0,
374         /*reserved2*/0,
375         /*rotation_control*/0,
376         /*cur_write_speed*/0,
377         /*num_speed_descr*/0,
378 };
379
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381         /*page_code*/SMS_CDDVD_CAPS_PAGE,
382         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383         /*caps1*/0,
384         /*caps2*/0,
385         /*caps3*/0,
386         /*caps4*/0,
387         /*caps5*/0,
388         /*caps6*/0,
389         /*obsolete*/{0, 0},
390         /*nvol_levels*/{0, 0},
391         /*buffer_size*/{0, 0},
392         /*obsolete2*/{0, 0},
393         /*reserved*/0,
394         /*digital*/0,
395         /*obsolete3*/0,
396         /*copy_management*/0,
397         /*reserved2*/0,
398         /*rotation_control*/0,
399         /*cur_write_speed*/0,
400         /*num_speed_descr*/0,
401 };
402
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407     &worker_threads, 1, "Number of worker threads");
408 static int ctl_debug = CTL_DEBUG_NONE;
409 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411     &ctl_debug, 0, "Enabled debug flags");
412 static int ctl_lun_map_size = 1024;
413 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
414     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
415
416 /*
417  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
418  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
419  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
420  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
421  */
422 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
423
424 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
425                                   int param);
426 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
427 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
428 static int ctl_init(void);
429 void ctl_shutdown(void);
430 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
431 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
432 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
433 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
434                               struct ctl_ooa *ooa_hdr,
435                               struct ctl_ooa_entry *kern_entries);
436 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
437                      struct thread *td);
438 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
439                          struct ctl_be_lun *be_lun);
440 static int ctl_free_lun(struct ctl_lun *lun);
441 static void ctl_create_lun(struct ctl_be_lun *be_lun);
442
443 static int ctl_do_mode_select(union ctl_io *io);
444 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
445                            uint64_t res_key, uint64_t sa_res_key,
446                            uint8_t type, uint32_t residx,
447                            struct ctl_scsiio *ctsio,
448                            struct scsi_per_res_out *cdb,
449                            struct scsi_per_res_out_parms* param);
450 static void ctl_pro_preempt_other(struct ctl_lun *lun,
451                                   union ctl_ha_msg *msg);
452 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
453 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
457 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
458 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
459                                          int alloc_len);
460 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
461                                          int alloc_len);
462 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
463 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
464 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
465 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
466 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
467 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
468     bool seq);
469 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
470 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
471     union ctl_io *pending_io, union ctl_io *ooa_io);
472 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
473                                 union ctl_io *starting_io);
474 static int ctl_check_blocked(struct ctl_lun *lun);
475 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
476                                 const struct ctl_cmd_entry *entry,
477                                 struct ctl_scsiio *ctsio);
478 static void ctl_failover_lun(union ctl_io *io);
479 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
480                                struct ctl_scsiio *ctsio);
481 static int ctl_scsiio(struct ctl_scsiio *ctsio);
482
483 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
484 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
485                             ctl_ua_type ua_type);
486 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
487                          ctl_ua_type ua_type);
488 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
489 static int ctl_abort_task(union ctl_io *io);
490 static int ctl_abort_task_set(union ctl_io *io);
491 static int ctl_query_task(union ctl_io *io, int task_set);
492 static int ctl_i_t_nexus_reset(union ctl_io *io);
493 static int ctl_query_async_event(union ctl_io *io);
494 static void ctl_run_task(union ctl_io *io);
495 #ifdef CTL_IO_DELAY
496 static void ctl_datamove_timer_wakeup(void *arg);
497 static void ctl_done_timer_wakeup(void *arg);
498 #endif /* CTL_IO_DELAY */
499
500 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
501 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
502 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
503 static void ctl_datamove_remote_write(union ctl_io *io);
504 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
505 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
506 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
507 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
508                                     ctl_ha_dt_cb callback);
509 static void ctl_datamove_remote_read(union ctl_io *io);
510 static void ctl_datamove_remote(union ctl_io *io);
511 static void ctl_process_done(union ctl_io *io);
512 static void ctl_lun_thread(void *arg);
513 static void ctl_thresh_thread(void *arg);
514 static void ctl_work_thread(void *arg);
515 static void ctl_enqueue_incoming(union ctl_io *io);
516 static void ctl_enqueue_rtr(union ctl_io *io);
517 static void ctl_enqueue_done(union ctl_io *io);
518 static void ctl_enqueue_isc(union ctl_io *io);
519 static const struct ctl_cmd_entry *
520     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
521 static const struct ctl_cmd_entry *
522     ctl_validate_command(struct ctl_scsiio *ctsio);
523 static int ctl_cmd_applicable(uint8_t lun_type,
524     const struct ctl_cmd_entry *entry);
525
526 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
528 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
529 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
530
531 /*
532  * Load the serialization table.  This isn't very pretty, but is probably
533  * the easiest way to do it.
534  */
535 #include "ctl_ser_table.c"
536
537 /*
538  * We only need to define open, close and ioctl routines for this driver.
539  */
540 static struct cdevsw ctl_cdevsw = {
541         .d_version =    D_VERSION,
542         .d_flags =      0,
543         .d_open =       ctl_open,
544         .d_close =      ctl_close,
545         .d_ioctl =      ctl_ioctl,
546         .d_name =       "ctl",
547 };
548
549
550 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
551
552 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
553
554 static moduledata_t ctl_moduledata = {
555         "ctl",
556         ctl_module_event_handler,
557         NULL
558 };
559
560 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
561 MODULE_VERSION(ctl, 1);
562
563 static struct ctl_frontend ha_frontend =
564 {
565         .name = "ha",
566 };
567
568 static void
569 ctl_ha_datamove(union ctl_io *io)
570 {
571         struct ctl_lun *lun = CTL_LUN(io);
572         struct ctl_sg_entry *sgl;
573         union ctl_ha_msg msg;
574         uint32_t sg_entries_sent;
575         int do_sg_copy, i, j;
576
577         memset(&msg.dt, 0, sizeof(msg.dt));
578         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
579         msg.hdr.original_sc = io->io_hdr.original_sc;
580         msg.hdr.serializing_sc = io;
581         msg.hdr.nexus = io->io_hdr.nexus;
582         msg.hdr.status = io->io_hdr.status;
583         msg.dt.flags = io->io_hdr.flags;
584
585         /*
586          * We convert everything into a S/G list here.  We can't
587          * pass by reference, only by value between controllers.
588          * So we can't pass a pointer to the S/G list, only as many
589          * S/G entries as we can fit in here.  If it's possible for
590          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
591          * then we need to break this up into multiple transfers.
592          */
593         if (io->scsiio.kern_sg_entries == 0) {
594                 msg.dt.kern_sg_entries = 1;
595 #if 0
596                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
597                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
598                 } else {
599                         /* XXX KDM use busdma here! */
600                         msg.dt.sg_list[0].addr =
601                             (void *)vtophys(io->scsiio.kern_data_ptr);
602                 }
603 #else
604                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
605                     ("HA does not support BUS_ADDR"));
606                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
607 #endif
608                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
609                 do_sg_copy = 0;
610         } else {
611                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
612                 do_sg_copy = 1;
613         }
614
615         msg.dt.kern_data_len = io->scsiio.kern_data_len;
616         msg.dt.kern_total_len = io->scsiio.kern_total_len;
617         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
618         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
619         msg.dt.sg_sequence = 0;
620
621         /*
622          * Loop until we've sent all of the S/G entries.  On the
623          * other end, we'll recompose these S/G entries into one
624          * contiguous list before processing.
625          */
626         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
627             msg.dt.sg_sequence++) {
628                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
629                     sizeof(msg.dt.sg_list[0])),
630                     msg.dt.kern_sg_entries - sg_entries_sent);
631                 if (do_sg_copy != 0) {
632                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
633                         for (i = sg_entries_sent, j = 0;
634                              i < msg.dt.cur_sg_entries; i++, j++) {
635 #if 0
636                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
637                                         msg.dt.sg_list[j].addr = sgl[i].addr;
638                                 } else {
639                                         /* XXX KDM use busdma here! */
640                                         msg.dt.sg_list[j].addr =
641                                             (void *)vtophys(sgl[i].addr);
642                                 }
643 #else
644                                 KASSERT((io->io_hdr.flags &
645                                     CTL_FLAG_BUS_ADDR) == 0,
646                                     ("HA does not support BUS_ADDR"));
647                                 msg.dt.sg_list[j].addr = sgl[i].addr;
648 #endif
649                                 msg.dt.sg_list[j].len = sgl[i].len;
650                         }
651                 }
652
653                 sg_entries_sent += msg.dt.cur_sg_entries;
654                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
655                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
656                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
657                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
658                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
659                         io->io_hdr.port_status = 31341;
660                         io->scsiio.be_move_done(io);
661                         return;
662                 }
663                 msg.dt.sent_sg_entries = sg_entries_sent;
664         }
665
666         /*
667          * Officially handover the request from us to peer.
668          * If failover has just happened, then we must return error.
669          * If failover happen just after, then it is not our problem.
670          */
671         if (lun)
672                 mtx_lock(&lun->lun_lock);
673         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
674                 if (lun)
675                         mtx_unlock(&lun->lun_lock);
676                 io->io_hdr.port_status = 31342;
677                 io->scsiio.be_move_done(io);
678                 return;
679         }
680         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
681         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
682         if (lun)
683                 mtx_unlock(&lun->lun_lock);
684 }
685
686 static void
687 ctl_ha_done(union ctl_io *io)
688 {
689         union ctl_ha_msg msg;
690
691         if (io->io_hdr.io_type == CTL_IO_SCSI) {
692                 memset(&msg, 0, sizeof(msg));
693                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
694                 msg.hdr.original_sc = io->io_hdr.original_sc;
695                 msg.hdr.nexus = io->io_hdr.nexus;
696                 msg.hdr.status = io->io_hdr.status;
697                 msg.scsi.scsi_status = io->scsiio.scsi_status;
698                 msg.scsi.tag_num = io->scsiio.tag_num;
699                 msg.scsi.tag_type = io->scsiio.tag_type;
700                 msg.scsi.sense_len = io->scsiio.sense_len;
701                 msg.scsi.sense_residual = io->scsiio.sense_residual;
702                 msg.scsi.residual = io->scsiio.residual;
703                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
704                     io->scsiio.sense_len);
705                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
706                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
707                     msg.scsi.sense_len, M_WAITOK);
708         }
709         ctl_free_io(io);
710 }
711
712 static void
713 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
714                             union ctl_ha_msg *msg_info)
715 {
716         struct ctl_scsiio *ctsio;
717
718         if (msg_info->hdr.original_sc == NULL) {
719                 printf("%s: original_sc == NULL!\n", __func__);
720                 /* XXX KDM now what? */
721                 return;
722         }
723
724         ctsio = &msg_info->hdr.original_sc->scsiio;
725         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
726         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
727         ctsio->io_hdr.status = msg_info->hdr.status;
728         ctsio->scsi_status = msg_info->scsi.scsi_status;
729         ctsio->sense_len = msg_info->scsi.sense_len;
730         ctsio->sense_residual = msg_info->scsi.sense_residual;
731         ctsio->residual = msg_info->scsi.residual;
732         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
733                msg_info->scsi.sense_len);
734         ctl_enqueue_isc((union ctl_io *)ctsio);
735 }
736
737 static void
738 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
739                                 union ctl_ha_msg *msg_info)
740 {
741         struct ctl_scsiio *ctsio;
742
743         if (msg_info->hdr.serializing_sc == NULL) {
744                 printf("%s: serializing_sc == NULL!\n", __func__);
745                 /* XXX KDM now what? */
746                 return;
747         }
748
749         ctsio = &msg_info->hdr.serializing_sc->scsiio;
750         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
751         ctl_enqueue_isc((union ctl_io *)ctsio);
752 }
753
754 void
755 ctl_isc_announce_lun(struct ctl_lun *lun)
756 {
757         struct ctl_softc *softc = lun->ctl_softc;
758         union ctl_ha_msg *msg;
759         struct ctl_ha_msg_lun_pr_key pr_key;
760         int i, k;
761
762         if (softc->ha_link != CTL_HA_LINK_ONLINE)
763                 return;
764         mtx_lock(&lun->lun_lock);
765         i = sizeof(msg->lun);
766         if (lun->lun_devid)
767                 i += lun->lun_devid->len;
768         i += sizeof(pr_key) * lun->pr_key_count;
769 alloc:
770         mtx_unlock(&lun->lun_lock);
771         msg = malloc(i, M_CTL, M_WAITOK);
772         mtx_lock(&lun->lun_lock);
773         k = sizeof(msg->lun);
774         if (lun->lun_devid)
775                 k += lun->lun_devid->len;
776         k += sizeof(pr_key) * lun->pr_key_count;
777         if (i < k) {
778                 free(msg, M_CTL);
779                 i = k;
780                 goto alloc;
781         }
782         bzero(&msg->lun, sizeof(msg->lun));
783         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
784         msg->hdr.nexus.targ_lun = lun->lun;
785         msg->hdr.nexus.targ_mapped_lun = lun->lun;
786         msg->lun.flags = lun->flags;
787         msg->lun.pr_generation = lun->pr_generation;
788         msg->lun.pr_res_idx = lun->pr_res_idx;
789         msg->lun.pr_res_type = lun->pr_res_type;
790         msg->lun.pr_key_count = lun->pr_key_count;
791         i = 0;
792         if (lun->lun_devid) {
793                 msg->lun.lun_devid_len = lun->lun_devid->len;
794                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
795                     msg->lun.lun_devid_len);
796                 i += msg->lun.lun_devid_len;
797         }
798         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
799                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
800                         continue;
801                 pr_key.pr_iid = k;
802                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
803                 i += sizeof(pr_key);
804         }
805         mtx_unlock(&lun->lun_lock);
806         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
807             M_WAITOK);
808         free(msg, M_CTL);
809
810         if (lun->flags & CTL_LUN_PRIMARY_SC) {
811                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
812                         ctl_isc_announce_mode(lun, -1,
813                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
814                             lun->mode_pages.index[i].subpage);
815                 }
816         }
817 }
818
819 void
820 ctl_isc_announce_port(struct ctl_port *port)
821 {
822         struct ctl_softc *softc = port->ctl_softc;
823         union ctl_ha_msg *msg;
824         int i;
825
826         if (port->targ_port < softc->port_min ||
827             port->targ_port >= softc->port_max ||
828             softc->ha_link != CTL_HA_LINK_ONLINE)
829                 return;
830         i = sizeof(msg->port) + strlen(port->port_name) + 1;
831         if (port->lun_map)
832                 i += port->lun_map_size * sizeof(uint32_t);
833         if (port->port_devid)
834                 i += port->port_devid->len;
835         if (port->target_devid)
836                 i += port->target_devid->len;
837         if (port->init_devid)
838                 i += port->init_devid->len;
839         msg = malloc(i, M_CTL, M_WAITOK);
840         bzero(&msg->port, sizeof(msg->port));
841         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
842         msg->hdr.nexus.targ_port = port->targ_port;
843         msg->port.port_type = port->port_type;
844         msg->port.physical_port = port->physical_port;
845         msg->port.virtual_port = port->virtual_port;
846         msg->port.status = port->status;
847         i = 0;
848         msg->port.name_len = sprintf(&msg->port.data[i],
849             "%d:%s", softc->ha_id, port->port_name) + 1;
850         i += msg->port.name_len;
851         if (port->lun_map) {
852                 msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
853                 memcpy(&msg->port.data[i], port->lun_map,
854                     msg->port.lun_map_len);
855                 i += msg->port.lun_map_len;
856         }
857         if (port->port_devid) {
858                 msg->port.port_devid_len = port->port_devid->len;
859                 memcpy(&msg->port.data[i], port->port_devid->data,
860                     msg->port.port_devid_len);
861                 i += msg->port.port_devid_len;
862         }
863         if (port->target_devid) {
864                 msg->port.target_devid_len = port->target_devid->len;
865                 memcpy(&msg->port.data[i], port->target_devid->data,
866                     msg->port.target_devid_len);
867                 i += msg->port.target_devid_len;
868         }
869         if (port->init_devid) {
870                 msg->port.init_devid_len = port->init_devid->len;
871                 memcpy(&msg->port.data[i], port->init_devid->data,
872                     msg->port.init_devid_len);
873                 i += msg->port.init_devid_len;
874         }
875         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
876             M_WAITOK);
877         free(msg, M_CTL);
878 }
879
880 void
881 ctl_isc_announce_iid(struct ctl_port *port, int iid)
882 {
883         struct ctl_softc *softc = port->ctl_softc;
884         union ctl_ha_msg *msg;
885         int i, l;
886
887         if (port->targ_port < softc->port_min ||
888             port->targ_port >= softc->port_max ||
889             softc->ha_link != CTL_HA_LINK_ONLINE)
890                 return;
891         mtx_lock(&softc->ctl_lock);
892         i = sizeof(msg->iid);
893         l = 0;
894         if (port->wwpn_iid[iid].name)
895                 l = strlen(port->wwpn_iid[iid].name) + 1;
896         i += l;
897         msg = malloc(i, M_CTL, M_NOWAIT);
898         if (msg == NULL) {
899                 mtx_unlock(&softc->ctl_lock);
900                 return;
901         }
902         bzero(&msg->iid, sizeof(msg->iid));
903         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
904         msg->hdr.nexus.targ_port = port->targ_port;
905         msg->hdr.nexus.initid = iid;
906         msg->iid.in_use = port->wwpn_iid[iid].in_use;
907         msg->iid.name_len = l;
908         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
909         if (port->wwpn_iid[iid].name)
910                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
911         mtx_unlock(&softc->ctl_lock);
912         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
913         free(msg, M_CTL);
914 }
915
916 void
917 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
918     uint8_t page, uint8_t subpage)
919 {
920         struct ctl_softc *softc = lun->ctl_softc;
921         union ctl_ha_msg msg;
922         u_int i;
923
924         if (softc->ha_link != CTL_HA_LINK_ONLINE)
925                 return;
926         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
927                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
928                     page && lun->mode_pages.index[i].subpage == subpage)
929                         break;
930         }
931         if (i == CTL_NUM_MODE_PAGES)
932                 return;
933
934         /* Don't try to replicate pages not present on this device. */
935         if (lun->mode_pages.index[i].page_data == NULL)
936                 return;
937
938         bzero(&msg.mode, sizeof(msg.mode));
939         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
940         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
941         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
942         msg.hdr.nexus.targ_lun = lun->lun;
943         msg.hdr.nexus.targ_mapped_lun = lun->lun;
944         msg.mode.page_code = page;
945         msg.mode.subpage = subpage;
946         msg.mode.page_len = lun->mode_pages.index[i].page_len;
947         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
948             msg.mode.page_len);
949         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
950             M_WAITOK);
951 }
952
953 static void
954 ctl_isc_ha_link_up(struct ctl_softc *softc)
955 {
956         struct ctl_port *port;
957         struct ctl_lun *lun;
958         union ctl_ha_msg msg;
959         int i;
960
961         /* Announce this node parameters to peer for validation. */
962         msg.login.msg_type = CTL_MSG_LOGIN;
963         msg.login.version = CTL_HA_VERSION;
964         msg.login.ha_mode = softc->ha_mode;
965         msg.login.ha_id = softc->ha_id;
966         msg.login.max_luns = CTL_MAX_LUNS;
967         msg.login.max_ports = CTL_MAX_PORTS;
968         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
969         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
970             M_WAITOK);
971
972         STAILQ_FOREACH(port, &softc->port_list, links) {
973                 ctl_isc_announce_port(port);
974                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
975                         if (port->wwpn_iid[i].in_use)
976                                 ctl_isc_announce_iid(port, i);
977                 }
978         }
979         STAILQ_FOREACH(lun, &softc->lun_list, links)
980                 ctl_isc_announce_lun(lun);
981 }
982
983 static void
984 ctl_isc_ha_link_down(struct ctl_softc *softc)
985 {
986         struct ctl_port *port;
987         struct ctl_lun *lun;
988         union ctl_io *io;
989         int i;
990
991         mtx_lock(&softc->ctl_lock);
992         STAILQ_FOREACH(lun, &softc->lun_list, links) {
993                 mtx_lock(&lun->lun_lock);
994                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
995                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
996                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
997                 }
998                 mtx_unlock(&lun->lun_lock);
999
1000                 mtx_unlock(&softc->ctl_lock);
1001                 io = ctl_alloc_io(softc->othersc_pool);
1002                 mtx_lock(&softc->ctl_lock);
1003                 ctl_zero_io(io);
1004                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1005                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1006                 ctl_enqueue_isc(io);
1007         }
1008
1009         STAILQ_FOREACH(port, &softc->port_list, links) {
1010                 if (port->targ_port >= softc->port_min &&
1011                     port->targ_port < softc->port_max)
1012                         continue;
1013                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1014                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1015                         port->wwpn_iid[i].in_use = 0;
1016                         free(port->wwpn_iid[i].name, M_CTL);
1017                         port->wwpn_iid[i].name = NULL;
1018                 }
1019         }
1020         mtx_unlock(&softc->ctl_lock);
1021 }
1022
1023 static void
1024 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1025 {
1026         struct ctl_lun *lun;
1027         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1028
1029         mtx_lock(&softc->ctl_lock);
1030         if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1031             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1032                 mtx_unlock(&softc->ctl_lock);
1033                 return;
1034         }
1035         mtx_lock(&lun->lun_lock);
1036         mtx_unlock(&softc->ctl_lock);
1037         if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1038                 memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1039         if (msg->ua.ua_all) {
1040                 if (msg->ua.ua_set)
1041                         ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1042                 else
1043                         ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1044         } else {
1045                 if (msg->ua.ua_set)
1046                         ctl_est_ua(lun, iid, msg->ua.ua_type);
1047                 else
1048                         ctl_clr_ua(lun, iid, msg->ua.ua_type);
1049         }
1050         mtx_unlock(&lun->lun_lock);
1051 }
1052
1053 static void
1054 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1055 {
1056         struct ctl_lun *lun;
1057         struct ctl_ha_msg_lun_pr_key pr_key;
1058         int i, k;
1059         ctl_lun_flags oflags;
1060         uint32_t targ_lun;
1061
1062         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1063         mtx_lock(&softc->ctl_lock);
1064         if (targ_lun >= CTL_MAX_LUNS ||
1065             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1066                 mtx_unlock(&softc->ctl_lock);
1067                 return;
1068         }
1069         mtx_lock(&lun->lun_lock);
1070         mtx_unlock(&softc->ctl_lock);
1071         if (lun->flags & CTL_LUN_DISABLED) {
1072                 mtx_unlock(&lun->lun_lock);
1073                 return;
1074         }
1075         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1076         if (msg->lun.lun_devid_len != i || (i > 0 &&
1077             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1078                 mtx_unlock(&lun->lun_lock);
1079                 printf("%s: Received conflicting HA LUN %d\n",
1080                     __func__, targ_lun);
1081                 return;
1082         } else {
1083                 /* Record whether peer is primary. */
1084                 oflags = lun->flags;
1085                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1086                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1087                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1088                 else
1089                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1090                 if (oflags != lun->flags)
1091                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1092
1093                 /* If peer is primary and we are not -- use data */
1094                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1095                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1096                         lun->pr_generation = msg->lun.pr_generation;
1097                         lun->pr_res_idx = msg->lun.pr_res_idx;
1098                         lun->pr_res_type = msg->lun.pr_res_type;
1099                         lun->pr_key_count = msg->lun.pr_key_count;
1100                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1101                                 ctl_clr_prkey(lun, k);
1102                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1103                                 memcpy(&pr_key, &msg->lun.data[i],
1104                                     sizeof(pr_key));
1105                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1106                                 ctl_set_prkey(lun, pr_key.pr_iid,
1107                                     pr_key.pr_key);
1108                                 i += sizeof(pr_key);
1109                         }
1110                 }
1111
1112                 mtx_unlock(&lun->lun_lock);
1113                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1114                     __func__, targ_lun,
1115                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1116                     "primary" : "secondary"));
1117
1118                 /* If we are primary but peer doesn't know -- notify */
1119                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1120                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1121                         ctl_isc_announce_lun(lun);
1122         }
1123 }
1124
1125 static void
1126 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1127 {
1128         struct ctl_port *port;
1129         struct ctl_lun *lun;
1130         int i, new;
1131
1132         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1133         if (port == NULL) {
1134                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1135                     msg->hdr.nexus.targ_port));
1136                 new = 1;
1137                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1138                 port->frontend = &ha_frontend;
1139                 port->targ_port = msg->hdr.nexus.targ_port;
1140                 port->fe_datamove = ctl_ha_datamove;
1141                 port->fe_done = ctl_ha_done;
1142         } else if (port->frontend == &ha_frontend) {
1143                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1144                     msg->hdr.nexus.targ_port));
1145                 new = 0;
1146         } else {
1147                 printf("%s: Received conflicting HA port %d\n",
1148                     __func__, msg->hdr.nexus.targ_port);
1149                 return;
1150         }
1151         port->port_type = msg->port.port_type;
1152         port->physical_port = msg->port.physical_port;
1153         port->virtual_port = msg->port.virtual_port;
1154         port->status = msg->port.status;
1155         i = 0;
1156         free(port->port_name, M_CTL);
1157         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1158             M_CTL);
1159         i += msg->port.name_len;
1160         if (msg->port.lun_map_len != 0) {
1161                 if (port->lun_map == NULL ||
1162                     port->lun_map_size * sizeof(uint32_t) <
1163                     msg->port.lun_map_len) {
1164                         port->lun_map_size = 0;
1165                         free(port->lun_map, M_CTL);
1166                         port->lun_map = malloc(msg->port.lun_map_len,
1167                             M_CTL, M_WAITOK);
1168                 }
1169                 memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1170                 port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1171                 i += msg->port.lun_map_len;
1172         } else {
1173                 port->lun_map_size = 0;
1174                 free(port->lun_map, M_CTL);
1175                 port->lun_map = NULL;
1176         }
1177         if (msg->port.port_devid_len != 0) {
1178                 if (port->port_devid == NULL ||
1179                     port->port_devid->len < msg->port.port_devid_len) {
1180                         free(port->port_devid, M_CTL);
1181                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1182                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1183                 }
1184                 memcpy(port->port_devid->data, &msg->port.data[i],
1185                     msg->port.port_devid_len);
1186                 port->port_devid->len = msg->port.port_devid_len;
1187                 i += msg->port.port_devid_len;
1188         } else {
1189                 free(port->port_devid, M_CTL);
1190                 port->port_devid = NULL;
1191         }
1192         if (msg->port.target_devid_len != 0) {
1193                 if (port->target_devid == NULL ||
1194                     port->target_devid->len < msg->port.target_devid_len) {
1195                         free(port->target_devid, M_CTL);
1196                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1197                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1198                 }
1199                 memcpy(port->target_devid->data, &msg->port.data[i],
1200                     msg->port.target_devid_len);
1201                 port->target_devid->len = msg->port.target_devid_len;
1202                 i += msg->port.target_devid_len;
1203         } else {
1204                 free(port->target_devid, M_CTL);
1205                 port->target_devid = NULL;
1206         }
1207         if (msg->port.init_devid_len != 0) {
1208                 if (port->init_devid == NULL ||
1209                     port->init_devid->len < msg->port.init_devid_len) {
1210                         free(port->init_devid, M_CTL);
1211                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1212                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1213                 }
1214                 memcpy(port->init_devid->data, &msg->port.data[i],
1215                     msg->port.init_devid_len);
1216                 port->init_devid->len = msg->port.init_devid_len;
1217                 i += msg->port.init_devid_len;
1218         } else {
1219                 free(port->init_devid, M_CTL);
1220                 port->init_devid = NULL;
1221         }
1222         if (new) {
1223                 if (ctl_port_register(port) != 0) {
1224                         printf("%s: ctl_port_register() failed with error\n",
1225                             __func__);
1226                 }
1227         }
1228         mtx_lock(&softc->ctl_lock);
1229         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1230                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1231                         continue;
1232                 mtx_lock(&lun->lun_lock);
1233                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1234                 mtx_unlock(&lun->lun_lock);
1235         }
1236         mtx_unlock(&softc->ctl_lock);
1237 }
1238
1239 static void
1240 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1241 {
1242         struct ctl_port *port;
1243         int iid;
1244
1245         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1246         if (port == NULL) {
1247                 printf("%s: Received IID for unknown port %d\n",
1248                     __func__, msg->hdr.nexus.targ_port);
1249                 return;
1250         }
1251         iid = msg->hdr.nexus.initid;
1252         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1253         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1254         free(port->wwpn_iid[iid].name, M_CTL);
1255         if (msg->iid.name_len) {
1256                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1257                     msg->iid.name_len, M_CTL);
1258         } else
1259                 port->wwpn_iid[iid].name = NULL;
1260 }
1261
1262 static void
1263 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1264 {
1265
1266         if (msg->login.version != CTL_HA_VERSION) {
1267                 printf("CTL HA peers have different versions %d != %d\n",
1268                     msg->login.version, CTL_HA_VERSION);
1269                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1270                 return;
1271         }
1272         if (msg->login.ha_mode != softc->ha_mode) {
1273                 printf("CTL HA peers have different ha_mode %d != %d\n",
1274                     msg->login.ha_mode, softc->ha_mode);
1275                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1276                 return;
1277         }
1278         if (msg->login.ha_id == softc->ha_id) {
1279                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1280                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281                 return;
1282         }
1283         if (msg->login.max_luns != CTL_MAX_LUNS ||
1284             msg->login.max_ports != CTL_MAX_PORTS ||
1285             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1286                 printf("CTL HA peers have different limits\n");
1287                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1288                 return;
1289         }
1290 }
1291
1292 static void
1293 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1294 {
1295         struct ctl_lun *lun;
1296         u_int i;
1297         uint32_t initidx, targ_lun;
1298
1299         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1300         mtx_lock(&softc->ctl_lock);
1301         if (targ_lun >= CTL_MAX_LUNS ||
1302             (lun = softc->ctl_luns[targ_lun]) == NULL) {
1303                 mtx_unlock(&softc->ctl_lock);
1304                 return;
1305         }
1306         mtx_lock(&lun->lun_lock);
1307         mtx_unlock(&softc->ctl_lock);
1308         if (lun->flags & CTL_LUN_DISABLED) {
1309                 mtx_unlock(&lun->lun_lock);
1310                 return;
1311         }
1312         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1313                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1314                     msg->mode.page_code &&
1315                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1316                         break;
1317         }
1318         if (i == CTL_NUM_MODE_PAGES) {
1319                 mtx_unlock(&lun->lun_lock);
1320                 return;
1321         }
1322         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1323             lun->mode_pages.index[i].page_len);
1324         initidx = ctl_get_initindex(&msg->hdr.nexus);
1325         if (initidx != -1)
1326                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1327         mtx_unlock(&lun->lun_lock);
1328 }
1329
1330 /*
1331  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1332  * subsystem come in here.
1333  */
1334 static void
1335 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1336 {
1337         struct ctl_softc *softc = control_softc;
1338         union ctl_io *io;
1339         struct ctl_prio *presio;
1340         ctl_ha_status isc_status;
1341
1342         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1343         if (event == CTL_HA_EVT_MSG_RECV) {
1344                 union ctl_ha_msg *msg, msgbuf;
1345
1346                 if (param > sizeof(msgbuf))
1347                         msg = malloc(param, M_CTL, M_WAITOK);
1348                 else
1349                         msg = &msgbuf;
1350                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1351                     M_WAITOK);
1352                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1353                         printf("%s: Error receiving message: %d\n",
1354                             __func__, isc_status);
1355                         if (msg != &msgbuf)
1356                                 free(msg, M_CTL);
1357                         return;
1358                 }
1359
1360                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1361                 switch (msg->hdr.msg_type) {
1362                 case CTL_MSG_SERIALIZE:
1363                         io = ctl_alloc_io(softc->othersc_pool);
1364                         ctl_zero_io(io);
1365                         // populate ctsio from msg
1366                         io->io_hdr.io_type = CTL_IO_SCSI;
1367                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1368                         io->io_hdr.original_sc = msg->hdr.original_sc;
1369                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1370                                             CTL_FLAG_IO_ACTIVE;
1371                         /*
1372                          * If we're in serialization-only mode, we don't
1373                          * want to go through full done processing.  Thus
1374                          * the COPY flag.
1375                          *
1376                          * XXX KDM add another flag that is more specific.
1377                          */
1378                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1379                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1380                         io->io_hdr.nexus = msg->hdr.nexus;
1381 #if 0
1382                         printf("port %u, iid %u, lun %u\n",
1383                                io->io_hdr.nexus.targ_port,
1384                                io->io_hdr.nexus.initid,
1385                                io->io_hdr.nexus.targ_lun);
1386 #endif
1387                         io->scsiio.tag_num = msg->scsi.tag_num;
1388                         io->scsiio.tag_type = msg->scsi.tag_type;
1389 #ifdef CTL_TIME_IO
1390                         io->io_hdr.start_time = time_uptime;
1391                         getbinuptime(&io->io_hdr.start_bt);
1392 #endif /* CTL_TIME_IO */
1393                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1394                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1395                                CTL_MAX_CDBLEN);
1396                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1397                                 const struct ctl_cmd_entry *entry;
1398
1399                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1400                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1401                                 io->io_hdr.flags |=
1402                                         entry->flags & CTL_FLAG_DATA_MASK;
1403                         }
1404                         ctl_enqueue_isc(io);
1405                         break;
1406
1407                 /* Performed on the Originating SC, XFER mode only */
1408                 case CTL_MSG_DATAMOVE: {
1409                         struct ctl_sg_entry *sgl;
1410                         int i, j;
1411
1412                         io = msg->hdr.original_sc;
1413                         if (io == NULL) {
1414                                 printf("%s: original_sc == NULL!\n", __func__);
1415                                 /* XXX KDM do something here */
1416                                 break;
1417                         }
1418                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1419                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1420                         /*
1421                          * Keep track of this, we need to send it back over
1422                          * when the datamove is complete.
1423                          */
1424                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1425                         if (msg->hdr.status == CTL_SUCCESS)
1426                                 io->io_hdr.status = msg->hdr.status;
1427
1428                         if (msg->dt.sg_sequence == 0) {
1429 #ifdef CTL_TIME_IO
1430                                 getbinuptime(&io->io_hdr.dma_start_bt);
1431 #endif
1432                                 i = msg->dt.kern_sg_entries +
1433                                     msg->dt.kern_data_len /
1434                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1435                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1436                                     M_WAITOK | M_ZERO);
1437                                 io->io_hdr.remote_sglist = sgl;
1438                                 io->io_hdr.local_sglist =
1439                                     &sgl[msg->dt.kern_sg_entries];
1440
1441                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1442
1443                                 io->scsiio.kern_sg_entries =
1444                                         msg->dt.kern_sg_entries;
1445                                 io->scsiio.rem_sg_entries =
1446                                         msg->dt.kern_sg_entries;
1447                                 io->scsiio.kern_data_len =
1448                                         msg->dt.kern_data_len;
1449                                 io->scsiio.kern_total_len =
1450                                         msg->dt.kern_total_len;
1451                                 io->scsiio.kern_data_resid =
1452                                         msg->dt.kern_data_resid;
1453                                 io->scsiio.kern_rel_offset =
1454                                         msg->dt.kern_rel_offset;
1455                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1456                                 io->io_hdr.flags |= msg->dt.flags &
1457                                     CTL_FLAG_BUS_ADDR;
1458                         } else
1459                                 sgl = (struct ctl_sg_entry *)
1460                                         io->scsiio.kern_data_ptr;
1461
1462                         for (i = msg->dt.sent_sg_entries, j = 0;
1463                              i < (msg->dt.sent_sg_entries +
1464                              msg->dt.cur_sg_entries); i++, j++) {
1465                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1466                                 sgl[i].len = msg->dt.sg_list[j].len;
1467
1468 #if 0
1469                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1470                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1471 #endif
1472                         }
1473
1474                         /*
1475                          * If this is the last piece of the I/O, we've got
1476                          * the full S/G list.  Queue processing in the thread.
1477                          * Otherwise wait for the next piece.
1478                          */
1479                         if (msg->dt.sg_last != 0)
1480                                 ctl_enqueue_isc(io);
1481                         break;
1482                 }
1483                 /* Performed on the Serializing (primary) SC, XFER mode only */
1484                 case CTL_MSG_DATAMOVE_DONE: {
1485                         if (msg->hdr.serializing_sc == NULL) {
1486                                 printf("%s: serializing_sc == NULL!\n",
1487                                        __func__);
1488                                 /* XXX KDM now what? */
1489                                 break;
1490                         }
1491                         /*
1492                          * We grab the sense information here in case
1493                          * there was a failure, so we can return status
1494                          * back to the initiator.
1495                          */
1496                         io = msg->hdr.serializing_sc;
1497                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1498                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1499                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1500                         io->io_hdr.port_status = msg->scsi.fetd_status;
1501                         io->scsiio.residual = msg->scsi.residual;
1502                         if (msg->hdr.status != CTL_STATUS_NONE) {
1503                                 io->io_hdr.status = msg->hdr.status;
1504                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1505                                 io->scsiio.sense_len = msg->scsi.sense_len;
1506                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1507                                 memcpy(&io->scsiio.sense_data,
1508                                     &msg->scsi.sense_data,
1509                                     msg->scsi.sense_len);
1510                                 if (msg->hdr.status == CTL_SUCCESS)
1511                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1512                         }
1513                         ctl_enqueue_isc(io);
1514                         break;
1515                 }
1516
1517                 /* Preformed on Originating SC, SER_ONLY mode */
1518                 case CTL_MSG_R2R:
1519                         io = msg->hdr.original_sc;
1520                         if (io == NULL) {
1521                                 printf("%s: original_sc == NULL!\n",
1522                                     __func__);
1523                                 break;
1524                         }
1525                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1526                         io->io_hdr.msg_type = CTL_MSG_R2R;
1527                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1528                         ctl_enqueue_isc(io);
1529                         break;
1530
1531                 /*
1532                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1533                  * mode.
1534                  * Performed on the Originating (i.e. secondary) SC in XFER
1535                  * mode
1536                  */
1537                 case CTL_MSG_FINISH_IO:
1538                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1539                                 ctl_isc_handler_finish_xfer(softc, msg);
1540                         else
1541                                 ctl_isc_handler_finish_ser_only(softc, msg);
1542                         break;
1543
1544                 /* Preformed on Originating SC */
1545                 case CTL_MSG_BAD_JUJU:
1546                         io = msg->hdr.original_sc;
1547                         if (io == NULL) {
1548                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1549                                        __func__);
1550                                 break;
1551                         }
1552                         ctl_copy_sense_data(msg, io);
1553                         /*
1554                          * IO should have already been cleaned up on other
1555                          * SC so clear this flag so we won't send a message
1556                          * back to finish the IO there.
1557                          */
1558                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1559                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1560
1561                         /* io = msg->hdr.serializing_sc; */
1562                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1563                         ctl_enqueue_isc(io);
1564                         break;
1565
1566                 /* Handle resets sent from the other side */
1567                 case CTL_MSG_MANAGE_TASKS: {
1568                         struct ctl_taskio *taskio;
1569                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1570                             softc->othersc_pool);
1571                         ctl_zero_io((union ctl_io *)taskio);
1572                         taskio->io_hdr.io_type = CTL_IO_TASK;
1573                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1574                         taskio->io_hdr.nexus = msg->hdr.nexus;
1575                         taskio->task_action = msg->task.task_action;
1576                         taskio->tag_num = msg->task.tag_num;
1577                         taskio->tag_type = msg->task.tag_type;
1578 #ifdef CTL_TIME_IO
1579                         taskio->io_hdr.start_time = time_uptime;
1580                         getbinuptime(&taskio->io_hdr.start_bt);
1581 #endif /* CTL_TIME_IO */
1582                         ctl_run_task((union ctl_io *)taskio);
1583                         break;
1584                 }
1585                 /* Persistent Reserve action which needs attention */
1586                 case CTL_MSG_PERS_ACTION:
1587                         presio = (struct ctl_prio *)ctl_alloc_io(
1588                             softc->othersc_pool);
1589                         ctl_zero_io((union ctl_io *)presio);
1590                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1591                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1592                         presio->io_hdr.nexus = msg->hdr.nexus;
1593                         presio->pr_msg = msg->pr;
1594                         ctl_enqueue_isc((union ctl_io *)presio);
1595                         break;
1596                 case CTL_MSG_UA:
1597                         ctl_isc_ua(softc, msg, param);
1598                         break;
1599                 case CTL_MSG_PORT_SYNC:
1600                         ctl_isc_port_sync(softc, msg, param);
1601                         break;
1602                 case CTL_MSG_LUN_SYNC:
1603                         ctl_isc_lun_sync(softc, msg, param);
1604                         break;
1605                 case CTL_MSG_IID_SYNC:
1606                         ctl_isc_iid_sync(softc, msg, param);
1607                         break;
1608                 case CTL_MSG_LOGIN:
1609                         ctl_isc_login(softc, msg, param);
1610                         break;
1611                 case CTL_MSG_MODE_SYNC:
1612                         ctl_isc_mode_sync(softc, msg, param);
1613                         break;
1614                 default:
1615                         printf("Received HA message of unknown type %d\n",
1616                             msg->hdr.msg_type);
1617                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1618                         break;
1619                 }
1620                 if (msg != &msgbuf)
1621                         free(msg, M_CTL);
1622         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1623                 printf("CTL: HA link status changed from %d to %d\n",
1624                     softc->ha_link, param);
1625                 if (param == softc->ha_link)
1626                         return;
1627                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1628                         softc->ha_link = param;
1629                         ctl_isc_ha_link_down(softc);
1630                 } else {
1631                         softc->ha_link = param;
1632                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1633                                 ctl_isc_ha_link_up(softc);
1634                 }
1635                 return;
1636         } else {
1637                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1638                 return;
1639         }
1640 }
1641
1642 static void
1643 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1644 {
1645
1646         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1647             src->scsi.sense_len);
1648         dest->scsiio.scsi_status = src->scsi.scsi_status;
1649         dest->scsiio.sense_len = src->scsi.sense_len;
1650         dest->io_hdr.status = src->hdr.status;
1651 }
1652
1653 static void
1654 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1655 {
1656
1657         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1658             src->scsiio.sense_len);
1659         dest->scsi.scsi_status = src->scsiio.scsi_status;
1660         dest->scsi.sense_len = src->scsiio.sense_len;
1661         dest->hdr.status = src->io_hdr.status;
1662 }
1663
1664 void
1665 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1666 {
1667         struct ctl_softc *softc = lun->ctl_softc;
1668         ctl_ua_type *pu;
1669
1670         if (initidx < softc->init_min || initidx >= softc->init_max)
1671                 return;
1672         mtx_assert(&lun->lun_lock, MA_OWNED);
1673         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1674         if (pu == NULL)
1675                 return;
1676         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1677 }
1678
1679 void
1680 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1681 {
1682         int i;
1683
1684         mtx_assert(&lun->lun_lock, MA_OWNED);
1685         if (lun->pending_ua[port] == NULL)
1686                 return;
1687         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1688                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1689                         continue;
1690                 lun->pending_ua[port][i] |= ua;
1691         }
1692 }
1693
1694 void
1695 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1696 {
1697         struct ctl_softc *softc = lun->ctl_softc;
1698         int i;
1699
1700         mtx_assert(&lun->lun_lock, MA_OWNED);
1701         for (i = softc->port_min; i < softc->port_max; i++)
1702                 ctl_est_ua_port(lun, i, except, ua);
1703 }
1704
1705 void
1706 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1707 {
1708         struct ctl_softc *softc = lun->ctl_softc;
1709         ctl_ua_type *pu;
1710
1711         if (initidx < softc->init_min || initidx >= softc->init_max)
1712                 return;
1713         mtx_assert(&lun->lun_lock, MA_OWNED);
1714         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1715         if (pu == NULL)
1716                 return;
1717         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1718 }
1719
1720 void
1721 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1722 {
1723         struct ctl_softc *softc = lun->ctl_softc;
1724         int i, j;
1725
1726         mtx_assert(&lun->lun_lock, MA_OWNED);
1727         for (i = softc->port_min; i < softc->port_max; i++) {
1728                 if (lun->pending_ua[i] == NULL)
1729                         continue;
1730                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1731                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1732                                 continue;
1733                         lun->pending_ua[i][j] &= ~ua;
1734                 }
1735         }
1736 }
1737
1738 void
1739 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1740     ctl_ua_type ua_type)
1741 {
1742         struct ctl_lun *lun;
1743
1744         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1745         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1746                 mtx_lock(&lun->lun_lock);
1747                 ctl_clr_ua(lun, initidx, ua_type);
1748                 mtx_unlock(&lun->lun_lock);
1749         }
1750 }
1751
1752 static int
1753 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1754 {
1755         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1756         struct ctl_lun *lun;
1757         struct ctl_lun_req ireq;
1758         int error, value;
1759
1760         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1761         error = sysctl_handle_int(oidp, &value, 0, req);
1762         if ((error != 0) || (req->newptr == NULL))
1763                 return (error);
1764
1765         mtx_lock(&softc->ctl_lock);
1766         if (value == 0)
1767                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1768         else
1769                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1770         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1771                 mtx_unlock(&softc->ctl_lock);
1772                 bzero(&ireq, sizeof(ireq));
1773                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1774                 ireq.reqdata.modify.lun_id = lun->lun;
1775                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1776                     curthread);
1777                 if (ireq.status != CTL_LUN_OK) {
1778                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1779                             __func__, ireq.status, ireq.error_str);
1780                 }
1781                 mtx_lock(&softc->ctl_lock);
1782         }
1783         mtx_unlock(&softc->ctl_lock);
1784         return (0);
1785 }
1786
1787 static int
1788 ctl_init(void)
1789 {
1790         struct make_dev_args args;
1791         struct ctl_softc *softc;
1792         void *other_pool;
1793         int i, error;
1794
1795         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1796                                M_WAITOK | M_ZERO);
1797
1798         make_dev_args_init(&args);
1799         args.mda_devsw = &ctl_cdevsw;
1800         args.mda_uid = UID_ROOT;
1801         args.mda_gid = GID_OPERATOR;
1802         args.mda_mode = 0600;
1803         args.mda_si_drv1 = softc;
1804         error = make_dev_s(&args, &softc->dev, "cam/ctl");
1805         if (error != 0) {
1806                 free(softc, M_DEVBUF);
1807                 control_softc = NULL;
1808                 return (error);
1809         }
1810
1811         sysctl_ctx_init(&softc->sysctl_ctx);
1812         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1813                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1814                 CTLFLAG_RD, 0, "CAM Target Layer");
1815
1816         if (softc->sysctl_tree == NULL) {
1817                 printf("%s: unable to allocate sysctl tree\n", __func__);
1818                 destroy_dev(softc->dev);
1819                 free(softc, M_DEVBUF);
1820                 control_softc = NULL;
1821                 return (ENOMEM);
1822         }
1823
1824         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1825         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1826             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1827         softc->flags = 0;
1828
1829         TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1830         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1831             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1832             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1833
1834         /*
1835          * In Copan's HA scheme, the "master" and "slave" roles are
1836          * figured out through the slot the controller is in.  Although it
1837          * is an active/active system, someone has to be in charge.
1838          */
1839         TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1840         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1841             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1842             "HA head ID (0 - no HA)");
1843         if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1844                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1845                 softc->is_single = 1;
1846                 softc->port_cnt = CTL_MAX_PORTS;
1847                 softc->port_min = 0;
1848         } else {
1849                 softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1850                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1851         }
1852         softc->port_max = softc->port_min + softc->port_cnt;
1853         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1854         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1855
1856         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1857             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1858             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1859
1860         STAILQ_INIT(&softc->lun_list);
1861         STAILQ_INIT(&softc->pending_lun_queue);
1862         STAILQ_INIT(&softc->fe_list);
1863         STAILQ_INIT(&softc->port_list);
1864         STAILQ_INIT(&softc->be_list);
1865         ctl_tpc_init(softc);
1866
1867         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1868                             &other_pool) != 0)
1869         {
1870                 printf("ctl: can't allocate %d entry other SC pool, "
1871                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1872                 return (ENOMEM);
1873         }
1874         softc->othersc_pool = other_pool;
1875
1876         if (worker_threads <= 0)
1877                 worker_threads = max(1, mp_ncpus / 4);
1878         if (worker_threads > CTL_MAX_THREADS)
1879                 worker_threads = CTL_MAX_THREADS;
1880
1881         for (i = 0; i < worker_threads; i++) {
1882                 struct ctl_thread *thr = &softc->threads[i];
1883
1884                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1885                 thr->ctl_softc = softc;
1886                 STAILQ_INIT(&thr->incoming_queue);
1887                 STAILQ_INIT(&thr->rtr_queue);
1888                 STAILQ_INIT(&thr->done_queue);
1889                 STAILQ_INIT(&thr->isc_queue);
1890
1891                 error = kproc_kthread_add(ctl_work_thread, thr,
1892                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1893                 if (error != 0) {
1894                         printf("error creating CTL work thread!\n");
1895                         ctl_pool_free(other_pool);
1896                         return (error);
1897                 }
1898         }
1899         error = kproc_kthread_add(ctl_lun_thread, softc,
1900             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1901         if (error != 0) {
1902                 printf("error creating CTL lun thread!\n");
1903                 ctl_pool_free(other_pool);
1904                 return (error);
1905         }
1906         error = kproc_kthread_add(ctl_thresh_thread, softc,
1907             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1908         if (error != 0) {
1909                 printf("error creating CTL threshold thread!\n");
1910                 ctl_pool_free(other_pool);
1911                 return (error);
1912         }
1913
1914         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1915             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1916             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1917
1918         if (softc->is_single == 0) {
1919                 ctl_frontend_register(&ha_frontend);
1920                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1921                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1922                         softc->is_single = 1;
1923                 } else
1924                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1925                     != CTL_HA_STATUS_SUCCESS) {
1926                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1927                         softc->is_single = 1;
1928                 }
1929         }
1930         return (0);
1931 }
1932
1933 void
1934 ctl_shutdown(void)
1935 {
1936         struct ctl_softc *softc = control_softc;
1937         struct ctl_lun *lun, *next_lun;
1938
1939         if (softc->is_single == 0) {
1940                 ctl_ha_msg_shutdown(softc);
1941                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1942                     != CTL_HA_STATUS_SUCCESS)
1943                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1944                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1945                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1946                 ctl_frontend_deregister(&ha_frontend);
1947         }
1948
1949         mtx_lock(&softc->ctl_lock);
1950
1951         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1952                 ctl_free_lun(lun);
1953
1954         mtx_unlock(&softc->ctl_lock);
1955
1956 #if 0
1957         ctl_shutdown_thread(softc->work_thread);
1958         mtx_destroy(&softc->queue_lock);
1959 #endif
1960
1961         ctl_tpc_shutdown(softc);
1962         uma_zdestroy(softc->io_zone);
1963         mtx_destroy(&softc->ctl_lock);
1964
1965         destroy_dev(softc->dev);
1966
1967         sysctl_ctx_free(&softc->sysctl_ctx);
1968
1969         free(softc, M_DEVBUF);
1970         control_softc = NULL;
1971 }
1972
1973 static int
1974 ctl_module_event_handler(module_t mod, int what, void *arg)
1975 {
1976
1977         switch (what) {
1978         case MOD_LOAD:
1979                 return (ctl_init());
1980         case MOD_UNLOAD:
1981                 return (EBUSY);
1982         default:
1983                 return (EOPNOTSUPP);
1984         }
1985 }
1986
1987 /*
1988  * XXX KDM should we do some access checks here?  Bump a reference count to
1989  * prevent a CTL module from being unloaded while someone has it open?
1990  */
1991 static int
1992 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1993 {
1994         return (0);
1995 }
1996
1997 static int
1998 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1999 {
2000         return (0);
2001 }
2002
2003 /*
2004  * Remove an initiator by port number and initiator ID.
2005  * Returns 0 for success, -1 for failure.
2006  */
2007 int
2008 ctl_remove_initiator(struct ctl_port *port, int iid)
2009 {
2010         struct ctl_softc *softc = port->ctl_softc;
2011
2012         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2013
2014         if (iid > CTL_MAX_INIT_PER_PORT) {
2015                 printf("%s: initiator ID %u > maximun %u!\n",
2016                        __func__, iid, CTL_MAX_INIT_PER_PORT);
2017                 return (-1);
2018         }
2019
2020         mtx_lock(&softc->ctl_lock);
2021         port->wwpn_iid[iid].in_use--;
2022         port->wwpn_iid[iid].last_use = time_uptime;
2023         mtx_unlock(&softc->ctl_lock);
2024         ctl_isc_announce_iid(port, iid);
2025
2026         return (0);
2027 }
2028
2029 /*
2030  * Add an initiator to the initiator map.
2031  * Returns iid for success, < 0 for failure.
2032  */
2033 int
2034 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2035 {
2036         struct ctl_softc *softc = port->ctl_softc;
2037         time_t best_time;
2038         int i, best;
2039
2040         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2041
2042         if (iid >= CTL_MAX_INIT_PER_PORT) {
2043                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2044                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2045                 free(name, M_CTL);
2046                 return (-1);
2047         }
2048
2049         mtx_lock(&softc->ctl_lock);
2050
2051         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2052                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2053                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2054                                 iid = i;
2055                                 break;
2056                         }
2057                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2058                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2059                                 iid = i;
2060                                 break;
2061                         }
2062                 }
2063         }
2064
2065         if (iid < 0) {
2066                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2067                         if (port->wwpn_iid[i].in_use == 0 &&
2068                             port->wwpn_iid[i].wwpn == 0 &&
2069                             port->wwpn_iid[i].name == NULL) {
2070                                 iid = i;
2071                                 break;
2072                         }
2073                 }
2074         }
2075
2076         if (iid < 0) {
2077                 best = -1;
2078                 best_time = INT32_MAX;
2079                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2080                         if (port->wwpn_iid[i].in_use == 0) {
2081                                 if (port->wwpn_iid[i].last_use < best_time) {
2082                                         best = i;
2083                                         best_time = port->wwpn_iid[i].last_use;
2084                                 }
2085                         }
2086                 }
2087                 iid = best;
2088         }
2089
2090         if (iid < 0) {
2091                 mtx_unlock(&softc->ctl_lock);
2092                 free(name, M_CTL);
2093                 return (-2);
2094         }
2095
2096         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2097                 /*
2098                  * This is not an error yet.
2099                  */
2100                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2101 #if 0
2102                         printf("%s: port %d iid %u WWPN %#jx arrived"
2103                             " again\n", __func__, port->targ_port,
2104                             iid, (uintmax_t)wwpn);
2105 #endif
2106                         goto take;
2107                 }
2108                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2109                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2110 #if 0
2111                         printf("%s: port %d iid %u name '%s' arrived"
2112                             " again\n", __func__, port->targ_port,
2113                             iid, name);
2114 #endif
2115                         goto take;
2116                 }
2117
2118                 /*
2119                  * This is an error, but what do we do about it?  The
2120                  * driver is telling us we have a new WWPN for this
2121                  * initiator ID, so we pretty much need to use it.
2122                  */
2123                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2124                     " but WWPN %#jx '%s' is still at that address\n",
2125                     __func__, port->targ_port, iid, wwpn, name,
2126                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2127                     port->wwpn_iid[iid].name);
2128
2129                 /*
2130                  * XXX KDM clear have_ca and ua_pending on each LUN for
2131                  * this initiator.
2132                  */
2133         }
2134 take:
2135         free(port->wwpn_iid[iid].name, M_CTL);
2136         port->wwpn_iid[iid].name = name;
2137         port->wwpn_iid[iid].wwpn = wwpn;
2138         port->wwpn_iid[iid].in_use++;
2139         mtx_unlock(&softc->ctl_lock);
2140         ctl_isc_announce_iid(port, iid);
2141
2142         return (iid);
2143 }
2144
2145 static int
2146 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2147 {
2148         int len;
2149
2150         switch (port->port_type) {
2151         case CTL_PORT_FC:
2152         {
2153                 struct scsi_transportid_fcp *id =
2154                     (struct scsi_transportid_fcp *)buf;
2155                 if (port->wwpn_iid[iid].wwpn == 0)
2156                         return (0);
2157                 memset(id, 0, sizeof(*id));
2158                 id->format_protocol = SCSI_PROTO_FC;
2159                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2160                 return (sizeof(*id));
2161         }
2162         case CTL_PORT_ISCSI:
2163         {
2164                 struct scsi_transportid_iscsi_port *id =
2165                     (struct scsi_transportid_iscsi_port *)buf;
2166                 if (port->wwpn_iid[iid].name == NULL)
2167                         return (0);
2168                 memset(id, 0, 256);
2169                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2170                     SCSI_PROTO_ISCSI;
2171                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2172                 len = roundup2(min(len, 252), 4);
2173                 scsi_ulto2b(len, id->additional_length);
2174                 return (sizeof(*id) + len);
2175         }
2176         case CTL_PORT_SAS:
2177         {
2178                 struct scsi_transportid_sas *id =
2179                     (struct scsi_transportid_sas *)buf;
2180                 if (port->wwpn_iid[iid].wwpn == 0)
2181                         return (0);
2182                 memset(id, 0, sizeof(*id));
2183                 id->format_protocol = SCSI_PROTO_SAS;
2184                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2185                 return (sizeof(*id));
2186         }
2187         default:
2188         {
2189                 struct scsi_transportid_spi *id =
2190                     (struct scsi_transportid_spi *)buf;
2191                 memset(id, 0, sizeof(*id));
2192                 id->format_protocol = SCSI_PROTO_SPI;
2193                 scsi_ulto2b(iid, id->scsi_addr);
2194                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2195                 return (sizeof(*id));
2196         }
2197         }
2198 }
2199
2200 /*
2201  * Serialize a command that went down the "wrong" side, and so was sent to
2202  * this controller for execution.  The logic is a little different than the
2203  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2204  * sent back to the other side, but in the success case, we execute the
2205  * command on this side (XFER mode) or tell the other side to execute it
2206  * (SER_ONLY mode).
2207  */
2208 static void
2209 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2210 {
2211         struct ctl_softc *softc = CTL_SOFTC(ctsio);
2212         struct ctl_port *port = CTL_PORT(ctsio);
2213         union ctl_ha_msg msg_info;
2214         struct ctl_lun *lun;
2215         const struct ctl_cmd_entry *entry;
2216         uint32_t targ_lun;
2217
2218         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2219
2220         /* Make sure that we know about this port. */
2221         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2222                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2223                                          /*retry_count*/ 1);
2224                 goto badjuju;
2225         }
2226
2227         /* Make sure that we know about this LUN. */
2228         mtx_lock(&softc->ctl_lock);
2229         if (targ_lun >= CTL_MAX_LUNS ||
2230             (lun = softc->ctl_luns[targ_lun]) == NULL) {
2231                 mtx_unlock(&softc->ctl_lock);
2232
2233                 /*
2234                  * The other node would not send this request to us unless
2235                  * received announce that we are primary node for this LUN.
2236                  * If this LUN does not exist now, it is probably result of
2237                  * a race, so respond to initiator in the most opaque way.
2238                  */
2239                 ctl_set_busy(ctsio);
2240                 goto badjuju;
2241         }
2242         mtx_lock(&lun->lun_lock);
2243         mtx_unlock(&softc->ctl_lock);
2244
2245         /*
2246          * If the LUN is invalid, pretend that it doesn't exist.
2247          * It will go away as soon as all pending I/Os completed.
2248          */
2249         if (lun->flags & CTL_LUN_DISABLED) {
2250                 mtx_unlock(&lun->lun_lock);
2251                 ctl_set_busy(ctsio);
2252                 goto badjuju;
2253         }
2254
2255         entry = ctl_get_cmd_entry(ctsio, NULL);
2256         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2257                 mtx_unlock(&lun->lun_lock);
2258                 goto badjuju;
2259         }
2260
2261         CTL_LUN(ctsio) = lun;
2262         CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2263
2264         /*
2265          * Every I/O goes into the OOA queue for a
2266          * particular LUN, and stays there until completion.
2267          */
2268 #ifdef CTL_TIME_IO
2269         if (TAILQ_EMPTY(&lun->ooa_queue))
2270                 lun->idle_time += getsbinuptime() - lun->last_busy;
2271 #endif
2272         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2273
2274         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2275                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2276                  ooa_links))) {
2277         case CTL_ACTION_BLOCK:
2278                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2279                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2280                                   blocked_links);
2281                 mtx_unlock(&lun->lun_lock);
2282                 break;
2283         case CTL_ACTION_PASS:
2284         case CTL_ACTION_SKIP:
2285                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2286                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2287                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2288                         mtx_unlock(&lun->lun_lock);
2289                 } else {
2290                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2291                         mtx_unlock(&lun->lun_lock);
2292
2293                         /* send msg back to other side */
2294                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2295                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2296                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2297                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2298                             sizeof(msg_info.hdr), M_WAITOK);
2299                 }
2300                 break;
2301         case CTL_ACTION_OVERLAP:
2302                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2303                 mtx_unlock(&lun->lun_lock);
2304                 ctl_set_overlapped_cmd(ctsio);
2305                 goto badjuju;
2306         case CTL_ACTION_OVERLAP_TAG:
2307                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2308                 mtx_unlock(&lun->lun_lock);
2309                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2310                 goto badjuju;
2311         case CTL_ACTION_ERROR:
2312         default:
2313                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2314                 mtx_unlock(&lun->lun_lock);
2315
2316                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2317                                          /*retry_count*/ 0);
2318 badjuju:
2319                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2320                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2321                 msg_info.hdr.serializing_sc = NULL;
2322                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2323                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2324                     sizeof(msg_info.scsi), M_WAITOK);
2325                 ctl_free_io((union ctl_io *)ctsio);
2326                 break;
2327         }
2328 }
2329
2330 /*
2331  * Returns 0 for success, errno for failure.
2332  */
2333 static void
2334 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2335                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2336 {
2337         union ctl_io *io;
2338
2339         mtx_lock(&lun->lun_lock);
2340         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2341              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2342              ooa_links)) {
2343                 struct ctl_ooa_entry *entry;
2344
2345                 /*
2346                  * If we've got more than we can fit, just count the
2347                  * remaining entries.
2348                  */
2349                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2350                         continue;
2351
2352                 entry = &kern_entries[*cur_fill_num];
2353
2354                 entry->tag_num = io->scsiio.tag_num;
2355                 entry->lun_num = lun->lun;
2356 #ifdef CTL_TIME_IO
2357                 entry->start_bt = io->io_hdr.start_bt;
2358 #endif
2359                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2360                 entry->cdb_len = io->scsiio.cdb_len;
2361                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2362                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2363
2364                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2365                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2366
2367                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2368                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2369
2370                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2371                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2372
2373                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2374                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2375         }
2376         mtx_unlock(&lun->lun_lock);
2377 }
2378
2379 static void *
2380 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2381                  size_t error_str_len)
2382 {
2383         void *kptr;
2384
2385         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2386
2387         if (copyin(user_addr, kptr, len) != 0) {
2388                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2389                          "from user address %p to kernel address %p", len,
2390                          user_addr, kptr);
2391                 free(kptr, M_CTL);
2392                 return (NULL);
2393         }
2394
2395         return (kptr);
2396 }
2397
2398 static void
2399 ctl_free_args(int num_args, struct ctl_be_arg *args)
2400 {
2401         int i;
2402
2403         if (args == NULL)
2404                 return;
2405
2406         for (i = 0; i < num_args; i++) {
2407                 free(args[i].kname, M_CTL);
2408                 free(args[i].kvalue, M_CTL);
2409         }
2410
2411         free(args, M_CTL);
2412 }
2413
2414 static struct ctl_be_arg *
2415 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2416                 char *error_str, size_t error_str_len)
2417 {
2418         struct ctl_be_arg *args;
2419         int i;
2420
2421         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2422                                 error_str, error_str_len);
2423
2424         if (args == NULL)
2425                 goto bailout;
2426
2427         for (i = 0; i < num_args; i++) {
2428                 args[i].kname = NULL;
2429                 args[i].kvalue = NULL;
2430         }
2431
2432         for (i = 0; i < num_args; i++) {
2433                 uint8_t *tmpptr;
2434
2435                 args[i].kname = ctl_copyin_alloc(args[i].name,
2436                         args[i].namelen, error_str, error_str_len);
2437                 if (args[i].kname == NULL)
2438                         goto bailout;
2439
2440                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2441                         snprintf(error_str, error_str_len, "Argument %d "
2442                                  "name is not NUL-terminated", i);
2443                         goto bailout;
2444                 }
2445
2446                 if (args[i].flags & CTL_BEARG_RD) {
2447                         tmpptr = ctl_copyin_alloc(args[i].value,
2448                                 args[i].vallen, error_str, error_str_len);
2449                         if (tmpptr == NULL)
2450                                 goto bailout;
2451                         if ((args[i].flags & CTL_BEARG_ASCII)
2452                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2453                                 snprintf(error_str, error_str_len, "Argument "
2454                                     "%d value is not NUL-terminated", i);
2455                                 free(tmpptr, M_CTL);
2456                                 goto bailout;
2457                         }
2458                         args[i].kvalue = tmpptr;
2459                 } else {
2460                         args[i].kvalue = malloc(args[i].vallen,
2461                             M_CTL, M_WAITOK | M_ZERO);
2462                 }
2463         }
2464
2465         return (args);
2466 bailout:
2467
2468         ctl_free_args(num_args, args);
2469
2470         return (NULL);
2471 }
2472
2473 static void
2474 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2475 {
2476         int i;
2477
2478         for (i = 0; i < num_args; i++) {
2479                 if (args[i].flags & CTL_BEARG_WR)
2480                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2481         }
2482 }
2483
2484 /*
2485  * Escape characters that are illegal or not recommended in XML.
2486  */
2487 int
2488 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2489 {
2490         char *end = str + size;
2491         int retval;
2492
2493         retval = 0;
2494
2495         for (; *str && str < end; str++) {
2496                 switch (*str) {
2497                 case '&':
2498                         retval = sbuf_printf(sb, "&amp;");
2499                         break;
2500                 case '>':
2501                         retval = sbuf_printf(sb, "&gt;");
2502                         break;
2503                 case '<':
2504                         retval = sbuf_printf(sb, "&lt;");
2505                         break;
2506                 default:
2507                         retval = sbuf_putc(sb, *str);
2508                         break;
2509                 }
2510
2511                 if (retval != 0)
2512                         break;
2513
2514         }
2515
2516         return (retval);
2517 }
2518
2519 static void
2520 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2521 {
2522         struct scsi_vpd_id_descriptor *desc;
2523         int i;
2524
2525         if (id == NULL || id->len < 4)
2526                 return;
2527         desc = (struct scsi_vpd_id_descriptor *)id->data;
2528         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2529         case SVPD_ID_TYPE_T10:
2530                 sbuf_printf(sb, "t10.");
2531                 break;
2532         case SVPD_ID_TYPE_EUI64:
2533                 sbuf_printf(sb, "eui.");
2534                 break;
2535         case SVPD_ID_TYPE_NAA:
2536                 sbuf_printf(sb, "naa.");
2537                 break;
2538         case SVPD_ID_TYPE_SCSI_NAME:
2539                 break;
2540         }
2541         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2542         case SVPD_ID_CODESET_BINARY:
2543                 for (i = 0; i < desc->length; i++)
2544                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2545                 break;
2546         case SVPD_ID_CODESET_ASCII:
2547                 sbuf_printf(sb, "%.*s", (int)desc->length,
2548                     (char *)desc->identifier);
2549                 break;
2550         case SVPD_ID_CODESET_UTF8:
2551                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2552                 break;
2553         }
2554 }
2555
2556 static int
2557 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2558           struct thread *td)
2559 {
2560         struct ctl_softc *softc = dev->si_drv1;
2561         struct ctl_lun *lun;
2562         int retval;
2563
2564         retval = 0;
2565
2566         switch (cmd) {
2567         case CTL_IO:
2568                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2569                 break;
2570         case CTL_ENABLE_PORT:
2571         case CTL_DISABLE_PORT:
2572         case CTL_SET_PORT_WWNS: {
2573                 struct ctl_port *port;
2574                 struct ctl_port_entry *entry;
2575
2576                 entry = (struct ctl_port_entry *)addr;
2577                 
2578                 mtx_lock(&softc->ctl_lock);
2579                 STAILQ_FOREACH(port, &softc->port_list, links) {
2580                         int action, done;
2581
2582                         if (port->targ_port < softc->port_min ||
2583                             port->targ_port >= softc->port_max)
2584                                 continue;
2585
2586                         action = 0;
2587                         done = 0;
2588                         if ((entry->port_type == CTL_PORT_NONE)
2589                          && (entry->targ_port == port->targ_port)) {
2590                                 /*
2591                                  * If the user only wants to enable or
2592                                  * disable or set WWNs on a specific port,
2593                                  * do the operation and we're done.
2594                                  */
2595                                 action = 1;
2596                                 done = 1;
2597                         } else if (entry->port_type & port->port_type) {
2598                                 /*
2599                                  * Compare the user's type mask with the
2600                                  * particular frontend type to see if we
2601                                  * have a match.
2602                                  */
2603                                 action = 1;
2604                                 done = 0;
2605
2606                                 /*
2607                                  * Make sure the user isn't trying to set
2608                                  * WWNs on multiple ports at the same time.
2609                                  */
2610                                 if (cmd == CTL_SET_PORT_WWNS) {
2611                                         printf("%s: Can't set WWNs on "
2612                                                "multiple ports\n", __func__);
2613                                         retval = EINVAL;
2614                                         break;
2615                                 }
2616                         }
2617                         if (action == 0)
2618                                 continue;
2619
2620                         /*
2621                          * XXX KDM we have to drop the lock here, because
2622                          * the online/offline operations can potentially
2623                          * block.  We need to reference count the frontends
2624                          * so they can't go away,
2625                          */
2626                         if (cmd == CTL_ENABLE_PORT) {
2627                                 mtx_unlock(&softc->ctl_lock);
2628                                 ctl_port_online(port);
2629                                 mtx_lock(&softc->ctl_lock);
2630                         } else if (cmd == CTL_DISABLE_PORT) {
2631                                 mtx_unlock(&softc->ctl_lock);
2632                                 ctl_port_offline(port);
2633                                 mtx_lock(&softc->ctl_lock);
2634                         } else if (cmd == CTL_SET_PORT_WWNS) {
2635                                 ctl_port_set_wwns(port,
2636                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2637                                     1 : 0, entry->wwnn,
2638                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2639                                     1 : 0, entry->wwpn);
2640                         }
2641                         if (done != 0)
2642                                 break;
2643                 }
2644                 mtx_unlock(&softc->ctl_lock);
2645                 break;
2646         }
2647         case CTL_GET_OOA: {
2648                 struct ctl_ooa *ooa_hdr;
2649                 struct ctl_ooa_entry *entries;
2650                 uint32_t cur_fill_num;
2651
2652                 ooa_hdr = (struct ctl_ooa *)addr;
2653
2654                 if ((ooa_hdr->alloc_len == 0)
2655                  || (ooa_hdr->alloc_num == 0)) {
2656                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2657                                "must be non-zero\n", __func__,
2658                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2659                         retval = EINVAL;
2660                         break;
2661                 }
2662
2663                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2664                     sizeof(struct ctl_ooa_entry))) {
2665                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2666                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2667                                __func__, ooa_hdr->alloc_len,
2668                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2669                         retval = EINVAL;
2670                         break;
2671                 }
2672
2673                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2674                 if (entries == NULL) {
2675                         printf("%s: could not allocate %d bytes for OOA "
2676                                "dump\n", __func__, ooa_hdr->alloc_len);
2677                         retval = ENOMEM;
2678                         break;
2679                 }
2680
2681                 mtx_lock(&softc->ctl_lock);
2682                 if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2683                     (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2684                      softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2685                         mtx_unlock(&softc->ctl_lock);
2686                         free(entries, M_CTL);
2687                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2688                                __func__, (uintmax_t)ooa_hdr->lun_num);
2689                         retval = EINVAL;
2690                         break;
2691                 }
2692
2693                 cur_fill_num = 0;
2694
2695                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2696                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2697                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2698                                     ooa_hdr, entries);
2699                         }
2700                 } else {
2701                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2702                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2703                             entries);
2704                 }
2705                 mtx_unlock(&softc->ctl_lock);
2706
2707                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2708                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2709                         sizeof(struct ctl_ooa_entry);
2710                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2711                 if (retval != 0) {
2712                         printf("%s: error copying out %d bytes for OOA dump\n", 
2713                                __func__, ooa_hdr->fill_len);
2714                 }
2715
2716                 getbinuptime(&ooa_hdr->cur_bt);
2717
2718                 if (cur_fill_num > ooa_hdr->alloc_num) {
2719                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2720                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2721                 } else {
2722                         ooa_hdr->dropped_num = 0;
2723                         ooa_hdr->status = CTL_OOA_OK;
2724                 }
2725
2726                 free(entries, M_CTL);
2727                 break;
2728         }
2729         case CTL_DELAY_IO: {
2730                 struct ctl_io_delay_info *delay_info;
2731
2732                 delay_info = (struct ctl_io_delay_info *)addr;
2733
2734 #ifdef CTL_IO_DELAY
2735                 mtx_lock(&softc->ctl_lock);
2736                 if (delay_info->lun_id >= CTL_MAX_LUNS ||
2737                     (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2738                         mtx_unlock(&softc->ctl_lock);
2739                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2740                         break;
2741                 }
2742                 mtx_lock(&lun->lun_lock);
2743                 mtx_unlock(&softc->ctl_lock);
2744                 delay_info->status = CTL_DELAY_STATUS_OK;
2745                 switch (delay_info->delay_type) {
2746                 case CTL_DELAY_TYPE_CONT:
2747                 case CTL_DELAY_TYPE_ONESHOT:
2748                         break;
2749                 default:
2750                         delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2751                         break;
2752                 }
2753                 switch (delay_info->delay_loc) {
2754                 case CTL_DELAY_LOC_DATAMOVE:
2755                         lun->delay_info.datamove_type = delay_info->delay_type;
2756                         lun->delay_info.datamove_delay = delay_info->delay_secs;
2757                         break;
2758                 case CTL_DELAY_LOC_DONE:
2759                         lun->delay_info.done_type = delay_info->delay_type;
2760                         lun->delay_info.done_delay = delay_info->delay_secs;
2761                         break;
2762                 default:
2763                         delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2764                         break;
2765                 }
2766                 mtx_unlock(&lun->lun_lock);
2767 #else
2768                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2769 #endif /* CTL_IO_DELAY */
2770                 break;
2771         }
2772         case CTL_GETSTATS: {
2773                 struct ctl_stats *stats;
2774                 int i;
2775
2776                 stats = (struct ctl_stats *)addr;
2777
2778                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2779                      stats->alloc_len) {
2780                         stats->status = CTL_SS_NEED_MORE_SPACE;
2781                         stats->num_luns = softc->num_luns;
2782                         break;
2783                 }
2784                 /*
2785                  * XXX KDM no locking here.  If the LUN list changes,
2786                  * things can blow up.
2787                  */
2788                 i = 0;
2789                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2790                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2791                                          sizeof(lun->stats));
2792                         if (retval != 0)
2793                                 break;
2794                 }
2795                 stats->num_luns = softc->num_luns;
2796                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2797                                  softc->num_luns;
2798                 stats->status = CTL_SS_OK;
2799 #ifdef CTL_TIME_IO
2800                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2801 #else
2802                 stats->flags = CTL_STATS_FLAG_NONE;
2803 #endif
2804                 getnanouptime(&stats->timestamp);
2805                 break;
2806         }
2807         case CTL_ERROR_INJECT: {
2808                 struct ctl_error_desc *err_desc, *new_err_desc;
2809
2810                 err_desc = (struct ctl_error_desc *)addr;
2811
2812                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2813                                       M_WAITOK | M_ZERO);
2814                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2815
2816                 mtx_lock(&softc->ctl_lock);
2817                 if (err_desc->lun_id >= CTL_MAX_LUNS ||
2818                     (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2819                         mtx_unlock(&softc->ctl_lock);
2820                         free(new_err_desc, M_CTL);
2821                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2822                                __func__, (uintmax_t)err_desc->lun_id);
2823                         retval = EINVAL;
2824                         break;
2825                 }
2826                 mtx_lock(&lun->lun_lock);
2827                 mtx_unlock(&softc->ctl_lock);
2828
2829                 /*
2830                  * We could do some checking here to verify the validity
2831                  * of the request, but given the complexity of error
2832                  * injection requests, the checking logic would be fairly
2833                  * complex.
2834                  *
2835                  * For now, if the request is invalid, it just won't get
2836                  * executed and might get deleted.
2837                  */
2838                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2839
2840                 /*
2841                  * XXX KDM check to make sure the serial number is unique,
2842                  * in case we somehow manage to wrap.  That shouldn't
2843                  * happen for a very long time, but it's the right thing to
2844                  * do.
2845                  */
2846                 new_err_desc->serial = lun->error_serial;
2847                 err_desc->serial = lun->error_serial;
2848                 lun->error_serial++;
2849
2850                 mtx_unlock(&lun->lun_lock);
2851                 break;
2852         }
2853         case CTL_ERROR_INJECT_DELETE: {
2854                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2855                 int delete_done;
2856
2857                 delete_desc = (struct ctl_error_desc *)addr;
2858                 delete_done = 0;
2859
2860                 mtx_lock(&softc->ctl_lock);
2861                 if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2862                     (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2863                         mtx_unlock(&softc->ctl_lock);
2864                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2865                                __func__, (uintmax_t)delete_desc->lun_id);
2866                         retval = EINVAL;
2867                         break;
2868                 }
2869                 mtx_lock(&lun->lun_lock);
2870                 mtx_unlock(&softc->ctl_lock);
2871                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2872                         if (desc->serial != delete_desc->serial)
2873                                 continue;
2874
2875                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2876                                       links);
2877                         free(desc, M_CTL);
2878                         delete_done = 1;
2879                 }
2880                 mtx_unlock(&lun->lun_lock);
2881                 if (delete_done == 0) {
2882                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2883                                "error serial %ju on LUN %u\n", __func__, 
2884                                delete_desc->serial, delete_desc->lun_id);
2885                         retval = EINVAL;
2886                         break;
2887                 }
2888                 break;
2889         }
2890         case CTL_DUMP_STRUCTS: {
2891                 int j, k;
2892                 struct ctl_port *port;
2893                 struct ctl_frontend *fe;
2894
2895                 mtx_lock(&softc->ctl_lock);
2896                 printf("CTL Persistent Reservation information start:\n");
2897                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2898                         mtx_lock(&lun->lun_lock);
2899                         if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2900                                 mtx_unlock(&lun->lun_lock);
2901                                 continue;
2902                         }
2903
2904                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2905                                 if (lun->pr_keys[j] == NULL)
2906                                         continue;
2907                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2908                                         if (lun->pr_keys[j][k] == 0)
2909                                                 continue;
2910                                         printf("  LUN %ju port %d iid %d key "
2911                                                "%#jx\n", lun->lun, j, k,
2912                                                (uintmax_t)lun->pr_keys[j][k]);
2913                                 }
2914                         }
2915                         mtx_unlock(&lun->lun_lock);
2916                 }
2917                 printf("CTL Persistent Reservation information end\n");
2918                 printf("CTL Ports:\n");
2919                 STAILQ_FOREACH(port, &softc->port_list, links) {
2920                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2921                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2922                                port->frontend->name, port->port_type,
2923                                port->physical_port, port->virtual_port,
2924                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2925                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2926                                 if (port->wwpn_iid[j].in_use == 0 &&
2927                                     port->wwpn_iid[j].wwpn == 0 &&
2928                                     port->wwpn_iid[j].name == NULL)
2929                                         continue;
2930
2931                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2932                                     j, port->wwpn_iid[j].in_use,
2933                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2934                                     port->wwpn_iid[j].name);
2935                         }
2936                 }
2937                 printf("CTL Port information end\n");
2938                 mtx_unlock(&softc->ctl_lock);
2939                 /*
2940                  * XXX KDM calling this without a lock.  We'd likely want
2941                  * to drop the lock before calling the frontend's dump
2942                  * routine anyway.
2943                  */
2944                 printf("CTL Frontends:\n");
2945                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2946                         printf("  Frontend '%s'\n", fe->name);
2947                         if (fe->fe_dump != NULL)
2948                                 fe->fe_dump();
2949                 }
2950                 printf("CTL Frontend information end\n");
2951                 break;
2952         }
2953         case CTL_LUN_REQ: {
2954                 struct ctl_lun_req *lun_req;
2955                 struct ctl_backend_driver *backend;
2956
2957                 lun_req = (struct ctl_lun_req *)addr;
2958
2959                 backend = ctl_backend_find(lun_req->backend);
2960                 if (backend == NULL) {
2961                         lun_req->status = CTL_LUN_ERROR;
2962                         snprintf(lun_req->error_str,
2963                                  sizeof(lun_req->error_str),
2964                                  "Backend \"%s\" not found.",
2965                                  lun_req->backend);
2966                         break;
2967                 }
2968                 if (lun_req->num_be_args > 0) {
2969                         lun_req->kern_be_args = ctl_copyin_args(
2970                                 lun_req->num_be_args,
2971                                 lun_req->be_args,
2972                                 lun_req->error_str,
2973                                 sizeof(lun_req->error_str));
2974                         if (lun_req->kern_be_args == NULL) {
2975                                 lun_req->status = CTL_LUN_ERROR;
2976                                 break;
2977                         }
2978                 }
2979
2980                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2981
2982                 if (lun_req->num_be_args > 0) {
2983                         ctl_copyout_args(lun_req->num_be_args,
2984                                       lun_req->kern_be_args);
2985                         ctl_free_args(lun_req->num_be_args,
2986                                       lun_req->kern_be_args);
2987                 }
2988                 break;
2989         }
2990         case CTL_LUN_LIST: {
2991                 struct sbuf *sb;
2992                 struct ctl_lun_list *list;
2993                 struct ctl_option *opt;
2994
2995                 list = (struct ctl_lun_list *)addr;
2996
2997                 /*
2998                  * Allocate a fixed length sbuf here, based on the length
2999                  * of the user's buffer.  We could allocate an auto-extending
3000                  * buffer, and then tell the user how much larger our
3001                  * amount of data is than his buffer, but that presents
3002                  * some problems:
3003                  *
3004                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3005                  *     we can't hold a lock while calling them with an
3006                  *     auto-extending buffer.
3007                  *
3008                  * 2.  There is not currently a LUN reference counting
3009                  *     mechanism, outside of outstanding transactions on
3010                  *     the LUN's OOA queue.  So a LUN could go away on us
3011                  *     while we're getting the LUN number, backend-specific
3012                  *     information, etc.  Thus, given the way things
3013                  *     currently work, we need to hold the CTL lock while
3014                  *     grabbing LUN information.
3015                  *
3016                  * So, from the user's standpoint, the best thing to do is
3017                  * allocate what he thinks is a reasonable buffer length,
3018                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3019                  * double the buffer length and try again.  (And repeat
3020                  * that until he succeeds.)
3021                  */
3022                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3023                 if (sb == NULL) {
3024                         list->status = CTL_LUN_LIST_ERROR;
3025                         snprintf(list->error_str, sizeof(list->error_str),
3026                                  "Unable to allocate %d bytes for LUN list",
3027                                  list->alloc_len);
3028                         break;
3029                 }
3030
3031                 sbuf_printf(sb, "<ctllunlist>\n");
3032
3033                 mtx_lock(&softc->ctl_lock);
3034                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3035                         mtx_lock(&lun->lun_lock);
3036                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3037                                              (uintmax_t)lun->lun);
3038
3039                         /*
3040                          * Bail out as soon as we see that we've overfilled
3041                          * the buffer.
3042                          */
3043                         if (retval != 0)
3044                                 break;
3045
3046                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3047                                              "</backend_type>\n",
3048                                              (lun->backend == NULL) ?  "none" :
3049                                              lun->backend->name);
3050
3051                         if (retval != 0)
3052                                 break;
3053
3054                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3055                                              lun->be_lun->lun_type);
3056
3057                         if (retval != 0)
3058                                 break;
3059
3060                         if (lun->backend == NULL) {
3061                                 retval = sbuf_printf(sb, "</lun>\n");
3062                                 if (retval != 0)
3063                                         break;
3064                                 continue;
3065                         }
3066
3067                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3068                                              (lun->be_lun->maxlba > 0) ?
3069                                              lun->be_lun->maxlba + 1 : 0);
3070
3071                         if (retval != 0)
3072                                 break;
3073
3074                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3075                                              lun->be_lun->blocksize);
3076
3077                         if (retval != 0)
3078                                 break;
3079
3080                         retval = sbuf_printf(sb, "\t<serial_number>");
3081
3082                         if (retval != 0)
3083                                 break;
3084
3085                         retval = ctl_sbuf_printf_esc(sb,
3086                             lun->be_lun->serial_num,
3087                             sizeof(lun->be_lun->serial_num));
3088
3089                         if (retval != 0)
3090                                 break;
3091
3092                         retval = sbuf_printf(sb, "</serial_number>\n");
3093                 
3094                         if (retval != 0)
3095                                 break;
3096
3097                         retval = sbuf_printf(sb, "\t<device_id>");
3098
3099                         if (retval != 0)
3100                                 break;
3101
3102                         retval = ctl_sbuf_printf_esc(sb,
3103                             lun->be_lun->device_id,
3104                             sizeof(lun->be_lun->device_id));
3105
3106                         if (retval != 0)
3107                                 break;
3108
3109                         retval = sbuf_printf(sb, "</device_id>\n");
3110
3111                         if (retval != 0)
3112                                 break;
3113
3114                         if (lun->backend->lun_info != NULL) {
3115                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3116                                 if (retval != 0)
3117                                         break;
3118                         }
3119                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3120                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3121                                     opt->name, opt->value, opt->name);
3122                                 if (retval != 0)
3123                                         break;
3124                         }
3125
3126                         retval = sbuf_printf(sb, "</lun>\n");
3127
3128                         if (retval != 0)
3129                                 break;
3130                         mtx_unlock(&lun->lun_lock);
3131                 }
3132                 if (lun != NULL)
3133                         mtx_unlock(&lun->lun_lock);
3134                 mtx_unlock(&softc->ctl_lock);
3135
3136                 if ((retval != 0)
3137                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3138                         retval = 0;
3139                         sbuf_delete(sb);
3140                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3141                         snprintf(list->error_str, sizeof(list->error_str),
3142                                  "Out of space, %d bytes is too small",
3143                                  list->alloc_len);
3144                         break;
3145                 }
3146
3147                 sbuf_finish(sb);
3148
3149                 retval = copyout(sbuf_data(sb), list->lun_xml,
3150                                  sbuf_len(sb) + 1);
3151
3152                 list->fill_len = sbuf_len(sb) + 1;
3153                 list->status = CTL_LUN_LIST_OK;
3154                 sbuf_delete(sb);
3155                 break;
3156         }
3157         case CTL_ISCSI: {
3158                 struct ctl_iscsi *ci;
3159                 struct ctl_frontend *fe;
3160
3161                 ci = (struct ctl_iscsi *)addr;
3162
3163                 fe = ctl_frontend_find("iscsi");
3164                 if (fe == NULL) {
3165                         ci->status = CTL_ISCSI_ERROR;
3166                         snprintf(ci->error_str, sizeof(ci->error_str),
3167                             "Frontend \"iscsi\" not found.");
3168                         break;
3169                 }
3170
3171                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3172                 break;
3173         }
3174         case CTL_PORT_REQ: {
3175                 struct ctl_req *req;
3176                 struct ctl_frontend *fe;
3177
3178                 req = (struct ctl_req *)addr;
3179
3180                 fe = ctl_frontend_find(req->driver);
3181                 if (fe == NULL) {
3182                         req->status = CTL_LUN_ERROR;
3183                         snprintf(req->error_str, sizeof(req->error_str),
3184                             "Frontend \"%s\" not found.", req->driver);
3185                         break;
3186                 }
3187                 if (req->num_args > 0) {
3188                         req->kern_args = ctl_copyin_args(req->num_args,
3189                             req->args, req->error_str, sizeof(req->error_str));
3190                         if (req->kern_args == NULL) {
3191                                 req->status = CTL_LUN_ERROR;
3192                                 break;
3193                         }
3194                 }
3195
3196                 if (fe->ioctl)
3197                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3198                 else
3199                         retval = ENODEV;
3200
3201                 if (req->num_args > 0) {
3202                         ctl_copyout_args(req->num_args, req->kern_args);
3203                         ctl_free_args(req->num_args, req->kern_args);
3204                 }
3205                 break;
3206         }
3207         case CTL_PORT_LIST: {
3208                 struct sbuf *sb;
3209                 struct ctl_port *port;
3210                 struct ctl_lun_list *list;
3211                 struct ctl_option *opt;
3212                 int j;
3213                 uint32_t plun;
3214
3215                 list = (struct ctl_lun_list *)addr;
3216
3217                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3218                 if (sb == NULL) {
3219                         list->status = CTL_LUN_LIST_ERROR;
3220                         snprintf(list->error_str, sizeof(list->error_str),
3221                                  "Unable to allocate %d bytes for LUN list",
3222                                  list->alloc_len);
3223                         break;
3224                 }
3225
3226                 sbuf_printf(sb, "<ctlportlist>\n");
3227
3228                 mtx_lock(&softc->ctl_lock);
3229                 STAILQ_FOREACH(port, &softc->port_list, links) {
3230                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3231                                              (uintmax_t)port->targ_port);
3232
3233                         /*
3234                          * Bail out as soon as we see that we've overfilled
3235                          * the buffer.
3236                          */
3237                         if (retval != 0)
3238                                 break;
3239
3240                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3241                             "</frontend_type>\n", port->frontend->name);
3242                         if (retval != 0)
3243                                 break;
3244
3245                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3246                                              port->port_type);
3247                         if (retval != 0)
3248                                 break;
3249
3250                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3251                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3252                         if (retval != 0)
3253                                 break;
3254
3255                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3256                             port->port_name);
3257                         if (retval != 0)
3258                                 break;
3259
3260                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3261                             port->physical_port);
3262                         if (retval != 0)
3263                                 break;
3264
3265                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3266                             port->virtual_port);
3267                         if (retval != 0)
3268                                 break;
3269
3270                         if (port->target_devid != NULL) {
3271                                 sbuf_printf(sb, "\t<target>");
3272                                 ctl_id_sbuf(port->target_devid, sb);
3273                                 sbuf_printf(sb, "</target>\n");
3274                         }
3275
3276                         if (port->port_devid != NULL) {
3277                                 sbuf_printf(sb, "\t<port>");
3278                                 ctl_id_sbuf(port->port_devid, sb);
3279                                 sbuf_printf(sb, "</port>\n");
3280                         }
3281
3282                         if (port->port_info != NULL) {
3283                                 retval = port->port_info(port->onoff_arg, sb);
3284                                 if (retval != 0)
3285                                         break;
3286                         }
3287                         STAILQ_FOREACH(opt, &port->options, links) {
3288                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3289                                     opt->name, opt->value, opt->name);
3290                                 if (retval != 0)
3291                                         break;
3292                         }
3293
3294                         if (port->lun_map != NULL) {
3295                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3296                                 for (j = 0; j < port->lun_map_size; j++) {
3297                                         plun = ctl_lun_map_from_port(port, j);
3298                                         if (plun == UINT32_MAX)
3299                                                 continue;
3300                                         sbuf_printf(sb,
3301                                             "\t<lun id=\"%u\">%u</lun>\n",
3302                                             j, plun);
3303                                 }
3304                         }
3305
3306                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3307                                 if (port->wwpn_iid[j].in_use == 0 ||
3308                                     (port->wwpn_iid[j].wwpn == 0 &&
3309                                      port->wwpn_iid[j].name == NULL))
3310                                         continue;
3311
3312                                 if (port->wwpn_iid[j].name != NULL)
3313                                         retval = sbuf_printf(sb,
3314                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3315                                             j, port->wwpn_iid[j].name);
3316                                 else
3317                                         retval = sbuf_printf(sb,
3318                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3319                                             j, port->wwpn_iid[j].wwpn);
3320                                 if (retval != 0)
3321                                         break;
3322                         }
3323                         if (retval != 0)
3324                                 break;
3325
3326                         retval = sbuf_printf(sb, "</targ_port>\n");
3327                         if (retval != 0)
3328                                 break;
3329                 }
3330                 mtx_unlock(&softc->ctl_lock);
3331
3332                 if ((retval != 0)
3333                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3334                         retval = 0;
3335                         sbuf_delete(sb);
3336                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3337                         snprintf(list->error_str, sizeof(list->error_str),
3338                                  "Out of space, %d bytes is too small",
3339                                  list->alloc_len);
3340                         break;
3341                 }
3342
3343                 sbuf_finish(sb);
3344
3345                 retval = copyout(sbuf_data(sb), list->lun_xml,
3346                                  sbuf_len(sb) + 1);
3347
3348                 list->fill_len = sbuf_len(sb) + 1;
3349                 list->status = CTL_LUN_LIST_OK;
3350                 sbuf_delete(sb);
3351                 break;
3352         }
3353         case CTL_LUN_MAP: {
3354                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3355                 struct ctl_port *port;
3356
3357                 mtx_lock(&softc->ctl_lock);
3358                 if (lm->port < softc->port_min ||
3359                     lm->port >= softc->port_max ||
3360                     (port = softc->ctl_ports[lm->port]) == NULL) {
3361                         mtx_unlock(&softc->ctl_lock);
3362                         return (ENXIO);
3363                 }
3364                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3365                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3366                                 if (ctl_lun_map_to_port(port, lun->lun) ==
3367                                     UINT32_MAX)
3368                                         continue;
3369                                 mtx_lock(&lun->lun_lock);
3370                                 ctl_est_ua_port(lun, lm->port, -1,
3371                                     CTL_UA_LUN_CHANGE);
3372                                 mtx_unlock(&lun->lun_lock);
3373                         }
3374                 }
3375                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3376                 if (lm->plun != UINT32_MAX) {
3377                         if (lm->lun == UINT32_MAX)
3378                                 retval = ctl_lun_map_unset(port, lm->plun);
3379                         else if (lm->lun < CTL_MAX_LUNS &&
3380                             softc->ctl_luns[lm->lun] != NULL)
3381                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3382                         else
3383                                 return (ENXIO);
3384                 } else {
3385                         if (lm->lun == UINT32_MAX)
3386                                 retval = ctl_lun_map_deinit(port);
3387                         else
3388                                 retval = ctl_lun_map_init(port);
3389                 }
3390                 if (port->status & CTL_PORT_STATUS_ONLINE)
3391                         ctl_isc_announce_port(port);
3392                 break;
3393         }
3394         default: {
3395                 /* XXX KDM should we fix this? */
3396 #if 0
3397                 struct ctl_backend_driver *backend;
3398                 unsigned int type;
3399                 int found;
3400
3401                 found = 0;
3402
3403                 /*
3404                  * We encode the backend type as the ioctl type for backend
3405                  * ioctls.  So parse it out here, and then search for a
3406                  * backend of this type.
3407                  */
3408                 type = _IOC_TYPE(cmd);
3409
3410                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3411                         if (backend->type == type) {
3412                                 found = 1;
3413                                 break;
3414                         }
3415                 }
3416                 if (found == 0) {
3417                         printf("ctl: unknown ioctl command %#lx or backend "
3418                                "%d\n", cmd, type);
3419                         retval = EINVAL;
3420                         break;
3421                 }
3422                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3423 #endif
3424                 retval = ENOTTY;
3425                 break;
3426         }
3427         }
3428         return (retval);
3429 }
3430
3431 uint32_t
3432 ctl_get_initindex(struct ctl_nexus *nexus)
3433 {
3434         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3435 }
3436
3437 int
3438 ctl_lun_map_init(struct ctl_port *port)
3439 {
3440         struct ctl_softc *softc = port->ctl_softc;
3441         struct ctl_lun *lun;
3442         int size = ctl_lun_map_size;
3443         uint32_t i;
3444
3445         if (port->lun_map == NULL || port->lun_map_size < size) {
3446                 port->lun_map_size = 0;
3447                 free(port->lun_map, M_CTL);
3448                 port->lun_map = malloc(size * sizeof(uint32_t),
3449                     M_CTL, M_NOWAIT);
3450         }
3451         if (port->lun_map == NULL)
3452                 return (ENOMEM);
3453         for (i = 0; i < size; i++)
3454                 port->lun_map[i] = UINT32_MAX;
3455         port->lun_map_size = size;
3456         if (port->status & CTL_PORT_STATUS_ONLINE) {
3457                 if (port->lun_disable != NULL) {
3458                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3459                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3460                 }
3461                 ctl_isc_announce_port(port);
3462         }
3463         return (0);
3464 }
3465
3466 int
3467 ctl_lun_map_deinit(struct ctl_port *port)
3468 {
3469         struct ctl_softc *softc = port->ctl_softc;
3470         struct ctl_lun *lun;
3471
3472         if (port->lun_map == NULL)
3473                 return (0);
3474         port->lun_map_size = 0;
3475         free(port->lun_map, M_CTL);
3476         port->lun_map = NULL;
3477         if (port->status & CTL_PORT_STATUS_ONLINE) {
3478                 if (port->lun_enable != NULL) {
3479                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3480                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3481                 }
3482                 ctl_isc_announce_port(port);
3483         }
3484         return (0);
3485 }
3486
3487 int
3488 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3489 {
3490         int status;
3491         uint32_t old;
3492
3493         if (port->lun_map == NULL) {
3494                 status = ctl_lun_map_init(port);
3495                 if (status != 0)
3496                         return (status);
3497         }
3498         if (plun >= port->lun_map_size)
3499                 return (EINVAL);
3500         old = port->lun_map[plun];
3501         port->lun_map[plun] = glun;
3502         if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3503                 if (port->lun_enable != NULL)
3504                         port->lun_enable(port->targ_lun_arg, plun);
3505                 ctl_isc_announce_port(port);
3506         }
3507         return (0);
3508 }
3509
3510 int
3511 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3512 {
3513         uint32_t old;
3514
3515         if (port->lun_map == NULL || plun >= port->lun_map_size)
3516                 return (0);
3517         old = port->lun_map[plun];
3518         port->lun_map[plun] = UINT32_MAX;
3519         if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3520                 if (port->lun_disable != NULL)
3521                         port->lun_disable(port->targ_lun_arg, plun);
3522                 ctl_isc_announce_port(port);
3523         }
3524         return (0);
3525 }
3526
3527 uint32_t
3528 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3529 {
3530
3531         if (port == NULL)
3532                 return (UINT32_MAX);
3533         if (port->lun_map == NULL)
3534                 return (lun_id);
3535         if (lun_id > port->lun_map_size)
3536                 return (UINT32_MAX);
3537         return (port->lun_map[lun_id]);
3538 }
3539
3540 uint32_t
3541 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3542 {
3543         uint32_t i;
3544
3545         if (port == NULL)
3546                 return (UINT32_MAX);
3547         if (port->lun_map == NULL)
3548                 return (lun_id);
3549         for (i = 0; i < port->lun_map_size; i++) {
3550                 if (port->lun_map[i] == lun_id)
3551                         return (i);
3552         }
3553         return (UINT32_MAX);
3554 }
3555
3556 uint32_t
3557 ctl_decode_lun(uint64_t encoded)
3558 {
3559         uint8_t lun[8];
3560         uint32_t result = 0xffffffff;
3561
3562         be64enc(lun, encoded);
3563         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3564         case RPL_LUNDATA_ATYP_PERIPH:
3565                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3566                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3567                         result = lun[1];
3568                 break;
3569         case RPL_LUNDATA_ATYP_FLAT:
3570                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3571                     lun[6] == 0 && lun[7] == 0)
3572                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3573                 break;
3574         case RPL_LUNDATA_ATYP_EXTLUN:
3575                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3576                 case 0x02:
3577                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3578                         case 0x00:
3579                                 result = lun[1];
3580                                 break;
3581                         case 0x10:
3582                                 result = (lun[1] << 16) + (lun[2] << 8) +
3583                                     lun[3];
3584                                 break;
3585                         case 0x20:
3586                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3587                                         result = (lun[2] << 24) +
3588                                             (lun[3] << 16) + (lun[4] << 8) +
3589                                             lun[5];
3590                                 break;
3591                         }
3592                         break;
3593                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3594                         result = 0xffffffff;
3595                         break;
3596                 }
3597                 break;
3598         }
3599         return (result);
3600 }
3601
3602 uint64_t
3603 ctl_encode_lun(uint32_t decoded)
3604 {
3605         uint64_t l = decoded;
3606
3607         if (l <= 0xff)
3608                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3609         if (l <= 0x3fff)
3610                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3611         if (l <= 0xffffff)
3612                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3613                     (l << 32));
3614         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3615 }
3616
3617 int
3618 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3619 {
3620         int i;
3621
3622         for (i = first; i < last; i++) {
3623                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3624                         return (i);
3625         }
3626         return (-1);
3627 }
3628
3629 int
3630 ctl_set_mask(uint32_t *mask, uint32_t bit)
3631 {
3632         uint32_t chunk, piece;
3633
3634         chunk = bit >> 5;
3635         piece = bit % (sizeof(uint32_t) * 8);
3636
3637         if ((mask[chunk] & (1 << piece)) != 0)
3638                 return (-1);
3639         else
3640                 mask[chunk] |= (1 << piece);
3641
3642         return (0);
3643 }
3644
3645 int
3646 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3647 {
3648         uint32_t chunk, piece;
3649
3650         chunk = bit >> 5;
3651         piece = bit % (sizeof(uint32_t) * 8);
3652
3653         if ((mask[chunk] & (1 << piece)) == 0)
3654                 return (-1);
3655         else
3656                 mask[chunk] &= ~(1 << piece);
3657
3658         return (0);
3659 }
3660
3661 int
3662 ctl_is_set(uint32_t *mask, uint32_t bit)
3663 {
3664         uint32_t chunk, piece;
3665
3666         chunk = bit >> 5;
3667         piece = bit % (sizeof(uint32_t) * 8);
3668
3669         if ((mask[chunk] & (1 << piece)) == 0)
3670                 return (0);
3671         else
3672                 return (1);
3673 }
3674
3675 static uint64_t
3676 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3677 {
3678         uint64_t *t;
3679
3680         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3681         if (t == NULL)
3682                 return (0);
3683         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3684 }
3685
3686 static void
3687 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3688 {
3689         uint64_t *t;
3690
3691         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3692         if (t == NULL)
3693                 return;
3694         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3695 }
3696
3697 static void
3698 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3699 {
3700         uint64_t *p;
3701         u_int i;
3702
3703         i = residx/CTL_MAX_INIT_PER_PORT;
3704         if (lun->pr_keys[i] != NULL)
3705                 return;
3706         mtx_unlock(&lun->lun_lock);
3707         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3708             M_WAITOK | M_ZERO);
3709         mtx_lock(&lun->lun_lock);
3710         if (lun->pr_keys[i] == NULL)
3711                 lun->pr_keys[i] = p;
3712         else
3713                 free(p, M_CTL);
3714 }
3715
3716 static void
3717 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3718 {
3719         uint64_t *t;
3720
3721         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3722         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3723         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3724 }
3725
3726 /*
3727  * ctl_softc, pool_name, total_ctl_io are passed in.
3728  * npool is passed out.
3729  */
3730 int
3731 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3732                 uint32_t total_ctl_io, void **npool)
3733 {
3734         struct ctl_io_pool *pool;
3735
3736         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3737                                             M_NOWAIT | M_ZERO);
3738         if (pool == NULL)
3739                 return (ENOMEM);
3740
3741         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3742         pool->ctl_softc = ctl_softc;
3743 #ifdef IO_POOLS
3744         pool->zone = uma_zsecond_create(pool->name, NULL,
3745             NULL, NULL, NULL, ctl_softc->io_zone);
3746         /* uma_prealloc(pool->zone, total_ctl_io); */
3747 #else
3748         pool->zone = ctl_softc->io_zone;
3749 #endif
3750
3751         *npool = pool;
3752         return (0);
3753 }
3754
3755 void
3756 ctl_pool_free(struct ctl_io_pool *pool)
3757 {
3758
3759         if (pool == NULL)
3760                 return;
3761
3762 #ifdef IO_POOLS
3763         uma_zdestroy(pool->zone);
3764 #endif
3765         free(pool, M_CTL);
3766 }
3767
3768 union ctl_io *
3769 ctl_alloc_io(void *pool_ref)
3770 {
3771         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3772         union ctl_io *io;
3773
3774         io = uma_zalloc(pool->zone, M_WAITOK);
3775         if (io != NULL) {
3776                 io->io_hdr.pool = pool_ref;
3777                 CTL_SOFTC(io) = pool->ctl_softc;
3778         }
3779         return (io);
3780 }
3781
3782 union ctl_io *
3783 ctl_alloc_io_nowait(void *pool_ref)
3784 {
3785         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3786         union ctl_io *io;
3787
3788         io = uma_zalloc(pool->zone, M_NOWAIT);
3789         if (io != NULL) {
3790                 io->io_hdr.pool = pool_ref;
3791                 CTL_SOFTC(io) = pool->ctl_softc;
3792         }
3793         return (io);
3794 }
3795
3796 void
3797 ctl_free_io(union ctl_io *io)
3798 {
3799         struct ctl_io_pool *pool;
3800
3801         if (io == NULL)
3802                 return;
3803
3804         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3805         uma_zfree(pool->zone, io);
3806 }
3807
3808 void
3809 ctl_zero_io(union ctl_io *io)
3810 {
3811         struct ctl_io_pool *pool;
3812
3813         if (io == NULL)
3814                 return;
3815
3816         /*
3817          * May need to preserve linked list pointers at some point too.
3818          */
3819         pool = io->io_hdr.pool;
3820         memset(io, 0, sizeof(*io));
3821         io->io_hdr.pool = pool;
3822         CTL_SOFTC(io) = pool->ctl_softc;
3823 }
3824
3825 int
3826 ctl_expand_number(const char *buf, uint64_t *num)
3827 {
3828         char *endptr;
3829         uint64_t number;
3830         unsigned shift;
3831
3832         number = strtoq(buf, &endptr, 0);
3833
3834         switch (tolower((unsigned char)*endptr)) {
3835         case 'e':
3836                 shift = 60;
3837                 break;
3838         case 'p':
3839                 shift = 50;
3840                 break;
3841         case 't':
3842                 shift = 40;
3843                 break;
3844         case 'g':
3845                 shift = 30;
3846                 break;
3847         case 'm':
3848                 shift = 20;
3849                 break;
3850         case 'k':
3851                 shift = 10;
3852                 break;
3853         case 'b':
3854         case '\0': /* No unit. */
3855                 *num = number;
3856                 return (0);
3857         default:
3858                 /* Unrecognized unit. */
3859                 return (-1);
3860         }
3861
3862         if ((number << shift) >> shift != number) {
3863                 /* Overflow */
3864                 return (-1);
3865         }
3866         *num = number << shift;
3867         return (0);
3868 }
3869
3870
3871 /*
3872  * This routine could be used in the future to load default and/or saved
3873  * mode page parameters for a particuar lun.
3874  */
3875 static int
3876 ctl_init_page_index(struct ctl_lun *lun)
3877 {
3878         int i, page_code;
3879         struct ctl_page_index *page_index;
3880         const char *value;
3881         uint64_t ival;
3882
3883         memcpy(&lun->mode_pages.index, page_index_template,
3884                sizeof(page_index_template));
3885
3886         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3887
3888                 page_index = &lun->mode_pages.index[i];
3889                 if (lun->be_lun->lun_type == T_DIRECT &&
3890                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3891                         continue;
3892                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3893                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3894                         continue;
3895                 if (lun->be_lun->lun_type == T_CDROM &&
3896                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3897                         continue;
3898
3899                 page_code = page_index->page_code & SMPH_PC_MASK;
3900                 switch (page_code) {
3901                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3902                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3903                             ("subpage %#x for page %#x is incorrect!",
3904                             page_index->subpage, page_code));
3905                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3906                                &rw_er_page_default,
3907                                sizeof(rw_er_page_default));
3908                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3909                                &rw_er_page_changeable,
3910                                sizeof(rw_er_page_changeable));
3911                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3912                                &rw_er_page_default,
3913                                sizeof(rw_er_page_default));
3914                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3915                                &rw_er_page_default,
3916                                sizeof(rw_er_page_default));
3917                         page_index->page_data =
3918                                 (uint8_t *)lun->mode_pages.rw_er_page;
3919                         break;
3920                 }
3921                 case SMS_FORMAT_DEVICE_PAGE: {
3922                         struct scsi_format_page *format_page;
3923
3924                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3925                             ("subpage %#x for page %#x is incorrect!",
3926                             page_index->subpage, page_code));
3927
3928                         /*
3929                          * Sectors per track are set above.  Bytes per
3930                          * sector need to be set here on a per-LUN basis.
3931                          */
3932                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3933                                &format_page_default,
3934                                sizeof(format_page_default));
3935                         memcpy(&lun->mode_pages.format_page[
3936                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3937                                sizeof(format_page_changeable));
3938                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3939                                &format_page_default,
3940                                sizeof(format_page_default));
3941                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3942                                &format_page_default,
3943                                sizeof(format_page_default));
3944
3945                         format_page = &lun->mode_pages.format_page[
3946                                 CTL_PAGE_CURRENT];
3947                         scsi_ulto2b(lun->be_lun->blocksize,
3948                                     format_page->bytes_per_sector);
3949
3950                         format_page = &lun->mode_pages.format_page[
3951                                 CTL_PAGE_DEFAULT];
3952                         scsi_ulto2b(lun->be_lun->blocksize,
3953                                     format_page->bytes_per_sector);
3954
3955                         format_page = &lun->mode_pages.format_page[
3956                                 CTL_PAGE_SAVED];
3957                         scsi_ulto2b(lun->be_lun->blocksize,
3958                                     format_page->bytes_per_sector);
3959
3960                         page_index->page_data =
3961                                 (uint8_t *)lun->mode_pages.format_page;
3962                         break;
3963                 }
3964                 case SMS_RIGID_DISK_PAGE: {
3965                         struct scsi_rigid_disk_page *rigid_disk_page;
3966                         uint32_t sectors_per_cylinder;
3967                         uint64_t cylinders;
3968 #ifndef __XSCALE__
3969                         int shift;
3970 #endif /* !__XSCALE__ */
3971
3972                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3973                             ("subpage %#x for page %#x is incorrect!",
3974                             page_index->subpage, page_code));
3975
3976                         /*
3977                          * Rotation rate and sectors per track are set
3978                          * above.  We calculate the cylinders here based on
3979                          * capacity.  Due to the number of heads and
3980                          * sectors per track we're using, smaller arrays
3981                          * may turn out to have 0 cylinders.  Linux and
3982                          * FreeBSD don't pay attention to these mode pages
3983                          * to figure out capacity, but Solaris does.  It
3984                          * seems to deal with 0 cylinders just fine, and
3985                          * works out a fake geometry based on the capacity.
3986                          */
3987                         memcpy(&lun->mode_pages.rigid_disk_page[
3988                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3989                                sizeof(rigid_disk_page_default));
3990                         memcpy(&lun->mode_pages.rigid_disk_page[
3991                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3992                                sizeof(rigid_disk_page_changeable));
3993
3994                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3995                                 CTL_DEFAULT_HEADS;
3996
3997                         /*
3998                          * The divide method here will be more accurate,
3999                          * probably, but results in floating point being
4000                          * used in the kernel on i386 (__udivdi3()).  On the
4001                          * XScale, though, __udivdi3() is implemented in
4002                          * software.
4003                          *
4004                          * The shift method for cylinder calculation is
4005                          * accurate if sectors_per_cylinder is a power of
4006                          * 2.  Otherwise it might be slightly off -- you
4007                          * might have a bit of a truncation problem.
4008                          */
4009 #ifdef  __XSCALE__
4010                         cylinders = (lun->be_lun->maxlba + 1) /
4011                                 sectors_per_cylinder;
4012 #else
4013                         for (shift = 31; shift > 0; shift--) {
4014                                 if (sectors_per_cylinder & (1 << shift))
4015                                         break;
4016                         }
4017                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4018 #endif
4019
4020                         /*
4021                          * We've basically got 3 bytes, or 24 bits for the
4022                          * cylinder size in the mode page.  If we're over,
4023                          * just round down to 2^24.
4024                          */
4025                         if (cylinders > 0xffffff)
4026                                 cylinders = 0xffffff;
4027
4028                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4029                                 CTL_PAGE_DEFAULT];
4030                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4031
4032                         if ((value = ctl_get_opt(&lun->be_lun->options,
4033                             "rpm")) != NULL) {
4034                                 scsi_ulto2b(strtol(value, NULL, 0),
4035                                      rigid_disk_page->rotation_rate);
4036                         }
4037
4038                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4039                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4040                                sizeof(rigid_disk_page_default));
4041                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4042                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4043                                sizeof(rigid_disk_page_default));
4044
4045                         page_index->page_data =
4046                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4047                         break;
4048                 }
4049                 case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4050                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4051                             ("subpage %#x for page %#x is incorrect!",
4052                             page_index->subpage, page_code));
4053                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4054                                &verify_er_page_default,
4055                                sizeof(verify_er_page_default));
4056                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4057                                &verify_er_page_changeable,
4058                                sizeof(verify_er_page_changeable));
4059                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4060                                &verify_er_page_default,
4061                                sizeof(verify_er_page_default));
4062                         memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4063                                &verify_er_page_default,
4064                                sizeof(verify_er_page_default));
4065                         page_index->page_data =
4066                                 (uint8_t *)lun->mode_pages.verify_er_page;
4067                         break;
4068                 }
4069                 case SMS_CACHING_PAGE: {
4070                         struct scsi_caching_page *caching_page;
4071
4072                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4073                             ("subpage %#x for page %#x is incorrect!",
4074                             page_index->subpage, page_code));
4075                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4076                                &caching_page_default,
4077                                sizeof(caching_page_default));
4078                         memcpy(&lun->mode_pages.caching_page[
4079                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4080                                sizeof(caching_page_changeable));
4081                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4082                                &caching_page_default,
4083                                sizeof(caching_page_default));
4084                         caching_page = &lun->mode_pages.caching_page[
4085                             CTL_PAGE_SAVED];
4086                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4087                         if (value != NULL && strcmp(value, "off") == 0)
4088                                 caching_page->flags1 &= ~SCP_WCE;
4089                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4090                         if (value != NULL && strcmp(value, "off") == 0)
4091                                 caching_page->flags1 |= SCP_RCD;
4092                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4093                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4094                                sizeof(caching_page_default));
4095                         page_index->page_data =
4096                                 (uint8_t *)lun->mode_pages.caching_page;
4097                         break;
4098                 }
4099                 case SMS_CONTROL_MODE_PAGE: {
4100                         switch (page_index->subpage) {
4101                         case SMS_SUBPAGE_PAGE_0: {
4102                                 struct scsi_control_page *control_page;
4103
4104                                 memcpy(&lun->mode_pages.control_page[
4105                                     CTL_PAGE_DEFAULT],
4106                                        &control_page_default,
4107                                        sizeof(control_page_default));
4108                                 memcpy(&lun->mode_pages.control_page[
4109                                     CTL_PAGE_CHANGEABLE],
4110                                        &control_page_changeable,
4111                                        sizeof(control_page_changeable));
4112                                 memcpy(&lun->mode_pages.control_page[
4113                                     CTL_PAGE_SAVED],
4114                                        &control_page_default,
4115                                        sizeof(control_page_default));
4116                                 control_page = &lun->mode_pages.control_page[
4117                                     CTL_PAGE_SAVED];
4118                                 value = ctl_get_opt(&lun->be_lun->options,
4119                                     "reordering");
4120                                 if (value != NULL &&
4121                                     strcmp(value, "unrestricted") == 0) {
4122                                         control_page->queue_flags &=
4123                                             ~SCP_QUEUE_ALG_MASK;
4124                                         control_page->queue_flags |=
4125                                             SCP_QUEUE_ALG_UNRESTRICTED;
4126                                 }
4127                                 memcpy(&lun->mode_pages.control_page[
4128                                     CTL_PAGE_CURRENT],
4129                                        &lun->mode_pages.control_page[
4130                                     CTL_PAGE_SAVED],
4131                                        sizeof(control_page_default));
4132                                 page_index->page_data =
4133                                     (uint8_t *)lun->mode_pages.control_page;
4134                                 break;
4135                         }
4136                         case 0x01:
4137                                 memcpy(&lun->mode_pages.control_ext_page[
4138                                     CTL_PAGE_DEFAULT],
4139                                        &control_ext_page_default,
4140                                        sizeof(control_ext_page_default));
4141                                 memcpy(&lun->mode_pages.control_ext_page[
4142                                     CTL_PAGE_CHANGEABLE],
4143                                        &control_ext_page_changeable,
4144                                        sizeof(control_ext_page_changeable));
4145                                 memcpy(&lun->mode_pages.control_ext_page[
4146                                     CTL_PAGE_SAVED],
4147                                        &control_ext_page_default,
4148                                        sizeof(control_ext_page_default));
4149                                 memcpy(&lun->mode_pages.control_ext_page[
4150                                     CTL_PAGE_CURRENT],
4151                                        &lun->mode_pages.control_ext_page[
4152                                     CTL_PAGE_SAVED],
4153                                        sizeof(control_ext_page_default));
4154                                 page_index->page_data =
4155                                     (uint8_t *)lun->mode_pages.control_ext_page;
4156                                 break;
4157                         default:
4158                                 panic("subpage %#x for page %#x is incorrect!",
4159                                       page_index->subpage, page_code);
4160                         }
4161                         break;
4162                 }
4163                 case SMS_INFO_EXCEPTIONS_PAGE: {
4164                         switch (page_index->subpage) {
4165                         case SMS_SUBPAGE_PAGE_0:
4166                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4167                                        &ie_page_default,
4168                                        sizeof(ie_page_default));
4169                                 memcpy(&lun->mode_pages.ie_page[
4170                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4171                                        sizeof(ie_page_changeable));
4172                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4173                                        &ie_page_default,
4174                                        sizeof(ie_page_default));
4175                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4176                                        &ie_page_default,
4177                                        sizeof(ie_page_default));
4178                                 page_index->page_data =
4179                                         (uint8_t *)lun->mode_pages.ie_page;
4180                                 break;
4181                         case 0x02: {
4182                                 struct ctl_logical_block_provisioning_page *page;
4183
4184                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4185                                        &lbp_page_default,
4186                                        sizeof(lbp_page_default));
4187                                 memcpy(&lun->mode_pages.lbp_page[
4188                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4189                                        sizeof(lbp_page_changeable));
4190                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4191                                        &lbp_page_default,
4192                                        sizeof(lbp_page_default));
4193                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4194                                 value = ctl_get_opt(&lun->be_lun->options,
4195                                     "avail-threshold");
4196                                 if (value != NULL &&
4197                                     ctl_expand_number(value, &ival) == 0) {
4198                                         page->descr[0].flags |= SLBPPD_ENABLED |
4199                                             SLBPPD_ARMING_DEC;
4200                                         if (lun->be_lun->blocksize)
4201                                                 ival /= lun->be_lun->blocksize;
4202                                         else
4203                                                 ival /= 512;
4204                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4205                                             page->descr[0].count);
4206                                 }
4207                                 value = ctl_get_opt(&lun->be_lun->options,
4208                                     "used-threshold");
4209                                 if (value != NULL &&
4210                                     ctl_expand_number(value, &ival) == 0) {
4211                                         page->descr[1].flags |= SLBPPD_ENABLED |
4212                                             SLBPPD_ARMING_INC;
4213                                         if (lun->be_lun->blocksize)
4214                                                 ival /= lun->be_lun->blocksize;
4215                                         else
4216                                                 ival /= 512;
4217                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4218                                             page->descr[1].count);
4219                                 }
4220                                 value = ctl_get_opt(&lun->be_lun->options,
4221                                     "pool-avail-threshold");
4222                                 if (value != NULL &&
4223                                     ctl_expand_number(value, &ival) == 0) {
4224                                         page->descr[2].flags |= SLBPPD_ENABLED |
4225                                             SLBPPD_ARMING_DEC;
4226                                         if (lun->be_lun->blocksize)
4227                                                 ival /= lun->be_lun->blocksize;
4228                                         else
4229                                                 ival /= 512;
4230                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4231                                             page->descr[2].count);
4232                                 }
4233                                 value = ctl_get_opt(&lun->be_lun->options,
4234                                     "pool-used-threshold");
4235                                 if (value != NULL &&
4236                                     ctl_expand_number(value, &ival) == 0) {
4237                                         page->descr[3].flags |= SLBPPD_ENABLED |
4238                                             SLBPPD_ARMING_INC;
4239                                         if (lun->be_lun->blocksize)
4240                                                 ival /= lun->be_lun->blocksize;
4241                                         else
4242                                                 ival /= 512;
4243                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4244                                             page->descr[3].count);
4245                                 }
4246                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4247                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4248                                        sizeof(lbp_page_default));
4249                                 page_index->page_data =
4250                                         (uint8_t *)lun->mode_pages.lbp_page;
4251                                 break;
4252                         }
4253                         default:
4254                                 panic("subpage %#x for page %#x is incorrect!",
4255                                       page_index->subpage, page_code);
4256                         }
4257                         break;
4258                 }
4259                 case SMS_CDDVD_CAPS_PAGE:{
4260                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4261                             ("subpage %#x for page %#x is incorrect!",
4262                             page_index->subpage, page_code));
4263                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4264                                &cddvd_page_default,
4265                                sizeof(cddvd_page_default));
4266                         memcpy(&lun->mode_pages.cddvd_page[
4267                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4268                                sizeof(cddvd_page_changeable));
4269                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4270                                &cddvd_page_default,
4271                                sizeof(cddvd_page_default));
4272                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4273                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4274                                sizeof(cddvd_page_default));
4275                         page_index->page_data =
4276                                 (uint8_t *)lun->mode_pages.cddvd_page;
4277                         break;
4278                 }
4279                 default:
4280                         panic("invalid page code value %#x", page_code);
4281                 }
4282         }
4283
4284         return (CTL_RETVAL_COMPLETE);
4285 }
4286
4287 static int
4288 ctl_init_log_page_index(struct ctl_lun *lun)
4289 {
4290         struct ctl_page_index *page_index;
4291         int i, j, k, prev;
4292
4293         memcpy(&lun->log_pages.index, log_page_index_template,
4294                sizeof(log_page_index_template));
4295
4296         prev = -1;
4297         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4298
4299                 page_index = &lun->log_pages.index[i];
4300                 if (lun->be_lun->lun_type == T_DIRECT &&
4301                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4302                         continue;
4303                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4304                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4305                         continue;
4306                 if (lun->be_lun->lun_type == T_CDROM &&
4307                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4308                         continue;
4309
4310                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4311                     lun->backend->lun_attr == NULL)
4312                         continue;
4313
4314                 if (page_index->page_code != prev) {
4315                         lun->log_pages.pages_page[j] = page_index->page_code;
4316                         prev = page_index->page_code;
4317                         j++;
4318                 }
4319                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4320                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4321                 k++;
4322         }
4323         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4324         lun->log_pages.index[0].page_len = j;
4325         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4326         lun->log_pages.index[1].page_len = k * 2;
4327         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4328         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4329         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4330         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4331         lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4332         lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4333
4334         return (CTL_RETVAL_COMPLETE);
4335 }
4336
4337 static int
4338 hex2bin(const char *str, uint8_t *buf, int buf_size)
4339 {
4340         int i;
4341         u_char c;
4342
4343         memset(buf, 0, buf_size);
4344         while (isspace(str[0]))
4345                 str++;
4346         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4347                 str += 2;
4348         buf_size *= 2;
4349         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4350                 while (str[i] == '-')   /* Skip dashes in UUIDs. */
4351                         str++;
4352                 c = str[i];
4353                 if (isdigit(c))
4354                         c -= '0';
4355                 else if (isalpha(c))
4356                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4357                 else
4358                         break;
4359                 if (c >= 16)
4360                         break;
4361                 if ((i & 1) == 0)
4362                         buf[i / 2] |= (c << 4);
4363                 else
4364                         buf[i / 2] |= c;
4365         }
4366         return ((i + 1) / 2);
4367 }
4368
4369 /*
4370  * LUN allocation.
4371  *
4372  * Requirements:
4373  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4374  *   wants us to allocate the LUN and he can block.
4375  * - ctl_softc is always set
4376  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4377  *
4378  * Returns 0 for success, non-zero (errno) for failure.
4379  */
4380 static int
4381 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4382               struct ctl_be_lun *const be_lun)
4383 {
4384         struct ctl_lun *nlun, *lun;
4385         struct scsi_vpd_id_descriptor *desc;
4386         struct scsi_vpd_id_t10 *t10id;
4387         const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4388         int lun_number, i, lun_malloced;
4389         int devidlen, idlen1, idlen2 = 0, len;
4390
4391         if (be_lun == NULL)
4392                 return (EINVAL);
4393
4394         /*
4395          * We currently only support Direct Access or Processor LUN types.
4396          */
4397         switch (be_lun->lun_type) {
4398         case T_DIRECT:
4399         case T_PROCESSOR:
4400         case T_CDROM:
4401                 break;
4402         case T_SEQUENTIAL:
4403         case T_CHANGER:
4404         default:
4405                 be_lun->lun_config_status(be_lun->be_lun,
4406                                           CTL_LUN_CONFIG_FAILURE);
4407                 break;
4408         }
4409         if (ctl_lun == NULL) {
4410                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4411                 lun_malloced = 1;
4412         } else {
4413                 lun_malloced = 0;
4414                 lun = ctl_lun;
4415         }
4416
4417         memset(lun, 0, sizeof(*lun));
4418         if (lun_malloced)
4419                 lun->flags = CTL_LUN_MALLOCED;
4420
4421         /* Generate LUN ID. */
4422         devidlen = max(CTL_DEVID_MIN_LEN,
4423             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4424         idlen1 = sizeof(*t10id) + devidlen;
4425         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4426         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4427         if (scsiname != NULL) {
4428                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4429                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4430         }
4431         eui = ctl_get_opt(&be_lun->options, "eui");
4432         if (eui != NULL) {
4433                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4434         }
4435         naa = ctl_get_opt(&be_lun->options, "naa");
4436         if (naa != NULL) {
4437                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4438         }
4439         uuid = ctl_get_opt(&be_lun->options, "uuid");
4440         if (uuid != NULL) {
4441                 len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4442         }
4443         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4444             M_CTL, M_WAITOK | M_ZERO);
4445         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4446         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4447         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4448         desc->length = idlen1;
4449         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4450         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4451         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4452                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4453         } else {
4454                 strncpy(t10id->vendor, vendor,
4455                     min(sizeof(t10id->vendor), strlen(vendor)));
4456         }
4457         strncpy((char *)t10id->vendor_spec_id,
4458             (char *)be_lun->device_id, devidlen);
4459         if (scsiname != NULL) {
4460                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4461                     desc->length);
4462                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4463                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4464                     SVPD_ID_TYPE_SCSI_NAME;
4465                 desc->length = idlen2;
4466                 strlcpy(desc->identifier, scsiname, idlen2);
4467         }
4468         if (eui != NULL) {
4469                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4470                     desc->length);
4471                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4472                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4473                     SVPD_ID_TYPE_EUI64;
4474                 desc->length = hex2bin(eui, desc->identifier, 16);
4475                 desc->length = desc->length > 12 ? 16 :
4476                     (desc->length > 8 ? 12 : 8);
4477                 len -= 16 - desc->length;
4478         }
4479         if (naa != NULL) {
4480                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4481                     desc->length);
4482                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4483                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4484                     SVPD_ID_TYPE_NAA;
4485                 desc->length = hex2bin(naa, desc->identifier, 16);
4486                 desc->length = desc->length > 8 ? 16 : 8;
4487                 len -= 16 - desc->length;
4488         }
4489         if (uuid != NULL) {
4490                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4491                     desc->length);
4492                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4493                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4494                     SVPD_ID_TYPE_UUID;
4495                 desc->identifier[0] = 0x10;
4496                 hex2bin(uuid, &desc->identifier[2], 16);
4497                 desc->length = 18;
4498         }
4499         lun->lun_devid->len = len;
4500
4501         mtx_lock(&ctl_softc->ctl_lock);
4502         /*
4503          * See if the caller requested a particular LUN number.  If so, see
4504          * if it is available.  Otherwise, allocate the first available LUN.
4505          */
4506         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4507                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4508                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4509                         mtx_unlock(&ctl_softc->ctl_lock);
4510                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4511                                 printf("ctl: requested LUN ID %d is higher "
4512                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4513                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4514                         } else {
4515                                 /*
4516                                  * XXX KDM return an error, or just assign
4517                                  * another LUN ID in this case??
4518                                  */
4519                                 printf("ctl: requested LUN ID %d is already "
4520                                        "in use\n", be_lun->req_lun_id);
4521                         }
4522                         if (lun->flags & CTL_LUN_MALLOCED)
4523                                 free(lun, M_CTL);
4524                         be_lun->lun_config_status(be_lun->be_lun,
4525                                                   CTL_LUN_CONFIG_FAILURE);
4526                         return (ENOSPC);
4527                 }
4528                 lun_number = be_lun->req_lun_id;
4529         } else {
4530                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4531                 if (lun_number == -1) {
4532                         mtx_unlock(&ctl_softc->ctl_lock);
4533                         printf("ctl: can't allocate LUN, out of LUNs\n");
4534                         if (lun->flags & CTL_LUN_MALLOCED)
4535                                 free(lun, M_CTL);
4536                         be_lun->lun_config_status(be_lun->be_lun,
4537                                                   CTL_LUN_CONFIG_FAILURE);
4538                         return (ENOSPC);
4539                 }
4540         }
4541         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4542
4543         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4544         lun->lun = lun_number;
4545         lun->be_lun = be_lun;
4546         /*
4547          * The processor LUN is always enabled.  Disk LUNs come on line
4548          * disabled, and must be enabled by the backend.
4549          */
4550         lun->flags |= CTL_LUN_DISABLED;
4551         lun->backend = be_lun->be;
4552         be_lun->ctl_lun = lun;
4553         be_lun->lun_id = lun_number;
4554         atomic_add_int(&be_lun->be->num_luns, 1);
4555         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4556                 lun->flags |= CTL_LUN_EJECTED;
4557         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4558                 lun->flags |= CTL_LUN_NO_MEDIA;
4559         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4560                 lun->flags |= CTL_LUN_STOPPED;
4561
4562         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4563                 lun->flags |= CTL_LUN_PRIMARY_SC;
4564
4565         value = ctl_get_opt(&be_lun->options, "removable");
4566         if (value != NULL) {
4567                 if (strcmp(value, "on") == 0)
4568                         lun->flags |= CTL_LUN_REMOVABLE;
4569         } else if (be_lun->lun_type == T_CDROM)
4570                 lun->flags |= CTL_LUN_REMOVABLE;
4571
4572         lun->ctl_softc = ctl_softc;
4573 #ifdef CTL_TIME_IO
4574         lun->last_busy = getsbinuptime();
4575 #endif
4576         TAILQ_INIT(&lun->ooa_queue);
4577         TAILQ_INIT(&lun->blocked_queue);
4578         STAILQ_INIT(&lun->error_list);
4579         lun->ie_reported = 1;
4580         callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4581         ctl_tpc_lun_init(lun);
4582
4583         /*
4584          * Initialize the mode and log page index.
4585          */
4586         ctl_init_page_index(lun);
4587         ctl_init_log_page_index(lun);
4588
4589         /*
4590          * Now, before we insert this lun on the lun list, set the lun
4591          * inventory changed UA for all other luns.
4592          */
4593         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4594                 mtx_lock(&nlun->lun_lock);
4595                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4596                 mtx_unlock(&nlun->lun_lock);
4597         }
4598
4599         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4600
4601         ctl_softc->ctl_luns[lun_number] = lun;
4602
4603         ctl_softc->num_luns++;
4604
4605         /* Setup statistics gathering */
4606         lun->stats.device_type = be_lun->lun_type;
4607         lun->stats.lun_number = lun_number;
4608         lun->stats.blocksize = be_lun->blocksize;
4609         if (be_lun->blocksize == 0)
4610                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4611         for (i = 0;i < CTL_MAX_PORTS;i++)
4612                 lun->stats.ports[i].targ_port = i;
4613
4614         mtx_unlock(&ctl_softc->ctl_lock);
4615
4616         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4617         return (0);
4618 }
4619
4620 /*
4621  * Delete a LUN.
4622  * Assumptions:
4623  * - LUN has already been marked invalid and any pending I/O has been taken
4624  *   care of.
4625  */
4626 static int
4627 ctl_free_lun(struct ctl_lun *lun)
4628 {
4629         struct ctl_softc *softc = lun->ctl_softc;
4630         struct ctl_lun *nlun;
4631         int i;
4632
4633         mtx_assert(&softc->ctl_lock, MA_OWNED);
4634
4635         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4636
4637         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4638
4639         softc->ctl_luns[lun->lun] = NULL;
4640
4641         if (!TAILQ_EMPTY(&lun->ooa_queue))
4642                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4643
4644         softc->num_luns--;
4645
4646         /*
4647          * Tell the backend to free resources, if this LUN has a backend.
4648          */
4649         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4650         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4651
4652         lun->ie_reportcnt = UINT32_MAX;
4653         callout_drain(&lun->ie_callout);
4654
4655         ctl_tpc_lun_shutdown(lun);
4656         mtx_destroy(&lun->lun_lock);
4657         free(lun->lun_devid, M_CTL);
4658         for (i = 0; i < CTL_MAX_PORTS; i++)
4659                 free(lun->pending_ua[i], M_CTL);
4660         for (i = 0; i < CTL_MAX_PORTS; i++)
4661                 free(lun->pr_keys[i], M_CTL);
4662         free(lun->write_buffer, M_CTL);
4663         if (lun->flags & CTL_LUN_MALLOCED)
4664                 free(lun, M_CTL);
4665
4666         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4667                 mtx_lock(&nlun->lun_lock);
4668                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4669                 mtx_unlock(&nlun->lun_lock);
4670         }
4671
4672         return (0);
4673 }
4674
4675 static void
4676 ctl_create_lun(struct ctl_be_lun *be_lun)
4677 {
4678
4679         /*
4680          * ctl_alloc_lun() should handle all potential failure cases.
4681          */
4682         ctl_alloc_lun(control_softc, NULL, be_lun);
4683 }
4684
4685 int
4686 ctl_add_lun(struct ctl_be_lun *be_lun)
4687 {
4688         struct ctl_softc *softc = control_softc;
4689
4690         mtx_lock(&softc->ctl_lock);
4691         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4692         mtx_unlock(&softc->ctl_lock);
4693         wakeup(&softc->pending_lun_queue);
4694
4695         return (0);
4696 }
4697
4698 int
4699 ctl_enable_lun(struct ctl_be_lun *be_lun)
4700 {
4701         struct ctl_softc *softc;
4702         struct ctl_port *port, *nport;
4703         struct ctl_lun *lun;
4704         int retval;
4705
4706         lun = (struct ctl_lun *)be_lun->ctl_lun;
4707         softc = lun->ctl_softc;
4708
4709         mtx_lock(&softc->ctl_lock);
4710         mtx_lock(&lun->lun_lock);
4711         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4712                 /*
4713                  * eh?  Why did we get called if the LUN is already
4714                  * enabled?
4715                  */
4716                 mtx_unlock(&lun->lun_lock);
4717                 mtx_unlock(&softc->ctl_lock);
4718                 return (0);
4719         }
4720         lun->flags &= ~CTL_LUN_DISABLED;
4721         mtx_unlock(&lun->lun_lock);
4722
4723         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4724                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4725                     port->lun_map != NULL || port->lun_enable == NULL)
4726                         continue;
4727
4728                 /*
4729                  * Drop the lock while we call the FETD's enable routine.
4730                  * This can lead to a callback into CTL (at least in the
4731                  * case of the internal initiator frontend.
4732                  */
4733                 mtx_unlock(&softc->ctl_lock);
4734                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4735                 mtx_lock(&softc->ctl_lock);
4736                 if (retval != 0) {
4737                         printf("%s: FETD %s port %d returned error "
4738                                "%d for lun_enable on lun %jd\n",
4739                                __func__, port->port_name, port->targ_port,
4740                                retval, (intmax_t)lun->lun);
4741                 }
4742         }
4743
4744         mtx_unlock(&softc->ctl_lock);
4745         ctl_isc_announce_lun(lun);
4746
4747         return (0);
4748 }
4749
4750 int
4751 ctl_disable_lun(struct ctl_be_lun *be_lun)
4752 {
4753         struct ctl_softc *softc;
4754         struct ctl_port *port;
4755         struct ctl_lun *lun;
4756         int retval;
4757
4758         lun = (struct ctl_lun *)be_lun->ctl_lun;
4759         softc = lun->ctl_softc;
4760
4761         mtx_lock(&softc->ctl_lock);
4762         mtx_lock(&lun->lun_lock);
4763         if (lun->flags & CTL_LUN_DISABLED) {
4764                 mtx_unlock(&lun->lun_lock);
4765                 mtx_unlock(&softc->ctl_lock);
4766                 return (0);
4767         }
4768         lun->flags |= CTL_LUN_DISABLED;
4769         mtx_unlock(&lun->lun_lock);
4770
4771         STAILQ_FOREACH(port, &softc->port_list, links) {
4772                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4773                     port->lun_map != NULL || port->lun_disable == NULL)
4774                         continue;
4775
4776                 /*
4777                  * Drop the lock before we call the frontend's disable
4778                  * routine, to avoid lock order reversals.
4779                  *
4780                  * XXX KDM what happens if the frontend list changes while
4781                  * we're traversing it?  It's unlikely, but should be handled.
4782                  */
4783                 mtx_unlock(&softc->ctl_lock);
4784                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4785                 mtx_lock(&softc->ctl_lock);
4786                 if (retval != 0) {
4787                         printf("%s: FETD %s port %d returned error "
4788                                "%d for lun_disable on lun %jd\n",
4789                                __func__, port->port_name, port->targ_port,
4790                                retval, (intmax_t)lun->lun);
4791                 }
4792         }
4793
4794         mtx_unlock(&softc->ctl_lock);
4795         ctl_isc_announce_lun(lun);
4796
4797         return (0);
4798 }
4799
4800 int
4801 ctl_start_lun(struct ctl_be_lun *be_lun)
4802 {
4803         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4804
4805         mtx_lock(&lun->lun_lock);
4806         lun->flags &= ~CTL_LUN_STOPPED;
4807         mtx_unlock(&lun->lun_lock);
4808         return (0);
4809 }
4810
4811 int
4812 ctl_stop_lun(struct ctl_be_lun *be_lun)
4813 {
4814         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4815
4816         mtx_lock(&lun->lun_lock);
4817         lun->flags |= CTL_LUN_STOPPED;
4818         mtx_unlock(&lun->lun_lock);
4819         return (0);
4820 }
4821
4822 int
4823 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4824 {
4825         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4826
4827         mtx_lock(&lun->lun_lock);
4828         lun->flags |= CTL_LUN_NO_MEDIA;
4829         mtx_unlock(&lun->lun_lock);
4830         return (0);
4831 }
4832
4833 int
4834 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4835 {
4836         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4837         union ctl_ha_msg msg;
4838
4839         mtx_lock(&lun->lun_lock);
4840         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4841         if (lun->flags & CTL_LUN_REMOVABLE)
4842                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4843         mtx_unlock(&lun->lun_lock);
4844         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4845             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4846                 bzero(&msg.ua, sizeof(msg.ua));
4847                 msg.hdr.msg_type = CTL_MSG_UA;
4848                 msg.hdr.nexus.initid = -1;
4849                 msg.hdr.nexus.targ_port = -1;
4850                 msg.hdr.nexus.targ_lun = lun->lun;
4851                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4852                 msg.ua.ua_all = 1;
4853                 msg.ua.ua_set = 1;
4854                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4855                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4856                     M_WAITOK);
4857         }
4858         return (0);
4859 }
4860
4861 int
4862 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4863 {
4864         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4865
4866         mtx_lock(&lun->lun_lock);
4867         lun->flags |= CTL_LUN_EJECTED;
4868         mtx_unlock(&lun->lun_lock);
4869         return (0);
4870 }
4871
4872 int
4873 ctl_lun_primary(struct ctl_be_lun *be_lun)
4874 {
4875         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4876
4877         mtx_lock(&lun->lun_lock);
4878         lun->flags |= CTL_LUN_PRIMARY_SC;
4879         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4880         mtx_unlock(&lun->lun_lock);
4881         ctl_isc_announce_lun(lun);
4882         return (0);
4883 }
4884
4885 int
4886 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4887 {
4888         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4889
4890         mtx_lock(&lun->lun_lock);
4891         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4892         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4893         mtx_unlock(&lun->lun_lock);
4894         ctl_isc_announce_lun(lun);
4895         return (0);
4896 }
4897
4898 int
4899 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4900 {
4901         struct ctl_softc *softc;
4902         struct ctl_lun *lun;
4903
4904         lun = (struct ctl_lun *)be_lun->ctl_lun;
4905         softc = lun->ctl_softc;
4906
4907         mtx_lock(&lun->lun_lock);
4908
4909         /*
4910          * The LUN needs to be disabled before it can be marked invalid.
4911          */
4912         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4913                 mtx_unlock(&lun->lun_lock);
4914                 return (-1);
4915         }
4916         /*
4917          * Mark the LUN invalid.
4918          */
4919         lun->flags |= CTL_LUN_INVALID;
4920
4921         /*
4922          * If there is nothing in the OOA queue, go ahead and free the LUN.
4923          * If we have something in the OOA queue, we'll free it when the
4924          * last I/O completes.
4925          */
4926         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4927                 mtx_unlock(&lun->lun_lock);
4928                 mtx_lock(&softc->ctl_lock);
4929                 ctl_free_lun(lun);
4930                 mtx_unlock(&softc->ctl_lock);
4931         } else
4932                 mtx_unlock(&lun->lun_lock);
4933
4934         return (0);
4935 }
4936
4937 void
4938 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4939 {
4940         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4941         union ctl_ha_msg msg;
4942
4943         mtx_lock(&lun->lun_lock);
4944         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4945         mtx_unlock(&lun->lun_lock);
4946         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4947                 /* Send msg to other side. */
4948                 bzero(&msg.ua, sizeof(msg.ua));
4949                 msg.hdr.msg_type = CTL_MSG_UA;
4950                 msg.hdr.nexus.initid = -1;
4951                 msg.hdr.nexus.targ_port = -1;
4952                 msg.hdr.nexus.targ_lun = lun->lun;
4953                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4954                 msg.ua.ua_all = 1;
4955                 msg.ua.ua_set = 1;
4956                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4957                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4958                     M_WAITOK);
4959         }
4960 }
4961
4962 /*
4963  * Backend "memory move is complete" callback for requests that never
4964  * make it down to say RAIDCore's configuration code.
4965  */
4966 int
4967 ctl_config_move_done(union ctl_io *io)
4968 {
4969         int retval;
4970
4971         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4972         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4973             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4974
4975         if ((io->io_hdr.port_status != 0) &&
4976             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4977              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4978                 /*
4979                  * For hardware error sense keys, the sense key
4980                  * specific value is defined to be a retry count,
4981                  * but we use it to pass back an internal FETD
4982                  * error code.  XXX KDM  Hopefully the FETD is only
4983                  * using 16 bits for an error code, since that's
4984                  * all the space we have in the sks field.
4985                  */
4986                 ctl_set_internal_failure(&io->scsiio,
4987                                          /*sks_valid*/ 1,
4988                                          /*retry_count*/
4989                                          io->io_hdr.port_status);
4990         }
4991
4992         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4993                 ctl_data_print(io);
4994         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4995             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4996              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4997             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4998                 /*
4999                  * XXX KDM just assuming a single pointer here, and not a
5000                  * S/G list.  If we start using S/G lists for config data,
5001                  * we'll need to know how to clean them up here as well.
5002                  */
5003                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5004                         free(io->scsiio.kern_data_ptr, M_CTL);
5005                 ctl_done(io);
5006                 retval = CTL_RETVAL_COMPLETE;
5007         } else {
5008                 /*
5009                  * XXX KDM now we need to continue data movement.  Some
5010                  * options:
5011                  * - call ctl_scsiio() again?  We don't do this for data
5012                  *   writes, because for those at least we know ahead of
5013                  *   time where the write will go and how long it is.  For
5014                  *   config writes, though, that information is largely
5015                  *   contained within the write itself, thus we need to
5016                  *   parse out the data again.
5017                  *
5018                  * - Call some other function once the data is in?
5019                  */
5020
5021                 /*
5022                  * XXX KDM call ctl_scsiio() again for now, and check flag
5023                  * bits to see whether we're allocated or not.
5024                  */
5025                 retval = ctl_scsiio(&io->scsiio);
5026         }
5027         return (retval);
5028 }
5029
5030 /*
5031  * This gets called by a backend driver when it is done with a
5032  * data_submit method.
5033  */
5034 void
5035 ctl_data_submit_done(union ctl_io *io)
5036 {
5037         /*
5038          * If the IO_CONT flag is set, we need to call the supplied
5039          * function to continue processing the I/O, instead of completing
5040          * the I/O just yet.
5041          *
5042          * If there is an error, though, we don't want to keep processing.
5043          * Instead, just send status back to the initiator.
5044          */
5045         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5046             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5047             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5048              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5049                 io->scsiio.io_cont(io);
5050                 return;
5051         }
5052         ctl_done(io);
5053 }
5054
5055 /*
5056  * This gets called by a backend driver when it is done with a
5057  * configuration write.
5058  */
5059 void
5060 ctl_config_write_done(union ctl_io *io)
5061 {
5062         uint8_t *buf;
5063
5064         /*
5065          * If the IO_CONT flag is set, we need to call the supplied
5066          * function to continue processing the I/O, instead of completing
5067          * the I/O just yet.
5068          *
5069          * If there is an error, though, we don't want to keep processing.
5070          * Instead, just send status back to the initiator.
5071          */
5072         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5073             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5074             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5075              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5076                 io->scsiio.io_cont(io);
5077                 return;
5078         }
5079         /*
5080          * Since a configuration write can be done for commands that actually
5081          * have data allocated, like write buffer, and commands that have
5082          * no data, like start/stop unit, we need to check here.
5083          */
5084         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5085                 buf = io->scsiio.kern_data_ptr;
5086         else
5087                 buf = NULL;
5088         ctl_done(io);
5089         if (buf)
5090                 free(buf, M_CTL);
5091 }
5092
5093 void
5094 ctl_config_read_done(union ctl_io *io)
5095 {
5096         uint8_t *buf;
5097
5098         /*
5099          * If there is some error -- we are done, skip data transfer.
5100          */
5101         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5102             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5103              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
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                 return;
5112         }
5113
5114         /*
5115          * If the IO_CONT flag is set, we need to call the supplied
5116          * function to continue processing the I/O, instead of completing
5117          * the I/O just yet.
5118          */
5119         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5120                 io->scsiio.io_cont(io);
5121                 return;
5122         }
5123
5124         ctl_datamove(io);
5125 }
5126
5127 /*
5128  * SCSI release command.
5129  */
5130 int
5131 ctl_scsi_release(struct ctl_scsiio *ctsio)
5132 {
5133         struct ctl_lun *lun = CTL_LUN(ctsio);
5134         uint32_t residx;
5135
5136         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5137
5138         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5139
5140         /*
5141          * XXX KDM right now, we only support LUN reservation.  We don't
5142          * support 3rd party reservations, or extent reservations, which
5143          * might actually need the parameter list.  If we've gotten this
5144          * far, we've got a LUN reservation.  Anything else got kicked out
5145          * above.  So, according to SPC, ignore the length.
5146          */
5147
5148         mtx_lock(&lun->lun_lock);
5149
5150         /*
5151          * According to SPC, it is not an error for an intiator to attempt
5152          * to release a reservation on a LUN that isn't reserved, or that
5153          * is reserved by another initiator.  The reservation can only be
5154          * released, though, by the initiator who made it or by one of
5155          * several reset type events.
5156          */
5157         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5158                         lun->flags &= ~CTL_LUN_RESERVED;
5159
5160         mtx_unlock(&lun->lun_lock);
5161
5162         ctl_set_success(ctsio);
5163         ctl_done((union ctl_io *)ctsio);
5164         return (CTL_RETVAL_COMPLETE);
5165 }
5166
5167 int
5168 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5169 {
5170         struct ctl_lun *lun = CTL_LUN(ctsio);
5171         uint32_t residx;
5172
5173         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5174
5175         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5176
5177         /*
5178          * XXX KDM right now, we only support LUN reservation.  We don't
5179          * support 3rd party reservations, or extent reservations, which
5180          * might actually need the parameter list.  If we've gotten this
5181          * far, we've got a LUN reservation.  Anything else got kicked out
5182          * above.  So, according to SPC, ignore the length.
5183          */
5184
5185         mtx_lock(&lun->lun_lock);
5186         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5187                 ctl_set_reservation_conflict(ctsio);
5188                 goto bailout;
5189         }
5190
5191         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5192         if (lun->flags & CTL_LUN_PR_RESERVED) {
5193                 ctl_set_success(ctsio);
5194                 goto bailout;
5195         }
5196
5197         lun->flags |= CTL_LUN_RESERVED;
5198         lun->res_idx = residx;
5199         ctl_set_success(ctsio);
5200
5201 bailout:
5202         mtx_unlock(&lun->lun_lock);
5203         ctl_done((union ctl_io *)ctsio);
5204         return (CTL_RETVAL_COMPLETE);
5205 }
5206
5207 int
5208 ctl_start_stop(struct ctl_scsiio *ctsio)
5209 {
5210         struct ctl_lun *lun = CTL_LUN(ctsio);
5211         struct scsi_start_stop_unit *cdb;
5212         int retval;
5213
5214         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5215
5216         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5217
5218         if ((cdb->how & SSS_PC_MASK) == 0) {
5219                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5220                     (cdb->how & SSS_START) == 0) {
5221                         uint32_t residx;
5222
5223                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5224                         if (ctl_get_prkey(lun, residx) == 0 ||
5225                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5226
5227                                 ctl_set_reservation_conflict(ctsio);
5228                                 ctl_done((union ctl_io *)ctsio);
5229                                 return (CTL_RETVAL_COMPLETE);
5230                         }
5231                 }
5232
5233                 if ((cdb->how & SSS_LOEJ) &&
5234                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5235                         ctl_set_invalid_field(ctsio,
5236                                               /*sks_valid*/ 1,
5237                                               /*command*/ 1,
5238                                               /*field*/ 4,
5239                                               /*bit_valid*/ 1,
5240                                               /*bit*/ 1);
5241                         ctl_done((union ctl_io *)ctsio);
5242                         return (CTL_RETVAL_COMPLETE);
5243                 }
5244
5245                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5246                     lun->prevent_count > 0) {
5247                         /* "Medium removal prevented" */
5248                         ctl_set_sense(ctsio, /*current_error*/ 1,
5249                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5250                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5251                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5252                         ctl_done((union ctl_io *)ctsio);
5253                         return (CTL_RETVAL_COMPLETE);
5254                 }
5255         }
5256
5257         retval = lun->backend->config_write((union ctl_io *)ctsio);
5258         return (retval);
5259 }
5260
5261 int
5262 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5263 {
5264         struct ctl_lun *lun = CTL_LUN(ctsio);
5265         struct scsi_prevent *cdb;
5266         int retval;
5267         uint32_t initidx;
5268
5269         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5270
5271         cdb = (struct scsi_prevent *)ctsio->cdb;
5272
5273         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5274                 ctl_set_invalid_opcode(ctsio);
5275                 ctl_done((union ctl_io *)ctsio);
5276                 return (CTL_RETVAL_COMPLETE);
5277         }
5278
5279         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5280         mtx_lock(&lun->lun_lock);
5281         if ((cdb->how & PR_PREVENT) &&
5282             ctl_is_set(lun->prevent, initidx) == 0) {
5283                 ctl_set_mask(lun->prevent, initidx);
5284                 lun->prevent_count++;
5285         } else if ((cdb->how & PR_PREVENT) == 0 &&
5286             ctl_is_set(lun->prevent, initidx)) {
5287                 ctl_clear_mask(lun->prevent, initidx);
5288                 lun->prevent_count--;
5289         }
5290         mtx_unlock(&lun->lun_lock);
5291         retval = lun->backend->config_write((union ctl_io *)ctsio);
5292         return (retval);
5293 }
5294
5295 /*
5296  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5297  * we don't really do anything with the LBA and length fields if the user
5298  * passes them in.  Instead we'll just flush out the cache for the entire
5299  * LUN.
5300  */
5301 int
5302 ctl_sync_cache(struct ctl_scsiio *ctsio)
5303 {
5304         struct ctl_lun *lun = CTL_LUN(ctsio);
5305         struct ctl_lba_len_flags *lbalen;
5306         uint64_t starting_lba;
5307         uint32_t block_count;
5308         int retval;
5309         uint8_t byte2;
5310
5311         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5312
5313         retval = 0;
5314
5315         switch (ctsio->cdb[0]) {
5316         case SYNCHRONIZE_CACHE: {
5317                 struct scsi_sync_cache *cdb;
5318                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5319
5320                 starting_lba = scsi_4btoul(cdb->begin_lba);
5321                 block_count = scsi_2btoul(cdb->lb_count);
5322                 byte2 = cdb->byte2;
5323                 break;
5324         }
5325         case SYNCHRONIZE_CACHE_16: {
5326                 struct scsi_sync_cache_16 *cdb;
5327                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5328
5329                 starting_lba = scsi_8btou64(cdb->begin_lba);
5330                 block_count = scsi_4btoul(cdb->lb_count);
5331                 byte2 = cdb->byte2;
5332                 break;
5333         }
5334         default:
5335                 ctl_set_invalid_opcode(ctsio);
5336                 ctl_done((union ctl_io *)ctsio);
5337                 goto bailout;
5338                 break; /* NOTREACHED */
5339         }
5340
5341         /*
5342          * We check the LBA and length, but don't do anything with them.
5343          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5344          * get flushed.  This check will just help satisfy anyone who wants
5345          * to see an error for an out of range LBA.
5346          */
5347         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5348                 ctl_set_lba_out_of_range(ctsio,
5349                     MAX(starting_lba, lun->be_lun->maxlba + 1));
5350                 ctl_done((union ctl_io *)ctsio);
5351                 goto bailout;
5352         }
5353
5354         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5355         lbalen->lba = starting_lba;
5356         lbalen->len = block_count;
5357         lbalen->flags = byte2;
5358         retval = lun->backend->config_write((union ctl_io *)ctsio);
5359
5360 bailout:
5361         return (retval);
5362 }
5363
5364 int
5365 ctl_format(struct ctl_scsiio *ctsio)
5366 {
5367         struct scsi_format *cdb;
5368         int length, defect_list_len;
5369
5370         CTL_DEBUG_PRINT(("ctl_format\n"));
5371
5372         cdb = (struct scsi_format *)ctsio->cdb;
5373
5374         length = 0;
5375         if (cdb->byte2 & SF_FMTDATA) {
5376                 if (cdb->byte2 & SF_LONGLIST)
5377                         length = sizeof(struct scsi_format_header_long);
5378                 else
5379                         length = sizeof(struct scsi_format_header_short);
5380         }
5381
5382         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5383          && (length > 0)) {
5384                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5385                 ctsio->kern_data_len = length;
5386                 ctsio->kern_total_len = length;
5387                 ctsio->kern_data_resid = 0;
5388                 ctsio->kern_rel_offset = 0;
5389                 ctsio->kern_sg_entries = 0;
5390                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5391                 ctsio->be_move_done = ctl_config_move_done;
5392                 ctl_datamove((union ctl_io *)ctsio);
5393
5394                 return (CTL_RETVAL_COMPLETE);
5395         }
5396
5397         defect_list_len = 0;
5398
5399         if (cdb->byte2 & SF_FMTDATA) {
5400                 if (cdb->byte2 & SF_LONGLIST) {
5401                         struct scsi_format_header_long *header;
5402
5403                         header = (struct scsi_format_header_long *)
5404                                 ctsio->kern_data_ptr;
5405
5406                         defect_list_len = scsi_4btoul(header->defect_list_len);
5407                         if (defect_list_len != 0) {
5408                                 ctl_set_invalid_field(ctsio,
5409                                                       /*sks_valid*/ 1,
5410                                                       /*command*/ 0,
5411                                                       /*field*/ 2,
5412                                                       /*bit_valid*/ 0,
5413                                                       /*bit*/ 0);
5414                                 goto bailout;
5415                         }
5416                 } else {
5417                         struct scsi_format_header_short *header;
5418
5419                         header = (struct scsi_format_header_short *)
5420                                 ctsio->kern_data_ptr;
5421
5422                         defect_list_len = scsi_2btoul(header->defect_list_len);
5423                         if (defect_list_len != 0) {
5424                                 ctl_set_invalid_field(ctsio,
5425                                                       /*sks_valid*/ 1,
5426                                                       /*command*/ 0,
5427                                                       /*field*/ 2,
5428                                                       /*bit_valid*/ 0,
5429                                                       /*bit*/ 0);
5430                                 goto bailout;
5431                         }
5432                 }
5433         }
5434
5435         ctl_set_success(ctsio);
5436 bailout:
5437
5438         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5439                 free(ctsio->kern_data_ptr, M_CTL);
5440                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5441         }
5442
5443         ctl_done((union ctl_io *)ctsio);
5444         return (CTL_RETVAL_COMPLETE);
5445 }
5446
5447 int
5448 ctl_read_buffer(struct ctl_scsiio *ctsio)
5449 {
5450         struct ctl_lun *lun = CTL_LUN(ctsio);
5451         uint64_t buffer_offset;
5452         uint32_t len;
5453         uint8_t byte2;
5454         static uint8_t descr[4];
5455         static uint8_t echo_descr[4] = { 0 };
5456
5457         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5458
5459         switch (ctsio->cdb[0]) {
5460         case READ_BUFFER: {
5461                 struct scsi_read_buffer *cdb;
5462
5463                 cdb = (struct scsi_read_buffer *)ctsio->cdb;
5464                 buffer_offset = scsi_3btoul(cdb->offset);
5465                 len = scsi_3btoul(cdb->length);
5466                 byte2 = cdb->byte2;
5467                 break;
5468         }
5469         case READ_BUFFER_16: {
5470                 struct scsi_read_buffer_16 *cdb;
5471
5472                 cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5473                 buffer_offset = scsi_8btou64(cdb->offset);
5474                 len = scsi_4btoul(cdb->length);
5475                 byte2 = cdb->byte2;
5476                 break;
5477         }
5478         default: /* This shouldn't happen. */
5479                 ctl_set_invalid_opcode(ctsio);
5480                 ctl_done((union ctl_io *)ctsio);
5481                 return (CTL_RETVAL_COMPLETE);
5482         }
5483
5484         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5485             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5486                 ctl_set_invalid_field(ctsio,
5487                                       /*sks_valid*/ 1,
5488                                       /*command*/ 1,
5489                                       /*field*/ 6,
5490                                       /*bit_valid*/ 0,
5491                                       /*bit*/ 0);
5492                 ctl_done((union ctl_io *)ctsio);
5493                 return (CTL_RETVAL_COMPLETE);
5494         }
5495
5496         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5497                 descr[0] = 0;
5498                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5499                 ctsio->kern_data_ptr = descr;
5500                 len = min(len, sizeof(descr));
5501         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5502                 ctsio->kern_data_ptr = echo_descr;
5503                 len = min(len, sizeof(echo_descr));
5504         } else {
5505                 if (lun->write_buffer == NULL) {
5506                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5507                             M_CTL, M_WAITOK);
5508                 }
5509                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5510         }
5511         ctsio->kern_data_len = len;
5512         ctsio->kern_total_len = len;
5513         ctsio->kern_data_resid = 0;
5514         ctsio->kern_rel_offset = 0;
5515         ctsio->kern_sg_entries = 0;
5516         ctl_set_success(ctsio);
5517         ctsio->be_move_done = ctl_config_move_done;
5518         ctl_datamove((union ctl_io *)ctsio);
5519         return (CTL_RETVAL_COMPLETE);
5520 }
5521
5522 int
5523 ctl_write_buffer(struct ctl_scsiio *ctsio)
5524 {
5525         struct ctl_lun *lun = CTL_LUN(ctsio);
5526         struct scsi_write_buffer *cdb;
5527         int buffer_offset, len;
5528
5529         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5530
5531         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5532
5533         len = scsi_3btoul(cdb->length);
5534         buffer_offset = scsi_3btoul(cdb->offset);
5535
5536         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5537                 ctl_set_invalid_field(ctsio,
5538                                       /*sks_valid*/ 1,
5539                                       /*command*/ 1,
5540                                       /*field*/ 6,
5541                                       /*bit_valid*/ 0,
5542                                       /*bit*/ 0);
5543                 ctl_done((union ctl_io *)ctsio);
5544                 return (CTL_RETVAL_COMPLETE);
5545         }
5546
5547         /*
5548          * If we've got a kernel request that hasn't been malloced yet,
5549          * malloc it and tell the caller the data buffer is here.
5550          */
5551         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5552                 if (lun->write_buffer == NULL) {
5553                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5554                             M_CTL, M_WAITOK);
5555                 }
5556                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5557                 ctsio->kern_data_len = len;
5558                 ctsio->kern_total_len = len;
5559                 ctsio->kern_data_resid = 0;
5560                 ctsio->kern_rel_offset = 0;
5561                 ctsio->kern_sg_entries = 0;
5562                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5563                 ctsio->be_move_done = ctl_config_move_done;
5564                 ctl_datamove((union ctl_io *)ctsio);
5565
5566                 return (CTL_RETVAL_COMPLETE);
5567         }
5568
5569         ctl_set_success(ctsio);
5570         ctl_done((union ctl_io *)ctsio);
5571         return (CTL_RETVAL_COMPLETE);
5572 }
5573
5574 int
5575 ctl_write_same(struct ctl_scsiio *ctsio)
5576 {
5577         struct ctl_lun *lun = CTL_LUN(ctsio);
5578         struct ctl_lba_len_flags *lbalen;
5579         uint64_t lba;
5580         uint32_t num_blocks;
5581         int len, retval;
5582         uint8_t byte2;
5583
5584         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5585
5586         switch (ctsio->cdb[0]) {
5587         case WRITE_SAME_10: {
5588                 struct scsi_write_same_10 *cdb;
5589
5590                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5591
5592                 lba = scsi_4btoul(cdb->addr);
5593                 num_blocks = scsi_2btoul(cdb->length);
5594                 byte2 = cdb->byte2;
5595                 break;
5596         }
5597         case WRITE_SAME_16: {
5598                 struct scsi_write_same_16 *cdb;
5599
5600                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5601
5602                 lba = scsi_8btou64(cdb->addr);
5603                 num_blocks = scsi_4btoul(cdb->length);
5604                 byte2 = cdb->byte2;
5605                 break;
5606         }
5607         default:
5608                 /*
5609                  * We got a command we don't support.  This shouldn't
5610                  * happen, commands should be filtered out above us.
5611                  */
5612                 ctl_set_invalid_opcode(ctsio);
5613                 ctl_done((union ctl_io *)ctsio);
5614
5615                 return (CTL_RETVAL_COMPLETE);
5616                 break; /* NOTREACHED */
5617         }
5618
5619         /* ANCHOR flag can be used only together with UNMAP */
5620         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5621                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5622                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5623                 ctl_done((union ctl_io *)ctsio);
5624                 return (CTL_RETVAL_COMPLETE);
5625         }
5626
5627         /*
5628          * The first check is to make sure we're in bounds, the second
5629          * check is to catch wrap-around problems.  If the lba + num blocks
5630          * is less than the lba, then we've wrapped around and the block
5631          * range is invalid anyway.
5632          */
5633         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5634          || ((lba + num_blocks) < lba)) {
5635                 ctl_set_lba_out_of_range(ctsio,
5636                     MAX(lba, lun->be_lun->maxlba + 1));
5637                 ctl_done((union ctl_io *)ctsio);
5638                 return (CTL_RETVAL_COMPLETE);
5639         }
5640
5641         /* Zero number of blocks means "to the last logical block" */
5642         if (num_blocks == 0) {
5643                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5644                         ctl_set_invalid_field(ctsio,
5645                                               /*sks_valid*/ 0,
5646                                               /*command*/ 1,
5647                                               /*field*/ 0,
5648                                               /*bit_valid*/ 0,
5649                                               /*bit*/ 0);
5650                         ctl_done((union ctl_io *)ctsio);
5651                         return (CTL_RETVAL_COMPLETE);
5652                 }
5653                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5654         }
5655
5656         len = lun->be_lun->blocksize;
5657
5658         /*
5659          * If we've got a kernel request that hasn't been malloced yet,
5660          * malloc it and tell the caller the data buffer is here.
5661          */
5662         if ((byte2 & SWS_NDOB) == 0 &&
5663             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5664                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5665                 ctsio->kern_data_len = len;
5666                 ctsio->kern_total_len = len;
5667                 ctsio->kern_data_resid = 0;
5668                 ctsio->kern_rel_offset = 0;
5669                 ctsio->kern_sg_entries = 0;
5670                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5671                 ctsio->be_move_done = ctl_config_move_done;
5672                 ctl_datamove((union ctl_io *)ctsio);
5673
5674                 return (CTL_RETVAL_COMPLETE);
5675         }
5676
5677         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5678         lbalen->lba = lba;
5679         lbalen->len = num_blocks;
5680         lbalen->flags = byte2;
5681         retval = lun->backend->config_write((union ctl_io *)ctsio);
5682
5683         return (retval);
5684 }
5685
5686 int
5687 ctl_unmap(struct ctl_scsiio *ctsio)
5688 {
5689         struct ctl_lun *lun = CTL_LUN(ctsio);
5690         struct scsi_unmap *cdb;
5691         struct ctl_ptr_len_flags *ptrlen;
5692         struct scsi_unmap_header *hdr;
5693         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5694         uint64_t lba;
5695         uint32_t num_blocks;
5696         int len, retval;
5697         uint8_t byte2;
5698
5699         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5700
5701         cdb = (struct scsi_unmap *)ctsio->cdb;
5702         len = scsi_2btoul(cdb->length);
5703         byte2 = cdb->byte2;
5704
5705         /*
5706          * If we've got a kernel request that hasn't been malloced yet,
5707          * malloc it and tell the caller the data buffer is here.
5708          */
5709         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5710                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5711                 ctsio->kern_data_len = len;
5712                 ctsio->kern_total_len = len;
5713                 ctsio->kern_data_resid = 0;
5714                 ctsio->kern_rel_offset = 0;
5715                 ctsio->kern_sg_entries = 0;
5716                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5717                 ctsio->be_move_done = ctl_config_move_done;
5718                 ctl_datamove((union ctl_io *)ctsio);
5719
5720                 return (CTL_RETVAL_COMPLETE);
5721         }
5722
5723         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5724         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5725         if (len < sizeof (*hdr) ||
5726             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5727             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5728             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5729                 ctl_set_invalid_field(ctsio,
5730                                       /*sks_valid*/ 0,
5731                                       /*command*/ 0,
5732                                       /*field*/ 0,
5733                                       /*bit_valid*/ 0,
5734                                       /*bit*/ 0);
5735                 goto done;
5736         }
5737         len = scsi_2btoul(hdr->desc_length);
5738         buf = (struct scsi_unmap_desc *)(hdr + 1);
5739         end = buf + len / sizeof(*buf);
5740
5741         endnz = buf;
5742         for (range = buf; range < end; range++) {
5743                 lba = scsi_8btou64(range->lba);
5744                 num_blocks = scsi_4btoul(range->length);
5745                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5746                  || ((lba + num_blocks) < lba)) {
5747                         ctl_set_lba_out_of_range(ctsio,
5748                             MAX(lba, lun->be_lun->maxlba + 1));
5749                         ctl_done((union ctl_io *)ctsio);
5750                         return (CTL_RETVAL_COMPLETE);
5751                 }
5752                 if (num_blocks != 0)
5753                         endnz = range + 1;
5754         }
5755
5756         /*
5757          * Block backend can not handle zero last range.
5758          * Filter it out and return if there is nothing left.
5759          */
5760         len = (uint8_t *)endnz - (uint8_t *)buf;
5761         if (len == 0) {
5762                 ctl_set_success(ctsio);
5763                 goto done;
5764         }
5765
5766         mtx_lock(&lun->lun_lock);
5767         ptrlen = (struct ctl_ptr_len_flags *)
5768             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5769         ptrlen->ptr = (void *)buf;
5770         ptrlen->len = len;
5771         ptrlen->flags = byte2;
5772         ctl_check_blocked(lun);
5773         mtx_unlock(&lun->lun_lock);
5774
5775         retval = lun->backend->config_write((union ctl_io *)ctsio);
5776         return (retval);
5777
5778 done:
5779         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5780                 free(ctsio->kern_data_ptr, M_CTL);
5781                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5782         }
5783         ctl_done((union ctl_io *)ctsio);
5784         return (CTL_RETVAL_COMPLETE);
5785 }
5786
5787 int
5788 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5789                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5790 {
5791         struct ctl_lun *lun = CTL_LUN(ctsio);
5792         uint8_t *current_cp;
5793         int set_ua;
5794         uint32_t initidx;
5795
5796         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5797         set_ua = 0;
5798
5799         current_cp = (page_index->page_data + (page_index->page_len *
5800             CTL_PAGE_CURRENT));
5801
5802         mtx_lock(&lun->lun_lock);
5803         if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5804                 memcpy(current_cp, page_ptr, page_index->page_len);
5805                 set_ua = 1;
5806         }
5807         if (set_ua != 0)
5808                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5809         mtx_unlock(&lun->lun_lock);
5810         if (set_ua) {
5811                 ctl_isc_announce_mode(lun,
5812                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5813                     page_index->page_code, page_index->subpage);
5814         }
5815         return (CTL_RETVAL_COMPLETE);
5816 }
5817
5818 static void
5819 ctl_ie_timer(void *arg)
5820 {
5821         struct ctl_lun *lun = arg;
5822         uint64_t t;
5823
5824         if (lun->ie_asc == 0)
5825                 return;
5826
5827         if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5828                 ctl_est_ua_all(lun, -1, CTL_UA_IE);
5829         else
5830                 lun->ie_reported = 0;
5831
5832         if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5833                 lun->ie_reportcnt++;
5834                 t = scsi_4btoul(lun->MODE_IE.interval_timer);
5835                 if (t == 0 || t == UINT32_MAX)
5836                         t = 3000;  /* 5 min */
5837                 callout_schedule(&lun->ie_callout, t * hz / 10);
5838         }
5839 }
5840
5841 int
5842 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5843                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5844 {
5845         struct ctl_lun *lun = CTL_LUN(ctsio);
5846         struct scsi_info_exceptions_page *pg;
5847         uint64_t t;
5848
5849         (void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5850
5851         pg = (struct scsi_info_exceptions_page *)page_ptr;
5852         mtx_lock(&lun->lun_lock);
5853         if (pg->info_flags & SIEP_FLAGS_TEST) {
5854                 lun->ie_asc = 0x5d;
5855                 lun->ie_ascq = 0xff;
5856                 if (pg->mrie == SIEP_MRIE_UA) {
5857                         ctl_est_ua_all(lun, -1, CTL_UA_IE);
5858                         lun->ie_reported = 1;
5859                 } else {
5860                         ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5861                         lun->ie_reported = -1;
5862                 }
5863                 lun->ie_reportcnt = 1;
5864                 if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5865                         lun->ie_reportcnt++;
5866                         t = scsi_4btoul(pg->interval_timer);
5867                         if (t == 0 || t == UINT32_MAX)
5868                                 t = 3000;  /* 5 min */
5869                         callout_reset(&lun->ie_callout, t * hz / 10,
5870                             ctl_ie_timer, lun);
5871                 }
5872         } else {
5873                 lun->ie_asc = 0;
5874                 lun->ie_ascq = 0;
5875                 lun->ie_reported = 1;
5876                 ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5877                 lun->ie_reportcnt = UINT32_MAX;
5878                 callout_stop(&lun->ie_callout);
5879         }
5880         mtx_unlock(&lun->lun_lock);
5881         return (CTL_RETVAL_COMPLETE);
5882 }
5883
5884 static int
5885 ctl_do_mode_select(union ctl_io *io)
5886 {
5887         struct ctl_lun *lun = CTL_LUN(io);
5888         struct scsi_mode_page_header *page_header;
5889         struct ctl_page_index *page_index;
5890         struct ctl_scsiio *ctsio;
5891         int page_len, page_len_offset, page_len_size;
5892         union ctl_modepage_info *modepage_info;
5893         uint16_t *len_left, *len_used;
5894         int retval, i;
5895
5896         ctsio = &io->scsiio;
5897         page_index = NULL;
5898         page_len = 0;
5899
5900         modepage_info = (union ctl_modepage_info *)
5901                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5902         len_left = &modepage_info->header.len_left;
5903         len_used = &modepage_info->header.len_used;
5904
5905 do_next_page:
5906
5907         page_header = (struct scsi_mode_page_header *)
5908                 (ctsio->kern_data_ptr + *len_used);
5909
5910         if (*len_left == 0) {
5911                 free(ctsio->kern_data_ptr, M_CTL);
5912                 ctl_set_success(ctsio);
5913                 ctl_done((union ctl_io *)ctsio);
5914                 return (CTL_RETVAL_COMPLETE);
5915         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5916
5917                 free(ctsio->kern_data_ptr, M_CTL);
5918                 ctl_set_param_len_error(ctsio);
5919                 ctl_done((union ctl_io *)ctsio);
5920                 return (CTL_RETVAL_COMPLETE);
5921
5922         } else if ((page_header->page_code & SMPH_SPF)
5923                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5924
5925                 free(ctsio->kern_data_ptr, M_CTL);
5926                 ctl_set_param_len_error(ctsio);
5927                 ctl_done((union ctl_io *)ctsio);
5928                 return (CTL_RETVAL_COMPLETE);
5929         }
5930
5931
5932         /*
5933          * XXX KDM should we do something with the block descriptor?
5934          */
5935         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5936                 page_index = &lun->mode_pages.index[i];
5937                 if (lun->be_lun->lun_type == T_DIRECT &&
5938                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5939                         continue;
5940                 if (lun->be_lun->lun_type == T_PROCESSOR &&
5941                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5942                         continue;
5943                 if (lun->be_lun->lun_type == T_CDROM &&
5944                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5945                         continue;
5946
5947                 if ((page_index->page_code & SMPH_PC_MASK) !=
5948                     (page_header->page_code & SMPH_PC_MASK))
5949                         continue;
5950
5951                 /*
5952                  * If neither page has a subpage code, then we've got a
5953                  * match.
5954                  */
5955                 if (((page_index->page_code & SMPH_SPF) == 0)
5956                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5957                         page_len = page_header->page_length;
5958                         break;
5959                 }
5960
5961                 /*
5962                  * If both pages have subpages, then the subpage numbers
5963                  * have to match.
5964                  */
5965                 if ((page_index->page_code & SMPH_SPF)
5966                   && (page_header->page_code & SMPH_SPF)) {
5967                         struct scsi_mode_page_header_sp *sph;
5968
5969                         sph = (struct scsi_mode_page_header_sp *)page_header;
5970                         if (page_index->subpage == sph->subpage) {
5971                                 page_len = scsi_2btoul(sph->page_length);
5972                                 break;
5973                         }
5974                 }
5975         }
5976
5977         /*
5978          * If we couldn't find the page, or if we don't have a mode select
5979          * handler for it, send back an error to the user.
5980          */
5981         if ((i >= CTL_NUM_MODE_PAGES)
5982          || (page_index->select_handler == NULL)) {
5983                 ctl_set_invalid_field(ctsio,
5984                                       /*sks_valid*/ 1,
5985                                       /*command*/ 0,
5986                                       /*field*/ *len_used,
5987                                       /*bit_valid*/ 0,
5988                                       /*bit*/ 0);
5989                 free(ctsio->kern_data_ptr, M_CTL);
5990                 ctl_done((union ctl_io *)ctsio);
5991                 return (CTL_RETVAL_COMPLETE);
5992         }
5993
5994         if (page_index->page_code & SMPH_SPF) {
5995                 page_len_offset = 2;
5996                 page_len_size = 2;
5997         } else {
5998                 page_len_size = 1;
5999                 page_len_offset = 1;
6000         }
6001
6002         /*
6003          * If the length the initiator gives us isn't the one we specify in
6004          * the mode page header, or if they didn't specify enough data in
6005          * the CDB to avoid truncating this page, kick out the request.
6006          */
6007         if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6008                 ctl_set_invalid_field(ctsio,
6009                                       /*sks_valid*/ 1,
6010                                       /*command*/ 0,
6011                                       /*field*/ *len_used + page_len_offset,
6012                                       /*bit_valid*/ 0,
6013                                       /*bit*/ 0);
6014                 free(ctsio->kern_data_ptr, M_CTL);
6015                 ctl_done((union ctl_io *)ctsio);
6016                 return (CTL_RETVAL_COMPLETE);
6017         }
6018         if (*len_left < page_index->page_len) {
6019                 free(ctsio->kern_data_ptr, M_CTL);
6020                 ctl_set_param_len_error(ctsio);
6021                 ctl_done((union ctl_io *)ctsio);
6022                 return (CTL_RETVAL_COMPLETE);
6023         }
6024
6025         /*
6026          * Run through the mode page, checking to make sure that the bits
6027          * the user changed are actually legal for him to change.
6028          */
6029         for (i = 0; i < page_index->page_len; i++) {
6030                 uint8_t *user_byte, *change_mask, *current_byte;
6031                 int bad_bit;
6032                 int j;
6033
6034                 user_byte = (uint8_t *)page_header + i;
6035                 change_mask = page_index->page_data +
6036                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6037                 current_byte = page_index->page_data +
6038                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6039
6040                 /*
6041                  * Check to see whether the user set any bits in this byte
6042                  * that he is not allowed to set.
6043                  */
6044                 if ((*user_byte & ~(*change_mask)) ==
6045                     (*current_byte & ~(*change_mask)))
6046                         continue;
6047
6048                 /*
6049                  * Go through bit by bit to determine which one is illegal.
6050                  */
6051                 bad_bit = 0;
6052                 for (j = 7; j >= 0; j--) {
6053                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6054                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6055                                 bad_bit = i;
6056                                 break;
6057                         }
6058                 }
6059                 ctl_set_invalid_field(ctsio,
6060                                       /*sks_valid*/ 1,
6061                                       /*command*/ 0,
6062                                       /*field*/ *len_used + i,
6063                                       /*bit_valid*/ 1,
6064                                       /*bit*/ bad_bit);
6065                 free(ctsio->kern_data_ptr, M_CTL);
6066                 ctl_done((union ctl_io *)ctsio);
6067                 return (CTL_RETVAL_COMPLETE);
6068         }
6069
6070         /*
6071          * Decrement these before we call the page handler, since we may
6072          * end up getting called back one way or another before the handler
6073          * returns to this context.
6074          */
6075         *len_left -= page_index->page_len;
6076         *len_used += page_index->page_len;
6077
6078         retval = page_index->select_handler(ctsio, page_index,
6079                                             (uint8_t *)page_header);
6080
6081         /*
6082          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6083          * wait until this queued command completes to finish processing
6084          * the mode page.  If it returns anything other than
6085          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6086          * already set the sense information, freed the data pointer, and
6087          * completed the io for us.
6088          */
6089         if (retval != CTL_RETVAL_COMPLETE)
6090                 goto bailout_no_done;
6091
6092         /*
6093          * If the initiator sent us more than one page, parse the next one.
6094          */
6095         if (*len_left > 0)
6096                 goto do_next_page;
6097
6098         ctl_set_success(ctsio);
6099         free(ctsio->kern_data_ptr, M_CTL);
6100         ctl_done((union ctl_io *)ctsio);
6101
6102 bailout_no_done:
6103
6104         return (CTL_RETVAL_COMPLETE);
6105
6106 }
6107
6108 int
6109 ctl_mode_select(struct ctl_scsiio *ctsio)
6110 {
6111         struct ctl_lun *lun = CTL_LUN(ctsio);
6112         union ctl_modepage_info *modepage_info;
6113         int bd_len, i, header_size, param_len, pf, rtd, sp;
6114         uint32_t initidx;
6115
6116         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6117         switch (ctsio->cdb[0]) {
6118         case MODE_SELECT_6: {
6119                 struct scsi_mode_select_6 *cdb;
6120
6121                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6122
6123                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6124                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6125                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6126                 param_len = cdb->length;
6127                 header_size = sizeof(struct scsi_mode_header_6);
6128                 break;
6129         }
6130         case MODE_SELECT_10: {
6131                 struct scsi_mode_select_10 *cdb;
6132
6133                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6134
6135                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6136                 rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6137                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6138                 param_len = scsi_2btoul(cdb->length);
6139                 header_size = sizeof(struct scsi_mode_header_10);
6140                 break;
6141         }
6142         default:
6143                 ctl_set_invalid_opcode(ctsio);
6144                 ctl_done((union ctl_io *)ctsio);
6145                 return (CTL_RETVAL_COMPLETE);
6146         }
6147
6148         if (rtd) {
6149                 if (param_len != 0) {
6150                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6151                             /*command*/ 1, /*field*/ 0,
6152                             /*bit_valid*/ 0, /*bit*/ 0);
6153                         ctl_done((union ctl_io *)ctsio);
6154                         return (CTL_RETVAL_COMPLETE);
6155                 }
6156
6157                 /* Revert to defaults. */
6158                 ctl_init_page_index(lun);
6159                 mtx_lock(&lun->lun_lock);
6160                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6161                 mtx_unlock(&lun->lun_lock);
6162                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6163                         ctl_isc_announce_mode(lun, -1,
6164                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6165                             lun->mode_pages.index[i].subpage);
6166                 }
6167                 ctl_set_success(ctsio);
6168                 ctl_done((union ctl_io *)ctsio);
6169                 return (CTL_RETVAL_COMPLETE);
6170         }
6171
6172         /*
6173          * From SPC-3:
6174          * "A parameter list length of zero indicates that the Data-Out Buffer
6175          * shall be empty. This condition shall not be considered as an error."
6176          */
6177         if (param_len == 0) {
6178                 ctl_set_success(ctsio);
6179                 ctl_done((union ctl_io *)ctsio);
6180                 return (CTL_RETVAL_COMPLETE);
6181         }
6182
6183         /*
6184          * Since we'll hit this the first time through, prior to
6185          * allocation, we don't need to free a data buffer here.
6186          */
6187         if (param_len < header_size) {
6188                 ctl_set_param_len_error(ctsio);
6189                 ctl_done((union ctl_io *)ctsio);
6190                 return (CTL_RETVAL_COMPLETE);
6191         }
6192
6193         /*
6194          * Allocate the data buffer and grab the user's data.  In theory,
6195          * we shouldn't have to sanity check the parameter list length here
6196          * because the maximum size is 64K.  We should be able to malloc
6197          * that much without too many problems.
6198          */
6199         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6200                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6201                 ctsio->kern_data_len = param_len;
6202                 ctsio->kern_total_len = param_len;
6203                 ctsio->kern_data_resid = 0;
6204                 ctsio->kern_rel_offset = 0;
6205                 ctsio->kern_sg_entries = 0;
6206                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6207                 ctsio->be_move_done = ctl_config_move_done;
6208                 ctl_datamove((union ctl_io *)ctsio);
6209
6210                 return (CTL_RETVAL_COMPLETE);
6211         }
6212
6213         switch (ctsio->cdb[0]) {
6214         case MODE_SELECT_6: {
6215                 struct scsi_mode_header_6 *mh6;
6216
6217                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6218                 bd_len = mh6->blk_desc_len;
6219                 break;
6220         }
6221         case MODE_SELECT_10: {
6222                 struct scsi_mode_header_10 *mh10;
6223
6224                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6225                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6226                 break;
6227         }
6228         default:
6229                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6230         }
6231
6232         if (param_len < (header_size + bd_len)) {
6233                 free(ctsio->kern_data_ptr, M_CTL);
6234                 ctl_set_param_len_error(ctsio);
6235                 ctl_done((union ctl_io *)ctsio);
6236                 return (CTL_RETVAL_COMPLETE);
6237         }
6238
6239         /*
6240          * Set the IO_CONT flag, so that if this I/O gets passed to
6241          * ctl_config_write_done(), it'll get passed back to
6242          * ctl_do_mode_select() for further processing, or completion if
6243          * we're all done.
6244          */
6245         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6246         ctsio->io_cont = ctl_do_mode_select;
6247
6248         modepage_info = (union ctl_modepage_info *)
6249                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6250         memset(modepage_info, 0, sizeof(*modepage_info));
6251         modepage_info->header.len_left = param_len - header_size - bd_len;
6252         modepage_info->header.len_used = header_size + bd_len;
6253
6254         return (ctl_do_mode_select((union ctl_io *)ctsio));
6255 }
6256
6257 int
6258 ctl_mode_sense(struct ctl_scsiio *ctsio)
6259 {
6260         struct ctl_lun *lun = CTL_LUN(ctsio);
6261         int pc, page_code, dbd, llba, subpage;
6262         int alloc_len, page_len, header_len, total_len;
6263         struct scsi_mode_block_descr *block_desc;
6264         struct ctl_page_index *page_index;
6265
6266         dbd = 0;
6267         llba = 0;
6268         block_desc = NULL;
6269
6270         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6271
6272         switch (ctsio->cdb[0]) {
6273         case MODE_SENSE_6: {
6274                 struct scsi_mode_sense_6 *cdb;
6275
6276                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6277
6278                 header_len = sizeof(struct scsi_mode_hdr_6);
6279                 if (cdb->byte2 & SMS_DBD)
6280                         dbd = 1;
6281                 else
6282                         header_len += sizeof(struct scsi_mode_block_descr);
6283
6284                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6285                 page_code = cdb->page & SMS_PAGE_CODE;
6286                 subpage = cdb->subpage;
6287                 alloc_len = cdb->length;
6288                 break;
6289         }
6290         case MODE_SENSE_10: {
6291                 struct scsi_mode_sense_10 *cdb;
6292
6293                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6294
6295                 header_len = sizeof(struct scsi_mode_hdr_10);
6296
6297                 if (cdb->byte2 & SMS_DBD)
6298                         dbd = 1;
6299                 else
6300                         header_len += sizeof(struct scsi_mode_block_descr);
6301                 if (cdb->byte2 & SMS10_LLBAA)
6302                         llba = 1;
6303                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6304                 page_code = cdb->page & SMS_PAGE_CODE;
6305                 subpage = cdb->subpage;
6306                 alloc_len = scsi_2btoul(cdb->length);
6307                 break;
6308         }
6309         default:
6310                 ctl_set_invalid_opcode(ctsio);
6311                 ctl_done((union ctl_io *)ctsio);
6312                 return (CTL_RETVAL_COMPLETE);
6313                 break; /* NOTREACHED */
6314         }
6315
6316         /*
6317          * We have to make a first pass through to calculate the size of
6318          * the pages that match the user's query.  Then we allocate enough
6319          * memory to hold it, and actually copy the data into the buffer.
6320          */
6321         switch (page_code) {
6322         case SMS_ALL_PAGES_PAGE: {
6323                 u_int i;
6324
6325                 page_len = 0;
6326
6327                 /*
6328                  * At the moment, values other than 0 and 0xff here are
6329                  * reserved according to SPC-3.
6330                  */
6331                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6332                  && (subpage != SMS_SUBPAGE_ALL)) {
6333                         ctl_set_invalid_field(ctsio,
6334                                               /*sks_valid*/ 1,
6335                                               /*command*/ 1,
6336                                               /*field*/ 3,
6337                                               /*bit_valid*/ 0,
6338                                               /*bit*/ 0);
6339                         ctl_done((union ctl_io *)ctsio);
6340                         return (CTL_RETVAL_COMPLETE);
6341                 }
6342
6343                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6344                         page_index = &lun->mode_pages.index[i];
6345
6346                         /* Make sure the page is supported for this dev type */
6347                         if (lun->be_lun->lun_type == T_DIRECT &&
6348                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6349                                 continue;
6350                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6351                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6352                                 continue;
6353                         if (lun->be_lun->lun_type == T_CDROM &&
6354                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6355                                 continue;
6356
6357                         /*
6358                          * We don't use this subpage if the user didn't
6359                          * request all subpages.
6360                          */
6361                         if ((page_index->subpage != 0)
6362                          && (subpage == SMS_SUBPAGE_PAGE_0))
6363                                 continue;
6364
6365 #if 0
6366                         printf("found page %#x len %d\n",
6367                                page_index->page_code & SMPH_PC_MASK,
6368                                page_index->page_len);
6369 #endif
6370                         page_len += page_index->page_len;
6371                 }
6372                 break;
6373         }
6374         default: {
6375                 u_int i;
6376
6377                 page_len = 0;
6378
6379                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6380                         page_index = &lun->mode_pages.index[i];
6381
6382                         /* Make sure the page is supported for this dev type */
6383                         if (lun->be_lun->lun_type == T_DIRECT &&
6384                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6385                                 continue;
6386                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6387                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6388                                 continue;
6389                         if (lun->be_lun->lun_type == T_CDROM &&
6390                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6391                                 continue;
6392
6393                         /* Look for the right page code */
6394                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6395                                 continue;
6396
6397                         /* Look for the right subpage or the subpage wildcard*/
6398                         if ((page_index->subpage != subpage)
6399                          && (subpage != SMS_SUBPAGE_ALL))
6400                                 continue;
6401
6402 #if 0
6403                         printf("found page %#x len %d\n",
6404                                page_index->page_code & SMPH_PC_MASK,
6405                                page_index->page_len);
6406 #endif
6407
6408                         page_len += page_index->page_len;
6409                 }
6410
6411                 if (page_len == 0) {
6412                         ctl_set_invalid_field(ctsio,
6413                                               /*sks_valid*/ 1,
6414                                               /*command*/ 1,
6415                                               /*field*/ 2,
6416                                               /*bit_valid*/ 1,
6417                                               /*bit*/ 5);
6418                         ctl_done((union ctl_io *)ctsio);
6419                         return (CTL_RETVAL_COMPLETE);
6420                 }
6421                 break;
6422         }
6423         }
6424
6425         total_len = header_len + page_len;
6426 #if 0
6427         printf("header_len = %d, page_len = %d, total_len = %d\n",
6428                header_len, page_len, total_len);
6429 #endif
6430
6431         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6432         ctsio->kern_sg_entries = 0;
6433         ctsio->kern_data_resid = 0;
6434         ctsio->kern_rel_offset = 0;
6435         if (total_len < alloc_len) {
6436                 ctsio->residual = alloc_len - total_len;
6437                 ctsio->kern_data_len = total_len;
6438                 ctsio->kern_total_len = total_len;
6439         } else {
6440                 ctsio->residual = 0;
6441                 ctsio->kern_data_len = alloc_len;
6442                 ctsio->kern_total_len = alloc_len;
6443         }
6444
6445         switch (ctsio->cdb[0]) {
6446         case MODE_SENSE_6: {
6447                 struct scsi_mode_hdr_6 *header;
6448
6449                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6450
6451                 header->datalen = MIN(total_len - 1, 254);
6452                 if (lun->be_lun->lun_type == T_DIRECT) {
6453                         header->dev_specific = 0x10; /* DPOFUA */
6454                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6455                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6456                                 header->dev_specific |= 0x80; /* WP */
6457                 }
6458                 if (dbd)
6459                         header->block_descr_len = 0;
6460                 else
6461                         header->block_descr_len =
6462                                 sizeof(struct scsi_mode_block_descr);
6463                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6464                 break;
6465         }
6466         case MODE_SENSE_10: {
6467                 struct scsi_mode_hdr_10 *header;
6468                 int datalen;
6469
6470                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6471
6472                 datalen = MIN(total_len - 2, 65533);
6473                 scsi_ulto2b(datalen, header->datalen);
6474                 if (lun->be_lun->lun_type == T_DIRECT) {
6475                         header->dev_specific = 0x10; /* DPOFUA */
6476                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6477                             (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6478                                 header->dev_specific |= 0x80; /* WP */
6479                 }
6480                 if (dbd)
6481                         scsi_ulto2b(0, header->block_descr_len);
6482                 else
6483                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6484                                     header->block_descr_len);
6485                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6486                 break;
6487         }
6488         default:
6489                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6490         }
6491
6492         /*
6493          * If we've got a disk, use its blocksize in the block
6494          * descriptor.  Otherwise, just set it to 0.
6495          */
6496         if (dbd == 0) {
6497                 if (lun->be_lun->lun_type == T_DIRECT)
6498                         scsi_ulto3b(lun->be_lun->blocksize,
6499                                     block_desc->block_len);
6500                 else
6501                         scsi_ulto3b(0, block_desc->block_len);
6502         }
6503
6504         switch (page_code) {
6505         case SMS_ALL_PAGES_PAGE: {
6506                 int i, data_used;
6507
6508                 data_used = header_len;
6509                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6510                         struct ctl_page_index *page_index;
6511
6512                         page_index = &lun->mode_pages.index[i];
6513                         if (lun->be_lun->lun_type == T_DIRECT &&
6514                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6515                                 continue;
6516                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6517                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6518                                 continue;
6519                         if (lun->be_lun->lun_type == T_CDROM &&
6520                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6521                                 continue;
6522
6523                         /*
6524                          * We don't use this subpage if the user didn't
6525                          * request all subpages.  We already checked (above)
6526                          * to make sure the user only specified a subpage
6527                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6528                          */
6529                         if ((page_index->subpage != 0)
6530                          && (subpage == SMS_SUBPAGE_PAGE_0))
6531                                 continue;
6532
6533                         /*
6534                          * Call the handler, if it exists, to update the
6535                          * page to the latest values.
6536                          */
6537                         if (page_index->sense_handler != NULL)
6538                                 page_index->sense_handler(ctsio, page_index,pc);
6539
6540                         memcpy(ctsio->kern_data_ptr + data_used,
6541                                page_index->page_data +
6542                                (page_index->page_len * pc),
6543                                page_index->page_len);
6544                         data_used += page_index->page_len;
6545                 }
6546                 break;
6547         }
6548         default: {
6549                 int i, data_used;
6550
6551                 data_used = header_len;
6552
6553                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6554                         struct ctl_page_index *page_index;
6555
6556                         page_index = &lun->mode_pages.index[i];
6557
6558                         /* Look for the right page code */
6559                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6560                                 continue;
6561
6562                         /* Look for the right subpage or the subpage wildcard*/
6563                         if ((page_index->subpage != subpage)
6564                          && (subpage != SMS_SUBPAGE_ALL))
6565                                 continue;
6566
6567                         /* Make sure the page is supported for this dev type */
6568                         if (lun->be_lun->lun_type == T_DIRECT &&
6569                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6570                                 continue;
6571                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6572                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6573                                 continue;
6574                         if (lun->be_lun->lun_type == T_CDROM &&
6575                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6576                                 continue;
6577
6578                         /*
6579                          * Call the handler, if it exists, to update the
6580                          * page to the latest values.
6581                          */
6582                         if (page_index->sense_handler != NULL)
6583                                 page_index->sense_handler(ctsio, page_index,pc);
6584
6585                         memcpy(ctsio->kern_data_ptr + data_used,
6586                                page_index->page_data +
6587                                (page_index->page_len * pc),
6588                                page_index->page_len);
6589                         data_used += page_index->page_len;
6590                 }
6591                 break;
6592         }
6593         }
6594
6595         ctl_set_success(ctsio);
6596         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6597         ctsio->be_move_done = ctl_config_move_done;
6598         ctl_datamove((union ctl_io *)ctsio);
6599         return (CTL_RETVAL_COMPLETE);
6600 }
6601
6602 int
6603 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6604                                struct ctl_page_index *page_index,
6605                                int pc)
6606 {
6607         struct ctl_lun *lun = CTL_LUN(ctsio);
6608         struct scsi_log_param_header *phdr;
6609         uint8_t *data;
6610         uint64_t val;
6611
6612         data = page_index->page_data;
6613
6614         if (lun->backend->lun_attr != NULL &&
6615             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6616              != UINT64_MAX) {
6617                 phdr = (struct scsi_log_param_header *)data;
6618                 scsi_ulto2b(0x0001, phdr->param_code);
6619                 phdr->param_control = SLP_LBIN | SLP_LP;
6620                 phdr->param_len = 8;
6621                 data = (uint8_t *)(phdr + 1);
6622                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6623                 data[4] = 0x02; /* per-pool */
6624                 data += phdr->param_len;
6625         }
6626
6627         if (lun->backend->lun_attr != NULL &&
6628             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6629              != UINT64_MAX) {
6630                 phdr = (struct scsi_log_param_header *)data;
6631                 scsi_ulto2b(0x0002, phdr->param_code);
6632                 phdr->param_control = SLP_LBIN | SLP_LP;
6633                 phdr->param_len = 8;
6634                 data = (uint8_t *)(phdr + 1);
6635                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6636                 data[4] = 0x01; /* per-LUN */
6637                 data += phdr->param_len;
6638         }
6639
6640         if (lun->backend->lun_attr != NULL &&
6641             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6642              != UINT64_MAX) {
6643                 phdr = (struct scsi_log_param_header *)data;
6644                 scsi_ulto2b(0x00f1, phdr->param_code);
6645                 phdr->param_control = SLP_LBIN | SLP_LP;
6646                 phdr->param_len = 8;
6647                 data = (uint8_t *)(phdr + 1);
6648                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6649                 data[4] = 0x02; /* per-pool */
6650                 data += phdr->param_len;
6651         }
6652
6653         if (lun->backend->lun_attr != NULL &&
6654             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6655              != UINT64_MAX) {
6656                 phdr = (struct scsi_log_param_header *)data;
6657                 scsi_ulto2b(0x00f2, phdr->param_code);
6658                 phdr->param_control = SLP_LBIN | SLP_LP;
6659                 phdr->param_len = 8;
6660                 data = (uint8_t *)(phdr + 1);
6661                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6662                 data[4] = 0x02; /* per-pool */
6663                 data += phdr->param_len;
6664         }
6665
6666         page_index->page_len = data - page_index->page_data;
6667         return (0);
6668 }
6669
6670 int
6671 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6672                                struct ctl_page_index *page_index,
6673                                int pc)
6674 {
6675         struct ctl_lun *lun = CTL_LUN(ctsio);
6676         struct stat_page *data;
6677         uint64_t rn, wn, rb, wb;
6678         struct bintime rt, wt;
6679         int i;
6680
6681         data = (struct stat_page *)page_index->page_data;
6682
6683         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6684         data->sap.hdr.param_control = SLP_LBIN;
6685         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6686             sizeof(struct scsi_log_param_header);
6687         rn = wn = rb = wb = 0;
6688         bintime_clear(&rt);
6689         bintime_clear(&wt);
6690         for (i = 0; i < CTL_MAX_PORTS; i++) {
6691                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6692                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6693                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6694                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6695                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6696                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6697         }
6698         scsi_u64to8b(rn, data->sap.read_num);
6699         scsi_u64to8b(wn, data->sap.write_num);
6700         if (lun->stats.blocksize > 0) {
6701                 scsi_u64to8b(wb / lun->stats.blocksize,
6702                     data->sap.recvieved_lba);
6703                 scsi_u64to8b(rb / lun->stats.blocksize,
6704                     data->sap.transmitted_lba);
6705         }
6706         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6707             data->sap.read_int);
6708         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6709             data->sap.write_int);
6710         scsi_u64to8b(0, data->sap.weighted_num);
6711         scsi_u64to8b(0, data->sap.weighted_int);
6712         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6713         data->it.hdr.param_control = SLP_LBIN;
6714         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6715             sizeof(struct scsi_log_param_header);
6716 #ifdef CTL_TIME_IO
6717         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6718 #endif
6719         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6720         data->it.hdr.param_control = SLP_LBIN;
6721         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6722             sizeof(struct scsi_log_param_header);
6723         scsi_ulto4b(3, data->ti.exponent);
6724         scsi_ulto4b(1, data->ti.integer);
6725         return (0);
6726 }
6727
6728 int
6729 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6730                                struct ctl_page_index *page_index,
6731                                int pc)
6732 {
6733         struct ctl_lun *lun = CTL_LUN(ctsio);
6734         struct scsi_log_informational_exceptions *data;
6735
6736         data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6737
6738         scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6739         data->hdr.param_control = SLP_LBIN;
6740         data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6741             sizeof(struct scsi_log_param_header);
6742         data->ie_asc = lun->ie_asc;
6743         data->ie_ascq = lun->ie_ascq;
6744         data->temperature = 0xff;
6745         return (0);
6746 }
6747
6748 int
6749 ctl_log_sense(struct ctl_scsiio *ctsio)
6750 {
6751         struct ctl_lun *lun = CTL_LUN(ctsio);
6752         int i, pc, page_code, subpage;
6753         int alloc_len, total_len;
6754         struct ctl_page_index *page_index;
6755         struct scsi_log_sense *cdb;
6756         struct scsi_log_header *header;
6757
6758         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6759
6760         cdb = (struct scsi_log_sense *)ctsio->cdb;
6761         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6762         page_code = cdb->page & SLS_PAGE_CODE;
6763         subpage = cdb->subpage;
6764         alloc_len = scsi_2btoul(cdb->length);
6765
6766         page_index = NULL;
6767         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6768                 page_index = &lun->log_pages.index[i];
6769
6770                 /* Look for the right page code */
6771                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6772                         continue;
6773
6774                 /* Look for the right subpage or the subpage wildcard*/
6775                 if (page_index->subpage != subpage)
6776                         continue;
6777
6778                 break;
6779         }
6780         if (i >= CTL_NUM_LOG_PAGES) {
6781                 ctl_set_invalid_field(ctsio,
6782                                       /*sks_valid*/ 1,
6783                                       /*command*/ 1,
6784                                       /*field*/ 2,
6785                                       /*bit_valid*/ 0,
6786                                       /*bit*/ 0);
6787                 ctl_done((union ctl_io *)ctsio);
6788                 return (CTL_RETVAL_COMPLETE);
6789         }
6790
6791         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6792
6793         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6794         ctsio->kern_sg_entries = 0;
6795         ctsio->kern_data_resid = 0;
6796         ctsio->kern_rel_offset = 0;
6797         if (total_len < alloc_len) {
6798                 ctsio->residual = alloc_len - total_len;
6799                 ctsio->kern_data_len = total_len;
6800                 ctsio->kern_total_len = total_len;
6801         } else {
6802                 ctsio->residual = 0;
6803                 ctsio->kern_data_len = alloc_len;
6804                 ctsio->kern_total_len = alloc_len;
6805         }
6806
6807         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6808         header->page = page_index->page_code;
6809         if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6810                 header->page |= SL_DS;
6811         if (page_index->subpage) {
6812                 header->page |= SL_SPF;
6813                 header->subpage = page_index->subpage;
6814         }
6815         scsi_ulto2b(page_index->page_len, header->datalen);
6816
6817         /*
6818          * Call the handler, if it exists, to update the
6819          * page to the latest values.
6820          */
6821         if (page_index->sense_handler != NULL)
6822                 page_index->sense_handler(ctsio, page_index, pc);
6823
6824         memcpy(header + 1, page_index->page_data, page_index->page_len);
6825
6826         ctl_set_success(ctsio);
6827         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6828         ctsio->be_move_done = ctl_config_move_done;
6829         ctl_datamove((union ctl_io *)ctsio);
6830         return (CTL_RETVAL_COMPLETE);
6831 }
6832
6833 int
6834 ctl_read_capacity(struct ctl_scsiio *ctsio)
6835 {
6836         struct ctl_lun *lun = CTL_LUN(ctsio);
6837         struct scsi_read_capacity *cdb;
6838         struct scsi_read_capacity_data *data;
6839         uint32_t lba;
6840
6841         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6842
6843         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6844
6845         lba = scsi_4btoul(cdb->addr);
6846         if (((cdb->pmi & SRC_PMI) == 0)
6847          && (lba != 0)) {
6848                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6849                                       /*sks_valid*/ 1,
6850                                       /*command*/ 1,
6851                                       /*field*/ 2,
6852                                       /*bit_valid*/ 0,
6853                                       /*bit*/ 0);
6854                 ctl_done((union ctl_io *)ctsio);
6855                 return (CTL_RETVAL_COMPLETE);
6856         }
6857
6858         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6859         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6860         ctsio->residual = 0;
6861         ctsio->kern_data_len = sizeof(*data);
6862         ctsio->kern_total_len = sizeof(*data);
6863         ctsio->kern_data_resid = 0;
6864         ctsio->kern_rel_offset = 0;
6865         ctsio->kern_sg_entries = 0;
6866
6867         /*
6868          * If the maximum LBA is greater than 0xfffffffe, the user must
6869          * issue a SERVICE ACTION IN (16) command, with the read capacity
6870          * serivce action set.
6871          */
6872         if (lun->be_lun->maxlba > 0xfffffffe)
6873                 scsi_ulto4b(0xffffffff, data->addr);
6874         else
6875                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6876
6877         /*
6878          * XXX KDM this may not be 512 bytes...
6879          */
6880         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6881
6882         ctl_set_success(ctsio);
6883         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6884         ctsio->be_move_done = ctl_config_move_done;
6885         ctl_datamove((union ctl_io *)ctsio);
6886         return (CTL_RETVAL_COMPLETE);
6887 }
6888
6889 int
6890 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6891 {
6892         struct ctl_lun *lun = CTL_LUN(ctsio);
6893         struct scsi_read_capacity_16 *cdb;
6894         struct scsi_read_capacity_data_long *data;
6895         uint64_t lba;
6896         uint32_t alloc_len;
6897
6898         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6899
6900         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6901
6902         alloc_len = scsi_4btoul(cdb->alloc_len);
6903         lba = scsi_8btou64(cdb->addr);
6904
6905         if ((cdb->reladr & SRC16_PMI)
6906          && (lba != 0)) {
6907                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6908                                       /*sks_valid*/ 1,
6909                                       /*command*/ 1,
6910                                       /*field*/ 2,
6911                                       /*bit_valid*/ 0,
6912                                       /*bit*/ 0);
6913                 ctl_done((union ctl_io *)ctsio);
6914                 return (CTL_RETVAL_COMPLETE);
6915         }
6916
6917         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6918         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6919
6920         if (sizeof(*data) < alloc_len) {
6921                 ctsio->residual = alloc_len - sizeof(*data);
6922                 ctsio->kern_data_len = sizeof(*data);
6923                 ctsio->kern_total_len = sizeof(*data);
6924         } else {
6925                 ctsio->residual = 0;
6926                 ctsio->kern_data_len = alloc_len;
6927                 ctsio->kern_total_len = alloc_len;
6928         }
6929         ctsio->kern_data_resid = 0;
6930         ctsio->kern_rel_offset = 0;
6931         ctsio->kern_sg_entries = 0;
6932
6933         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6934         /* XXX KDM this may not be 512 bytes... */
6935         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6936         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6937         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6938         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6939                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6940
6941         ctl_set_success(ctsio);
6942         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6943         ctsio->be_move_done = ctl_config_move_done;
6944         ctl_datamove((union ctl_io *)ctsio);
6945         return (CTL_RETVAL_COMPLETE);
6946 }
6947
6948 int
6949 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6950 {
6951         struct ctl_lun *lun = CTL_LUN(ctsio);
6952         struct scsi_get_lba_status *cdb;
6953         struct scsi_get_lba_status_data *data;
6954         struct ctl_lba_len_flags *lbalen;
6955         uint64_t lba;
6956         uint32_t alloc_len, total_len;
6957         int retval;
6958
6959         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6960
6961         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6962         lba = scsi_8btou64(cdb->addr);
6963         alloc_len = scsi_4btoul(cdb->alloc_len);
6964
6965         if (lba > lun->be_lun->maxlba) {
6966                 ctl_set_lba_out_of_range(ctsio, lba);
6967                 ctl_done((union ctl_io *)ctsio);
6968                 return (CTL_RETVAL_COMPLETE);
6969         }
6970
6971         total_len = sizeof(*data) + sizeof(data->descr[0]);
6972         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6973         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6974
6975         if (total_len < alloc_len) {
6976                 ctsio->residual = alloc_len - total_len;
6977                 ctsio->kern_data_len = total_len;
6978                 ctsio->kern_total_len = total_len;
6979         } else {
6980                 ctsio->residual = 0;
6981                 ctsio->kern_data_len = alloc_len;
6982                 ctsio->kern_total_len = alloc_len;
6983         }
6984         ctsio->kern_data_resid = 0;
6985         ctsio->kern_rel_offset = 0;
6986         ctsio->kern_sg_entries = 0;
6987
6988         /* Fill dummy data in case backend can't tell anything. */
6989         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6990         scsi_u64to8b(lba, data->descr[0].addr);
6991         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6992             data->descr[0].length);
6993         data->descr[0].status = 0; /* Mapped or unknown. */
6994
6995         ctl_set_success(ctsio);
6996         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6997         ctsio->be_move_done = ctl_config_move_done;
6998
6999         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7000         lbalen->lba = lba;
7001         lbalen->len = total_len;
7002         lbalen->flags = 0;
7003         retval = lun->backend->config_read((union ctl_io *)ctsio);
7004         return (CTL_RETVAL_COMPLETE);
7005 }
7006
7007 int
7008 ctl_read_defect(struct ctl_scsiio *ctsio)
7009 {
7010         struct scsi_read_defect_data_10 *ccb10;
7011         struct scsi_read_defect_data_12 *ccb12;
7012         struct scsi_read_defect_data_hdr_10 *data10;
7013         struct scsi_read_defect_data_hdr_12 *data12;
7014         uint32_t alloc_len, data_len;
7015         uint8_t format;
7016
7017         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7018
7019         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7020                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7021                 format = ccb10->format;
7022                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7023                 data_len = sizeof(*data10);
7024         } else {
7025                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7026                 format = ccb12->format;
7027                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7028                 data_len = sizeof(*data12);
7029         }
7030         if (alloc_len == 0) {
7031                 ctl_set_success(ctsio);
7032                 ctl_done((union ctl_io *)ctsio);
7033                 return (CTL_RETVAL_COMPLETE);
7034         }
7035
7036         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7037         if (data_len < alloc_len) {
7038                 ctsio->residual = alloc_len - data_len;
7039                 ctsio->kern_data_len = data_len;
7040                 ctsio->kern_total_len = data_len;
7041         } else {
7042                 ctsio->residual = 0;
7043                 ctsio->kern_data_len = alloc_len;
7044                 ctsio->kern_total_len = alloc_len;
7045         }
7046         ctsio->kern_data_resid = 0;
7047         ctsio->kern_rel_offset = 0;
7048         ctsio->kern_sg_entries = 0;
7049
7050         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7051                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7052                     ctsio->kern_data_ptr;
7053                 data10->format = format;
7054                 scsi_ulto2b(0, data10->length);
7055         } else {
7056                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7057                     ctsio->kern_data_ptr;
7058                 data12->format = format;
7059                 scsi_ulto2b(0, data12->generation);
7060                 scsi_ulto4b(0, data12->length);
7061         }
7062
7063         ctl_set_success(ctsio);
7064         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7065         ctsio->be_move_done = ctl_config_move_done;
7066         ctl_datamove((union ctl_io *)ctsio);
7067         return (CTL_RETVAL_COMPLETE);
7068 }
7069
7070 int
7071 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7072 {
7073         struct ctl_softc *softc = CTL_SOFTC(ctsio);
7074         struct ctl_lun *lun = CTL_LUN(ctsio);
7075         struct scsi_maintenance_in *cdb;
7076         int retval;
7077         int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7078         int num_ha_groups, num_target_ports, shared_group;
7079         struct ctl_port *port;
7080         struct scsi_target_group_data *rtg_ptr;
7081         struct scsi_target_group_data_extended *rtg_ext_ptr;
7082         struct scsi_target_port_group_descriptor *tpg_desc;
7083
7084         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7085
7086         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7087         retval = CTL_RETVAL_COMPLETE;
7088
7089         switch (cdb->byte2 & STG_PDF_MASK) {
7090         case STG_PDF_LENGTH:
7091                 ext = 0;
7092                 break;
7093         case STG_PDF_EXTENDED:
7094                 ext = 1;
7095                 break;
7096         default:
7097                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7098                                       /*sks_valid*/ 1,
7099                                       /*command*/ 1,
7100                                       /*field*/ 2,
7101                                       /*bit_valid*/ 1,
7102                                       /*bit*/ 5);
7103                 ctl_done((union ctl_io *)ctsio);
7104                 return(retval);
7105         }
7106
7107         num_target_ports = 0;
7108         shared_group = (softc->is_single != 0);
7109         mtx_lock(&softc->ctl_lock);
7110         STAILQ_FOREACH(port, &softc->port_list, links) {
7111                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7112                         continue;
7113                 if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7114                         continue;
7115                 num_target_ports++;
7116                 if (port->status & CTL_PORT_STATUS_HA_SHARED)
7117                         shared_group = 1;
7118         }
7119         mtx_unlock(&softc->ctl_lock);
7120         num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7121
7122         if (ext)
7123                 total_len = sizeof(struct scsi_target_group_data_extended);
7124         else
7125                 total_len = sizeof(struct scsi_target_group_data);
7126         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7127                 (shared_group + num_ha_groups) +
7128             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7129
7130         alloc_len = scsi_4btoul(cdb->length);
7131
7132         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7133
7134         ctsio->kern_sg_entries = 0;
7135
7136         if (total_len < alloc_len) {
7137                 ctsio->residual = alloc_len - total_len;
7138                 ctsio->kern_data_len = total_len;
7139                 ctsio->kern_total_len = total_len;
7140         } else {
7141                 ctsio->residual = 0;
7142                 ctsio->kern_data_len = alloc_len;
7143                 ctsio->kern_total_len = alloc_len;
7144         }
7145         ctsio->kern_data_resid = 0;
7146         ctsio->kern_rel_offset = 0;
7147
7148         if (ext) {
7149                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7150                     ctsio->kern_data_ptr;
7151                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7152                 rtg_ext_ptr->format_type = 0x10;
7153                 rtg_ext_ptr->implicit_transition_time = 0;
7154                 tpg_desc = &rtg_ext_ptr->groups[0];
7155         } else {
7156                 rtg_ptr = (struct scsi_target_group_data *)
7157                     ctsio->kern_data_ptr;
7158                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7159                 tpg_desc = &rtg_ptr->groups[0];
7160         }
7161
7162         mtx_lock(&softc->ctl_lock);
7163         pg = softc->port_min / softc->port_cnt;
7164         if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7165                 /* Some shelf is known to be primary. */
7166                 if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7167                         os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7168                 else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7169                         os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7170                 else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7171                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7172                 else
7173                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7174                 if (lun->flags & CTL_LUN_PRIMARY_SC) {
7175                         ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7176                 } else {
7177                         ts = os;
7178                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7179                 }
7180         } else {
7181                 /* No known primary shelf. */
7182                 if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7183                         ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7184                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7185                 } else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7186                         ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7187                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7188                 } else {
7189                         ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7190                 }
7191         }
7192         if (shared_group) {
7193                 tpg_desc->pref_state = ts;
7194                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7195                     TPG_U_SUP | TPG_T_SUP;
7196                 scsi_ulto2b(1, tpg_desc->target_port_group);
7197                 tpg_desc->status = TPG_IMPLICIT;
7198                 pc = 0;
7199                 STAILQ_FOREACH(port, &softc->port_list, links) {
7200                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7201                                 continue;
7202                         if (!softc->is_single &&
7203                             (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7204                                 continue;
7205                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7206                                 continue;
7207                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7208                             relative_target_port_identifier);
7209                         pc++;
7210                 }
7211                 tpg_desc->target_port_count = pc;
7212                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7213                     &tpg_desc->descriptors[pc];
7214         }
7215         for (g = 0; g < num_ha_groups; g++) {
7216                 tpg_desc->pref_state = (g == pg) ? ts : os;
7217                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7218                     TPG_U_SUP | TPG_T_SUP;
7219                 scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7220                 tpg_desc->status = TPG_IMPLICIT;
7221                 pc = 0;
7222                 STAILQ_FOREACH(port, &softc->port_list, links) {
7223                         if (port->targ_port < g * softc->port_cnt ||
7224                             port->targ_port >= (g + 1) * softc->port_cnt)
7225                                 continue;
7226                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7227                                 continue;
7228                         if (port->status & CTL_PORT_STATUS_HA_SHARED)
7229                                 continue;
7230                         if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7231                                 continue;
7232                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7233                             relative_target_port_identifier);
7234                         pc++;
7235                 }
7236                 tpg_desc->target_port_count = pc;
7237                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7238                     &tpg_desc->descriptors[pc];
7239         }
7240         mtx_unlock(&softc->ctl_lock);
7241
7242         ctl_set_success(ctsio);
7243         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7244         ctsio->be_move_done = ctl_config_move_done;
7245         ctl_datamove((union ctl_io *)ctsio);
7246         return(retval);
7247 }
7248
7249 int
7250 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7251 {
7252         struct ctl_lun *lun = CTL_LUN(ctsio);
7253         struct scsi_report_supported_opcodes *cdb;
7254         const struct ctl_cmd_entry *entry, *sentry;
7255         struct scsi_report_supported_opcodes_all *all;
7256         struct scsi_report_supported_opcodes_descr *descr;
7257         struct scsi_report_supported_opcodes_one *one;
7258         int retval;
7259         int alloc_len, total_len;
7260         int opcode, service_action, i, j, num;
7261
7262         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7263
7264         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7265         retval = CTL_RETVAL_COMPLETE;
7266
7267         opcode = cdb->requested_opcode;
7268         service_action = scsi_2btoul(cdb->requested_service_action);
7269         switch (cdb->options & RSO_OPTIONS_MASK) {
7270         case RSO_OPTIONS_ALL:
7271                 num = 0;
7272                 for (i = 0; i < 256; i++) {
7273                         entry = &ctl_cmd_table[i];
7274                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7275                                 for (j = 0; j < 32; j++) {
7276                                         sentry = &((const struct ctl_cmd_entry *)
7277                                             entry->execute)[j];
7278                                         if (ctl_cmd_applicable(
7279                                             lun->be_lun->lun_type, sentry))
7280                                                 num++;
7281                                 }
7282                         } else {
7283                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7284                                     entry))
7285                                         num++;
7286                         }
7287                 }
7288                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7289                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7290                 break;
7291         case RSO_OPTIONS_OC:
7292                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7293                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7294                                               /*sks_valid*/ 1,
7295                                               /*command*/ 1,
7296                                               /*field*/ 2,
7297                                               /*bit_valid*/ 1,
7298                                               /*bit*/ 2);
7299                         ctl_done((union ctl_io *)ctsio);
7300                         return (CTL_RETVAL_COMPLETE);
7301                 }
7302                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7303                 break;
7304         case RSO_OPTIONS_OC_SA:
7305                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7306                     service_action >= 32) {
7307                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7308                                               /*sks_valid*/ 1,
7309                                               /*command*/ 1,
7310                                               /*field*/ 2,
7311                                               /*bit_valid*/ 1,
7312                                               /*bit*/ 2);
7313                         ctl_done((union ctl_io *)ctsio);
7314                         return (CTL_RETVAL_COMPLETE);
7315                 }
7316                 /* FALLTHROUGH */
7317         case RSO_OPTIONS_OC_ASA:
7318                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7319                 break;
7320         default:
7321                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7322                                       /*sks_valid*/ 1,
7323                                       /*command*/ 1,
7324                                       /*field*/ 2,
7325                                       /*bit_valid*/ 1,
7326                                       /*bit*/ 2);
7327                 ctl_done((union ctl_io *)ctsio);
7328                 return (CTL_RETVAL_COMPLETE);
7329         }
7330
7331         alloc_len = scsi_4btoul(cdb->length);
7332
7333         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7334
7335         ctsio->kern_sg_entries = 0;
7336
7337         if (total_len < alloc_len) {
7338                 ctsio->residual = alloc_len - total_len;
7339                 ctsio->kern_data_len = total_len;
7340                 ctsio->kern_total_len = total_len;
7341         } else {
7342                 ctsio->residual = 0;
7343                 ctsio->kern_data_len = alloc_len;
7344                 ctsio->kern_total_len = alloc_len;
7345         }
7346         ctsio->kern_data_resid = 0;
7347         ctsio->kern_rel_offset = 0;
7348
7349         switch (cdb->options & RSO_OPTIONS_MASK) {
7350         case RSO_OPTIONS_ALL:
7351                 all = (struct scsi_report_supported_opcodes_all *)
7352                     ctsio->kern_data_ptr;
7353                 num = 0;
7354                 for (i = 0; i < 256; i++) {
7355                         entry = &ctl_cmd_table[i];
7356                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7357                                 for (j = 0; j < 32; j++) {
7358                                         sentry = &((const struct ctl_cmd_entry *)
7359                                             entry->execute)[j];
7360                                         if (!ctl_cmd_applicable(
7361                                             lun->be_lun->lun_type, sentry))
7362                                                 continue;
7363                                         descr = &all->descr[num++];
7364                                         descr->opcode = i;
7365                                         scsi_ulto2b(j, descr->service_action);
7366                                         descr->flags = RSO_SERVACTV;
7367                                         scsi_ulto2b(sentry->length,
7368                                             descr->cdb_length);
7369                                 }
7370                         } else {
7371                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7372                                     entry))
7373                                         continue;
7374                                 descr = &all->descr[num++];
7375                                 descr->opcode = i;
7376                                 scsi_ulto2b(0, descr->service_action);
7377                                 descr->flags = 0;
7378                                 scsi_ulto2b(entry->length, descr->cdb_length);
7379                         }
7380                 }
7381                 scsi_ulto4b(
7382                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7383                     all->length);
7384                 break;
7385         case RSO_OPTIONS_OC:
7386                 one = (struct scsi_report_supported_opcodes_one *)
7387                     ctsio->kern_data_ptr;
7388                 entry = &ctl_cmd_table[opcode];
7389                 goto fill_one;
7390         case RSO_OPTIONS_OC_SA:
7391                 one = (struct scsi_report_supported_opcodes_one *)
7392                     ctsio->kern_data_ptr;
7393                 entry = &ctl_cmd_table[opcode];
7394                 entry = &((const struct ctl_cmd_entry *)
7395                     entry->execute)[service_action];
7396 fill_one:
7397                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7398                         one->support = 3;
7399                         scsi_ulto2b(entry->length, one->cdb_length);
7400                         one->cdb_usage[0] = opcode;
7401                         memcpy(&one->cdb_usage[1], entry->usage,
7402                             entry->length - 1);
7403                 } else
7404                         one->support = 1;
7405                 break;
7406         case RSO_OPTIONS_OC_ASA:
7407                 one = (struct scsi_report_supported_opcodes_one *)
7408                     ctsio->kern_data_ptr;
7409                 entry = &ctl_cmd_table[opcode];
7410                 if (entry->flags & CTL_CMD_FLAG_SA5) {
7411                         entry = &((const struct ctl_cmd_entry *)
7412                             entry->execute)[service_action];
7413                 } else if (service_action != 0) {
7414                         one->support = 1;
7415                         break;
7416                 }
7417                 goto fill_one;
7418         }
7419
7420         ctl_set_success(ctsio);
7421         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7422         ctsio->be_move_done = ctl_config_move_done;
7423         ctl_datamove((union ctl_io *)ctsio);
7424         return(retval);
7425 }
7426
7427 int
7428 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7429 {
7430         struct scsi_report_supported_tmf *cdb;
7431         struct scsi_report_supported_tmf_ext_data *data;
7432         int retval;
7433         int alloc_len, total_len;
7434
7435         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7436
7437         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7438
7439         retval = CTL_RETVAL_COMPLETE;
7440
7441         if (cdb->options & RST_REPD)
7442                 total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7443         else
7444                 total_len = sizeof(struct scsi_report_supported_tmf_data);
7445         alloc_len = scsi_4btoul(cdb->length);
7446
7447         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7448
7449         ctsio->kern_sg_entries = 0;
7450
7451         if (total_len < alloc_len) {
7452                 ctsio->residual = alloc_len - total_len;
7453                 ctsio->kern_data_len = total_len;
7454                 ctsio->kern_total_len = total_len;
7455         } else {
7456                 ctsio->residual = 0;
7457                 ctsio->kern_data_len = alloc_len;
7458                 ctsio->kern_total_len = alloc_len;
7459         }
7460         ctsio->kern_data_resid = 0;
7461         ctsio->kern_rel_offset = 0;
7462
7463         data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7464         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7465             RST_TRS;
7466         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7467         data->length = total_len - 4;
7468
7469         ctl_set_success(ctsio);
7470         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7471         ctsio->be_move_done = ctl_config_move_done;
7472         ctl_datamove((union ctl_io *)ctsio);
7473         return (retval);
7474 }
7475
7476 int
7477 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7478 {
7479         struct scsi_report_timestamp *cdb;
7480         struct scsi_report_timestamp_data *data;
7481         struct timeval tv;
7482         int64_t timestamp;
7483         int retval;
7484         int alloc_len, total_len;
7485
7486         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7487
7488         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7489
7490         retval = CTL_RETVAL_COMPLETE;
7491
7492         total_len = sizeof(struct scsi_report_timestamp_data);
7493         alloc_len = scsi_4btoul(cdb->length);
7494
7495         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7496
7497         ctsio->kern_sg_entries = 0;
7498
7499         if (total_len < alloc_len) {
7500                 ctsio->residual = alloc_len - total_len;
7501                 ctsio->kern_data_len = total_len;
7502                 ctsio->kern_total_len = total_len;
7503         } else {
7504                 ctsio->residual = 0;
7505                 ctsio->kern_data_len = alloc_len;
7506                 ctsio->kern_total_len = alloc_len;
7507         }
7508         ctsio->kern_data_resid = 0;
7509         ctsio->kern_rel_offset = 0;
7510
7511         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7512         scsi_ulto2b(sizeof(*data) - 2, data->length);
7513         data->origin = RTS_ORIG_OUTSIDE;
7514         getmicrotime(&tv);
7515         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7516         scsi_ulto4b(timestamp >> 16, data->timestamp);
7517         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7518
7519         ctl_set_success(ctsio);
7520         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7521         ctsio->be_move_done = ctl_config_move_done;
7522         ctl_datamove((union ctl_io *)ctsio);
7523         return (retval);
7524 }
7525
7526 int
7527 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7528 {
7529         struct ctl_softc *softc = CTL_SOFTC(ctsio);
7530         struct ctl_lun *lun = CTL_LUN(ctsio);
7531         struct scsi_per_res_in *cdb;
7532         int alloc_len, total_len = 0;
7533         /* struct scsi_per_res_in_rsrv in_data; */
7534         uint64_t key;
7535
7536         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7537
7538         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7539
7540         alloc_len = scsi_2btoul(cdb->length);
7541
7542 retry:
7543         mtx_lock(&lun->lun_lock);
7544         switch (cdb->action) {
7545         case SPRI_RK: /* read keys */
7546                 total_len = sizeof(struct scsi_per_res_in_keys) +
7547                         lun->pr_key_count *
7548                         sizeof(struct scsi_per_res_key);
7549                 break;
7550         case SPRI_RR: /* read reservation */
7551                 if (lun->flags & CTL_LUN_PR_RESERVED)
7552                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7553                 else
7554                         total_len = sizeof(struct scsi_per_res_in_header);
7555                 break;
7556         case SPRI_RC: /* report capabilities */
7557                 total_len = sizeof(struct scsi_per_res_cap);
7558                 break;
7559         case SPRI_RS: /* read full status */
7560                 total_len = sizeof(struct scsi_per_res_in_header) +
7561                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7562                     lun->pr_key_count;
7563                 break;
7564         default:
7565                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7566         }
7567         mtx_unlock(&lun->lun_lock);
7568
7569         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7570
7571         if (total_len < alloc_len) {
7572                 ctsio->residual = alloc_len - total_len;
7573                 ctsio->kern_data_len = total_len;
7574                 ctsio->kern_total_len = total_len;
7575         } else {
7576                 ctsio->residual = 0;
7577                 ctsio->kern_data_len = alloc_len;
7578                 ctsio->kern_total_len = alloc_len;
7579         }
7580
7581         ctsio->kern_data_resid = 0;
7582         ctsio->kern_rel_offset = 0;
7583         ctsio->kern_sg_entries = 0;
7584
7585         mtx_lock(&lun->lun_lock);
7586         switch (cdb->action) {
7587         case SPRI_RK: { // read keys
7588         struct scsi_per_res_in_keys *res_keys;
7589                 int i, key_count;
7590
7591                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7592
7593                 /*
7594                  * We had to drop the lock to allocate our buffer, which
7595                  * leaves time for someone to come in with another
7596                  * persistent reservation.  (That is unlikely, though,
7597                  * since this should be the only persistent reservation
7598                  * command active right now.)
7599                  */
7600                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7601                     (lun->pr_key_count *
7602                      sizeof(struct scsi_per_res_key)))){
7603                         mtx_unlock(&lun->lun_lock);
7604                         free(ctsio->kern_data_ptr, M_CTL);
7605                         printf("%s: reservation length changed, retrying\n",
7606                                __func__);
7607                         goto retry;
7608                 }
7609
7610                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7611
7612                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7613                              lun->pr_key_count, res_keys->header.length);
7614
7615                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7616                         if ((key = ctl_get_prkey(lun, i)) == 0)
7617                                 continue;
7618
7619                         /*
7620                          * We used lun->pr_key_count to calculate the
7621                          * size to allocate.  If it turns out the number of
7622                          * initiators with the registered flag set is
7623                          * larger than that (i.e. they haven't been kept in
7624                          * sync), we've got a problem.
7625                          */
7626                         if (key_count >= lun->pr_key_count) {
7627                                 key_count++;
7628                                 continue;
7629                         }
7630                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7631                         key_count++;
7632                 }
7633                 break;
7634         }
7635         case SPRI_RR: { // read reservation
7636                 struct scsi_per_res_in_rsrv *res;
7637                 int tmp_len, header_only;
7638
7639                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7640
7641                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7642
7643                 if (lun->flags & CTL_LUN_PR_RESERVED)
7644                 {
7645                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7646                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7647                                     res->header.length);
7648                         header_only = 0;
7649                 } else {
7650                         tmp_len = sizeof(struct scsi_per_res_in_header);
7651                         scsi_ulto4b(0, res->header.length);
7652                         header_only = 1;
7653                 }
7654
7655                 /*
7656                  * We had to drop the lock to allocate our buffer, which
7657                  * leaves time for someone to come in with another
7658                  * persistent reservation.  (That is unlikely, though,
7659                  * since this should be the only persistent reservation
7660                  * command active right now.)
7661                  */
7662                 if (tmp_len != total_len) {
7663                         mtx_unlock(&lun->lun_lock);
7664                         free(ctsio->kern_data_ptr, M_CTL);
7665                         printf("%s: reservation status changed, retrying\n",
7666                                __func__);
7667                         goto retry;
7668                 }
7669
7670                 /*
7671                  * No reservation held, so we're done.
7672                  */
7673                 if (header_only != 0)
7674                         break;
7675
7676                 /*
7677                  * If the registration is an All Registrants type, the key
7678                  * is 0, since it doesn't really matter.
7679                  */
7680                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7681                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7682                             res->data.reservation);
7683                 }
7684                 res->data.scopetype = lun->pr_res_type;
7685                 break;
7686         }
7687         case SPRI_RC:     //report capabilities
7688         {
7689                 struct scsi_per_res_cap *res_cap;
7690                 uint16_t type_mask;
7691
7692                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7693                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7694                 res_cap->flags1 = SPRI_CRH;
7695                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7696                 type_mask = SPRI_TM_WR_EX_AR |
7697                             SPRI_TM_EX_AC_RO |
7698                             SPRI_TM_WR_EX_RO |
7699                             SPRI_TM_EX_AC |
7700                             SPRI_TM_WR_EX |
7701                             SPRI_TM_EX_AC_AR;
7702                 scsi_ulto2b(type_mask, res_cap->type_mask);
7703                 break;
7704         }
7705         case SPRI_RS: { // read full status
7706                 struct scsi_per_res_in_full *res_status;
7707                 struct scsi_per_res_in_full_desc *res_desc;
7708                 struct ctl_port *port;
7709                 int i, len;
7710
7711                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7712
7713                 /*
7714                  * We had to drop the lock to allocate our buffer, which
7715                  * leaves time for someone to come in with another
7716                  * persistent reservation.  (That is unlikely, though,
7717                  * since this should be the only persistent reservation
7718                  * command active right now.)
7719                  */
7720                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7721                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7722                      lun->pr_key_count)){
7723                         mtx_unlock(&lun->lun_lock);
7724                         free(ctsio->kern_data_ptr, M_CTL);
7725                         printf("%s: reservation length changed, retrying\n",
7726                                __func__);
7727                         goto retry;
7728                 }
7729
7730                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7731
7732                 res_desc = &res_status->desc[0];
7733                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7734                         if ((key = ctl_get_prkey(lun, i)) == 0)
7735                                 continue;
7736
7737                         scsi_u64to8b(key, res_desc->res_key.key);
7738                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7739                             (lun->pr_res_idx == i ||
7740                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7741                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7742                                 res_desc->scopetype = lun->pr_res_type;
7743                         }
7744                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7745                             res_desc->rel_trgt_port_id);
7746                         len = 0;
7747                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7748                         if (port != NULL)
7749                                 len = ctl_create_iid(port,
7750                                     i % CTL_MAX_INIT_PER_PORT,
7751                                     res_desc->transport_id);
7752                         scsi_ulto4b(len, res_desc->additional_length);
7753                         res_desc = (struct scsi_per_res_in_full_desc *)
7754                             &res_desc->transport_id[len];
7755                 }
7756                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7757                     res_status->header.length);
7758                 break;
7759         }
7760         default:
7761                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7762         }
7763         mtx_unlock(&lun->lun_lock);
7764
7765         ctl_set_success(ctsio);
7766         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7767         ctsio->be_move_done = ctl_config_move_done;
7768         ctl_datamove((union ctl_io *)ctsio);
7769         return (CTL_RETVAL_COMPLETE);
7770 }
7771
7772 /*
7773  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7774  * it should return.
7775  */
7776 static int
7777 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7778                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7779                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7780                 struct scsi_per_res_out_parms* param)
7781 {
7782         union ctl_ha_msg persis_io;
7783         int i;
7784
7785         mtx_lock(&lun->lun_lock);
7786         if (sa_res_key == 0) {
7787                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7788                         /* validate scope and type */
7789                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7790                              SPR_LU_SCOPE) {
7791                                 mtx_unlock(&lun->lun_lock);
7792                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7793                                                       /*sks_valid*/ 1,
7794                                                       /*command*/ 1,
7795                                                       /*field*/ 2,
7796                                                       /*bit_valid*/ 1,
7797                                                       /*bit*/ 4);
7798                                 ctl_done((union ctl_io *)ctsio);
7799                                 return (1);
7800                         }
7801
7802                         if (type>8 || type==2 || type==4 || type==0) {
7803                                 mtx_unlock(&lun->lun_lock);
7804                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7805                                                       /*sks_valid*/ 1,
7806                                                       /*command*/ 1,
7807                                                       /*field*/ 2,
7808                                                       /*bit_valid*/ 1,
7809                                                       /*bit*/ 0);
7810                                 ctl_done((union ctl_io *)ctsio);
7811                                 return (1);
7812                         }
7813
7814                         /*
7815                          * Unregister everybody else and build UA for
7816                          * them
7817                          */
7818                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7819                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7820                                         continue;
7821
7822                                 ctl_clr_prkey(lun, i);
7823                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7824                         }
7825                         lun->pr_key_count = 1;
7826                         lun->pr_res_type = type;
7827                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7828                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7829                                 lun->pr_res_idx = residx;
7830                         lun->pr_generation++;
7831                         mtx_unlock(&lun->lun_lock);
7832
7833                         /* send msg to other side */
7834                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7835                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7836                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7837                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7838                         persis_io.pr.pr_info.res_type = type;
7839                         memcpy(persis_io.pr.pr_info.sa_res_key,
7840                                param->serv_act_res_key,
7841                                sizeof(param->serv_act_res_key));
7842                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7843                             sizeof(persis_io.pr), M_WAITOK);
7844                 } else {
7845                         /* not all registrants */
7846                         mtx_unlock(&lun->lun_lock);
7847                         free(ctsio->kern_data_ptr, M_CTL);
7848                         ctl_set_invalid_field(ctsio,
7849                                               /*sks_valid*/ 1,
7850                                               /*command*/ 0,
7851                                               /*field*/ 8,
7852                                               /*bit_valid*/ 0,
7853                                               /*bit*/ 0);
7854                         ctl_done((union ctl_io *)ctsio);
7855                         return (1);
7856                 }
7857         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7858                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7859                 int found = 0;
7860
7861                 if (res_key == sa_res_key) {
7862                         /* special case */
7863                         /*
7864                          * The spec implies this is not good but doesn't
7865                          * say what to do. There are two choices either
7866                          * generate a res conflict or check condition
7867                          * with illegal field in parameter data. Since
7868                          * that is what is done when the sa_res_key is
7869                          * zero I'll take that approach since this has
7870                          * to do with the sa_res_key.
7871                          */
7872                         mtx_unlock(&lun->lun_lock);
7873                         free(ctsio->kern_data_ptr, M_CTL);
7874                         ctl_set_invalid_field(ctsio,
7875                                               /*sks_valid*/ 1,
7876                                               /*command*/ 0,
7877                                               /*field*/ 8,
7878                                               /*bit_valid*/ 0,
7879                                               /*bit*/ 0);
7880                         ctl_done((union ctl_io *)ctsio);
7881                         return (1);
7882                 }
7883
7884                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7885                         if (ctl_get_prkey(lun, i) != sa_res_key)
7886                                 continue;
7887
7888                         found = 1;
7889                         ctl_clr_prkey(lun, i);
7890                         lun->pr_key_count--;
7891                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7892                 }
7893                 if (!found) {
7894                         mtx_unlock(&lun->lun_lock);
7895                         free(ctsio->kern_data_ptr, M_CTL);
7896                         ctl_set_reservation_conflict(ctsio);
7897                         ctl_done((union ctl_io *)ctsio);
7898                         return (CTL_RETVAL_COMPLETE);
7899                 }
7900                 lun->pr_generation++;
7901                 mtx_unlock(&lun->lun_lock);
7902
7903                 /* send msg to other side */
7904                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7905                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7906                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7907                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7908                 persis_io.pr.pr_info.res_type = type;
7909                 memcpy(persis_io.pr.pr_info.sa_res_key,
7910                        param->serv_act_res_key,
7911                        sizeof(param->serv_act_res_key));
7912                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7913                     sizeof(persis_io.pr), M_WAITOK);
7914         } else {
7915                 /* Reserved but not all registrants */
7916                 /* sa_res_key is res holder */
7917                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7918                         /* validate scope and type */
7919                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7920                              SPR_LU_SCOPE) {
7921                                 mtx_unlock(&lun->lun_lock);
7922                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7923                                                       /*sks_valid*/ 1,
7924                                                       /*command*/ 1,
7925                                                       /*field*/ 2,
7926                                                       /*bit_valid*/ 1,
7927                                                       /*bit*/ 4);
7928                                 ctl_done((union ctl_io *)ctsio);
7929                                 return (1);
7930                         }
7931
7932                         if (type>8 || type==2 || type==4 || type==0) {
7933                                 mtx_unlock(&lun->lun_lock);
7934                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7935                                                       /*sks_valid*/ 1,
7936                                                       /*command*/ 1,
7937                                                       /*field*/ 2,
7938                                                       /*bit_valid*/ 1,
7939                                                       /*bit*/ 0);
7940                                 ctl_done((union ctl_io *)ctsio);
7941                                 return (1);
7942                         }
7943
7944                         /*
7945                          * Do the following:
7946                          * if sa_res_key != res_key remove all
7947                          * registrants w/sa_res_key and generate UA
7948                          * for these registrants(Registrations
7949                          * Preempted) if it wasn't an exclusive
7950                          * reservation generate UA(Reservations
7951                          * Preempted) for all other registered nexuses
7952                          * if the type has changed. Establish the new
7953                          * reservation and holder. If res_key and
7954                          * sa_res_key are the same do the above
7955                          * except don't unregister the res holder.
7956                          */
7957
7958                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7959                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7960                                         continue;
7961
7962                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7963                                         ctl_clr_prkey(lun, i);
7964                                         lun->pr_key_count--;
7965                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7966                                 } else if (type != lun->pr_res_type &&
7967                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7968                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7969                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7970                                 }
7971                         }
7972                         lun->pr_res_type = type;
7973                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7974                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7975                                 lun->pr_res_idx = residx;
7976                         else
7977                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7978                         lun->pr_generation++;
7979                         mtx_unlock(&lun->lun_lock);
7980
7981                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7982                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7983                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7984                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7985                         persis_io.pr.pr_info.res_type = type;
7986                         memcpy(persis_io.pr.pr_info.sa_res_key,
7987                                param->serv_act_res_key,
7988                                sizeof(param->serv_act_res_key));
7989                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7990                             sizeof(persis_io.pr), M_WAITOK);
7991                 } else {
7992                         /*
7993                          * sa_res_key is not the res holder just
7994                          * remove registrants
7995                          */
7996                         int found=0;
7997
7998                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7999                                 if (sa_res_key != ctl_get_prkey(lun, i))
8000                                         continue;
8001
8002                                 found = 1;
8003                                 ctl_clr_prkey(lun, i);
8004                                 lun->pr_key_count--;
8005                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8006                         }
8007
8008                         if (!found) {
8009                                 mtx_unlock(&lun->lun_lock);
8010                                 free(ctsio->kern_data_ptr, M_CTL);
8011                                 ctl_set_reservation_conflict(ctsio);
8012                                 ctl_done((union ctl_io *)ctsio);
8013                                 return (1);
8014                         }
8015                         lun->pr_generation++;
8016                         mtx_unlock(&lun->lun_lock);
8017
8018                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8019                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8020                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8021                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8022                         persis_io.pr.pr_info.res_type = type;
8023                         memcpy(persis_io.pr.pr_info.sa_res_key,
8024                                param->serv_act_res_key,
8025                                sizeof(param->serv_act_res_key));
8026                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8027                             sizeof(persis_io.pr), M_WAITOK);
8028                 }
8029         }
8030         return (0);
8031 }
8032
8033 static void
8034 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8035 {
8036         uint64_t sa_res_key;
8037         int i;
8038
8039         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8040
8041         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8042          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8043          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8044                 if (sa_res_key == 0) {
8045                         /*
8046                          * Unregister everybody else and build UA for
8047                          * them
8048                          */
8049                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8050                                 if (i == msg->pr.pr_info.residx ||
8051                                     ctl_get_prkey(lun, i) == 0)
8052                                         continue;
8053
8054                                 ctl_clr_prkey(lun, i);
8055                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8056                         }
8057
8058                         lun->pr_key_count = 1;
8059                         lun->pr_res_type = msg->pr.pr_info.res_type;
8060                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8061                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8062                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8063                 } else {
8064                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8065                                 if (sa_res_key == ctl_get_prkey(lun, i))
8066                                         continue;
8067
8068                                 ctl_clr_prkey(lun, i);
8069                                 lun->pr_key_count--;
8070                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8071                         }
8072                 }
8073         } else {
8074                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8075                         if (i == msg->pr.pr_info.residx ||
8076                             ctl_get_prkey(lun, i) == 0)
8077                                 continue;
8078
8079                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8080                                 ctl_clr_prkey(lun, i);
8081                                 lun->pr_key_count--;
8082                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8083                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8084                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8085                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8086                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8087                         }
8088                 }
8089                 lun->pr_res_type = msg->pr.pr_info.res_type;
8090                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8091                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8092                         lun->pr_res_idx = msg->pr.pr_info.residx;
8093                 else
8094                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8095         }
8096         lun->pr_generation++;
8097
8098 }
8099
8100
8101 int
8102 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8103 {
8104         struct ctl_softc *softc = CTL_SOFTC(ctsio);
8105         struct ctl_lun *lun = CTL_LUN(ctsio);
8106         int retval;
8107         u_int32_t param_len;
8108         struct scsi_per_res_out *cdb;
8109         struct scsi_per_res_out_parms* param;
8110         uint32_t residx;
8111         uint64_t res_key, sa_res_key, key;
8112         uint8_t type;
8113         union ctl_ha_msg persis_io;
8114         int    i;
8115
8116         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8117
8118         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8119         retval = CTL_RETVAL_COMPLETE;
8120
8121         /*
8122          * We only support whole-LUN scope.  The scope & type are ignored for
8123          * register, register and ignore existing key and clear.
8124          * We sometimes ignore scope and type on preempts too!!
8125          * Verify reservation type here as well.
8126          */
8127         type = cdb->scope_type & SPR_TYPE_MASK;
8128         if ((cdb->action == SPRO_RESERVE)
8129          || (cdb->action == SPRO_RELEASE)) {
8130                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8131                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8132                                               /*sks_valid*/ 1,
8133                                               /*command*/ 1,
8134                                               /*field*/ 2,
8135                                               /*bit_valid*/ 1,
8136                                               /*bit*/ 4);
8137                         ctl_done((union ctl_io *)ctsio);
8138                         return (CTL_RETVAL_COMPLETE);
8139                 }
8140
8141                 if (type>8 || type==2 || type==4 || type==0) {
8142                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8143                                               /*sks_valid*/ 1,
8144                                               /*command*/ 1,
8145                                               /*field*/ 2,
8146                                               /*bit_valid*/ 1,
8147                                               /*bit*/ 0);
8148                         ctl_done((union ctl_io *)ctsio);
8149                         return (CTL_RETVAL_COMPLETE);
8150                 }
8151         }
8152
8153         param_len = scsi_4btoul(cdb->length);
8154
8155         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8156                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8157                 ctsio->kern_data_len = param_len;
8158                 ctsio->kern_total_len = param_len;
8159                 ctsio->kern_data_resid = 0;
8160                 ctsio->kern_rel_offset = 0;
8161                 ctsio->kern_sg_entries = 0;
8162                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8163                 ctsio->be_move_done = ctl_config_move_done;
8164                 ctl_datamove((union ctl_io *)ctsio);
8165
8166                 return (CTL_RETVAL_COMPLETE);
8167         }
8168
8169         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8170
8171         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8172         res_key = scsi_8btou64(param->res_key.key);
8173         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8174
8175         /*
8176          * Validate the reservation key here except for SPRO_REG_IGNO
8177          * This must be done for all other service actions
8178          */
8179         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8180                 mtx_lock(&lun->lun_lock);
8181                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8182                         if (res_key != key) {
8183                                 /*
8184                                  * The current key passed in doesn't match
8185                                  * the one the initiator previously
8186                                  * registered.
8187                                  */
8188                                 mtx_unlock(&lun->lun_lock);
8189                                 free(ctsio->kern_data_ptr, M_CTL);
8190                                 ctl_set_reservation_conflict(ctsio);
8191                                 ctl_done((union ctl_io *)ctsio);
8192                                 return (CTL_RETVAL_COMPLETE);
8193                         }
8194                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8195                         /*
8196                          * We are not registered
8197                          */
8198                         mtx_unlock(&lun->lun_lock);
8199                         free(ctsio->kern_data_ptr, M_CTL);
8200                         ctl_set_reservation_conflict(ctsio);
8201                         ctl_done((union ctl_io *)ctsio);
8202                         return (CTL_RETVAL_COMPLETE);
8203                 } else if (res_key != 0) {
8204                         /*
8205                          * We are not registered and trying to register but
8206                          * the register key isn't zero.
8207                          */
8208                         mtx_unlock(&lun->lun_lock);
8209                         free(ctsio->kern_data_ptr, M_CTL);
8210                         ctl_set_reservation_conflict(ctsio);
8211                         ctl_done((union ctl_io *)ctsio);
8212                         return (CTL_RETVAL_COMPLETE);
8213                 }
8214                 mtx_unlock(&lun->lun_lock);
8215         }
8216
8217         switch (cdb->action & SPRO_ACTION_MASK) {
8218         case SPRO_REGISTER:
8219         case SPRO_REG_IGNO: {
8220
8221 #if 0
8222                 printf("Registration received\n");
8223 #endif
8224
8225                 /*
8226                  * We don't support any of these options, as we report in
8227                  * the read capabilities request (see
8228                  * ctl_persistent_reserve_in(), above).
8229                  */
8230                 if ((param->flags & SPR_SPEC_I_PT)
8231                  || (param->flags & SPR_ALL_TG_PT)
8232                  || (param->flags & SPR_APTPL)) {
8233                         int bit_ptr;
8234
8235                         if (param->flags & SPR_APTPL)
8236                                 bit_ptr = 0;
8237                         else if (param->flags & SPR_ALL_TG_PT)
8238                                 bit_ptr = 2;
8239                         else /* SPR_SPEC_I_PT */
8240                                 bit_ptr = 3;
8241
8242                         free(ctsio->kern_data_ptr, M_CTL);
8243                         ctl_set_invalid_field(ctsio,
8244                                               /*sks_valid*/ 1,
8245                                               /*command*/ 0,
8246                                               /*field*/ 20,
8247                                               /*bit_valid*/ 1,
8248                                               /*bit*/ bit_ptr);
8249                         ctl_done((union ctl_io *)ctsio);
8250                         return (CTL_RETVAL_COMPLETE);
8251                 }
8252
8253                 mtx_lock(&lun->lun_lock);
8254
8255                 /*
8256                  * The initiator wants to clear the
8257                  * key/unregister.
8258                  */
8259                 if (sa_res_key == 0) {
8260                         if ((res_key == 0
8261                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8262                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8263                           && ctl_get_prkey(lun, residx) == 0)) {
8264                                 mtx_unlock(&lun->lun_lock);
8265                                 goto done;
8266                         }
8267
8268                         ctl_clr_prkey(lun, residx);
8269                         lun->pr_key_count--;
8270
8271                         if (residx == lun->pr_res_idx) {
8272                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8273                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8274
8275                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8276                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8277                                     lun->pr_key_count) {
8278                                         /*
8279                                          * If the reservation is a registrants
8280                                          * only type we need to generate a UA
8281                                          * for other registered inits.  The
8282                                          * sense code should be RESERVATIONS
8283                                          * RELEASED
8284                                          */
8285
8286                                         for (i = softc->init_min; i < softc->init_max; i++){
8287                                                 if (ctl_get_prkey(lun, i) == 0)
8288                                                         continue;
8289                                                 ctl_est_ua(lun, i,
8290                                                     CTL_UA_RES_RELEASE);
8291                                         }
8292                                 }
8293                                 lun->pr_res_type = 0;
8294                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8295                                 if (lun->pr_key_count==0) {
8296                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8297                                         lun->pr_res_type = 0;
8298                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8299                                 }
8300                         }
8301                         lun->pr_generation++;
8302                         mtx_unlock(&lun->lun_lock);
8303
8304                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8305                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8306                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8307                         persis_io.pr.pr_info.residx = residx;
8308                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8309                             sizeof(persis_io.pr), M_WAITOK);
8310                 } else /* sa_res_key != 0 */ {
8311
8312                         /*
8313                          * If we aren't registered currently then increment
8314                          * the key count and set the registered flag.
8315                          */
8316                         ctl_alloc_prkey(lun, residx);
8317                         if (ctl_get_prkey(lun, residx) == 0)
8318                                 lun->pr_key_count++;
8319                         ctl_set_prkey(lun, residx, sa_res_key);
8320                         lun->pr_generation++;
8321                         mtx_unlock(&lun->lun_lock);
8322
8323                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8324                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8325                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8326                         persis_io.pr.pr_info.residx = residx;
8327                         memcpy(persis_io.pr.pr_info.sa_res_key,
8328                                param->serv_act_res_key,
8329                                sizeof(param->serv_act_res_key));
8330                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8331                             sizeof(persis_io.pr), M_WAITOK);
8332                 }
8333
8334                 break;
8335         }
8336         case SPRO_RESERVE:
8337 #if 0
8338                 printf("Reserve executed type %d\n", type);
8339 #endif
8340                 mtx_lock(&lun->lun_lock);
8341                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8342                         /*
8343                          * if this isn't the reservation holder and it's
8344                          * not a "all registrants" type or if the type is
8345                          * different then we have a conflict
8346                          */
8347                         if ((lun->pr_res_idx != residx
8348                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8349                          || lun->pr_res_type != type) {
8350                                 mtx_unlock(&lun->lun_lock);
8351                                 free(ctsio->kern_data_ptr, M_CTL);
8352                                 ctl_set_reservation_conflict(ctsio);
8353                                 ctl_done((union ctl_io *)ctsio);
8354                                 return (CTL_RETVAL_COMPLETE);
8355                         }
8356                         mtx_unlock(&lun->lun_lock);
8357                 } else /* create a reservation */ {
8358                         /*
8359                          * If it's not an "all registrants" type record
8360                          * reservation holder
8361                          */
8362                         if (type != SPR_TYPE_WR_EX_AR
8363                          && type != SPR_TYPE_EX_AC_AR)
8364                                 lun->pr_res_idx = residx; /* Res holder */
8365                         else
8366                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8367
8368                         lun->flags |= CTL_LUN_PR_RESERVED;
8369                         lun->pr_res_type = type;
8370
8371                         mtx_unlock(&lun->lun_lock);
8372
8373                         /* send msg to other side */
8374                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8375                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8376                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8377                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8378                         persis_io.pr.pr_info.res_type = type;
8379                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8380                             sizeof(persis_io.pr), M_WAITOK);
8381                 }
8382                 break;
8383
8384         case SPRO_RELEASE:
8385                 mtx_lock(&lun->lun_lock);
8386                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8387                         /* No reservation exists return good status */
8388                         mtx_unlock(&lun->lun_lock);
8389                         goto done;
8390                 }
8391                 /*
8392                  * Is this nexus a reservation holder?
8393                  */
8394                 if (lun->pr_res_idx != residx
8395                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8396                         /*
8397                          * not a res holder return good status but
8398                          * do nothing
8399                          */
8400                         mtx_unlock(&lun->lun_lock);
8401                         goto done;
8402                 }
8403
8404                 if (lun->pr_res_type != type) {
8405                         mtx_unlock(&lun->lun_lock);
8406                         free(ctsio->kern_data_ptr, M_CTL);
8407                         ctl_set_illegal_pr_release(ctsio);
8408                         ctl_done((union ctl_io *)ctsio);
8409                         return (CTL_RETVAL_COMPLETE);
8410                 }
8411
8412                 /* okay to release */
8413                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8414                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8415                 lun->pr_res_type = 0;
8416
8417                 /*
8418                  * If this isn't an exclusive access reservation and NUAR
8419                  * is not set, generate UA for all other registrants.
8420                  */
8421                 if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8422                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8423                         for (i = softc->init_min; i < softc->init_max; i++) {
8424                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8425                                         continue;
8426                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8427                         }
8428                 }
8429                 mtx_unlock(&lun->lun_lock);
8430
8431                 /* Send msg to other side */
8432                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8433                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8434                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8435                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8436                      sizeof(persis_io.pr), M_WAITOK);
8437                 break;
8438
8439         case SPRO_CLEAR:
8440                 /* send msg to other side */
8441
8442                 mtx_lock(&lun->lun_lock);
8443                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8444                 lun->pr_res_type = 0;
8445                 lun->pr_key_count = 0;
8446                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8447
8448                 ctl_clr_prkey(lun, residx);
8449                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8450                         if (ctl_get_prkey(lun, i) != 0) {
8451                                 ctl_clr_prkey(lun, i);
8452                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8453                         }
8454                 lun->pr_generation++;
8455                 mtx_unlock(&lun->lun_lock);
8456
8457                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8458                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8459                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8460                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8461                      sizeof(persis_io.pr), M_WAITOK);
8462                 break;
8463
8464         case SPRO_PREEMPT:
8465         case SPRO_PRE_ABO: {
8466                 int nretval;
8467
8468                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8469                                           residx, ctsio, cdb, param);
8470                 if (nretval != 0)
8471                         return (CTL_RETVAL_COMPLETE);
8472                 break;
8473         }
8474         default:
8475                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8476         }
8477
8478 done:
8479         free(ctsio->kern_data_ptr, M_CTL);
8480         ctl_set_success(ctsio);
8481         ctl_done((union ctl_io *)ctsio);
8482
8483         return (retval);
8484 }
8485
8486 /*
8487  * This routine is for handling a message from the other SC pertaining to
8488  * persistent reserve out. All the error checking will have been done
8489  * so only perorming the action need be done here to keep the two
8490  * in sync.
8491  */
8492 static void
8493 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8494 {
8495         struct ctl_softc *softc = CTL_SOFTC(io);
8496         union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8497         struct ctl_lun *lun;
8498         int i;
8499         uint32_t residx, targ_lun;
8500
8501         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8502         mtx_lock(&softc->ctl_lock);
8503         if (targ_lun >= CTL_MAX_LUNS ||
8504             (lun = softc->ctl_luns[targ_lun]) == NULL) {
8505                 mtx_unlock(&softc->ctl_lock);
8506                 return;
8507         }
8508         mtx_lock(&lun->lun_lock);
8509         mtx_unlock(&softc->ctl_lock);
8510         if (lun->flags & CTL_LUN_DISABLED) {
8511                 mtx_unlock(&lun->lun_lock);
8512                 return;
8513         }
8514         residx = ctl_get_initindex(&msg->hdr.nexus);
8515         switch(msg->pr.pr_info.action) {
8516         case CTL_PR_REG_KEY:
8517                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8518                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8519                         lun->pr_key_count++;
8520                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8521                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8522                 lun->pr_generation++;
8523                 break;
8524
8525         case CTL_PR_UNREG_KEY:
8526                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8527                 lun->pr_key_count--;
8528
8529                 /* XXX Need to see if the reservation has been released */
8530                 /* if so do we need to generate UA? */
8531                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8532                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8533                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8534
8535                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8536                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8537                             lun->pr_key_count) {
8538                                 /*
8539                                  * If the reservation is a registrants
8540                                  * only type we need to generate a UA
8541                                  * for other registered inits.  The
8542                                  * sense code should be RESERVATIONS
8543                                  * RELEASED
8544                                  */
8545
8546                                 for (i = softc->init_min; i < softc->init_max; i++) {
8547                                         if (ctl_get_prkey(lun, i) == 0)
8548                                                 continue;
8549
8550                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8551                                 }
8552                         }
8553                         lun->pr_res_type = 0;
8554                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8555                         if (lun->pr_key_count==0) {
8556                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8557                                 lun->pr_res_type = 0;
8558                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8559                         }
8560                 }
8561                 lun->pr_generation++;
8562                 break;
8563
8564         case CTL_PR_RESERVE:
8565                 lun->flags |= CTL_LUN_PR_RESERVED;
8566                 lun->pr_res_type = msg->pr.pr_info.res_type;
8567                 lun->pr_res_idx = msg->pr.pr_info.residx;
8568
8569                 break;
8570
8571         case CTL_PR_RELEASE:
8572                 /*
8573                  * If this isn't an exclusive access reservation and NUAR
8574                  * is not set, generate UA for all other registrants.
8575                  */
8576                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8577                     lun->pr_res_type != SPR_TYPE_WR_EX &&
8578                     (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8579                         for (i = softc->init_min; i < softc->init_max; i++)
8580                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8581                                         continue;
8582                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8583                 }
8584
8585                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8586                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8587                 lun->pr_res_type = 0;
8588                 break;
8589
8590         case CTL_PR_PREEMPT:
8591                 ctl_pro_preempt_other(lun, msg);
8592                 break;
8593         case CTL_PR_CLEAR:
8594                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8595                 lun->pr_res_type = 0;
8596                 lun->pr_key_count = 0;
8597                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8598
8599                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8600                         if (ctl_get_prkey(lun, i) == 0)
8601                                 continue;
8602                         ctl_clr_prkey(lun, i);
8603                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8604                 }
8605                 lun->pr_generation++;
8606                 break;
8607         }
8608
8609         mtx_unlock(&lun->lun_lock);
8610 }
8611
8612 int
8613 ctl_read_write(struct ctl_scsiio *ctsio)
8614 {
8615         struct ctl_lun *lun = CTL_LUN(ctsio);
8616         struct ctl_lba_len_flags *lbalen;
8617         uint64_t lba;
8618         uint32_t num_blocks;
8619         int flags, retval;
8620         int isread;
8621
8622         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8623
8624         flags = 0;
8625         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8626               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8627         switch (ctsio->cdb[0]) {
8628         case READ_6:
8629         case WRITE_6: {
8630                 struct scsi_rw_6 *cdb;
8631
8632                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8633
8634                 lba = scsi_3btoul(cdb->addr);
8635                 /* only 5 bits are valid in the most significant address byte */
8636                 lba &= 0x1fffff;
8637                 num_blocks = cdb->length;
8638                 /*
8639                  * This is correct according to SBC-2.
8640                  */
8641                 if (num_blocks == 0)
8642                         num_blocks = 256;
8643                 break;
8644         }
8645         case READ_10:
8646         case WRITE_10: {
8647                 struct scsi_rw_10 *cdb;
8648
8649                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8650                 if (cdb->byte2 & SRW10_FUA)
8651                         flags |= CTL_LLF_FUA;
8652                 if (cdb->byte2 & SRW10_DPO)
8653                         flags |= CTL_LLF_DPO;
8654                 lba = scsi_4btoul(cdb->addr);
8655                 num_blocks = scsi_2btoul(cdb->length);
8656                 break;
8657         }
8658         case WRITE_VERIFY_10: {
8659                 struct scsi_write_verify_10 *cdb;
8660
8661                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8662                 flags |= CTL_LLF_FUA;
8663                 if (cdb->byte2 & SWV_DPO)
8664                         flags |= CTL_LLF_DPO;
8665                 lba = scsi_4btoul(cdb->addr);
8666                 num_blocks = scsi_2btoul(cdb->length);
8667                 break;
8668         }
8669         case READ_12:
8670         case WRITE_12: {
8671                 struct scsi_rw_12 *cdb;
8672
8673                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8674                 if (cdb->byte2 & SRW12_FUA)
8675                         flags |= CTL_LLF_FUA;
8676                 if (cdb->byte2 & SRW12_DPO)
8677                         flags |= CTL_LLF_DPO;
8678                 lba = scsi_4btoul(cdb->addr);
8679                 num_blocks = scsi_4btoul(cdb->length);
8680                 break;
8681         }
8682         case WRITE_VERIFY_12: {
8683                 struct scsi_write_verify_12 *cdb;
8684
8685                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8686                 flags |= CTL_LLF_FUA;
8687                 if (cdb->byte2 & SWV_DPO)
8688                         flags |= CTL_LLF_DPO;
8689                 lba = scsi_4btoul(cdb->addr);
8690                 num_blocks = scsi_4btoul(cdb->length);
8691                 break;
8692         }
8693         case READ_16:
8694         case WRITE_16: {
8695                 struct scsi_rw_16 *cdb;
8696
8697                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8698                 if (cdb->byte2 & SRW12_FUA)
8699                         flags |= CTL_LLF_FUA;
8700                 if (cdb->byte2 & SRW12_DPO)
8701                         flags |= CTL_LLF_DPO;
8702                 lba = scsi_8btou64(cdb->addr);
8703                 num_blocks = scsi_4btoul(cdb->length);
8704                 break;
8705         }
8706         case WRITE_ATOMIC_16: {
8707                 struct scsi_write_atomic_16 *cdb;
8708
8709                 if (lun->be_lun->atomicblock == 0) {
8710                         ctl_set_invalid_opcode(ctsio);
8711                         ctl_done((union ctl_io *)ctsio);
8712                         return (CTL_RETVAL_COMPLETE);
8713                 }
8714
8715                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8716                 if (cdb->byte2 & SRW12_FUA)
8717                         flags |= CTL_LLF_FUA;
8718                 if (cdb->byte2 & SRW12_DPO)
8719                         flags |= CTL_LLF_DPO;
8720                 lba = scsi_8btou64(cdb->addr);
8721                 num_blocks = scsi_2btoul(cdb->length);
8722                 if (num_blocks > lun->be_lun->atomicblock) {
8723                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8724                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8725                             /*bit*/ 0);
8726                         ctl_done((union ctl_io *)ctsio);
8727                         return (CTL_RETVAL_COMPLETE);
8728                 }
8729                 break;
8730         }
8731         case WRITE_VERIFY_16: {
8732                 struct scsi_write_verify_16 *cdb;
8733
8734                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8735                 flags |= CTL_LLF_FUA;
8736                 if (cdb->byte2 & SWV_DPO)
8737                         flags |= CTL_LLF_DPO;
8738                 lba = scsi_8btou64(cdb->addr);
8739                 num_blocks = scsi_4btoul(cdb->length);
8740                 break;
8741         }
8742         default:
8743                 /*
8744                  * We got a command we don't support.  This shouldn't
8745                  * happen, commands should be filtered out above us.
8746                  */
8747                 ctl_set_invalid_opcode(ctsio);
8748                 ctl_done((union ctl_io *)ctsio);
8749
8750                 return (CTL_RETVAL_COMPLETE);
8751                 break; /* NOTREACHED */
8752         }
8753
8754         /*
8755          * The first check is to make sure we're in bounds, the second
8756          * check is to catch wrap-around problems.  If the lba + num blocks
8757          * is less than the lba, then we've wrapped around and the block
8758          * range is invalid anyway.
8759          */
8760         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8761          || ((lba + num_blocks) < lba)) {
8762                 ctl_set_lba_out_of_range(ctsio,
8763                     MAX(lba, lun->be_lun->maxlba + 1));
8764                 ctl_done((union ctl_io *)ctsio);
8765                 return (CTL_RETVAL_COMPLETE);
8766         }
8767
8768         /*
8769          * According to SBC-3, a transfer length of 0 is not an error.
8770          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8771          * translates to 256 blocks for those commands.
8772          */
8773         if (num_blocks == 0) {
8774                 ctl_set_success(ctsio);
8775                 ctl_done((union ctl_io *)ctsio);
8776                 return (CTL_RETVAL_COMPLETE);
8777         }
8778
8779         /* Set FUA and/or DPO if caches are disabled. */
8780         if (isread) {
8781                 if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8782                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8783         } else {
8784                 if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8785                         flags |= CTL_LLF_FUA;
8786         }
8787
8788         lbalen = (struct ctl_lba_len_flags *)
8789             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8790         lbalen->lba = lba;
8791         lbalen->len = num_blocks;
8792         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8793
8794         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8795         ctsio->kern_rel_offset = 0;
8796
8797         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8798
8799         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8800         return (retval);
8801 }
8802
8803 static int
8804 ctl_cnw_cont(union ctl_io *io)
8805 {
8806         struct ctl_lun *lun = CTL_LUN(io);
8807         struct ctl_scsiio *ctsio;
8808         struct ctl_lba_len_flags *lbalen;
8809         int retval;
8810
8811         ctsio = &io->scsiio;
8812         ctsio->io_hdr.status = CTL_STATUS_NONE;
8813         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8814         lbalen = (struct ctl_lba_len_flags *)
8815             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8816         lbalen->flags &= ~CTL_LLF_COMPARE;
8817         lbalen->flags |= CTL_LLF_WRITE;
8818
8819         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8820         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8821         return (retval);
8822 }
8823
8824 int
8825 ctl_cnw(struct ctl_scsiio *ctsio)
8826 {
8827         struct ctl_lun *lun = CTL_LUN(ctsio);
8828         struct ctl_lba_len_flags *lbalen;
8829         uint64_t lba;
8830         uint32_t num_blocks;
8831         int flags, retval;
8832
8833         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8834
8835         flags = 0;
8836         switch (ctsio->cdb[0]) {
8837         case COMPARE_AND_WRITE: {
8838                 struct scsi_compare_and_write *cdb;
8839
8840                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8841                 if (cdb->byte2 & SRW10_FUA)
8842                         flags |= CTL_LLF_FUA;
8843                 if (cdb->byte2 & SRW10_DPO)
8844                         flags |= CTL_LLF_DPO;
8845                 lba = scsi_8btou64(cdb->addr);
8846                 num_blocks = cdb->length;
8847                 break;
8848         }
8849         default:
8850                 /*
8851                  * We got a command we don't support.  This shouldn't
8852                  * happen, commands should be filtered out above us.
8853                  */
8854                 ctl_set_invalid_opcode(ctsio);
8855                 ctl_done((union ctl_io *)ctsio);
8856
8857                 return (CTL_RETVAL_COMPLETE);
8858                 break; /* NOTREACHED */
8859         }
8860
8861         /*
8862          * The first check is to make sure we're in bounds, the second
8863          * check is to catch wrap-around problems.  If the lba + num blocks
8864          * is less than the lba, then we've wrapped around and the block
8865          * range is invalid anyway.
8866          */
8867         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8868          || ((lba + num_blocks) < lba)) {
8869                 ctl_set_lba_out_of_range(ctsio,
8870                     MAX(lba, lun->be_lun->maxlba + 1));
8871                 ctl_done((union ctl_io *)ctsio);
8872                 return (CTL_RETVAL_COMPLETE);
8873         }
8874
8875         /*
8876          * According to SBC-3, a transfer length of 0 is not an error.
8877          */
8878         if (num_blocks == 0) {
8879                 ctl_set_success(ctsio);
8880                 ctl_done((union ctl_io *)ctsio);
8881                 return (CTL_RETVAL_COMPLETE);
8882         }
8883
8884         /* Set FUA if write cache is disabled. */
8885         if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8886                 flags |= CTL_LLF_FUA;
8887
8888         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8889         ctsio->kern_rel_offset = 0;
8890
8891         /*
8892          * Set the IO_CONT flag, so that if this I/O gets passed to
8893          * ctl_data_submit_done(), it'll get passed back to
8894          * ctl_ctl_cnw_cont() for further processing.
8895          */
8896         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8897         ctsio->io_cont = ctl_cnw_cont;
8898
8899         lbalen = (struct ctl_lba_len_flags *)
8900             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8901         lbalen->lba = lba;
8902         lbalen->len = num_blocks;
8903         lbalen->flags = CTL_LLF_COMPARE | flags;
8904
8905         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8906         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8907         return (retval);
8908 }
8909
8910 int
8911 ctl_verify(struct ctl_scsiio *ctsio)
8912 {
8913         struct ctl_lun *lun = CTL_LUN(ctsio);
8914         struct ctl_lba_len_flags *lbalen;
8915         uint64_t lba;
8916         uint32_t num_blocks;
8917         int bytchk, flags;
8918         int retval;
8919
8920         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8921
8922         bytchk = 0;
8923         flags = CTL_LLF_FUA;
8924         switch (ctsio->cdb[0]) {
8925         case VERIFY_10: {
8926                 struct scsi_verify_10 *cdb;
8927
8928                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8929                 if (cdb->byte2 & SVFY_BYTCHK)
8930                         bytchk = 1;
8931                 if (cdb->byte2 & SVFY_DPO)
8932                         flags |= CTL_LLF_DPO;
8933                 lba = scsi_4btoul(cdb->addr);
8934                 num_blocks = scsi_2btoul(cdb->length);
8935                 break;
8936         }
8937         case VERIFY_12: {
8938                 struct scsi_verify_12 *cdb;
8939
8940                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8941                 if (cdb->byte2 & SVFY_BYTCHK)
8942                         bytchk = 1;
8943                 if (cdb->byte2 & SVFY_DPO)
8944                         flags |= CTL_LLF_DPO;
8945                 lba = scsi_4btoul(cdb->addr);
8946                 num_blocks = scsi_4btoul(cdb->length);
8947                 break;
8948         }
8949         case VERIFY_16: {
8950                 struct scsi_rw_16 *cdb;
8951
8952                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8953                 if (cdb->byte2 & SVFY_BYTCHK)
8954                         bytchk = 1;
8955                 if (cdb->byte2 & SVFY_DPO)
8956                         flags |= CTL_LLF_DPO;
8957                 lba = scsi_8btou64(cdb->addr);
8958                 num_blocks = scsi_4btoul(cdb->length);
8959                 break;
8960         }
8961         default:
8962                 /*
8963                  * We got a command we don't support.  This shouldn't
8964                  * happen, commands should be filtered out above us.
8965                  */
8966                 ctl_set_invalid_opcode(ctsio);
8967                 ctl_done((union ctl_io *)ctsio);
8968                 return (CTL_RETVAL_COMPLETE);
8969         }
8970
8971         /*
8972          * The first check is to make sure we're in bounds, the second
8973          * check is to catch wrap-around problems.  If the lba + num blocks
8974          * is less than the lba, then we've wrapped around and the block
8975          * range is invalid anyway.
8976          */
8977         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8978          || ((lba + num_blocks) < lba)) {
8979                 ctl_set_lba_out_of_range(ctsio,
8980                     MAX(lba, lun->be_lun->maxlba + 1));
8981                 ctl_done((union ctl_io *)ctsio);
8982                 return (CTL_RETVAL_COMPLETE);
8983         }
8984
8985         /*
8986          * According to SBC-3, a transfer length of 0 is not an error.
8987          */
8988         if (num_blocks == 0) {
8989                 ctl_set_success(ctsio);
8990                 ctl_done((union ctl_io *)ctsio);
8991                 return (CTL_RETVAL_COMPLETE);
8992         }
8993
8994         lbalen = (struct ctl_lba_len_flags *)
8995             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8996         lbalen->lba = lba;
8997         lbalen->len = num_blocks;
8998         if (bytchk) {
8999                 lbalen->flags = CTL_LLF_COMPARE | flags;
9000                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9001         } else {
9002                 lbalen->flags = CTL_LLF_VERIFY | flags;
9003                 ctsio->kern_total_len = 0;
9004         }
9005         ctsio->kern_rel_offset = 0;
9006
9007         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9008         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9009         return (retval);
9010 }
9011
9012 int
9013 ctl_report_luns(struct ctl_scsiio *ctsio)
9014 {
9015         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9016         struct ctl_port *port = CTL_PORT(ctsio);
9017         struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9018         struct scsi_report_luns *cdb;
9019         struct scsi_report_luns_data *lun_data;
9020         int num_filled, num_luns, num_port_luns, retval;
9021         uint32_t alloc_len, lun_datalen;
9022         uint32_t initidx, targ_lun_id, lun_id;
9023
9024         retval = CTL_RETVAL_COMPLETE;
9025         cdb = (struct scsi_report_luns *)ctsio->cdb;
9026
9027         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9028
9029         num_luns = 0;
9030         num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9031         mtx_lock(&softc->ctl_lock);
9032         for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9033                 if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9034                         num_luns++;
9035         }
9036         mtx_unlock(&softc->ctl_lock);
9037
9038         switch (cdb->select_report) {
9039         case RPL_REPORT_DEFAULT:
9040         case RPL_REPORT_ALL:
9041         case RPL_REPORT_NONSUBSID:
9042                 break;
9043         case RPL_REPORT_WELLKNOWN:
9044         case RPL_REPORT_ADMIN:
9045         case RPL_REPORT_CONGLOM:
9046                 num_luns = 0;
9047                 break;
9048         default:
9049                 ctl_set_invalid_field(ctsio,
9050                                       /*sks_valid*/ 1,
9051                                       /*command*/ 1,
9052                                       /*field*/ 2,
9053                                       /*bit_valid*/ 0,
9054                                       /*bit*/ 0);
9055                 ctl_done((union ctl_io *)ctsio);
9056                 return (retval);
9057                 break; /* NOTREACHED */
9058         }
9059
9060         alloc_len = scsi_4btoul(cdb->length);
9061         /*
9062          * The initiator has to allocate at least 16 bytes for this request,
9063          * so he can at least get the header and the first LUN.  Otherwise
9064          * we reject the request (per SPC-3 rev 14, section 6.21).
9065          */
9066         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9067             sizeof(struct scsi_report_luns_lundata))) {
9068                 ctl_set_invalid_field(ctsio,
9069                                       /*sks_valid*/ 1,
9070                                       /*command*/ 1,
9071                                       /*field*/ 6,
9072                                       /*bit_valid*/ 0,
9073                                       /*bit*/ 0);
9074                 ctl_done((union ctl_io *)ctsio);
9075                 return (retval);
9076         }
9077
9078         lun_datalen = sizeof(*lun_data) +
9079                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9080
9081         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9082         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9083         ctsio->kern_sg_entries = 0;
9084
9085         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9086
9087         mtx_lock(&softc->ctl_lock);
9088         for (targ_lun_id = 0, num_filled = 0;
9089             targ_lun_id < num_port_luns && num_filled < num_luns;
9090             targ_lun_id++) {
9091                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9092                 if (lun_id == UINT32_MAX)
9093                         continue;
9094                 lun = softc->ctl_luns[lun_id];
9095                 if (lun == NULL)
9096                         continue;
9097
9098                 be64enc(lun_data->luns[num_filled++].lundata,
9099                     ctl_encode_lun(targ_lun_id));
9100
9101                 /*
9102                  * According to SPC-3, rev 14 section 6.21:
9103                  *
9104                  * "The execution of a REPORT LUNS command to any valid and
9105                  * installed logical unit shall clear the REPORTED LUNS DATA
9106                  * HAS CHANGED unit attention condition for all logical
9107                  * units of that target with respect to the requesting
9108                  * initiator. A valid and installed logical unit is one
9109                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9110                  * INQUIRY data (see 6.4.2)."
9111                  *
9112                  * If request_lun is NULL, the LUN this report luns command
9113                  * was issued to is either disabled or doesn't exist. In that
9114                  * case, we shouldn't clear any pending lun change unit
9115                  * attention.
9116                  */
9117                 if (request_lun != NULL) {
9118                         mtx_lock(&lun->lun_lock);
9119                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9120                         mtx_unlock(&lun->lun_lock);
9121                 }
9122         }
9123         mtx_unlock(&softc->ctl_lock);
9124
9125         /*
9126          * It's quite possible that we've returned fewer LUNs than we allocated
9127          * space for.  Trim it.
9128          */
9129         lun_datalen = sizeof(*lun_data) +
9130                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9131
9132         if (lun_datalen < alloc_len) {
9133                 ctsio->residual = alloc_len - lun_datalen;
9134                 ctsio->kern_data_len = lun_datalen;
9135                 ctsio->kern_total_len = lun_datalen;
9136         } else {
9137                 ctsio->residual = 0;
9138                 ctsio->kern_data_len = alloc_len;
9139                 ctsio->kern_total_len = alloc_len;
9140         }
9141         ctsio->kern_data_resid = 0;
9142         ctsio->kern_rel_offset = 0;
9143         ctsio->kern_sg_entries = 0;
9144
9145         /*
9146          * We set this to the actual data length, regardless of how much
9147          * space we actually have to return results.  If the user looks at
9148          * this value, he'll know whether or not he allocated enough space
9149          * and reissue the command if necessary.  We don't support well
9150          * known logical units, so if the user asks for that, return none.
9151          */
9152         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9153
9154         /*
9155          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9156          * this request.
9157          */
9158         ctl_set_success(ctsio);
9159         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9160         ctsio->be_move_done = ctl_config_move_done;
9161         ctl_datamove((union ctl_io *)ctsio);
9162         return (retval);
9163 }
9164
9165 int
9166 ctl_request_sense(struct ctl_scsiio *ctsio)
9167 {
9168         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9169         struct ctl_lun *lun = CTL_LUN(ctsio);
9170         struct scsi_request_sense *cdb;
9171         struct scsi_sense_data *sense_ptr;
9172         uint32_t initidx;
9173         int have_error;
9174         u_int sense_len = SSD_FULL_SIZE;
9175         scsi_sense_data_type sense_format;
9176         ctl_ua_type ua_type;
9177         uint8_t asc = 0, ascq = 0;
9178
9179         cdb = (struct scsi_request_sense *)ctsio->cdb;
9180
9181         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9182
9183         /*
9184          * Determine which sense format the user wants.
9185          */
9186         if (cdb->byte2 & SRS_DESC)
9187                 sense_format = SSD_TYPE_DESC;
9188         else
9189                 sense_format = SSD_TYPE_FIXED;
9190
9191         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9192         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9193         ctsio->kern_sg_entries = 0;
9194
9195         /*
9196          * struct scsi_sense_data, which is currently set to 256 bytes, is
9197          * larger than the largest allowed value for the length field in the
9198          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9199          */
9200         ctsio->residual = 0;
9201         ctsio->kern_data_len = cdb->length;
9202         ctsio->kern_total_len = cdb->length;
9203
9204         ctsio->kern_data_resid = 0;
9205         ctsio->kern_rel_offset = 0;
9206         ctsio->kern_sg_entries = 0;
9207
9208         /*
9209          * If we don't have a LUN, we don't have any pending sense.
9210          */
9211         if (lun == NULL ||
9212             ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9213              softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9214                 /* "Logical unit not supported" */
9215                 ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9216                     /*current_error*/ 1,
9217                     /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9218                     /*asc*/ 0x25,
9219                     /*ascq*/ 0x00,
9220                     SSD_ELEM_NONE);
9221                 goto send;
9222         }
9223
9224         have_error = 0;
9225         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9226         /*
9227          * Check for pending sense, and then for pending unit attentions.
9228          * Pending sense gets returned first, then pending unit attentions.
9229          */
9230         mtx_lock(&lun->lun_lock);
9231 #ifdef CTL_WITH_CA
9232         if (ctl_is_set(lun->have_ca, initidx)) {
9233                 scsi_sense_data_type stored_format;
9234
9235                 /*
9236                  * Check to see which sense format was used for the stored
9237                  * sense data.
9238                  */
9239                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9240
9241                 /*
9242                  * If the user requested a different sense format than the
9243                  * one we stored, then we need to convert it to the other
9244                  * format.  If we're going from descriptor to fixed format
9245                  * sense data, we may lose things in translation, depending
9246                  * on what options were used.
9247                  *
9248                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9249                  * for some reason we'll just copy it out as-is.
9250                  */
9251                 if ((stored_format == SSD_TYPE_FIXED)
9252                  && (sense_format == SSD_TYPE_DESC))
9253                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9254                             &lun->pending_sense[initidx],
9255                             (struct scsi_sense_data_desc *)sense_ptr);
9256                 else if ((stored_format == SSD_TYPE_DESC)
9257                       && (sense_format == SSD_TYPE_FIXED))
9258                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9259                             &lun->pending_sense[initidx],
9260                             (struct scsi_sense_data_fixed *)sense_ptr);
9261                 else
9262                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9263                                MIN(sizeof(*sense_ptr),
9264                                sizeof(lun->pending_sense[initidx])));
9265
9266                 ctl_clear_mask(lun->have_ca, initidx);
9267                 have_error = 1;
9268         } else
9269 #endif
9270         if (have_error == 0) {
9271                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9272                     sense_format);
9273                 if (ua_type != CTL_UA_NONE)
9274                         have_error = 1;
9275         }
9276         if (have_error == 0) {
9277                 /*
9278                  * Report informational exception if have one and allowed.
9279                  */
9280                 if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9281                         asc = lun->ie_asc;
9282                         ascq = lun->ie_ascq;
9283                 }
9284                 ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9285                     /*current_error*/ 1,
9286                     /*sense_key*/ SSD_KEY_NO_SENSE,
9287                     /*asc*/ asc,
9288                     /*ascq*/ ascq,
9289                     SSD_ELEM_NONE);
9290         }
9291         mtx_unlock(&lun->lun_lock);
9292
9293 send:
9294         /*
9295          * We report the SCSI status as OK, since the status of the command
9296          * itself is OK.  We're reporting sense as parameter data.
9297          */
9298         ctl_set_success(ctsio);
9299         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9300         ctsio->be_move_done = ctl_config_move_done;
9301         ctl_datamove((union ctl_io *)ctsio);
9302         return (CTL_RETVAL_COMPLETE);
9303 }
9304
9305 int
9306 ctl_tur(struct ctl_scsiio *ctsio)
9307 {
9308
9309         CTL_DEBUG_PRINT(("ctl_tur\n"));
9310
9311         ctl_set_success(ctsio);
9312         ctl_done((union ctl_io *)ctsio);
9313
9314         return (CTL_RETVAL_COMPLETE);
9315 }
9316
9317 /*
9318  * SCSI VPD page 0x00, the Supported VPD Pages page.
9319  */
9320 static int
9321 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9322 {
9323         struct ctl_lun *lun = CTL_LUN(ctsio);
9324         struct scsi_vpd_supported_pages *pages;
9325         int sup_page_size;
9326         int p;
9327
9328         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9329             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9330         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9331         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9332         ctsio->kern_sg_entries = 0;
9333
9334         if (sup_page_size < alloc_len) {
9335                 ctsio->residual = alloc_len - sup_page_size;
9336                 ctsio->kern_data_len = sup_page_size;
9337                 ctsio->kern_total_len = sup_page_size;
9338         } else {
9339                 ctsio->residual = 0;
9340                 ctsio->kern_data_len = alloc_len;
9341                 ctsio->kern_total_len = alloc_len;
9342         }
9343         ctsio->kern_data_resid = 0;
9344         ctsio->kern_rel_offset = 0;
9345         ctsio->kern_sg_entries = 0;
9346
9347         /*
9348          * The control device is always connected.  The disk device, on the
9349          * other hand, may not be online all the time.  Need to change this
9350          * to figure out whether the disk device is actually online or not.
9351          */
9352         if (lun != NULL)
9353                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9354                                 lun->be_lun->lun_type;
9355         else
9356                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9357
9358         p = 0;
9359         /* Supported VPD pages */
9360         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9361         /* Serial Number */
9362         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9363         /* Device Identification */
9364         pages->page_list[p++] = SVPD_DEVICE_ID;
9365         /* Extended INQUIRY Data */
9366         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9367         /* Mode Page Policy */
9368         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9369         /* SCSI Ports */
9370         pages->page_list[p++] = SVPD_SCSI_PORTS;
9371         /* Third-party Copy */
9372         pages->page_list[p++] = SVPD_SCSI_TPC;
9373         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9374                 /* Block limits */
9375                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9376                 /* Block Device Characteristics */
9377                 pages->page_list[p++] = SVPD_BDC;
9378                 /* Logical Block Provisioning */
9379                 pages->page_list[p++] = SVPD_LBP;
9380         }
9381         pages->length = p;
9382
9383         ctl_set_success(ctsio);
9384         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9385         ctsio->be_move_done = ctl_config_move_done;
9386         ctl_datamove((union ctl_io *)ctsio);
9387         return (CTL_RETVAL_COMPLETE);
9388 }
9389
9390 /*
9391  * SCSI VPD page 0x80, the Unit Serial Number page.
9392  */
9393 static int
9394 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9395 {
9396         struct ctl_lun *lun = CTL_LUN(ctsio);
9397         struct scsi_vpd_unit_serial_number *sn_ptr;
9398         int data_len;
9399
9400         data_len = 4 + CTL_SN_LEN;
9401         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9402         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9403         if (data_len < alloc_len) {
9404                 ctsio->residual = alloc_len - data_len;
9405                 ctsio->kern_data_len = data_len;
9406                 ctsio->kern_total_len = data_len;
9407         } else {
9408                 ctsio->residual = 0;
9409                 ctsio->kern_data_len = alloc_len;
9410                 ctsio->kern_total_len = alloc_len;
9411         }
9412         ctsio->kern_data_resid = 0;
9413         ctsio->kern_rel_offset = 0;
9414         ctsio->kern_sg_entries = 0;
9415
9416         /*
9417          * The control device is always connected.  The disk device, on the
9418          * other hand, may not be online all the time.  Need to change this
9419          * to figure out whether the disk device is actually online or not.
9420          */
9421         if (lun != NULL)
9422                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9423                                   lun->be_lun->lun_type;
9424         else
9425                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9426
9427         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9428         sn_ptr->length = CTL_SN_LEN;
9429         /*
9430          * If we don't have a LUN, we just leave the serial number as
9431          * all spaces.
9432          */
9433         if (lun != NULL) {
9434                 strncpy((char *)sn_ptr->serial_num,
9435                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9436         } else
9437                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9438
9439         ctl_set_success(ctsio);
9440         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9441         ctsio->be_move_done = ctl_config_move_done;
9442         ctl_datamove((union ctl_io *)ctsio);
9443         return (CTL_RETVAL_COMPLETE);
9444 }
9445
9446
9447 /*
9448  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9449  */
9450 static int
9451 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9452 {
9453         struct ctl_lun *lun = CTL_LUN(ctsio);
9454         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9455         int data_len;
9456
9457         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9458         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9459         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9460         ctsio->kern_sg_entries = 0;
9461
9462         if (data_len < alloc_len) {
9463                 ctsio->residual = alloc_len - data_len;
9464                 ctsio->kern_data_len = data_len;
9465                 ctsio->kern_total_len = data_len;
9466         } else {
9467                 ctsio->residual = 0;
9468                 ctsio->kern_data_len = alloc_len;
9469                 ctsio->kern_total_len = alloc_len;
9470         }
9471         ctsio->kern_data_resid = 0;
9472         ctsio->kern_rel_offset = 0;
9473         ctsio->kern_sg_entries = 0;
9474
9475         /*
9476          * The control device is always connected.  The disk device, on the
9477          * other hand, may not be online all the time.
9478          */
9479         if (lun != NULL)
9480                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9481                                      lun->be_lun->lun_type;
9482         else
9483                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9484         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9485         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9486         /*
9487          * We support head of queue, ordered and simple tags.
9488          */
9489         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9490         /*
9491          * Volatile cache supported.
9492          */
9493         eid_ptr->flags3 = SVPD_EID_V_SUP;
9494
9495         /*
9496          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9497          * attention for a particular IT nexus on all LUNs once we report
9498          * it to that nexus once.  This bit is required as of SPC-4.
9499          */
9500         eid_ptr->flags4 = SVPD_EID_LUICLR;
9501
9502         /*
9503          * We support revert to defaults (RTD) bit in MODE SELECT.
9504          */
9505         eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9506
9507         /*
9508          * XXX KDM in order to correctly answer this, we would need
9509          * information from the SIM to determine how much sense data it
9510          * can send.  So this would really be a path inquiry field, most
9511          * likely.  This can be set to a maximum of 252 according to SPC-4,
9512          * but the hardware may or may not be able to support that much.
9513          * 0 just means that the maximum sense data length is not reported.
9514          */
9515         eid_ptr->max_sense_length = 0;
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 static int
9525 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9526 {
9527         struct ctl_lun *lun = CTL_LUN(ctsio);
9528         struct scsi_vpd_mode_page_policy *mpp_ptr;
9529         int data_len;
9530
9531         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9532             sizeof(struct scsi_vpd_mode_page_policy_descr);
9533
9534         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9535         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9536         ctsio->kern_sg_entries = 0;
9537
9538         if (data_len < alloc_len) {
9539                 ctsio->residual = alloc_len - data_len;
9540                 ctsio->kern_data_len = data_len;
9541                 ctsio->kern_total_len = data_len;
9542         } else {
9543                 ctsio->residual = 0;
9544                 ctsio->kern_data_len = alloc_len;
9545                 ctsio->kern_total_len = alloc_len;
9546         }
9547         ctsio->kern_data_resid = 0;
9548         ctsio->kern_rel_offset = 0;
9549         ctsio->kern_sg_entries = 0;
9550
9551         /*
9552          * The control device is always connected.  The disk device, on the
9553          * other hand, may not be online all the time.
9554          */
9555         if (lun != NULL)
9556                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9557                                      lun->be_lun->lun_type;
9558         else
9559                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9560         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9561         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9562         mpp_ptr->descr[0].page_code = 0x3f;
9563         mpp_ptr->descr[0].subpage_code = 0xff;
9564         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9565
9566         ctl_set_success(ctsio);
9567         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9568         ctsio->be_move_done = ctl_config_move_done;
9569         ctl_datamove((union ctl_io *)ctsio);
9570         return (CTL_RETVAL_COMPLETE);
9571 }
9572
9573 /*
9574  * SCSI VPD page 0x83, the Device Identification page.
9575  */
9576 static int
9577 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9578 {
9579         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9580         struct ctl_port *port = CTL_PORT(ctsio);
9581         struct ctl_lun *lun = CTL_LUN(ctsio);
9582         struct scsi_vpd_device_id *devid_ptr;
9583         struct scsi_vpd_id_descriptor *desc;
9584         int data_len, g;
9585         uint8_t proto;
9586
9587         data_len = sizeof(struct scsi_vpd_device_id) +
9588             sizeof(struct scsi_vpd_id_descriptor) +
9589                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9590             sizeof(struct scsi_vpd_id_descriptor) +
9591                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9592         if (lun && lun->lun_devid)
9593                 data_len += lun->lun_devid->len;
9594         if (port && port->port_devid)
9595                 data_len += port->port_devid->len;
9596         if (port && port->target_devid)
9597                 data_len += port->target_devid->len;
9598
9599         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9600         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9601         ctsio->kern_sg_entries = 0;
9602
9603         if (data_len < alloc_len) {
9604                 ctsio->residual = alloc_len - data_len;
9605                 ctsio->kern_data_len = data_len;
9606                 ctsio->kern_total_len = data_len;
9607         } else {
9608                 ctsio->residual = 0;
9609                 ctsio->kern_data_len = alloc_len;
9610                 ctsio->kern_total_len = alloc_len;
9611         }
9612         ctsio->kern_data_resid = 0;
9613         ctsio->kern_rel_offset = 0;
9614         ctsio->kern_sg_entries = 0;
9615
9616         /*
9617          * The control device is always connected.  The disk device, on the
9618          * other hand, may not be online all the time.
9619          */
9620         if (lun != NULL)
9621                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9622                                      lun->be_lun->lun_type;
9623         else
9624                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9625         devid_ptr->page_code = SVPD_DEVICE_ID;
9626         scsi_ulto2b(data_len - 4, devid_ptr->length);
9627
9628         if (port && port->port_type == CTL_PORT_FC)
9629                 proto = SCSI_PROTO_FC << 4;
9630         else if (port && port->port_type == CTL_PORT_ISCSI)
9631                 proto = SCSI_PROTO_ISCSI << 4;
9632         else
9633                 proto = SCSI_PROTO_SPI << 4;
9634         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9635
9636         /*
9637          * We're using a LUN association here.  i.e., this device ID is a
9638          * per-LUN identifier.
9639          */
9640         if (lun && lun->lun_devid) {
9641                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9642                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9643                     lun->lun_devid->len);
9644         }
9645
9646         /*
9647          * This is for the WWPN which is a port association.
9648          */
9649         if (port && port->port_devid) {
9650                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9651                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9652                     port->port_devid->len);
9653         }
9654
9655         /*
9656          * This is for the Relative Target Port(type 4h) identifier
9657          */
9658         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9659         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9660             SVPD_ID_TYPE_RELTARG;
9661         desc->length = 4;
9662         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9663         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9664             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9665
9666         /*
9667          * This is for the Target Port Group(type 5h) identifier
9668          */
9669         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9670         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9671             SVPD_ID_TYPE_TPORTGRP;
9672         desc->length = 4;
9673         if (softc->is_single ||
9674             (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9675                 g = 1;
9676         else
9677                 g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9678         scsi_ulto2b(g, &desc->identifier[2]);
9679         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9680             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9681
9682         /*
9683          * This is for the Target identifier
9684          */
9685         if (port && port->target_devid) {
9686                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9687         }
9688
9689         ctl_set_success(ctsio);
9690         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9691         ctsio->be_move_done = ctl_config_move_done;
9692         ctl_datamove((union ctl_io *)ctsio);
9693         return (CTL_RETVAL_COMPLETE);
9694 }
9695
9696 static int
9697 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9698 {
9699         struct ctl_softc *softc = CTL_SOFTC(ctsio);
9700         struct ctl_lun *lun = CTL_LUN(ctsio);
9701         struct scsi_vpd_scsi_ports *sp;
9702         struct scsi_vpd_port_designation *pd;
9703         struct scsi_vpd_port_designation_cont *pdc;
9704         struct ctl_port *port;
9705         int data_len, num_target_ports, iid_len, id_len;
9706
9707         num_target_ports = 0;
9708         iid_len = 0;
9709         id_len = 0;
9710         mtx_lock(&softc->ctl_lock);
9711         STAILQ_FOREACH(port, &softc->port_list, links) {
9712                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9713                         continue;
9714                 if (lun != NULL &&
9715                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9716                         continue;
9717                 num_target_ports++;
9718                 if (port->init_devid)
9719                         iid_len += port->init_devid->len;
9720                 if (port->port_devid)
9721                         id_len += port->port_devid->len;
9722         }
9723         mtx_unlock(&softc->ctl_lock);
9724
9725         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9726             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9727              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9728         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9729         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9730         ctsio->kern_sg_entries = 0;
9731
9732         if (data_len < alloc_len) {
9733                 ctsio->residual = alloc_len - data_len;
9734                 ctsio->kern_data_len = data_len;
9735                 ctsio->kern_total_len = data_len;
9736         } else {
9737                 ctsio->residual = 0;
9738                 ctsio->kern_data_len = alloc_len;
9739                 ctsio->kern_total_len = alloc_len;
9740         }
9741         ctsio->kern_data_resid = 0;
9742         ctsio->kern_rel_offset = 0;
9743         ctsio->kern_sg_entries = 0;
9744
9745         /*
9746          * The control device is always connected.  The disk device, on the
9747          * other hand, may not be online all the time.  Need to change this
9748          * to figure out whether the disk device is actually online or not.
9749          */
9750         if (lun != NULL)
9751                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9752                                   lun->be_lun->lun_type;
9753         else
9754                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9755
9756         sp->page_code = SVPD_SCSI_PORTS;
9757         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9758             sp->page_length);
9759         pd = &sp->design[0];
9760
9761         mtx_lock(&softc->ctl_lock);
9762         STAILQ_FOREACH(port, &softc->port_list, links) {
9763                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9764                         continue;
9765                 if (lun != NULL &&
9766                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9767                         continue;
9768                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9769                 if (port->init_devid) {
9770                         iid_len = port->init_devid->len;
9771                         memcpy(pd->initiator_transportid,
9772                             port->init_devid->data, port->init_devid->len);
9773                 } else
9774                         iid_len = 0;
9775                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9776                 pdc = (struct scsi_vpd_port_designation_cont *)
9777                     (&pd->initiator_transportid[iid_len]);
9778                 if (port->port_devid) {
9779                         id_len = port->port_devid->len;
9780                         memcpy(pdc->target_port_descriptors,
9781                             port->port_devid->data, port->port_devid->len);
9782                 } else
9783                         id_len = 0;
9784                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9785                 pd = (struct scsi_vpd_port_designation *)
9786                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9787         }
9788         mtx_unlock(&softc->ctl_lock);
9789
9790         ctl_set_success(ctsio);
9791         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9792         ctsio->be_move_done = ctl_config_move_done;
9793         ctl_datamove((union ctl_io *)ctsio);
9794         return (CTL_RETVAL_COMPLETE);
9795 }
9796
9797 static int
9798 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9799 {
9800         struct ctl_lun *lun = CTL_LUN(ctsio);
9801         struct scsi_vpd_block_limits *bl_ptr;
9802         uint64_t ival;
9803
9804         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9805         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9806         ctsio->kern_sg_entries = 0;
9807
9808         if (sizeof(*bl_ptr) < alloc_len) {
9809                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9810                 ctsio->kern_data_len = sizeof(*bl_ptr);
9811                 ctsio->kern_total_len = sizeof(*bl_ptr);
9812         } else {
9813                 ctsio->residual = 0;
9814                 ctsio->kern_data_len = alloc_len;
9815                 ctsio->kern_total_len = alloc_len;
9816         }
9817         ctsio->kern_data_resid = 0;
9818         ctsio->kern_rel_offset = 0;
9819         ctsio->kern_sg_entries = 0;
9820
9821         /*
9822          * The control device is always connected.  The disk device, on the
9823          * other hand, may not be online all the time.  Need to change this
9824          * to figure out whether the disk device is actually online or not.
9825          */
9826         if (lun != NULL)
9827                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9828                                   lun->be_lun->lun_type;
9829         else
9830                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9831
9832         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9833         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9834         bl_ptr->max_cmp_write_len = 0xff;
9835         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9836         if (lun != NULL) {
9837                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9838                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9839                         ival = 0xffffffff;
9840                         ctl_get_opt_number(&lun->be_lun->options,
9841                             "unmap_max_lba", &ival);
9842                         scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9843                         ival = 0xffffffff;
9844                         ctl_get_opt_number(&lun->be_lun->options,
9845                             "unmap_max_descr", &ival);
9846                         scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9847                         if (lun->be_lun->ublockexp != 0) {
9848                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9849                                     bl_ptr->opt_unmap_grain);
9850                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9851                                     bl_ptr->unmap_grain_align);
9852                         }
9853                 }
9854                 scsi_ulto4b(lun->be_lun->atomicblock,
9855                     bl_ptr->max_atomic_transfer_length);
9856                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9857                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9858                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9859                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9860                 ival = UINT64_MAX;
9861                 ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9862                 scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9863         }
9864
9865         ctl_set_success(ctsio);
9866         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9867         ctsio->be_move_done = ctl_config_move_done;
9868         ctl_datamove((union ctl_io *)ctsio);
9869         return (CTL_RETVAL_COMPLETE);
9870 }
9871
9872 static int
9873 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9874 {
9875         struct ctl_lun *lun = CTL_LUN(ctsio);
9876         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9877         const char *value;
9878         u_int i;
9879
9880         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9881         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9882         ctsio->kern_sg_entries = 0;
9883
9884         if (sizeof(*bdc_ptr) < alloc_len) {
9885                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9886                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9887                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9888         } else {
9889                 ctsio->residual = 0;
9890                 ctsio->kern_data_len = alloc_len;
9891                 ctsio->kern_total_len = alloc_len;
9892         }
9893         ctsio->kern_data_resid = 0;
9894         ctsio->kern_rel_offset = 0;
9895         ctsio->kern_sg_entries = 0;
9896
9897         /*
9898          * The control device is always connected.  The disk device, on the
9899          * other hand, may not be online all the time.  Need to change this
9900          * to figure out whether the disk device is actually online or not.
9901          */
9902         if (lun != NULL)
9903                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9904                                   lun->be_lun->lun_type;
9905         else
9906                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9907         bdc_ptr->page_code = SVPD_BDC;
9908         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9909         if (lun != NULL &&
9910             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9911                 i = strtol(value, NULL, 0);
9912         else
9913                 i = CTL_DEFAULT_ROTATION_RATE;
9914         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9915         if (lun != NULL &&
9916             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9917                 i = strtol(value, NULL, 0);
9918         else
9919                 i = 0;
9920         bdc_ptr->wab_wac_ff = (i & 0x0f);
9921         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9922
9923         ctl_set_success(ctsio);
9924         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9925         ctsio->be_move_done = ctl_config_move_done;
9926         ctl_datamove((union ctl_io *)ctsio);
9927         return (CTL_RETVAL_COMPLETE);
9928 }
9929
9930 static int
9931 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9932 {
9933         struct ctl_lun *lun = CTL_LUN(ctsio);
9934         struct scsi_vpd_logical_block_prov *lbp_ptr;
9935         const char *value;
9936
9937         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9938         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9939         ctsio->kern_sg_entries = 0;
9940
9941         if (sizeof(*lbp_ptr) < alloc_len) {
9942                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9943                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9944                 ctsio->kern_total_len = sizeof(*lbp_ptr);
9945         } else {
9946                 ctsio->residual = 0;
9947                 ctsio->kern_data_len = alloc_len;
9948                 ctsio->kern_total_len = alloc_len;
9949         }
9950         ctsio->kern_data_resid = 0;
9951         ctsio->kern_rel_offset = 0;
9952         ctsio->kern_sg_entries = 0;
9953
9954         /*
9955          * The control device is always connected.  The disk device, on the
9956          * other hand, may not be online all the time.  Need to change this
9957          * to figure out whether the disk device is actually online or not.
9958          */
9959         if (lun != NULL)
9960                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9961                                   lun->be_lun->lun_type;
9962         else
9963                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9964
9965         lbp_ptr->page_code = SVPD_LBP;
9966         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9967         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9968         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9969                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9970                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9971                 value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
9972                 if (value != NULL) {
9973                         if (strcmp(value, "resource") == 0)
9974                                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9975                         else if (strcmp(value, "thin") == 0)
9976                                 lbp_ptr->prov_type = SVPD_LBP_THIN;
9977                 } else
9978                         lbp_ptr->prov_type = SVPD_LBP_THIN;
9979         }
9980
9981         ctl_set_success(ctsio);
9982         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9983         ctsio->be_move_done = ctl_config_move_done;
9984         ctl_datamove((union ctl_io *)ctsio);
9985         return (CTL_RETVAL_COMPLETE);
9986 }
9987
9988 /*
9989  * INQUIRY with the EVPD bit set.
9990  */
9991 static int
9992 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9993 {
9994         struct ctl_lun *lun = CTL_LUN(ctsio);
9995         struct scsi_inquiry *cdb;
9996         int alloc_len, retval;
9997
9998         cdb = (struct scsi_inquiry *)ctsio->cdb;
9999         alloc_len = scsi_2btoul(cdb->length);
10000
10001         switch (cdb->page_code) {
10002         case SVPD_SUPPORTED_PAGES:
10003                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10004                 break;
10005         case SVPD_UNIT_SERIAL_NUMBER:
10006                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10007                 break;
10008         case SVPD_DEVICE_ID:
10009                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10010                 break;
10011         case SVPD_EXTENDED_INQUIRY_DATA:
10012                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10013                 break;
10014         case SVPD_MODE_PAGE_POLICY:
10015                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10016                 break;
10017         case SVPD_SCSI_PORTS:
10018                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10019                 break;
10020         case SVPD_SCSI_TPC:
10021                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10022                 break;
10023         case SVPD_BLOCK_LIMITS:
10024                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10025                         goto err;
10026                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10027                 break;
10028         case SVPD_BDC:
10029                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10030                         goto err;
10031                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10032                 break;
10033         case SVPD_LBP:
10034                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10035                         goto err;
10036                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10037                 break;
10038         default:
10039 err:
10040                 ctl_set_invalid_field(ctsio,
10041                                       /*sks_valid*/ 1,
10042                                       /*command*/ 1,
10043                                       /*field*/ 2,
10044                                       /*bit_valid*/ 0,
10045                                       /*bit*/ 0);
10046                 ctl_done((union ctl_io *)ctsio);
10047                 retval = CTL_RETVAL_COMPLETE;
10048                 break;
10049         }
10050
10051         return (retval);
10052 }
10053
10054 /*
10055  * Standard INQUIRY data.
10056  */
10057 static int
10058 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10059 {
10060         struct ctl_softc *softc = CTL_SOFTC(ctsio);
10061         struct ctl_port *port = CTL_PORT(ctsio);
10062         struct ctl_lun *lun = CTL_LUN(ctsio);
10063         struct scsi_inquiry_data *inq_ptr;
10064         struct scsi_inquiry *cdb;
10065         char *val;
10066         uint32_t alloc_len, data_len;
10067         ctl_port_type port_type;
10068
10069         port_type = port->port_type;
10070         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10071                 port_type = CTL_PORT_SCSI;
10072
10073         cdb = (struct scsi_inquiry *)ctsio->cdb;
10074         alloc_len = scsi_2btoul(cdb->length);
10075
10076         /*
10077          * We malloc the full inquiry data size here and fill it
10078          * in.  If the user only asks for less, we'll give him
10079          * that much.
10080          */
10081         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10082         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10083         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10084         ctsio->kern_sg_entries = 0;
10085         ctsio->kern_data_resid = 0;
10086         ctsio->kern_rel_offset = 0;
10087
10088         if (data_len < alloc_len) {
10089                 ctsio->residual = alloc_len - data_len;
10090                 ctsio->kern_data_len = data_len;
10091                 ctsio->kern_total_len = data_len;
10092         } else {
10093                 ctsio->residual = 0;
10094                 ctsio->kern_data_len = alloc_len;
10095                 ctsio->kern_total_len = alloc_len;
10096         }
10097
10098         if (lun != NULL) {
10099                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10100                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10101                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10102                             lun->be_lun->lun_type;
10103                 } else {
10104                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10105                             lun->be_lun->lun_type;
10106                 }
10107                 if (lun->flags & CTL_LUN_REMOVABLE)
10108                         inq_ptr->dev_qual2 |= SID_RMB;
10109         } else
10110                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10111
10112         /* RMB in byte 2 is 0 */
10113         inq_ptr->version = SCSI_REV_SPC5;
10114
10115         /*
10116          * According to SAM-3, even if a device only supports a single
10117          * level of LUN addressing, it should still set the HISUP bit:
10118          *
10119          * 4.9.1 Logical unit numbers overview
10120          *
10121          * All logical unit number formats described in this standard are
10122          * hierarchical in structure even when only a single level in that
10123          * hierarchy is used. The HISUP bit shall be set to one in the
10124          * standard INQUIRY data (see SPC-2) when any logical unit number
10125          * format described in this standard is used.  Non-hierarchical
10126          * formats are outside the scope of this standard.
10127          *
10128          * Therefore we set the HiSup bit here.
10129          *
10130          * The response format is 2, per SPC-3.
10131          */
10132         inq_ptr->response_format = SID_HiSup | 2;
10133
10134         inq_ptr->additional_length = data_len -
10135             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10136         CTL_DEBUG_PRINT(("additional_length = %d\n",
10137                          inq_ptr->additional_length));
10138
10139         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10140         if (port_type == CTL_PORT_SCSI)
10141                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10142         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10143         inq_ptr->flags = SID_CmdQue;
10144         if (port_type == CTL_PORT_SCSI)
10145                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10146
10147         /*
10148          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10149          * We have 8 bytes for the vendor name, and 16 bytes for the device
10150          * name and 4 bytes for the revision.
10151          */
10152         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10153             "vendor")) == NULL) {
10154                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10155         } else {
10156                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10157                 strncpy(inq_ptr->vendor, val,
10158                     min(sizeof(inq_ptr->vendor), strlen(val)));
10159         }
10160         if (lun == NULL) {
10161                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10162                     sizeof(inq_ptr->product));
10163         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10164                 switch (lun->be_lun->lun_type) {
10165                 case T_DIRECT:
10166                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10167                             sizeof(inq_ptr->product));
10168                         break;
10169                 case T_PROCESSOR:
10170                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10171                             sizeof(inq_ptr->product));
10172                         break;
10173                 case T_CDROM:
10174                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10175                             sizeof(inq_ptr->product));
10176                         break;
10177                 default:
10178                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10179                             sizeof(inq_ptr->product));
10180                         break;
10181                 }
10182         } else {
10183                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10184                 strncpy(inq_ptr->product, val,
10185                     min(sizeof(inq_ptr->product), strlen(val)));
10186         }
10187
10188         /*
10189          * XXX make this a macro somewhere so it automatically gets
10190          * incremented when we make changes.
10191          */
10192         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10193             "revision")) == NULL) {
10194                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10195         } else {
10196                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10197                 strncpy(inq_ptr->revision, val,
10198                     min(sizeof(inq_ptr->revision), strlen(val)));
10199         }
10200
10201         /*
10202          * For parallel SCSI, we support double transition and single
10203          * transition clocking.  We also support QAS (Quick Arbitration
10204          * and Selection) and Information Unit transfers on both the
10205          * control and array devices.
10206          */
10207         if (port_type == CTL_PORT_SCSI)
10208                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10209                                     SID_SPI_IUS;
10210
10211         /* SAM-6 (no version claimed) */
10212         scsi_ulto2b(0x00C0, inq_ptr->version1);
10213         /* SPC-5 (no version claimed) */
10214         scsi_ulto2b(0x05C0, inq_ptr->version2);
10215         if (port_type == CTL_PORT_FC) {
10216                 /* FCP-2 ANSI INCITS.350:2003 */
10217                 scsi_ulto2b(0x0917, inq_ptr->version3);
10218         } else if (port_type == CTL_PORT_SCSI) {
10219                 /* SPI-4 ANSI INCITS.362:200x */
10220                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10221         } else if (port_type == CTL_PORT_ISCSI) {
10222                 /* iSCSI (no version claimed) */
10223                 scsi_ulto2b(0x0960, inq_ptr->version3);
10224         } else if (port_type == CTL_PORT_SAS) {
10225                 /* SAS (no version claimed) */
10226                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10227         }
10228
10229         if (lun == NULL) {
10230                 /* SBC-4 (no version claimed) */
10231                 scsi_ulto2b(0x0600, inq_ptr->version4);
10232         } else {
10233                 switch (lun->be_lun->lun_type) {
10234                 case T_DIRECT:
10235                         /* SBC-4 (no version claimed) */
10236                         scsi_ulto2b(0x0600, inq_ptr->version4);
10237                         break;
10238                 case T_PROCESSOR:
10239                         break;
10240                 case T_CDROM:
10241                         /* MMC-6 (no version claimed) */
10242                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10243                         break;
10244                 default:
10245                         break;
10246                 }
10247         }
10248
10249         ctl_set_success(ctsio);
10250         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10251         ctsio->be_move_done = ctl_config_move_done;
10252         ctl_datamove((union ctl_io *)ctsio);
10253         return (CTL_RETVAL_COMPLETE);
10254 }
10255
10256 int
10257 ctl_inquiry(struct ctl_scsiio *ctsio)
10258 {
10259         struct scsi_inquiry *cdb;
10260         int retval;
10261
10262         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10263
10264         cdb = (struct scsi_inquiry *)ctsio->cdb;
10265         if (cdb->byte2 & SI_EVPD)
10266                 retval = ctl_inquiry_evpd(ctsio);
10267         else if (cdb->page_code == 0)
10268                 retval = ctl_inquiry_std(ctsio);
10269         else {
10270                 ctl_set_invalid_field(ctsio,
10271                                       /*sks_valid*/ 1,
10272                                       /*command*/ 1,
10273                                       /*field*/ 2,
10274                                       /*bit_valid*/ 0,
10275                                       /*bit*/ 0);
10276                 ctl_done((union ctl_io *)ctsio);
10277                 return (CTL_RETVAL_COMPLETE);
10278         }
10279
10280         return (retval);
10281 }
10282
10283 int
10284 ctl_get_config(struct ctl_scsiio *ctsio)
10285 {
10286         struct ctl_lun *lun = CTL_LUN(ctsio);
10287         struct scsi_get_config_header *hdr;
10288         struct scsi_get_config_feature *feature;
10289         struct scsi_get_config *cdb;
10290         uint32_t alloc_len, data_len;
10291         int rt, starting;
10292
10293         cdb = (struct scsi_get_config *)ctsio->cdb;
10294         rt = (cdb->rt & SGC_RT_MASK);
10295         starting = scsi_2btoul(cdb->starting_feature);
10296         alloc_len = scsi_2btoul(cdb->length);
10297
10298         data_len = sizeof(struct scsi_get_config_header) +
10299             sizeof(struct scsi_get_config_feature) + 8 +
10300             sizeof(struct scsi_get_config_feature) + 8 +
10301             sizeof(struct scsi_get_config_feature) + 4 +
10302             sizeof(struct scsi_get_config_feature) + 4 +
10303             sizeof(struct scsi_get_config_feature) + 8 +
10304             sizeof(struct scsi_get_config_feature) +
10305             sizeof(struct scsi_get_config_feature) + 4 +
10306             sizeof(struct scsi_get_config_feature) + 4 +
10307             sizeof(struct scsi_get_config_feature) + 4 +
10308             sizeof(struct scsi_get_config_feature) + 4 +
10309             sizeof(struct scsi_get_config_feature) + 4 +
10310             sizeof(struct scsi_get_config_feature) + 4;
10311         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10312         ctsio->kern_sg_entries = 0;
10313         ctsio->kern_data_resid = 0;
10314         ctsio->kern_rel_offset = 0;
10315
10316         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10317         if (lun->flags & CTL_LUN_NO_MEDIA)
10318                 scsi_ulto2b(0x0000, hdr->current_profile);
10319         else
10320                 scsi_ulto2b(0x0010, hdr->current_profile);
10321         feature = (struct scsi_get_config_feature *)(hdr + 1);
10322
10323         if (starting > 0x003b)
10324                 goto done;
10325         if (starting > 0x003a)
10326                 goto f3b;
10327         if (starting > 0x002b)
10328                 goto f3a;
10329         if (starting > 0x002a)
10330                 goto f2b;
10331         if (starting > 0x001f)
10332                 goto f2a;
10333         if (starting > 0x001e)
10334                 goto f1f;
10335         if (starting > 0x001d)
10336                 goto f1e;
10337         if (starting > 0x0010)
10338                 goto f1d;
10339         if (starting > 0x0003)
10340                 goto f10;
10341         if (starting > 0x0002)
10342                 goto f3;
10343         if (starting > 0x0001)
10344                 goto f2;
10345         if (starting > 0x0000)
10346                 goto f1;
10347
10348         /* Profile List */
10349         scsi_ulto2b(0x0000, feature->feature_code);
10350         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10351         feature->add_length = 8;
10352         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10353         feature->feature_data[2] = 0x00;
10354         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10355         feature->feature_data[6] = 0x01;
10356         feature = (struct scsi_get_config_feature *)
10357             &feature->feature_data[feature->add_length];
10358
10359 f1:     /* Core */
10360         scsi_ulto2b(0x0001, feature->feature_code);
10361         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10362         feature->add_length = 8;
10363         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10364         feature->feature_data[4] = 0x03;
10365         feature = (struct scsi_get_config_feature *)
10366             &feature->feature_data[feature->add_length];
10367
10368 f2:     /* Morphing */
10369         scsi_ulto2b(0x0002, feature->feature_code);
10370         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10371         feature->add_length = 4;
10372         feature->feature_data[0] = 0x02;
10373         feature = (struct scsi_get_config_feature *)
10374             &feature->feature_data[feature->add_length];
10375
10376 f3:     /* Removable Medium */
10377         scsi_ulto2b(0x0003, feature->feature_code);
10378         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10379         feature->add_length = 4;
10380         feature->feature_data[0] = 0x39;
10381         feature = (struct scsi_get_config_feature *)
10382             &feature->feature_data[feature->add_length];
10383
10384         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10385                 goto done;
10386
10387 f10:    /* Random Read */
10388         scsi_ulto2b(0x0010, feature->feature_code);
10389         feature->flags = 0x00;
10390         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10391                 feature->flags |= SGC_F_CURRENT;
10392         feature->add_length = 8;
10393         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10394         scsi_ulto2b(1, &feature->feature_data[4]);
10395         feature->feature_data[6] = 0x00;
10396         feature = (struct scsi_get_config_feature *)
10397             &feature->feature_data[feature->add_length];
10398
10399 f1d:    /* Multi-Read */
10400         scsi_ulto2b(0x001D, feature->feature_code);
10401         feature->flags = 0x00;
10402         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10403                 feature->flags |= SGC_F_CURRENT;
10404         feature->add_length = 0;
10405         feature = (struct scsi_get_config_feature *)
10406             &feature->feature_data[feature->add_length];
10407
10408 f1e:    /* CD Read */
10409         scsi_ulto2b(0x001E, feature->feature_code);
10410         feature->flags = 0x00;
10411         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10412                 feature->flags |= SGC_F_CURRENT;
10413         feature->add_length = 4;
10414         feature->feature_data[0] = 0x00;
10415         feature = (struct scsi_get_config_feature *)
10416             &feature->feature_data[feature->add_length];
10417
10418 f1f:    /* DVD Read */
10419         scsi_ulto2b(0x001F, feature->feature_code);
10420         feature->flags = 0x08;
10421         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10422                 feature->flags |= SGC_F_CURRENT;
10423         feature->add_length = 4;
10424         feature->feature_data[0] = 0x01;
10425         feature->feature_data[2] = 0x03;
10426         feature = (struct scsi_get_config_feature *)
10427             &feature->feature_data[feature->add_length];
10428
10429 f2a:    /* DVD+RW */
10430         scsi_ulto2b(0x002A, feature->feature_code);
10431         feature->flags = 0x04;
10432         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10433                 feature->flags |= SGC_F_CURRENT;
10434         feature->add_length = 4;
10435         feature->feature_data[0] = 0x00;
10436         feature->feature_data[1] = 0x00;
10437         feature = (struct scsi_get_config_feature *)
10438             &feature->feature_data[feature->add_length];
10439
10440 f2b:    /* DVD+R */
10441         scsi_ulto2b(0x002B, feature->feature_code);
10442         feature->flags = 0x00;
10443         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10444                 feature->flags |= SGC_F_CURRENT;
10445         feature->add_length = 4;
10446         feature->feature_data[0] = 0x00;
10447         feature = (struct scsi_get_config_feature *)
10448             &feature->feature_data[feature->add_length];
10449
10450 f3a:    /* DVD+RW Dual Layer */
10451         scsi_ulto2b(0x003A, feature->feature_code);
10452         feature->flags = 0x00;
10453         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10454                 feature->flags |= SGC_F_CURRENT;
10455         feature->add_length = 4;
10456         feature->feature_data[0] = 0x00;
10457         feature->feature_data[1] = 0x00;
10458         feature = (struct scsi_get_config_feature *)
10459             &feature->feature_data[feature->add_length];
10460
10461 f3b:    /* DVD+R Dual Layer */
10462         scsi_ulto2b(0x003B, feature->feature_code);
10463         feature->flags = 0x00;
10464         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10465                 feature->flags |= SGC_F_CURRENT;
10466         feature->add_length = 4;
10467         feature->feature_data[0] = 0x00;
10468         feature = (struct scsi_get_config_feature *)
10469             &feature->feature_data[feature->add_length];
10470
10471 done:
10472         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10473         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10474                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10475                 if (scsi_2btoul(feature->feature_code) == starting)
10476                         feature = (struct scsi_get_config_feature *)
10477                             &feature->feature_data[feature->add_length];
10478                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10479         }
10480         scsi_ulto4b(data_len - 4, hdr->data_length);
10481         if (data_len < alloc_len) {
10482                 ctsio->residual = alloc_len - data_len;
10483                 ctsio->kern_data_len = data_len;
10484                 ctsio->kern_total_len = data_len;
10485         } else {
10486                 ctsio->residual = 0;
10487                 ctsio->kern_data_len = alloc_len;
10488                 ctsio->kern_total_len = alloc_len;
10489         }
10490
10491         ctl_set_success(ctsio);
10492         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10493         ctsio->be_move_done = ctl_config_move_done;
10494         ctl_datamove((union ctl_io *)ctsio);
10495         return (CTL_RETVAL_COMPLETE);
10496 }
10497
10498 int
10499 ctl_get_event_status(struct ctl_scsiio *ctsio)
10500 {
10501         struct scsi_get_event_status_header *hdr;
10502         struct scsi_get_event_status *cdb;
10503         uint32_t alloc_len, data_len;
10504         int notif_class;
10505
10506         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10507         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10508                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10509                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10510                 ctl_done((union ctl_io *)ctsio);
10511                 return (CTL_RETVAL_COMPLETE);
10512         }
10513         notif_class = cdb->notif_class;
10514         alloc_len = scsi_2btoul(cdb->length);
10515
10516         data_len = sizeof(struct scsi_get_event_status_header);
10517         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10518         ctsio->kern_sg_entries = 0;
10519         ctsio->kern_data_resid = 0;
10520         ctsio->kern_rel_offset = 0;
10521
10522         if (data_len < alloc_len) {
10523                 ctsio->residual = alloc_len - data_len;
10524                 ctsio->kern_data_len = data_len;
10525                 ctsio->kern_total_len = data_len;
10526         } else {
10527                 ctsio->residual = 0;
10528                 ctsio->kern_data_len = alloc_len;
10529                 ctsio->kern_total_len = alloc_len;
10530         }
10531
10532         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10533         scsi_ulto2b(0, hdr->descr_length);
10534         hdr->nea_class = SGESN_NEA;
10535         hdr->supported_class = 0;
10536
10537         ctl_set_success(ctsio);
10538         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10539         ctsio->be_move_done = ctl_config_move_done;
10540         ctl_datamove((union ctl_io *)ctsio);
10541         return (CTL_RETVAL_COMPLETE);
10542 }
10543
10544 int
10545 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10546 {
10547         struct scsi_mechanism_status_header *hdr;
10548         struct scsi_mechanism_status *cdb;
10549         uint32_t alloc_len, data_len;
10550
10551         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10552         alloc_len = scsi_2btoul(cdb->length);
10553
10554         data_len = sizeof(struct scsi_mechanism_status_header);
10555         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10556         ctsio->kern_sg_entries = 0;
10557         ctsio->kern_data_resid = 0;
10558         ctsio->kern_rel_offset = 0;
10559
10560         if (data_len < alloc_len) {
10561                 ctsio->residual = alloc_len - data_len;
10562                 ctsio->kern_data_len = data_len;
10563                 ctsio->kern_total_len = data_len;
10564         } else {
10565                 ctsio->residual = 0;
10566                 ctsio->kern_data_len = alloc_len;
10567                 ctsio->kern_total_len = alloc_len;
10568         }
10569
10570         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10571         hdr->state1 = 0x00;
10572         hdr->state2 = 0xe0;
10573         scsi_ulto3b(0, hdr->lba);
10574         hdr->slots_num = 0;
10575         scsi_ulto2b(0, hdr->slots_length);
10576
10577         ctl_set_success(ctsio);
10578         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10579         ctsio->be_move_done = ctl_config_move_done;
10580         ctl_datamove((union ctl_io *)ctsio);
10581         return (CTL_RETVAL_COMPLETE);
10582 }
10583
10584 static void
10585 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10586 {
10587
10588         lba += 150;
10589         buf[0] = 0;
10590         buf[1] = bin2bcd((lba / 75) / 60);
10591         buf[2] = bin2bcd((lba / 75) % 60);
10592         buf[3] = bin2bcd(lba % 75);
10593 }
10594
10595 int
10596 ctl_read_toc(struct ctl_scsiio *ctsio)
10597 {
10598         struct ctl_lun *lun = CTL_LUN(ctsio);
10599         struct scsi_read_toc_hdr *hdr;
10600         struct scsi_read_toc_type01_descr *descr;
10601         struct scsi_read_toc *cdb;
10602         uint32_t alloc_len, data_len;
10603         int format, msf;
10604
10605         cdb = (struct scsi_read_toc *)ctsio->cdb;
10606         msf = (cdb->byte2 & CD_MSF) != 0;
10607         format = cdb->format;
10608         alloc_len = scsi_2btoul(cdb->data_len);
10609
10610         data_len = sizeof(struct scsi_read_toc_hdr);
10611         if (format == 0)
10612                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10613         else
10614                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10615         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10616         ctsio->kern_sg_entries = 0;
10617         ctsio->kern_data_resid = 0;
10618         ctsio->kern_rel_offset = 0;
10619
10620         if (data_len < alloc_len) {
10621                 ctsio->residual = alloc_len - data_len;
10622                 ctsio->kern_data_len = data_len;
10623                 ctsio->kern_total_len = data_len;
10624         } else {
10625                 ctsio->residual = 0;
10626                 ctsio->kern_data_len = alloc_len;
10627                 ctsio->kern_total_len = alloc_len;
10628         }
10629
10630         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10631         if (format == 0) {
10632                 scsi_ulto2b(0x12, hdr->data_length);
10633                 hdr->first = 1;
10634                 hdr->last = 1;
10635                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10636                 descr->addr_ctl = 0x14;
10637                 descr->track_number = 1;
10638                 if (msf)
10639                         ctl_ultomsf(0, descr->track_start);
10640                 else
10641                         scsi_ulto4b(0, descr->track_start);
10642                 descr++;
10643                 descr->addr_ctl = 0x14;
10644                 descr->track_number = 0xaa;
10645                 if (msf)
10646                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10647                 else
10648                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10649         } else {
10650                 scsi_ulto2b(0x0a, hdr->data_length);
10651                 hdr->first = 1;
10652                 hdr->last = 1;
10653                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10654                 descr->addr_ctl = 0x14;
10655                 descr->track_number = 1;
10656                 if (msf)
10657                         ctl_ultomsf(0, descr->track_start);
10658                 else
10659                         scsi_ulto4b(0, descr->track_start);
10660         }
10661
10662         ctl_set_success(ctsio);
10663         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10664         ctsio->be_move_done = ctl_config_move_done;
10665         ctl_datamove((union ctl_io *)ctsio);
10666         return (CTL_RETVAL_COMPLETE);
10667 }
10668
10669 /*
10670  * For known CDB types, parse the LBA and length.
10671  */
10672 static int
10673 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10674 {
10675         if (io->io_hdr.io_type != CTL_IO_SCSI)
10676                 return (1);
10677
10678         switch (io->scsiio.cdb[0]) {
10679         case COMPARE_AND_WRITE: {
10680                 struct scsi_compare_and_write *cdb;
10681
10682                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10683
10684                 *lba = scsi_8btou64(cdb->addr);
10685                 *len = cdb->length;
10686                 break;
10687         }
10688         case READ_6:
10689         case WRITE_6: {
10690                 struct scsi_rw_6 *cdb;
10691
10692                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10693
10694                 *lba = scsi_3btoul(cdb->addr);
10695                 /* only 5 bits are valid in the most significant address byte */
10696                 *lba &= 0x1fffff;
10697                 *len = cdb->length;
10698                 break;
10699         }
10700         case READ_10:
10701         case WRITE_10: {
10702                 struct scsi_rw_10 *cdb;
10703
10704                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10705
10706                 *lba = scsi_4btoul(cdb->addr);
10707                 *len = scsi_2btoul(cdb->length);
10708                 break;
10709         }
10710         case WRITE_VERIFY_10: {
10711                 struct scsi_write_verify_10 *cdb;
10712
10713                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10714
10715                 *lba = scsi_4btoul(cdb->addr);
10716                 *len = scsi_2btoul(cdb->length);
10717                 break;
10718         }
10719         case READ_12:
10720         case WRITE_12: {
10721                 struct scsi_rw_12 *cdb;
10722
10723                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10724
10725                 *lba = scsi_4btoul(cdb->addr);
10726                 *len = scsi_4btoul(cdb->length);
10727                 break;
10728         }
10729         case WRITE_VERIFY_12: {
10730                 struct scsi_write_verify_12 *cdb;
10731
10732                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10733
10734                 *lba = scsi_4btoul(cdb->addr);
10735                 *len = scsi_4btoul(cdb->length);
10736                 break;
10737         }
10738         case READ_16:
10739         case WRITE_16: {
10740                 struct scsi_rw_16 *cdb;
10741
10742                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10743
10744                 *lba = scsi_8btou64(cdb->addr);
10745                 *len = scsi_4btoul(cdb->length);
10746                 break;
10747         }
10748         case WRITE_ATOMIC_16: {
10749                 struct scsi_write_atomic_16 *cdb;
10750
10751                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10752
10753                 *lba = scsi_8btou64(cdb->addr);
10754                 *len = scsi_2btoul(cdb->length);
10755                 break;
10756         }
10757         case WRITE_VERIFY_16: {
10758                 struct scsi_write_verify_16 *cdb;
10759
10760                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10761
10762                 *lba = scsi_8btou64(cdb->addr);
10763                 *len = scsi_4btoul(cdb->length);
10764                 break;
10765         }
10766         case WRITE_SAME_10: {
10767                 struct scsi_write_same_10 *cdb;
10768
10769                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10770
10771                 *lba = scsi_4btoul(cdb->addr);
10772                 *len = scsi_2btoul(cdb->length);
10773                 break;
10774         }
10775         case WRITE_SAME_16: {
10776                 struct scsi_write_same_16 *cdb;
10777
10778                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10779
10780                 *lba = scsi_8btou64(cdb->addr);
10781                 *len = scsi_4btoul(cdb->length);
10782                 break;
10783         }
10784         case VERIFY_10: {
10785                 struct scsi_verify_10 *cdb;
10786
10787                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10788
10789                 *lba = scsi_4btoul(cdb->addr);
10790                 *len = scsi_2btoul(cdb->length);
10791                 break;
10792         }
10793         case VERIFY_12: {
10794                 struct scsi_verify_12 *cdb;
10795
10796                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10797
10798                 *lba = scsi_4btoul(cdb->addr);
10799                 *len = scsi_4btoul(cdb->length);
10800                 break;
10801         }
10802         case VERIFY_16: {
10803                 struct scsi_verify_16 *cdb;
10804
10805                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10806
10807                 *lba = scsi_8btou64(cdb->addr);
10808                 *len = scsi_4btoul(cdb->length);
10809                 break;
10810         }
10811         case UNMAP: {
10812                 *lba = 0;
10813                 *len = UINT64_MAX;
10814                 break;
10815         }
10816         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10817                 struct scsi_get_lba_status *cdb;
10818
10819                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10820                 *lba = scsi_8btou64(cdb->addr);
10821                 *len = UINT32_MAX;
10822                 break;
10823         }
10824         default:
10825                 return (1);
10826                 break; /* NOTREACHED */
10827         }
10828
10829         return (0);
10830 }
10831
10832 static ctl_action
10833 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10834     bool seq)
10835 {
10836         uint64_t endlba1, endlba2;
10837
10838         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10839         endlba2 = lba2 + len2 - 1;
10840
10841         if ((endlba1 < lba2) || (endlba2 < lba1))
10842                 return (CTL_ACTION_PASS);
10843         else
10844                 return (CTL_ACTION_BLOCK);
10845 }
10846
10847 static int
10848 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10849 {
10850         struct ctl_ptr_len_flags *ptrlen;
10851         struct scsi_unmap_desc *buf, *end, *range;
10852         uint64_t lba;
10853         uint32_t len;
10854
10855         /* If not UNMAP -- go other way. */
10856         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10857             io->scsiio.cdb[0] != UNMAP)
10858                 return (CTL_ACTION_ERROR);
10859
10860         /* If UNMAP without data -- block and wait for data. */
10861         ptrlen = (struct ctl_ptr_len_flags *)
10862             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10863         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10864             ptrlen->ptr == NULL)
10865                 return (CTL_ACTION_BLOCK);
10866
10867         /* UNMAP with data -- check for collision. */
10868         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10869         end = buf + ptrlen->len / sizeof(*buf);
10870         for (range = buf; range < end; range++) {
10871                 lba = scsi_8btou64(range->lba);
10872                 len = scsi_4btoul(range->length);
10873                 if ((lba < lba2 + len2) && (lba + len > lba2))
10874                         return (CTL_ACTION_BLOCK);
10875         }
10876         return (CTL_ACTION_PASS);
10877 }
10878
10879 static ctl_action
10880 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10881 {
10882         uint64_t lba1, lba2;
10883         uint64_t len1, len2;
10884         int retval;
10885
10886         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10887                 return (CTL_ACTION_ERROR);
10888
10889         retval = ctl_extent_check_unmap(io1, lba2, len2);
10890         if (retval != CTL_ACTION_ERROR)
10891                 return (retval);
10892
10893         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10894                 return (CTL_ACTION_ERROR);
10895
10896         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10897                 seq = FALSE;
10898         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10899 }
10900
10901 static ctl_action
10902 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10903 {
10904         uint64_t lba1, lba2;
10905         uint64_t len1, len2;
10906
10907         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10908                 return (CTL_ACTION_PASS);
10909         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10910                 return (CTL_ACTION_ERROR);
10911         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10912                 return (CTL_ACTION_ERROR);
10913
10914         if (lba1 + len1 == lba2)
10915                 return (CTL_ACTION_BLOCK);
10916         return (CTL_ACTION_PASS);
10917 }
10918
10919 static ctl_action
10920 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10921     union ctl_io *ooa_io)
10922 {
10923         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10924         const ctl_serialize_action *serialize_row;
10925
10926         /*
10927          * The initiator attempted multiple untagged commands at the same
10928          * time.  Can't do that.
10929          */
10930         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10931          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10932          && ((pending_io->io_hdr.nexus.targ_port ==
10933               ooa_io->io_hdr.nexus.targ_port)
10934           && (pending_io->io_hdr.nexus.initid ==
10935               ooa_io->io_hdr.nexus.initid))
10936          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10937               CTL_FLAG_STATUS_SENT)) == 0))
10938                 return (CTL_ACTION_OVERLAP);
10939
10940         /*
10941          * The initiator attempted to send multiple tagged commands with
10942          * the same ID.  (It's fine if different initiators have the same
10943          * tag ID.)
10944          *
10945          * Even if all of those conditions are true, we don't kill the I/O
10946          * if the command ahead of us has been aborted.  We won't end up
10947          * sending it to the FETD, and it's perfectly legal to resend a
10948          * command with the same tag number as long as the previous
10949          * instance of this tag number has been aborted somehow.
10950          */
10951         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10952          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10953          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10954          && ((pending_io->io_hdr.nexus.targ_port ==
10955               ooa_io->io_hdr.nexus.targ_port)
10956           && (pending_io->io_hdr.nexus.initid ==
10957               ooa_io->io_hdr.nexus.initid))
10958          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10959               CTL_FLAG_STATUS_SENT)) == 0))
10960                 return (CTL_ACTION_OVERLAP_TAG);
10961
10962         /*
10963          * If we get a head of queue tag, SAM-3 says that we should
10964          * immediately execute it.
10965          *
10966          * What happens if this command would normally block for some other
10967          * reason?  e.g. a request sense with a head of queue tag
10968          * immediately after a write.  Normally that would block, but this
10969          * will result in its getting executed immediately...
10970          *
10971          * We currently return "pass" instead of "skip", so we'll end up
10972          * going through the rest of the queue to check for overlapped tags.
10973          *
10974          * XXX KDM check for other types of blockage first??
10975          */
10976         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10977                 return (CTL_ACTION_PASS);
10978
10979         /*
10980          * Ordered tags have to block until all items ahead of them
10981          * have completed.  If we get called with an ordered tag, we always
10982          * block, if something else is ahead of us in the queue.
10983          */
10984         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10985                 return (CTL_ACTION_BLOCK);
10986
10987         /*
10988          * Simple tags get blocked until all head of queue and ordered tags
10989          * ahead of them have completed.  I'm lumping untagged commands in
10990          * with simple tags here.  XXX KDM is that the right thing to do?
10991          */
10992         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10993           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10994          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10995           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10996                 return (CTL_ACTION_BLOCK);
10997
10998         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10999         KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11000             ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11001              __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11002              pending_io->scsiio.cdb[1], pending_io));
11003         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11004         if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11005                 return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11006         KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11007             ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11008              __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11009              ooa_io->scsiio.cdb[1], ooa_io));
11010
11011         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11012
11013         switch (serialize_row[pending_entry->seridx]) {
11014         case CTL_SER_BLOCK:
11015                 return (CTL_ACTION_BLOCK);
11016         case CTL_SER_EXTENT:
11017                 return (ctl_extent_check(ooa_io, pending_io,
11018                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11019         case CTL_SER_EXTENTOPT:
11020                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11021                     SCP_QUEUE_ALG_UNRESTRICTED)
11022                         return (ctl_extent_check(ooa_io, pending_io,
11023                             (lun->be_lun &&
11024                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11025                 return (CTL_ACTION_PASS);
11026         case CTL_SER_EXTENTSEQ:
11027                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11028                         return (ctl_extent_check_seq(ooa_io, pending_io));
11029                 return (CTL_ACTION_PASS);
11030         case CTL_SER_PASS:
11031                 return (CTL_ACTION_PASS);
11032         case CTL_SER_BLOCKOPT:
11033                 if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11034                     SCP_QUEUE_ALG_UNRESTRICTED)
11035                         return (CTL_ACTION_BLOCK);
11036                 return (CTL_ACTION_PASS);
11037         case CTL_SER_SKIP:
11038                 return (CTL_ACTION_SKIP);
11039         default:
11040                 panic("%s: Invalid serialization value %d for %d => %d",
11041                     __func__, serialize_row[pending_entry->seridx],
11042                     pending_entry->seridx, ooa_entry->seridx);
11043         }
11044
11045         return (CTL_ACTION_ERROR);
11046 }
11047
11048 /*
11049  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11050  * Assumptions:
11051  * - pending_io is generally either incoming, or on the blocked queue
11052  * - starting I/O is the I/O we want to start the check with.
11053  */
11054 static ctl_action
11055 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11056               union ctl_io *starting_io)
11057 {
11058         union ctl_io *ooa_io;
11059         ctl_action action;
11060
11061         mtx_assert(&lun->lun_lock, MA_OWNED);
11062
11063         /*
11064          * Run back along the OOA queue, starting with the current
11065          * blocked I/O and going through every I/O before it on the
11066          * queue.  If starting_io is NULL, we'll just end up returning
11067          * CTL_ACTION_PASS.
11068          */
11069         for (ooa_io = starting_io; ooa_io != NULL;
11070              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11071              ooa_links)){
11072
11073                 /*
11074                  * This routine just checks to see whether
11075                  * cur_blocked is blocked by ooa_io, which is ahead
11076                  * of it in the queue.  It doesn't queue/dequeue
11077                  * cur_blocked.
11078                  */
11079                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11080                 switch (action) {
11081                 case CTL_ACTION_BLOCK:
11082                 case CTL_ACTION_OVERLAP:
11083                 case CTL_ACTION_OVERLAP_TAG:
11084                 case CTL_ACTION_SKIP:
11085                 case CTL_ACTION_ERROR:
11086                         return (action);
11087                         break; /* NOTREACHED */
11088                 case CTL_ACTION_PASS:
11089                         break;
11090                 default:
11091                         panic("%s: Invalid action %d\n", __func__, action);
11092                 }
11093         }
11094
11095         return (CTL_ACTION_PASS);
11096 }
11097
11098 /*
11099  * Assumptions:
11100  * - An I/O has just completed, and has been removed from the per-LUN OOA
11101  *   queue, so some items on the blocked queue may now be unblocked.
11102  */
11103 static int
11104 ctl_check_blocked(struct ctl_lun *lun)
11105 {
11106         struct ctl_softc *softc = lun->ctl_softc;
11107         union ctl_io *cur_blocked, *next_blocked;
11108
11109         mtx_assert(&lun->lun_lock, MA_OWNED);
11110
11111         /*
11112          * Run forward from the head of the blocked queue, checking each
11113          * entry against the I/Os prior to it on the OOA queue to see if
11114          * there is still any blockage.
11115          *
11116          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11117          * with our removing a variable on it while it is traversing the
11118          * list.
11119          */
11120         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11121              cur_blocked != NULL; cur_blocked = next_blocked) {
11122                 union ctl_io *prev_ooa;
11123                 ctl_action action;
11124
11125                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11126                                                           blocked_links);
11127
11128                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11129                                                       ctl_ooaq, ooa_links);
11130
11131                 /*
11132                  * If cur_blocked happens to be the first item in the OOA
11133                  * queue now, prev_ooa will be NULL, and the action
11134                  * returned will just be CTL_ACTION_PASS.
11135                  */
11136                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11137
11138                 switch (action) {
11139                 case CTL_ACTION_BLOCK:
11140                         /* Nothing to do here, still blocked */
11141                         break;
11142                 case CTL_ACTION_OVERLAP:
11143                 case CTL_ACTION_OVERLAP_TAG:
11144                         /*
11145                          * This shouldn't happen!  In theory we've already
11146                          * checked this command for overlap...
11147                          */
11148                         break;
11149                 case CTL_ACTION_PASS:
11150                 case CTL_ACTION_SKIP: {
11151                         const struct ctl_cmd_entry *entry;
11152
11153                         /*
11154                          * The skip case shouldn't happen, this transaction
11155                          * should have never made it onto the blocked queue.
11156                          */
11157                         /*
11158                          * This I/O is no longer blocked, we can remove it
11159                          * from the blocked queue.  Since this is a TAILQ
11160                          * (doubly linked list), we can do O(1) removals
11161                          * from any place on the list.
11162                          */
11163                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11164                                      blocked_links);
11165                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11166
11167                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11168                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11169                                 /*
11170                                  * Need to send IO back to original side to
11171                                  * run
11172                                  */
11173                                 union ctl_ha_msg msg_info;
11174
11175                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11176                                 msg_info.hdr.original_sc =
11177                                         cur_blocked->io_hdr.original_sc;
11178                                 msg_info.hdr.serializing_sc = cur_blocked;
11179                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11180                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11181                                     sizeof(msg_info.hdr), M_NOWAIT);
11182                                 break;
11183                         }
11184                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11185
11186                         /*
11187                          * Check this I/O for LUN state changes that may
11188                          * have happened while this command was blocked.
11189                          * The LUN state may have been changed by a command
11190                          * ahead of us in the queue, so we need to re-check
11191                          * for any states that can be caused by SCSI
11192                          * commands.
11193                          */
11194                         if (ctl_scsiio_lun_check(lun, entry,
11195                                                  &cur_blocked->scsiio) == 0) {
11196                                 cur_blocked->io_hdr.flags |=
11197                                                       CTL_FLAG_IS_WAS_ON_RTR;
11198                                 ctl_enqueue_rtr(cur_blocked);
11199                         } else
11200                                 ctl_done(cur_blocked);
11201                         break;
11202                 }
11203                 default:
11204                         /*
11205                          * This probably shouldn't happen -- we shouldn't
11206                          * get CTL_ACTION_ERROR, or anything else.
11207                          */
11208                         break;
11209                 }
11210         }
11211
11212         return (CTL_RETVAL_COMPLETE);
11213 }
11214
11215 /*
11216  * This routine (with one exception) checks LUN flags that can be set by
11217  * commands ahead of us in the OOA queue.  These flags have to be checked
11218  * when a command initially comes in, and when we pull a command off the
11219  * blocked queue and are preparing to execute it.  The reason we have to
11220  * check these flags for commands on the blocked queue is that the LUN
11221  * state may have been changed by a command ahead of us while we're on the
11222  * blocked queue.
11223  *
11224  * Ordering is somewhat important with these checks, so please pay
11225  * careful attention to the placement of any new checks.
11226  */
11227 static int
11228 ctl_scsiio_lun_check(struct ctl_lun *lun,
11229     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11230 {
11231         struct ctl_softc *softc = lun->ctl_softc;
11232         int retval;
11233         uint32_t residx;
11234
11235         retval = 0;
11236
11237         mtx_assert(&lun->lun_lock, MA_OWNED);
11238
11239         /*
11240          * If this shelf is a secondary shelf controller, we may have to
11241          * reject some commands disallowed by HA mode and link state.
11242          */
11243         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11244                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11245                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11246                         ctl_set_lun_unavail(ctsio);
11247                         retval = 1;
11248                         goto bailout;
11249                 }
11250                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11251                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11252                         ctl_set_lun_transit(ctsio);
11253                         retval = 1;
11254                         goto bailout;
11255                 }
11256                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11257                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11258                         ctl_set_lun_standby(ctsio);
11259                         retval = 1;
11260                         goto bailout;
11261                 }
11262
11263                 /* The rest of checks are only done on executing side */
11264                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11265                         goto bailout;
11266         }
11267
11268         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11269                 if (lun->be_lun &&
11270                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11271                         ctl_set_hw_write_protected(ctsio);
11272                         retval = 1;
11273                         goto bailout;
11274                 }
11275                 if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11276                         ctl_set_sense(ctsio, /*current_error*/ 1,
11277                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11278                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11279                         retval = 1;
11280                         goto bailout;
11281                 }
11282         }
11283
11284         /*
11285          * Check for a reservation conflict.  If this command isn't allowed
11286          * even on reserved LUNs, and if this initiator isn't the one who
11287          * reserved us, reject the command with a reservation conflict.
11288          */
11289         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11290         if ((lun->flags & CTL_LUN_RESERVED)
11291          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11292                 if (lun->res_idx != residx) {
11293                         ctl_set_reservation_conflict(ctsio);
11294                         retval = 1;
11295                         goto bailout;
11296                 }
11297         }
11298
11299         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11300             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11301                 /* No reservation or command is allowed. */;
11302         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11303             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11304              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11305              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11306                 /* The command is allowed for Write Exclusive resv. */;
11307         } else {
11308                 /*
11309                  * if we aren't registered or it's a res holder type
11310                  * reservation and this isn't the res holder then set a
11311                  * conflict.
11312                  */
11313                 if (ctl_get_prkey(lun, residx) == 0 ||
11314                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11315                         ctl_set_reservation_conflict(ctsio);
11316                         retval = 1;
11317                         goto bailout;
11318                 }
11319         }
11320
11321         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11322                 if (lun->flags & CTL_LUN_EJECTED)
11323                         ctl_set_lun_ejected(ctsio);
11324                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11325                         if (lun->flags & CTL_LUN_REMOVABLE)
11326                                 ctl_set_lun_no_media(ctsio);
11327                         else
11328                                 ctl_set_lun_int_reqd(ctsio);
11329                 } else if (lun->flags & CTL_LUN_STOPPED)
11330                         ctl_set_lun_stopped(ctsio);
11331                 else
11332                         goto bailout;
11333                 retval = 1;
11334                 goto bailout;
11335         }
11336
11337 bailout:
11338         return (retval);
11339 }
11340
11341 static void
11342 ctl_failover_io(union ctl_io *io, int have_lock)
11343 {
11344         ctl_set_busy(&io->scsiio);
11345         ctl_done(io);
11346 }
11347
11348 static void
11349 ctl_failover_lun(union ctl_io *rio)
11350 {
11351         struct ctl_softc *softc = CTL_SOFTC(rio);
11352         struct ctl_lun *lun;
11353         struct ctl_io_hdr *io, *next_io;
11354         uint32_t targ_lun;
11355
11356         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11357         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11358
11359         /* Find and lock the LUN. */
11360         mtx_lock(&softc->ctl_lock);
11361         if (targ_lun > CTL_MAX_LUNS ||
11362             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11363                 mtx_unlock(&softc->ctl_lock);
11364                 return;
11365         }
11366         mtx_lock(&lun->lun_lock);
11367         mtx_unlock(&softc->ctl_lock);
11368         if (lun->flags & CTL_LUN_DISABLED) {
11369                 mtx_unlock(&lun->lun_lock);
11370                 return;
11371         }
11372
11373         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11374                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11375                         /* We are master */
11376                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11377                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11378                                         io->flags |= CTL_FLAG_ABORT;
11379                                         io->flags |= CTL_FLAG_FAILOVER;
11380                                 } else { /* This can be only due to DATAMOVE */
11381                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11382                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11383                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11384                                         io->port_status = 31340;
11385                                         ctl_enqueue_isc((union ctl_io *)io);
11386                                 }
11387                         }
11388                         /* We are slave */
11389                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11390                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11391                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11392                                         io->flags |= CTL_FLAG_FAILOVER;
11393                                 } else {
11394                                         ctl_set_busy(&((union ctl_io *)io)->
11395                                             scsiio);
11396                                         ctl_done((union ctl_io *)io);
11397                                 }
11398                         }
11399                 }
11400         } else { /* SERIALIZE modes */
11401                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11402                     next_io) {
11403                         /* We are master */
11404                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11405                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11406                                     blocked_links);
11407                                 io->flags &= ~CTL_FLAG_BLOCKED;
11408                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11409                                 ctl_free_io((union ctl_io *)io);
11410                         }
11411                 }
11412                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11413                         /* We are master */
11414                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11415                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11416                                 ctl_free_io((union ctl_io *)io);
11417                         }
11418                         /* We are slave */
11419                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11420                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11421                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11422                                         ctl_set_busy(&((union ctl_io *)io)->
11423                                             scsiio);
11424                                         ctl_done((union ctl_io *)io);
11425                                 }
11426                         }
11427                 }
11428                 ctl_check_blocked(lun);
11429         }
11430         mtx_unlock(&lun->lun_lock);
11431 }
11432
11433 static int
11434 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11435 {
11436         struct ctl_lun *lun;
11437         const struct ctl_cmd_entry *entry;
11438         uint32_t initidx, targ_lun;
11439         int retval = 0;
11440
11441         lun = NULL;
11442         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11443         if (targ_lun < CTL_MAX_LUNS)
11444                 lun = softc->ctl_luns[targ_lun];
11445         if (lun) {
11446                 /*
11447                  * If the LUN is invalid, pretend that it doesn't exist.
11448                  * It will go away as soon as all pending I/O has been
11449                  * completed.
11450                  */
11451                 mtx_lock(&lun->lun_lock);
11452                 if (lun->flags & CTL_LUN_DISABLED) {
11453                         mtx_unlock(&lun->lun_lock);
11454                         lun = NULL;
11455                 }
11456         }
11457         CTL_LUN(ctsio) = lun;
11458         if (lun) {
11459                 CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11460
11461                 /*
11462                  * Every I/O goes into the OOA queue for a particular LUN,
11463                  * and stays there until completion.
11464                  */
11465 #ifdef CTL_TIME_IO
11466                 if (TAILQ_EMPTY(&lun->ooa_queue))
11467                         lun->idle_time += getsbinuptime() - lun->last_busy;
11468 #endif
11469                 TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11470         }
11471
11472         /* Get command entry and return error if it is unsuppotyed. */
11473         entry = ctl_validate_command(ctsio);
11474         if (entry == NULL) {
11475                 if (lun)
11476                         mtx_unlock(&lun->lun_lock);
11477                 return (retval);
11478         }
11479
11480         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11481         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11482
11483         /*
11484          * Check to see whether we can send this command to LUNs that don't
11485          * exist.  This should pretty much only be the case for inquiry
11486          * and request sense.  Further checks, below, really require having
11487          * a LUN, so we can't really check the command anymore.  Just put
11488          * it on the rtr queue.
11489          */
11490         if (lun == NULL) {
11491                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11492                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11493                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11494                         return (retval);
11495                 }
11496
11497                 ctl_set_unsupported_lun(ctsio);
11498                 ctl_done((union ctl_io *)ctsio);
11499                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11500                 return (retval);
11501         } else {
11502                 /*
11503                  * Make sure we support this particular command on this LUN.
11504                  * e.g., we don't support writes to the control LUN.
11505                  */
11506                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11507                         mtx_unlock(&lun->lun_lock);
11508                         ctl_set_invalid_opcode(ctsio);
11509                         ctl_done((union ctl_io *)ctsio);
11510                         return (retval);
11511                 }
11512         }
11513
11514         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11515
11516 #ifdef CTL_WITH_CA
11517         /*
11518          * If we've got a request sense, it'll clear the contingent
11519          * allegiance condition.  Otherwise, if we have a CA condition for
11520          * this initiator, clear it, because it sent down a command other
11521          * than request sense.
11522          */
11523         if ((ctsio->cdb[0] != REQUEST_SENSE)
11524          && (ctl_is_set(lun->have_ca, initidx)))
11525                 ctl_clear_mask(lun->have_ca, initidx);
11526 #endif
11527
11528         /*
11529          * If the command has this flag set, it handles its own unit
11530          * attention reporting, we shouldn't do anything.  Otherwise we
11531          * check for any pending unit attentions, and send them back to the
11532          * initiator.  We only do this when a command initially comes in,
11533          * not when we pull it off the blocked queue.
11534          *
11535          * According to SAM-3, section 5.3.2, the order that things get
11536          * presented back to the host is basically unit attentions caused
11537          * by some sort of reset event, busy status, reservation conflicts
11538          * or task set full, and finally any other status.
11539          *
11540          * One issue here is that some of the unit attentions we report
11541          * don't fall into the "reset" category (e.g. "reported luns data
11542          * has changed").  So reporting it here, before the reservation
11543          * check, may be technically wrong.  I guess the only thing to do
11544          * would be to check for and report the reset events here, and then
11545          * check for the other unit attention types after we check for a
11546          * reservation conflict.
11547          *
11548          * XXX KDM need to fix this
11549          */
11550         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11551                 ctl_ua_type ua_type;
11552                 u_int sense_len = 0;
11553
11554                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11555                     &sense_len, SSD_TYPE_NONE);
11556                 if (ua_type != CTL_UA_NONE) {
11557                         mtx_unlock(&lun->lun_lock);
11558                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11559                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11560                         ctsio->sense_len = sense_len;
11561                         ctl_done((union ctl_io *)ctsio);
11562                         return (retval);
11563                 }
11564         }
11565
11566
11567         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11568                 mtx_unlock(&lun->lun_lock);
11569                 ctl_done((union ctl_io *)ctsio);
11570                 return (retval);
11571         }
11572
11573         /*
11574          * XXX CHD this is where we want to send IO to other side if
11575          * this LUN is secondary on this SC. We will need to make a copy
11576          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11577          * the copy we send as FROM_OTHER.
11578          * We also need to stuff the address of the original IO so we can
11579          * find it easily. Something similar will need be done on the other
11580          * side so when we are done we can find the copy.
11581          */
11582         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11583             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11584             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11585                 union ctl_ha_msg msg_info;
11586                 int isc_retval;
11587
11588                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11589                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11590                 mtx_unlock(&lun->lun_lock);
11591
11592                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11593                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11594                 msg_info.hdr.serializing_sc = NULL;
11595                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11596                 msg_info.scsi.tag_num = ctsio->tag_num;
11597                 msg_info.scsi.tag_type = ctsio->tag_type;
11598                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11599                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11600
11601                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11602                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11603                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11604                         ctl_set_busy(ctsio);
11605                         ctl_done((union ctl_io *)ctsio);
11606                         return (retval);
11607                 }
11608                 return (retval);
11609         }
11610
11611         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11612                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11613                               ctl_ooaq, ooa_links))) {
11614         case CTL_ACTION_BLOCK:
11615                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11616                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11617                                   blocked_links);
11618                 mtx_unlock(&lun->lun_lock);
11619                 return (retval);
11620         case CTL_ACTION_PASS:
11621         case CTL_ACTION_SKIP:
11622                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11623                 mtx_unlock(&lun->lun_lock);
11624                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11625                 break;
11626         case CTL_ACTION_OVERLAP:
11627                 mtx_unlock(&lun->lun_lock);
11628                 ctl_set_overlapped_cmd(ctsio);
11629                 ctl_done((union ctl_io *)ctsio);
11630                 break;
11631         case CTL_ACTION_OVERLAP_TAG:
11632                 mtx_unlock(&lun->lun_lock);
11633                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11634                 ctl_done((union ctl_io *)ctsio);
11635                 break;
11636         case CTL_ACTION_ERROR:
11637         default:
11638                 mtx_unlock(&lun->lun_lock);
11639                 ctl_set_internal_failure(ctsio,
11640                                          /*sks_valid*/ 0,
11641                                          /*retry_count*/ 0);
11642                 ctl_done((union ctl_io *)ctsio);
11643                 break;
11644         }
11645         return (retval);
11646 }
11647
11648 const struct ctl_cmd_entry *
11649 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11650 {
11651         const struct ctl_cmd_entry *entry;
11652         int service_action;
11653
11654         entry = &ctl_cmd_table[ctsio->cdb[0]];
11655         if (sa)
11656                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11657         if (entry->flags & CTL_CMD_FLAG_SA5) {
11658                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11659                 entry = &((const struct ctl_cmd_entry *)
11660                     entry->execute)[service_action];
11661         }
11662         return (entry);
11663 }
11664
11665 const struct ctl_cmd_entry *
11666 ctl_validate_command(struct ctl_scsiio *ctsio)
11667 {
11668         const struct ctl_cmd_entry *entry;
11669         int i, sa;
11670         uint8_t diff;
11671
11672         entry = ctl_get_cmd_entry(ctsio, &sa);
11673         if (entry->execute == NULL) {
11674                 if (sa)
11675                         ctl_set_invalid_field(ctsio,
11676                                               /*sks_valid*/ 1,
11677                                               /*command*/ 1,
11678                                               /*field*/ 1,
11679                                               /*bit_valid*/ 1,
11680                                               /*bit*/ 4);
11681                 else
11682                         ctl_set_invalid_opcode(ctsio);
11683                 ctl_done((union ctl_io *)ctsio);
11684                 return (NULL);
11685         }
11686         KASSERT(entry->length > 0,
11687             ("Not defined length for command 0x%02x/0x%02x",
11688              ctsio->cdb[0], ctsio->cdb[1]));
11689         for (i = 1; i < entry->length; i++) {
11690                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11691                 if (diff == 0)
11692                         continue;
11693                 ctl_set_invalid_field(ctsio,
11694                                       /*sks_valid*/ 1,
11695                                       /*command*/ 1,
11696                                       /*field*/ i,
11697                                       /*bit_valid*/ 1,
11698                                       /*bit*/ fls(diff) - 1);
11699                 ctl_done((union ctl_io *)ctsio);
11700                 return (NULL);
11701         }
11702         return (entry);
11703 }
11704
11705 static int
11706 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11707 {
11708
11709         switch (lun_type) {
11710         case T_DIRECT:
11711                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11712                         return (0);
11713                 break;
11714         case T_PROCESSOR:
11715                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11716                         return (0);
11717                 break;
11718         case T_CDROM:
11719                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11720                         return (0);
11721                 break;
11722         default:
11723                 return (0);
11724         }
11725         return (1);
11726 }
11727
11728 static int
11729 ctl_scsiio(struct ctl_scsiio *ctsio)
11730 {
11731         int retval;
11732         const struct ctl_cmd_entry *entry;
11733
11734         retval = CTL_RETVAL_COMPLETE;
11735
11736         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11737
11738         entry = ctl_get_cmd_entry(ctsio, NULL);
11739
11740         /*
11741          * If this I/O has been aborted, just send it straight to
11742          * ctl_done() without executing it.
11743          */
11744         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11745                 ctl_done((union ctl_io *)ctsio);
11746                 goto bailout;
11747         }
11748
11749         /*
11750          * All the checks should have been handled by ctl_scsiio_precheck().
11751          * We should be clear now to just execute the I/O.
11752          */
11753         retval = entry->execute(ctsio);
11754
11755 bailout:
11756         return (retval);
11757 }
11758
11759 /*
11760  * Since we only implement one target right now, a bus reset simply resets
11761  * our single target.
11762  */
11763 static int
11764 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11765 {
11766         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11767 }
11768
11769 static int
11770 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11771                  ctl_ua_type ua_type)
11772 {
11773         struct ctl_port *port = CTL_PORT(io);
11774         struct ctl_lun *lun;
11775         int retval;
11776
11777         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11778                 union ctl_ha_msg msg_info;
11779
11780                 msg_info.hdr.nexus = io->io_hdr.nexus;
11781                 if (ua_type==CTL_UA_TARG_RESET)
11782                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11783                 else
11784                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11785                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11786                 msg_info.hdr.original_sc = NULL;
11787                 msg_info.hdr.serializing_sc = NULL;
11788                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11789                     sizeof(msg_info.task), M_WAITOK);
11790         }
11791         retval = 0;
11792
11793         mtx_lock(&softc->ctl_lock);
11794         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11795                 if (port != NULL &&
11796                     ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11797                         continue;
11798                 retval += ctl_do_lun_reset(lun, io, ua_type);
11799         }
11800         mtx_unlock(&softc->ctl_lock);
11801         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11802         return (retval);
11803 }
11804
11805 /*
11806  * The LUN should always be set.  The I/O is optional, and is used to
11807  * distinguish between I/Os sent by this initiator, and by other
11808  * initiators.  We set unit attention for initiators other than this one.
11809  * SAM-3 is vague on this point.  It does say that a unit attention should
11810  * be established for other initiators when a LUN is reset (see section
11811  * 5.7.3), but it doesn't specifically say that the unit attention should
11812  * be established for this particular initiator when a LUN is reset.  Here
11813  * is the relevant text, from SAM-3 rev 8:
11814  *
11815  * 5.7.2 When a SCSI initiator port aborts its own tasks
11816  *
11817  * When a SCSI initiator port causes its own task(s) to be aborted, no
11818  * notification that the task(s) have been aborted shall be returned to
11819  * the SCSI initiator port other than the completion response for the
11820  * command or task management function action that caused the task(s) to
11821  * be aborted and notification(s) associated with related effects of the
11822  * action (e.g., a reset unit attention condition).
11823  *
11824  * XXX KDM for now, we're setting unit attention for all initiators.
11825  */
11826 static int
11827 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11828 {
11829         union ctl_io *xio;
11830 #if 0
11831         uint32_t initidx;
11832 #endif
11833         int i;
11834
11835         mtx_lock(&lun->lun_lock);
11836         /*
11837          * Run through the OOA queue and abort each I/O.
11838          */
11839         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11840              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11841                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11842         }
11843
11844         /*
11845          * This version sets unit attention for every
11846          */
11847 #if 0
11848         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11849         ctl_est_ua_all(lun, initidx, ua_type);
11850 #else
11851         ctl_est_ua_all(lun, -1, ua_type);
11852 #endif
11853
11854         /*
11855          * A reset (any kind, really) clears reservations established with
11856          * RESERVE/RELEASE.  It does not clear reservations established
11857          * with PERSISTENT RESERVE OUT, but we don't support that at the
11858          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11859          * reservations made with the RESERVE/RELEASE commands, because
11860          * those commands are obsolete in SPC-3.
11861          */
11862         lun->flags &= ~CTL_LUN_RESERVED;
11863
11864 #ifdef CTL_WITH_CA
11865         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11866                 ctl_clear_mask(lun->have_ca, i);
11867 #endif
11868         lun->prevent_count = 0;
11869         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11870                 ctl_clear_mask(lun->prevent, i);
11871         mtx_unlock(&lun->lun_lock);
11872
11873         return (0);
11874 }
11875
11876 static int
11877 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11878 {
11879         struct ctl_lun *lun;
11880         uint32_t targ_lun;
11881         int retval;
11882
11883         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11884         mtx_lock(&softc->ctl_lock);
11885         if (targ_lun >= CTL_MAX_LUNS ||
11886             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11887                 mtx_unlock(&softc->ctl_lock);
11888                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11889                 return (1);
11890         }
11891         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11892         mtx_unlock(&softc->ctl_lock);
11893         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11894
11895         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11896                 union ctl_ha_msg msg_info;
11897
11898                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11899                 msg_info.hdr.nexus = io->io_hdr.nexus;
11900                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11901                 msg_info.hdr.original_sc = NULL;
11902                 msg_info.hdr.serializing_sc = NULL;
11903                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11904                     sizeof(msg_info.task), M_WAITOK);
11905         }
11906         return (retval);
11907 }
11908
11909 static void
11910 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11911     int other_sc)
11912 {
11913         union ctl_io *xio;
11914
11915         mtx_assert(&lun->lun_lock, MA_OWNED);
11916
11917         /*
11918          * Run through the OOA queue and attempt to find the given I/O.
11919          * The target port, initiator ID, tag type and tag number have to
11920          * match the values that we got from the initiator.  If we have an
11921          * untagged command to abort, simply abort the first untagged command
11922          * we come to.  We only allow one untagged command at a time of course.
11923          */
11924         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11925              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11926
11927                 if ((targ_port == UINT32_MAX ||
11928                      targ_port == xio->io_hdr.nexus.targ_port) &&
11929                     (init_id == UINT32_MAX ||
11930                      init_id == xio->io_hdr.nexus.initid)) {
11931                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11932                             init_id != xio->io_hdr.nexus.initid)
11933                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11934                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11935                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11936                                 union ctl_ha_msg msg_info;
11937
11938                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11939                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11940                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11941                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11942                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11943                                 msg_info.hdr.original_sc = NULL;
11944                                 msg_info.hdr.serializing_sc = NULL;
11945                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11946                                     sizeof(msg_info.task), M_NOWAIT);
11947                         }
11948                 }
11949         }
11950 }
11951
11952 static int
11953 ctl_abort_task_set(union ctl_io *io)
11954 {
11955         struct ctl_softc *softc = CTL_SOFTC(io);
11956         struct ctl_lun *lun;
11957         uint32_t targ_lun;
11958
11959         /*
11960          * Look up the LUN.
11961          */
11962         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11963         mtx_lock(&softc->ctl_lock);
11964         if (targ_lun >= CTL_MAX_LUNS ||
11965             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11966                 mtx_unlock(&softc->ctl_lock);
11967                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11968                 return (1);
11969         }
11970
11971         mtx_lock(&lun->lun_lock);
11972         mtx_unlock(&softc->ctl_lock);
11973         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11974                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11975                     io->io_hdr.nexus.initid,
11976                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11977         } else { /* CTL_TASK_CLEAR_TASK_SET */
11978                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11979                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11980         }
11981         mtx_unlock(&lun->lun_lock);
11982         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11983         return (0);
11984 }
11985
11986 static int
11987 ctl_i_t_nexus_reset(union ctl_io *io)
11988 {
11989         struct ctl_softc *softc = CTL_SOFTC(io);
11990         struct ctl_lun *lun;
11991         uint32_t initidx;
11992
11993         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11994                 union ctl_ha_msg msg_info;
11995
11996                 msg_info.hdr.nexus = io->io_hdr.nexus;
11997                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11998                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11999                 msg_info.hdr.original_sc = NULL;
12000                 msg_info.hdr.serializing_sc = NULL;
12001                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12002                     sizeof(msg_info.task), M_WAITOK);
12003         }
12004
12005         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12006         mtx_lock(&softc->ctl_lock);
12007         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12008                 mtx_lock(&lun->lun_lock);
12009                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12010                     io->io_hdr.nexus.initid, 1);
12011 #ifdef CTL_WITH_CA
12012                 ctl_clear_mask(lun->have_ca, initidx);
12013 #endif
12014                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12015                         lun->flags &= ~CTL_LUN_RESERVED;
12016                 if (ctl_is_set(lun->prevent, initidx)) {
12017                         ctl_clear_mask(lun->prevent, initidx);
12018                         lun->prevent_count--;
12019                 }
12020                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12021                 mtx_unlock(&lun->lun_lock);
12022         }
12023         mtx_unlock(&softc->ctl_lock);
12024         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12025         return (0);
12026 }
12027
12028 static int
12029 ctl_abort_task(union ctl_io *io)
12030 {
12031         struct ctl_softc *softc = CTL_SOFTC(io);
12032         union ctl_io *xio;
12033         struct ctl_lun *lun;
12034 #if 0
12035         struct sbuf sb;
12036         char printbuf[128];
12037 #endif
12038         int found;
12039         uint32_t targ_lun;
12040
12041         found = 0;
12042
12043         /*
12044          * Look up the LUN.
12045          */
12046         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12047         mtx_lock(&softc->ctl_lock);
12048         if (targ_lun >= CTL_MAX_LUNS ||
12049             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12050                 mtx_unlock(&softc->ctl_lock);
12051                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12052                 return (1);
12053         }
12054
12055 #if 0
12056         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12057                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12058 #endif
12059
12060         mtx_lock(&lun->lun_lock);
12061         mtx_unlock(&softc->ctl_lock);
12062         /*
12063          * Run through the OOA queue and attempt to find the given I/O.
12064          * The target port, initiator ID, tag type and tag number have to
12065          * match the values that we got from the initiator.  If we have an
12066          * untagged command to abort, simply abort the first untagged command
12067          * we come to.  We only allow one untagged command at a time of course.
12068          */
12069         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12070              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12071 #if 0
12072                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12073
12074                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12075                             lun->lun, xio->scsiio.tag_num,
12076                             xio->scsiio.tag_type,
12077                             (xio->io_hdr.blocked_links.tqe_prev
12078                             == NULL) ? "" : " BLOCKED",
12079                             (xio->io_hdr.flags &
12080                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12081                             (xio->io_hdr.flags &
12082                             CTL_FLAG_ABORT) ? " ABORT" : "",
12083                             (xio->io_hdr.flags &
12084                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12085                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12086                 sbuf_finish(&sb);
12087                 printf("%s\n", sbuf_data(&sb));
12088 #endif
12089
12090                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12091                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12092                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12093                         continue;
12094
12095                 /*
12096                  * If the abort says that the task is untagged, the
12097                  * task in the queue must be untagged.  Otherwise,
12098                  * we just check to see whether the tag numbers
12099                  * match.  This is because the QLogic firmware
12100                  * doesn't pass back the tag type in an abort
12101                  * request.
12102                  */
12103 #if 0
12104                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12105                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12106                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12107 #endif
12108                 /*
12109                  * XXX KDM we've got problems with FC, because it
12110                  * doesn't send down a tag type with aborts.  So we
12111                  * can only really go by the tag number...
12112                  * This may cause problems with parallel SCSI.
12113                  * Need to figure that out!!
12114                  */
12115                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12116                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12117                         found = 1;
12118                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12119                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12120                                 union ctl_ha_msg msg_info;
12121
12122                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12123                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12124                                 msg_info.task.tag_num = io->taskio.tag_num;
12125                                 msg_info.task.tag_type = io->taskio.tag_type;
12126                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12127                                 msg_info.hdr.original_sc = NULL;
12128                                 msg_info.hdr.serializing_sc = NULL;
12129 #if 0
12130                                 printf("Sent Abort to other side\n");
12131 #endif
12132                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12133                                     sizeof(msg_info.task), M_NOWAIT);
12134                         }
12135 #if 0
12136                         printf("ctl_abort_task: found I/O to abort\n");
12137 #endif
12138                 }
12139         }
12140         mtx_unlock(&lun->lun_lock);
12141
12142         if (found == 0) {
12143                 /*
12144                  * This isn't really an error.  It's entirely possible for
12145                  * the abort and command completion to cross on the wire.
12146                  * This is more of an informative/diagnostic error.
12147                  */
12148 #if 0
12149                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12150                        "%u:%u:%u tag %d type %d\n",
12151                        io->io_hdr.nexus.initid,
12152                        io->io_hdr.nexus.targ_port,
12153                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12154                        io->taskio.tag_type);
12155 #endif
12156         }
12157         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12158         return (0);
12159 }
12160
12161 static int
12162 ctl_query_task(union ctl_io *io, int task_set)
12163 {
12164         struct ctl_softc *softc = CTL_SOFTC(io);
12165         union ctl_io *xio;
12166         struct ctl_lun *lun;
12167         int found = 0;
12168         uint32_t targ_lun;
12169
12170         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12171         mtx_lock(&softc->ctl_lock);
12172         if (targ_lun >= CTL_MAX_LUNS ||
12173             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12174                 mtx_unlock(&softc->ctl_lock);
12175                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12176                 return (1);
12177         }
12178         mtx_lock(&lun->lun_lock);
12179         mtx_unlock(&softc->ctl_lock);
12180         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12181              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12182
12183                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12184                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12185                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12186                         continue;
12187
12188                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12189                         found = 1;
12190                         break;
12191                 }
12192         }
12193         mtx_unlock(&lun->lun_lock);
12194         if (found)
12195                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12196         else
12197                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12198         return (0);
12199 }
12200
12201 static int
12202 ctl_query_async_event(union ctl_io *io)
12203 {
12204         struct ctl_softc *softc = CTL_SOFTC(io);
12205         struct ctl_lun *lun;
12206         ctl_ua_type ua;
12207         uint32_t targ_lun, initidx;
12208
12209         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12210         mtx_lock(&softc->ctl_lock);
12211         if (targ_lun >= CTL_MAX_LUNS ||
12212             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12213                 mtx_unlock(&softc->ctl_lock);
12214                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12215                 return (1);
12216         }
12217         mtx_lock(&lun->lun_lock);
12218         mtx_unlock(&softc->ctl_lock);
12219         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12220         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12221         mtx_unlock(&lun->lun_lock);
12222         if (ua != CTL_UA_NONE)
12223                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12224         else
12225                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12226         return (0);
12227 }
12228
12229 static void
12230 ctl_run_task(union ctl_io *io)
12231 {
12232         struct ctl_softc *softc = CTL_SOFTC(io);
12233         int retval = 1;
12234
12235         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12236         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12237             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12238         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12239         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12240         switch (io->taskio.task_action) {
12241         case CTL_TASK_ABORT_TASK:
12242                 retval = ctl_abort_task(io);
12243                 break;
12244         case CTL_TASK_ABORT_TASK_SET:
12245         case CTL_TASK_CLEAR_TASK_SET:
12246                 retval = ctl_abort_task_set(io);
12247                 break;
12248         case CTL_TASK_CLEAR_ACA:
12249                 break;
12250         case CTL_TASK_I_T_NEXUS_RESET:
12251                 retval = ctl_i_t_nexus_reset(io);
12252                 break;
12253         case CTL_TASK_LUN_RESET:
12254                 retval = ctl_lun_reset(softc, io);
12255                 break;
12256         case CTL_TASK_TARGET_RESET:
12257                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12258                 break;
12259         case CTL_TASK_BUS_RESET:
12260                 retval = ctl_bus_reset(softc, io);
12261                 break;
12262         case CTL_TASK_PORT_LOGIN:
12263                 break;
12264         case CTL_TASK_PORT_LOGOUT:
12265                 break;
12266         case CTL_TASK_QUERY_TASK:
12267                 retval = ctl_query_task(io, 0);
12268                 break;
12269         case CTL_TASK_QUERY_TASK_SET:
12270                 retval = ctl_query_task(io, 1);
12271                 break;
12272         case CTL_TASK_QUERY_ASYNC_EVENT:
12273                 retval = ctl_query_async_event(io);
12274                 break;
12275         default:
12276                 printf("%s: got unknown task management event %d\n",
12277                        __func__, io->taskio.task_action);
12278                 break;
12279         }
12280         if (retval == 0)
12281                 io->io_hdr.status = CTL_SUCCESS;
12282         else
12283                 io->io_hdr.status = CTL_ERROR;
12284         ctl_done(io);
12285 }
12286
12287 /*
12288  * For HA operation.  Handle commands that come in from the other
12289  * controller.
12290  */
12291 static void
12292 ctl_handle_isc(union ctl_io *io)
12293 {
12294         struct ctl_softc *softc = CTL_SOFTC(io);
12295         struct ctl_lun *lun;
12296         const struct ctl_cmd_entry *entry;
12297         uint32_t targ_lun;
12298
12299         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12300         switch (io->io_hdr.msg_type) {
12301         case CTL_MSG_SERIALIZE:
12302                 ctl_serialize_other_sc_cmd(&io->scsiio);
12303                 break;
12304         case CTL_MSG_R2R:               /* Only used in SER_ONLY mode. */
12305                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12306                 if (targ_lun >= CTL_MAX_LUNS ||
12307                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12308                         ctl_done(io);
12309                         break;
12310                 }
12311                 mtx_lock(&lun->lun_lock);
12312                 if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12313                         mtx_unlock(&lun->lun_lock);
12314                         ctl_done(io);
12315                         break;
12316                 }
12317                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12318                 mtx_unlock(&lun->lun_lock);
12319                 ctl_enqueue_rtr(io);
12320                 break;
12321         case CTL_MSG_FINISH_IO:
12322                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12323                         ctl_done(io);
12324                         break;
12325                 }
12326                 if (targ_lun >= CTL_MAX_LUNS ||
12327                     (lun = softc->ctl_luns[targ_lun]) == NULL) {
12328                         ctl_free_io(io);
12329                         break;
12330                 }
12331                 mtx_lock(&lun->lun_lock);
12332                 TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12333                 ctl_check_blocked(lun);
12334                 mtx_unlock(&lun->lun_lock);
12335                 ctl_free_io(io);
12336                 break;
12337         case CTL_MSG_PERS_ACTION:
12338                 ctl_hndl_per_res_out_on_other_sc(io);
12339                 ctl_free_io(io);
12340                 break;
12341         case CTL_MSG_BAD_JUJU:
12342                 ctl_done(io);
12343                 break;
12344         case CTL_MSG_DATAMOVE:          /* Only used in XFER mode */
12345                 ctl_datamove_remote(io);
12346                 break;
12347         case CTL_MSG_DATAMOVE_DONE:     /* Only used in XFER mode */
12348                 io->scsiio.be_move_done(io);
12349                 break;
12350         case CTL_MSG_FAILOVER:
12351                 ctl_failover_lun(io);
12352                 ctl_free_io(io);
12353                 break;
12354         default:
12355                 printf("%s: Invalid message type %d\n",
12356                        __func__, io->io_hdr.msg_type);
12357                 ctl_free_io(io);
12358                 break;
12359         }
12360
12361 }
12362
12363
12364 /*
12365  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12366  * there is no match.
12367  */
12368 static ctl_lun_error_pattern
12369 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12370 {
12371         const struct ctl_cmd_entry *entry;
12372         ctl_lun_error_pattern filtered_pattern, pattern;
12373
12374         pattern = desc->error_pattern;
12375
12376         /*
12377          * XXX KDM we need more data passed into this function to match a
12378          * custom pattern, and we actually need to implement custom pattern
12379          * matching.
12380          */
12381         if (pattern & CTL_LUN_PAT_CMD)
12382                 return (CTL_LUN_PAT_CMD);
12383
12384         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12385                 return (CTL_LUN_PAT_ANY);
12386
12387         entry = ctl_get_cmd_entry(ctsio, NULL);
12388
12389         filtered_pattern = entry->pattern & pattern;
12390
12391         /*
12392          * If the user requested specific flags in the pattern (e.g.
12393          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12394          * flags.
12395          *
12396          * If the user did not specify any flags, it doesn't matter whether
12397          * or not the command supports the flags.
12398          */
12399         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12400              (pattern & ~CTL_LUN_PAT_MASK))
12401                 return (CTL_LUN_PAT_NONE);
12402
12403         /*
12404          * If the user asked for a range check, see if the requested LBA
12405          * range overlaps with this command's LBA range.
12406          */
12407         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12408                 uint64_t lba1;
12409                 uint64_t len1;
12410                 ctl_action action;
12411                 int retval;
12412
12413                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12414                 if (retval != 0)
12415                         return (CTL_LUN_PAT_NONE);
12416
12417                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12418                                               desc->lba_range.len, FALSE);
12419                 /*
12420                  * A "pass" means that the LBA ranges don't overlap, so
12421                  * this doesn't match the user's range criteria.
12422                  */
12423                 if (action == CTL_ACTION_PASS)
12424                         return (CTL_LUN_PAT_NONE);
12425         }
12426
12427         return (filtered_pattern);
12428 }
12429
12430 static void
12431 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12432 {
12433         struct ctl_error_desc *desc, *desc2;
12434
12435         mtx_assert(&lun->lun_lock, MA_OWNED);
12436
12437         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12438                 ctl_lun_error_pattern pattern;
12439                 /*
12440                  * Check to see whether this particular command matches
12441                  * the pattern in the descriptor.
12442                  */
12443                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12444                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12445                         continue;
12446
12447                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12448                 case CTL_LUN_INJ_ABORTED:
12449                         ctl_set_aborted(&io->scsiio);
12450                         break;
12451                 case CTL_LUN_INJ_MEDIUM_ERR:
12452                         ctl_set_medium_error(&io->scsiio,
12453                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12454                              CTL_FLAG_DATA_OUT);
12455                         break;
12456                 case CTL_LUN_INJ_UA:
12457                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12458                          * OCCURRED */
12459                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12460                         break;
12461                 case CTL_LUN_INJ_CUSTOM:
12462                         /*
12463                          * We're assuming the user knows what he is doing.
12464                          * Just copy the sense information without doing
12465                          * checks.
12466                          */
12467                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12468                               MIN(sizeof(desc->custom_sense),
12469                                   sizeof(io->scsiio.sense_data)));
12470                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12471                         io->scsiio.sense_len = SSD_FULL_SIZE;
12472                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12473                         break;
12474                 case CTL_LUN_INJ_NONE:
12475                 default:
12476                         /*
12477                          * If this is an error injection type we don't know
12478                          * about, clear the continuous flag (if it is set)
12479                          * so it will get deleted below.
12480                          */
12481                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12482                         break;
12483                 }
12484                 /*
12485                  * By default, each error injection action is a one-shot
12486                  */
12487                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12488                         continue;
12489
12490                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12491
12492                 free(desc, M_CTL);
12493         }
12494 }
12495
12496 #ifdef CTL_IO_DELAY
12497 static void
12498 ctl_datamove_timer_wakeup(void *arg)
12499 {
12500         union ctl_io *io;
12501
12502         io = (union ctl_io *)arg;
12503
12504         ctl_datamove(io);
12505 }
12506 #endif /* CTL_IO_DELAY */
12507
12508 void
12509 ctl_datamove(union ctl_io *io)
12510 {
12511         void (*fe_datamove)(union ctl_io *io);
12512
12513         mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12514
12515         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12516
12517 #ifdef CTL_TIME_IO
12518         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12519                 char str[256];
12520                 char path_str[64];
12521                 struct sbuf sb;
12522
12523                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12524                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12525
12526                 sbuf_cat(&sb, path_str);
12527                 switch (io->io_hdr.io_type) {
12528                 case CTL_IO_SCSI:
12529                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12530                         sbuf_printf(&sb, "\n");
12531                         sbuf_cat(&sb, path_str);
12532                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12533                                     io->scsiio.tag_num, io->scsiio.tag_type);
12534                         break;
12535                 case CTL_IO_TASK:
12536                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12537                                     "Tag Type: %d\n", io->taskio.task_action,
12538                                     io->taskio.tag_num, io->taskio.tag_type);
12539                         break;
12540                 default:
12541                         panic("%s: Invalid CTL I/O type %d\n",
12542                             __func__, io->io_hdr.io_type);
12543                 }
12544                 sbuf_cat(&sb, path_str);
12545                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12546                             (intmax_t)time_uptime - io->io_hdr.start_time);
12547                 sbuf_finish(&sb);
12548                 printf("%s", sbuf_data(&sb));
12549         }
12550 #endif /* CTL_TIME_IO */
12551
12552 #ifdef CTL_IO_DELAY
12553         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12554                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12555         } else {
12556                 if ((lun != NULL)
12557                  && (lun->delay_info.datamove_delay > 0)) {
12558
12559                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12560                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12561                         callout_reset(&io->io_hdr.delay_callout,
12562                                       lun->delay_info.datamove_delay * hz,
12563                                       ctl_datamove_timer_wakeup, io);
12564                         if (lun->delay_info.datamove_type ==
12565                             CTL_DELAY_TYPE_ONESHOT)
12566                                 lun->delay_info.datamove_delay = 0;
12567                         return;
12568                 }
12569         }
12570 #endif
12571
12572         /*
12573          * This command has been aborted.  Set the port status, so we fail
12574          * the data move.
12575          */
12576         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12577                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12578                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12579                        io->io_hdr.nexus.targ_port,
12580                        io->io_hdr.nexus.targ_lun);
12581                 io->io_hdr.port_status = 31337;
12582                 /*
12583                  * Note that the backend, in this case, will get the
12584                  * callback in its context.  In other cases it may get
12585                  * called in the frontend's interrupt thread context.
12586                  */
12587                 io->scsiio.be_move_done(io);
12588                 return;
12589         }
12590
12591         /* Don't confuse frontend with zero length data move. */
12592         if (io->scsiio.kern_data_len == 0) {
12593                 io->scsiio.be_move_done(io);
12594                 return;
12595         }
12596
12597         fe_datamove = CTL_PORT(io)->fe_datamove;
12598         fe_datamove(io);
12599 }
12600
12601 static void
12602 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12603 {
12604         union ctl_ha_msg msg;
12605 #ifdef CTL_TIME_IO
12606         struct bintime cur_bt;
12607 #endif
12608
12609         memset(&msg, 0, sizeof(msg));
12610         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12611         msg.hdr.original_sc = io;
12612         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12613         msg.hdr.nexus = io->io_hdr.nexus;
12614         msg.hdr.status = io->io_hdr.status;
12615         msg.scsi.tag_num = io->scsiio.tag_num;
12616         msg.scsi.tag_type = io->scsiio.tag_type;
12617         msg.scsi.scsi_status = io->scsiio.scsi_status;
12618         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12619                io->scsiio.sense_len);
12620         msg.scsi.sense_len = io->scsiio.sense_len;
12621         msg.scsi.sense_residual = io->scsiio.sense_residual;
12622         msg.scsi.fetd_status = io->io_hdr.port_status;
12623         msg.scsi.residual = io->scsiio.residual;
12624         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12625         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12626                 ctl_failover_io(io, /*have_lock*/ have_lock);
12627                 return;
12628         }
12629         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12630             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12631             msg.scsi.sense_len, M_WAITOK);
12632
12633 #ifdef CTL_TIME_IO
12634         getbinuptime(&cur_bt);
12635         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12636         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12637 #endif
12638         io->io_hdr.num_dmas++;
12639 }
12640
12641 /*
12642  * The DMA to the remote side is done, now we need to tell the other side
12643  * we're done so it can continue with its data movement.
12644  */
12645 static void
12646 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12647 {
12648         union ctl_io *io;
12649         uint32_t i;
12650
12651         io = rq->context;
12652
12653         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12654                 printf("%s: ISC DMA write failed with error %d", __func__,
12655                        rq->ret);
12656                 ctl_set_internal_failure(&io->scsiio,
12657                                          /*sks_valid*/ 1,
12658                                          /*retry_count*/ rq->ret);
12659         }
12660
12661         ctl_dt_req_free(rq);
12662
12663         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12664                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12665         free(io->io_hdr.remote_sglist, M_CTL);
12666         io->io_hdr.remote_sglist = NULL;
12667         io->io_hdr.local_sglist = NULL;
12668
12669         /*
12670          * The data is in local and remote memory, so now we need to send
12671          * status (good or back) back to the other side.
12672          */
12673         ctl_send_datamove_done(io, /*have_lock*/ 0);
12674 }
12675
12676 /*
12677  * We've moved the data from the host/controller into local memory.  Now we
12678  * need to push it over to the remote controller's memory.
12679  */
12680 static int
12681 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12682 {
12683         int retval;
12684
12685         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12686                                           ctl_datamove_remote_write_cb);
12687         return (retval);
12688 }
12689
12690 static void
12691 ctl_datamove_remote_write(union ctl_io *io)
12692 {
12693         int retval;
12694         void (*fe_datamove)(union ctl_io *io);
12695
12696         /*
12697          * - Get the data from the host/HBA into local memory.
12698          * - DMA memory from the local controller to the remote controller.
12699          * - Send status back to the remote controller.
12700          */
12701
12702         retval = ctl_datamove_remote_sgl_setup(io);
12703         if (retval != 0)
12704                 return;
12705
12706         /* Switch the pointer over so the FETD knows what to do */
12707         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12708
12709         /*
12710          * Use a custom move done callback, since we need to send completion
12711          * back to the other controller, not to the backend on this side.
12712          */
12713         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12714
12715         fe_datamove = CTL_PORT(io)->fe_datamove;
12716         fe_datamove(io);
12717 }
12718
12719 static int
12720 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12721 {
12722 #if 0
12723         char str[256];
12724         char path_str[64];
12725         struct sbuf sb;
12726 #endif
12727         uint32_t i;
12728
12729         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12730                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12731         free(io->io_hdr.remote_sglist, M_CTL);
12732         io->io_hdr.remote_sglist = NULL;
12733         io->io_hdr.local_sglist = NULL;
12734
12735 #if 0
12736         scsi_path_string(io, path_str, sizeof(path_str));
12737         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12738         sbuf_cat(&sb, path_str);
12739         scsi_command_string(&io->scsiio, NULL, &sb);
12740         sbuf_printf(&sb, "\n");
12741         sbuf_cat(&sb, path_str);
12742         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12743                     io->scsiio.tag_num, io->scsiio.tag_type);
12744         sbuf_cat(&sb, path_str);
12745         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12746                     io->io_hdr.flags, io->io_hdr.status);
12747         sbuf_finish(&sb);
12748         printk("%s", sbuf_data(&sb));
12749 #endif
12750
12751
12752         /*
12753          * The read is done, now we need to send status (good or bad) back
12754          * to the other side.
12755          */
12756         ctl_send_datamove_done(io, /*have_lock*/ 0);
12757
12758         return (0);
12759 }
12760
12761 static void
12762 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12763 {
12764         union ctl_io *io;
12765         void (*fe_datamove)(union ctl_io *io);
12766
12767         io = rq->context;
12768
12769         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12770                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12771                        rq->ret);
12772                 ctl_set_internal_failure(&io->scsiio,
12773                                          /*sks_valid*/ 1,
12774                                          /*retry_count*/ rq->ret);
12775         }
12776
12777         ctl_dt_req_free(rq);
12778
12779         /* Switch the pointer over so the FETD knows what to do */
12780         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12781
12782         /*
12783          * Use a custom move done callback, since we need to send completion
12784          * back to the other controller, not to the backend on this side.
12785          */
12786         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12787
12788         /* XXX KDM add checks like the ones in ctl_datamove? */
12789
12790         fe_datamove = CTL_PORT(io)->fe_datamove;
12791         fe_datamove(io);
12792 }
12793
12794 static int
12795 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12796 {
12797         struct ctl_sg_entry *local_sglist;
12798         uint32_t len_to_go;
12799         int retval;
12800         int i;
12801
12802         retval = 0;
12803         local_sglist = io->io_hdr.local_sglist;
12804         len_to_go = io->scsiio.kern_data_len;
12805
12806         /*
12807          * The difficult thing here is that the size of the various
12808          * S/G segments may be different than the size from the
12809          * remote controller.  That'll make it harder when DMAing
12810          * the data back to the other side.
12811          */
12812         for (i = 0; len_to_go > 0; i++) {
12813                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12814                 local_sglist[i].addr =
12815                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12816
12817                 len_to_go -= local_sglist[i].len;
12818         }
12819         /*
12820          * Reset the number of S/G entries accordingly.  The original
12821          * number of S/G entries is available in rem_sg_entries.
12822          */
12823         io->scsiio.kern_sg_entries = i;
12824
12825 #if 0
12826         printf("%s: kern_sg_entries = %d\n", __func__,
12827                io->scsiio.kern_sg_entries);
12828         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12829                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12830                        local_sglist[i].addr, local_sglist[i].len);
12831 #endif
12832
12833         return (retval);
12834 }
12835
12836 static int
12837 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12838                          ctl_ha_dt_cb callback)
12839 {
12840         struct ctl_ha_dt_req *rq;
12841         struct ctl_sg_entry *remote_sglist, *local_sglist;
12842         uint32_t local_used, remote_used, total_used;
12843         int i, j, isc_ret;
12844
12845         rq = ctl_dt_req_alloc();
12846
12847         /*
12848          * If we failed to allocate the request, and if the DMA didn't fail
12849          * anyway, set busy status.  This is just a resource allocation
12850          * failure.
12851          */
12852         if ((rq == NULL)
12853          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12854              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12855                 ctl_set_busy(&io->scsiio);
12856
12857         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12858             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12859
12860                 if (rq != NULL)
12861                         ctl_dt_req_free(rq);
12862
12863                 /*
12864                  * The data move failed.  We need to return status back
12865                  * to the other controller.  No point in trying to DMA
12866                  * data to the remote controller.
12867                  */
12868
12869                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12870
12871                 return (1);
12872         }
12873
12874         local_sglist = io->io_hdr.local_sglist;
12875         remote_sglist = io->io_hdr.remote_sglist;
12876         local_used = 0;
12877         remote_used = 0;
12878         total_used = 0;
12879
12880         /*
12881          * Pull/push the data over the wire from/to the other controller.
12882          * This takes into account the possibility that the local and
12883          * remote sglists may not be identical in terms of the size of
12884          * the elements and the number of elements.
12885          *
12886          * One fundamental assumption here is that the length allocated for
12887          * both the local and remote sglists is identical.  Otherwise, we've
12888          * essentially got a coding error of some sort.
12889          */
12890         isc_ret = CTL_HA_STATUS_SUCCESS;
12891         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12892                 uint32_t cur_len;
12893                 uint8_t *tmp_ptr;
12894
12895                 rq->command = command;
12896                 rq->context = io;
12897
12898                 /*
12899                  * Both pointers should be aligned.  But it is possible
12900                  * that the allocation length is not.  They should both
12901                  * also have enough slack left over at the end, though,
12902                  * to round up to the next 8 byte boundary.
12903                  */
12904                 cur_len = MIN(local_sglist[i].len - local_used,
12905                               remote_sglist[j].len - remote_used);
12906                 rq->size = cur_len;
12907
12908                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12909                 tmp_ptr += local_used;
12910
12911 #if 0
12912                 /* Use physical addresses when talking to ISC hardware */
12913                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12914                         /* XXX KDM use busdma */
12915                         rq->local = vtophys(tmp_ptr);
12916                 } else
12917                         rq->local = tmp_ptr;
12918 #else
12919                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12920                     ("HA does not support BUS_ADDR"));
12921                 rq->local = tmp_ptr;
12922 #endif
12923
12924                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12925                 tmp_ptr += remote_used;
12926                 rq->remote = tmp_ptr;
12927
12928                 rq->callback = NULL;
12929
12930                 local_used += cur_len;
12931                 if (local_used >= local_sglist[i].len) {
12932                         i++;
12933                         local_used = 0;
12934                 }
12935
12936                 remote_used += cur_len;
12937                 if (remote_used >= remote_sglist[j].len) {
12938                         j++;
12939                         remote_used = 0;
12940                 }
12941                 total_used += cur_len;
12942
12943                 if (total_used >= io->scsiio.kern_data_len)
12944                         rq->callback = callback;
12945
12946 #if 0
12947                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12948                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12949                        rq->local, rq->remote, rq->size);
12950 #endif
12951
12952                 isc_ret = ctl_dt_single(rq);
12953                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12954                         break;
12955         }
12956         if (isc_ret != CTL_HA_STATUS_WAIT) {
12957                 rq->ret = isc_ret;
12958                 callback(rq);
12959         }
12960
12961         return (0);
12962 }
12963
12964 static void
12965 ctl_datamove_remote_read(union ctl_io *io)
12966 {
12967         int retval;
12968         uint32_t i;
12969
12970         /*
12971          * This will send an error to the other controller in the case of a
12972          * failure.
12973          */
12974         retval = ctl_datamove_remote_sgl_setup(io);
12975         if (retval != 0)
12976                 return;
12977
12978         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12979                                           ctl_datamove_remote_read_cb);
12980         if (retval != 0) {
12981                 /*
12982                  * Make sure we free memory if there was an error..  The
12983                  * ctl_datamove_remote_xfer() function will send the
12984                  * datamove done message, or call the callback with an
12985                  * error if there is a problem.
12986                  */
12987                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12988                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12989                 free(io->io_hdr.remote_sglist, M_CTL);
12990                 io->io_hdr.remote_sglist = NULL;
12991                 io->io_hdr.local_sglist = NULL;
12992         }
12993 }
12994
12995 /*
12996  * Process a datamove request from the other controller.  This is used for
12997  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12998  * first.  Once that is complete, the data gets DMAed into the remote
12999  * controller's memory.  For reads, we DMA from the remote controller's
13000  * memory into our memory first, and then move it out to the FETD.
13001  */
13002 static void
13003 ctl_datamove_remote(union ctl_io *io)
13004 {
13005
13006         mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13007
13008         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13009                 ctl_failover_io(io, /*have_lock*/ 0);
13010                 return;
13011         }
13012
13013         /*
13014          * Note that we look for an aborted I/O here, but don't do some of
13015          * the other checks that ctl_datamove() normally does.
13016          * We don't need to run the datamove delay code, since that should
13017          * have been done if need be on the other controller.
13018          */
13019         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13020                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13021                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13022                        io->io_hdr.nexus.targ_port,
13023                        io->io_hdr.nexus.targ_lun);
13024                 io->io_hdr.port_status = 31338;
13025                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13026                 return;
13027         }
13028
13029         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13030                 ctl_datamove_remote_write(io);
13031         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13032                 ctl_datamove_remote_read(io);
13033         else {
13034                 io->io_hdr.port_status = 31339;
13035                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13036         }
13037 }
13038
13039 static void
13040 ctl_process_done(union ctl_io *io)
13041 {
13042         struct ctl_softc *softc = CTL_SOFTC(io);
13043         struct ctl_lun *lun = CTL_LUN(io);
13044         void (*fe_done)(union ctl_io *io);
13045         union ctl_ha_msg msg;
13046         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13047
13048         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13049         fe_done = softc->ctl_ports[targ_port]->fe_done;
13050
13051 #ifdef CTL_TIME_IO
13052         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13053                 char str[256];
13054                 char path_str[64];
13055                 struct sbuf sb;
13056
13057                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13058                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13059
13060                 sbuf_cat(&sb, path_str);
13061                 switch (io->io_hdr.io_type) {
13062                 case CTL_IO_SCSI:
13063                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13064                         sbuf_printf(&sb, "\n");
13065                         sbuf_cat(&sb, path_str);
13066                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13067                                     io->scsiio.tag_num, io->scsiio.tag_type);
13068                         break;
13069                 case CTL_IO_TASK:
13070                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13071                                     "Tag Type: %d\n", io->taskio.task_action,
13072                                     io->taskio.tag_num, io->taskio.tag_type);
13073                         break;
13074                 default:
13075                         panic("%s: Invalid CTL I/O type %d\n",
13076                             __func__, io->io_hdr.io_type);
13077                 }
13078                 sbuf_cat(&sb, path_str);
13079                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13080                             (intmax_t)time_uptime - io->io_hdr.start_time);
13081                 sbuf_finish(&sb);
13082                 printf("%s", sbuf_data(&sb));
13083         }
13084 #endif /* CTL_TIME_IO */
13085
13086         switch (io->io_hdr.io_type) {
13087         case CTL_IO_SCSI:
13088                 break;
13089         case CTL_IO_TASK:
13090                 if (ctl_debug & CTL_DEBUG_INFO)
13091                         ctl_io_error_print(io, NULL);
13092                 fe_done(io);
13093                 return;
13094         default:
13095                 panic("%s: Invalid CTL I/O type %d\n",
13096                     __func__, io->io_hdr.io_type);
13097         }
13098
13099         if (lun == NULL) {
13100                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13101                                  io->io_hdr.nexus.targ_mapped_lun));
13102                 goto bailout;
13103         }
13104
13105         mtx_lock(&lun->lun_lock);
13106
13107         /*
13108          * Check to see if we have any informational exception and status
13109          * of this command can be modified to report it in form of either
13110          * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13111          */
13112         if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13113             io->io_hdr.status == CTL_SUCCESS &&
13114             (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13115                 uint8_t mrie = lun->MODE_IE.mrie;
13116                 uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13117                     (lun->MODE_VER.byte3 & SMS_VER_PER));
13118                 if (((mrie == SIEP_MRIE_REC_COND && per) ||
13119                      mrie == SIEP_MRIE_REC_UNCOND ||
13120                      mrie == SIEP_MRIE_NO_SENSE) &&
13121                     (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13122                      CTL_CMD_FLAG_NO_SENSE) == 0) {
13123                         ctl_set_sense(&io->scsiio,
13124                               /*current_error*/ 1,
13125                               /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13126                                 SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13127                               /*asc*/ lun->ie_asc,
13128                               /*ascq*/ lun->ie_ascq,
13129                               SSD_ELEM_NONE);
13130                         lun->ie_reported = 1;
13131                 }
13132         } else if (lun->ie_reported < 0)
13133                 lun->ie_reported = 0;
13134
13135         /*
13136          * Check to see if we have any errors to inject here.  We only
13137          * inject errors for commands that don't already have errors set.
13138          */
13139         if (!STAILQ_EMPTY(&lun->error_list) &&
13140             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13141             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13142                 ctl_inject_error(lun, io);
13143
13144         /*
13145          * XXX KDM how do we treat commands that aren't completed
13146          * successfully?
13147          *
13148          * XXX KDM should we also track I/O latency?
13149          */
13150         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13151             io->io_hdr.io_type == CTL_IO_SCSI) {
13152 #ifdef CTL_TIME_IO
13153                 struct bintime cur_bt;
13154 #endif
13155                 int type;
13156
13157                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13158                     CTL_FLAG_DATA_IN)
13159                         type = CTL_STATS_READ;
13160                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13161                     CTL_FLAG_DATA_OUT)
13162                         type = CTL_STATS_WRITE;
13163                 else
13164                         type = CTL_STATS_NO_IO;
13165
13166                 lun->stats.ports[targ_port].bytes[type] +=
13167                     io->scsiio.kern_total_len;
13168                 lun->stats.ports[targ_port].operations[type]++;
13169 #ifdef CTL_TIME_IO
13170                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13171                    &io->io_hdr.dma_bt);
13172                 getbinuptime(&cur_bt);
13173                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13174                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13175 #endif
13176                 lun->stats.ports[targ_port].num_dmas[type] +=
13177                     io->io_hdr.num_dmas;
13178         }
13179
13180         /*
13181          * Remove this from the OOA queue.
13182          */
13183         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13184 #ifdef CTL_TIME_IO
13185         if (TAILQ_EMPTY(&lun->ooa_queue))
13186                 lun->last_busy = getsbinuptime();
13187 #endif
13188
13189         /*
13190          * Run through the blocked queue on this LUN and see if anything
13191          * has become unblocked, now that this transaction is done.
13192          */
13193         ctl_check_blocked(lun);
13194
13195         /*
13196          * If the LUN has been invalidated, free it if there is nothing
13197          * left on its OOA queue.
13198          */
13199         if ((lun->flags & CTL_LUN_INVALID)
13200          && TAILQ_EMPTY(&lun->ooa_queue)) {
13201                 mtx_unlock(&lun->lun_lock);
13202                 mtx_lock(&softc->ctl_lock);
13203                 ctl_free_lun(lun);
13204                 mtx_unlock(&softc->ctl_lock);
13205         } else
13206                 mtx_unlock(&lun->lun_lock);
13207
13208 bailout:
13209
13210         /*
13211          * If this command has been aborted, make sure we set the status
13212          * properly.  The FETD is responsible for freeing the I/O and doing
13213          * whatever it needs to do to clean up its state.
13214          */
13215         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13216                 ctl_set_task_aborted(&io->scsiio);
13217
13218         /*
13219          * If enabled, print command error status.
13220          */
13221         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13222             (ctl_debug & CTL_DEBUG_INFO) != 0)
13223                 ctl_io_error_print(io, NULL);
13224
13225         /*
13226          * Tell the FETD or the other shelf controller we're done with this
13227          * command.  Note that only SCSI commands get to this point.  Task
13228          * management commands are completed above.
13229          */
13230         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13231             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13232                 memset(&msg, 0, sizeof(msg));
13233                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13234                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13235                 msg.hdr.nexus = io->io_hdr.nexus;
13236                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13237                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13238                     M_WAITOK);
13239         }
13240
13241         fe_done(io);
13242 }
13243
13244 #ifdef CTL_WITH_CA
13245 /*
13246  * Front end should call this if it doesn't do autosense.  When the request
13247  * sense comes back in from the initiator, we'll dequeue this and send it.
13248  */
13249 int
13250 ctl_queue_sense(union ctl_io *io)
13251 {
13252         struct ctl_softc *softc = CTL_SOFTC(io);
13253         struct ctl_port *port = CTL_PORT(io);
13254         struct ctl_lun *lun;
13255         uint32_t initidx, targ_lun;
13256
13257         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13258
13259         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13260
13261         /*
13262          * LUN lookup will likely move to the ctl_work_thread() once we
13263          * have our new queueing infrastructure (that doesn't put things on
13264          * a per-LUN queue initially).  That is so that we can handle
13265          * things like an INQUIRY to a LUN that we don't have enabled.  We
13266          * can't deal with that right now.
13267          * If we don't have a LUN for this, just toss the sense information.
13268          */
13269         mtx_lock(&softc->ctl_lock);
13270         if (targ_lun >= CTL_MAX_LUNS ||
13271             (lun = softc->ctl_luns[targ_lun]) == NULL) {
13272                 mtx_unlock(&softc->ctl_lock);
13273                 goto bailout;
13274         }
13275         mtx_lock(&lun->lun_lock);
13276         mtx_unlock(&softc->ctl_lock);
13277
13278         /*
13279          * Already have CA set for this LUN...toss the sense information.
13280          */
13281         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13282         if (ctl_is_set(lun->have_ca, initidx)) {
13283                 mtx_unlock(&lun->lun_lock);
13284                 goto bailout;
13285         }
13286
13287         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13288                MIN(sizeof(lun->pending_sense[initidx]),
13289                sizeof(io->scsiio.sense_data)));
13290         ctl_set_mask(lun->have_ca, initidx);
13291         mtx_unlock(&lun->lun_lock);
13292
13293 bailout:
13294         ctl_free_io(io);
13295         return (CTL_RETVAL_COMPLETE);
13296 }
13297 #endif
13298
13299 /*
13300  * Primary command inlet from frontend ports.  All SCSI and task I/O
13301  * requests must go through this function.
13302  */
13303 int
13304 ctl_queue(union ctl_io *io)
13305 {
13306         struct ctl_port *port = CTL_PORT(io);
13307
13308         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13309
13310 #ifdef CTL_TIME_IO
13311         io->io_hdr.start_time = time_uptime;
13312         getbinuptime(&io->io_hdr.start_bt);
13313 #endif /* CTL_TIME_IO */
13314
13315         /* Map FE-specific LUN ID into global one. */
13316         io->io_hdr.nexus.targ_mapped_lun =
13317             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13318
13319         switch (io->io_hdr.io_type) {
13320         case CTL_IO_SCSI:
13321         case CTL_IO_TASK:
13322                 if (ctl_debug & CTL_DEBUG_CDB)
13323                         ctl_io_print(io);
13324                 ctl_enqueue_incoming(io);
13325                 break;
13326         default:
13327                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13328                 return (EINVAL);
13329         }
13330
13331         return (CTL_RETVAL_COMPLETE);
13332 }
13333
13334 #ifdef CTL_IO_DELAY
13335 static void
13336 ctl_done_timer_wakeup(void *arg)
13337 {
13338         union ctl_io *io;
13339
13340         io = (union ctl_io *)arg;
13341         ctl_done(io);
13342 }
13343 #endif /* CTL_IO_DELAY */
13344
13345 void
13346 ctl_serseq_done(union ctl_io *io)
13347 {
13348         struct ctl_lun *lun = CTL_LUN(io);;
13349
13350         if (lun->be_lun == NULL ||
13351             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13352                 return;
13353         mtx_lock(&lun->lun_lock);
13354         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13355         ctl_check_blocked(lun);
13356         mtx_unlock(&lun->lun_lock);
13357 }
13358
13359 void
13360 ctl_done(union ctl_io *io)
13361 {
13362
13363         /*
13364          * Enable this to catch duplicate completion issues.
13365          */
13366 #if 0
13367         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13368                 printf("%s: type %d msg %d cdb %x iptl: "
13369                        "%u:%u:%u tag 0x%04x "
13370                        "flag %#x status %x\n",
13371                         __func__,
13372                         io->io_hdr.io_type,
13373                         io->io_hdr.msg_type,
13374                         io->scsiio.cdb[0],
13375                         io->io_hdr.nexus.initid,
13376                         io->io_hdr.nexus.targ_port,
13377                         io->io_hdr.nexus.targ_lun,
13378                         (io->io_hdr.io_type ==
13379                         CTL_IO_TASK) ?
13380                         io->taskio.tag_num :
13381                         io->scsiio.tag_num,
13382                         io->io_hdr.flags,
13383                         io->io_hdr.status);
13384         } else
13385                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13386 #endif
13387
13388         /*
13389          * This is an internal copy of an I/O, and should not go through
13390          * the normal done processing logic.
13391          */
13392         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13393                 return;
13394
13395 #ifdef CTL_IO_DELAY
13396         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13397                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13398         } else {
13399                 struct ctl_lun *lun = CTL_LUN(io);
13400
13401                 if ((lun != NULL)
13402                  && (lun->delay_info.done_delay > 0)) {
13403
13404                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13405                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13406                         callout_reset(&io->io_hdr.delay_callout,
13407                                       lun->delay_info.done_delay * hz,
13408                                       ctl_done_timer_wakeup, io);
13409                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13410                                 lun->delay_info.done_delay = 0;
13411                         return;
13412                 }
13413         }
13414 #endif /* CTL_IO_DELAY */
13415
13416         ctl_enqueue_done(io);
13417 }
13418
13419 static void
13420 ctl_work_thread(void *arg)
13421 {
13422         struct ctl_thread *thr = (struct ctl_thread *)arg;
13423         struct ctl_softc *softc = thr->ctl_softc;
13424         union ctl_io *io;
13425         int retval;
13426
13427         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13428
13429         for (;;) {
13430                 /*
13431                  * We handle the queues in this order:
13432                  * - ISC
13433                  * - done queue (to free up resources, unblock other commands)
13434                  * - RtR queue
13435                  * - incoming queue
13436                  *
13437                  * If those queues are empty, we break out of the loop and
13438                  * go to sleep.
13439                  */
13440                 mtx_lock(&thr->queue_lock);
13441                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13442                 if (io != NULL) {
13443                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13444                         mtx_unlock(&thr->queue_lock);
13445                         ctl_handle_isc(io);
13446                         continue;
13447                 }
13448                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13449                 if (io != NULL) {
13450                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13451                         /* clear any blocked commands, call fe_done */
13452                         mtx_unlock(&thr->queue_lock);
13453                         ctl_process_done(io);
13454                         continue;
13455                 }
13456                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13457                 if (io != NULL) {
13458                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13459                         mtx_unlock(&thr->queue_lock);
13460                         if (io->io_hdr.io_type == CTL_IO_TASK)
13461                                 ctl_run_task(io);
13462                         else
13463                                 ctl_scsiio_precheck(softc, &io->scsiio);
13464                         continue;
13465                 }
13466                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13467                 if (io != NULL) {
13468                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13469                         mtx_unlock(&thr->queue_lock);
13470                         retval = ctl_scsiio(&io->scsiio);
13471                         if (retval != CTL_RETVAL_COMPLETE)
13472                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13473                         continue;
13474                 }
13475
13476                 /* Sleep until we have something to do. */
13477                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13478         }
13479 }
13480
13481 static void
13482 ctl_lun_thread(void *arg)
13483 {
13484         struct ctl_softc *softc = (struct ctl_softc *)arg;
13485         struct ctl_be_lun *be_lun;
13486
13487         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13488
13489         for (;;) {
13490                 mtx_lock(&softc->ctl_lock);
13491                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13492                 if (be_lun != NULL) {
13493                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13494                         mtx_unlock(&softc->ctl_lock);
13495                         ctl_create_lun(be_lun);
13496                         continue;
13497                 }
13498
13499                 /* Sleep until we have something to do. */
13500                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13501                     PDROP | PRIBIO, "-", 0);
13502         }
13503 }
13504
13505 static void
13506 ctl_thresh_thread(void *arg)
13507 {
13508         struct ctl_softc *softc = (struct ctl_softc *)arg;
13509         struct ctl_lun *lun;
13510         struct ctl_logical_block_provisioning_page *page;
13511         const char *attr;
13512         union ctl_ha_msg msg;
13513         uint64_t thres, val;
13514         int i, e, set;
13515
13516         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13517
13518         for (;;) {
13519                 mtx_lock(&softc->ctl_lock);
13520                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13521                         if ((lun->flags & CTL_LUN_DISABLED) ||
13522                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13523                             lun->backend->lun_attr == NULL)
13524                                 continue;
13525                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13526                             softc->ha_mode == CTL_HA_MODE_XFER)
13527                                 continue;
13528                         if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13529                                 continue;
13530                         e = 0;
13531                         page = &lun->MODE_LBP;
13532                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13533                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13534                                         continue;
13535                                 thres = scsi_4btoul(page->descr[i].count);
13536                                 thres <<= CTL_LBP_EXPONENT;
13537                                 switch (page->descr[i].resource) {
13538                                 case 0x01:
13539                                         attr = "blocksavail";
13540                                         break;
13541                                 case 0x02:
13542                                         attr = "blocksused";
13543                                         break;
13544                                 case 0xf1:
13545                                         attr = "poolblocksavail";
13546                                         break;
13547                                 case 0xf2:
13548                                         attr = "poolblocksused";
13549                                         break;
13550                                 default:
13551                                         continue;
13552                                 }
13553                                 mtx_unlock(&softc->ctl_lock); // XXX
13554                                 val = lun->backend->lun_attr(
13555                                     lun->be_lun->be_lun, attr);
13556                                 mtx_lock(&softc->ctl_lock);
13557                                 if (val == UINT64_MAX)
13558                                         continue;
13559                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13560                                     == SLBPPD_ARMING_INC)
13561                                         e = (val >= thres);
13562                                 else
13563                                         e = (val <= thres);
13564                                 if (e)
13565                                         break;
13566                         }
13567                         mtx_lock(&lun->lun_lock);
13568                         if (e) {
13569                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13570                                     (uint8_t *)page, lun->ua_tpt_info);
13571                                 if (lun->lasttpt == 0 ||
13572                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13573                                         lun->lasttpt = time_uptime;
13574                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13575                                         set = 1;
13576                                 } else
13577                                         set = 0;
13578                         } else {
13579                                 lun->lasttpt = 0;
13580                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13581                                 set = -1;
13582                         }
13583                         mtx_unlock(&lun->lun_lock);
13584                         if (set != 0 &&
13585                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13586                                 /* Send msg to other side. */
13587                                 bzero(&msg.ua, sizeof(msg.ua));
13588                                 msg.hdr.msg_type = CTL_MSG_UA;
13589                                 msg.hdr.nexus.initid = -1;
13590                                 msg.hdr.nexus.targ_port = -1;
13591                                 msg.hdr.nexus.targ_lun = lun->lun;
13592                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13593                                 msg.ua.ua_all = 1;
13594                                 msg.ua.ua_set = (set > 0);
13595                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13596                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13597                                 mtx_unlock(&softc->ctl_lock); // XXX
13598                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13599                                     sizeof(msg.ua), M_WAITOK);
13600                                 mtx_lock(&softc->ctl_lock);
13601                         }
13602                 }
13603                 mtx_unlock(&softc->ctl_lock);
13604                 pause("-", CTL_LBP_PERIOD * hz);
13605         }
13606 }
13607
13608 static void
13609 ctl_enqueue_incoming(union ctl_io *io)
13610 {
13611         struct ctl_softc *softc = CTL_SOFTC(io);
13612         struct ctl_thread *thr;
13613         u_int idx;
13614
13615         idx = (io->io_hdr.nexus.targ_port * 127 +
13616                io->io_hdr.nexus.initid) % worker_threads;
13617         thr = &softc->threads[idx];
13618         mtx_lock(&thr->queue_lock);
13619         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13620         mtx_unlock(&thr->queue_lock);
13621         wakeup(thr);
13622 }
13623
13624 static void
13625 ctl_enqueue_rtr(union ctl_io *io)
13626 {
13627         struct ctl_softc *softc = CTL_SOFTC(io);
13628         struct ctl_thread *thr;
13629
13630         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13631         mtx_lock(&thr->queue_lock);
13632         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13633         mtx_unlock(&thr->queue_lock);
13634         wakeup(thr);
13635 }
13636
13637 static void
13638 ctl_enqueue_done(union ctl_io *io)
13639 {
13640         struct ctl_softc *softc = CTL_SOFTC(io);
13641         struct ctl_thread *thr;
13642
13643         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13644         mtx_lock(&thr->queue_lock);
13645         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13646         mtx_unlock(&thr->queue_lock);
13647         wakeup(thr);
13648 }
13649
13650 static void
13651 ctl_enqueue_isc(union ctl_io *io)
13652 {
13653         struct ctl_softc *softc = CTL_SOFTC(io);
13654         struct ctl_thread *thr;
13655
13656         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13657         mtx_lock(&thr->queue_lock);
13658         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13659         mtx_unlock(&thr->queue_lock);
13660         wakeup(thr);
13661 }
13662
13663 /*
13664  *  vim: ts=8
13665  */