]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r289881: Give CTL support for PIM_EXTLUNS when talking to CAM.
[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 copan_debugconf_subpage debugconf_page_default = {
97         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
98         DBGCNF_SUBPAGE_CODE,            /* subpage */
99         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
100          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
101         DBGCNF_VERSION,                 /* page_version */
102         {CTL_TIME_IO_DEFAULT_SECS>>8,
103          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
104 };
105
106 const static struct copan_debugconf_subpage debugconf_page_changeable = {
107         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
108         DBGCNF_SUBPAGE_CODE,            /* subpage */
109         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
110          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
111         0,                              /* page_version */
112         {0xff,0xff},                    /* ctl_time_io_secs */
113 };
114
115 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
116         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
117         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
118         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
119         /*read_retry_count*/0,
120         /*correction_span*/0,
121         /*head_offset_count*/0,
122         /*data_strobe_offset_cnt*/0,
123         /*byte8*/SMS_RWER_LBPERE,
124         /*write_retry_count*/0,
125         /*reserved2*/0,
126         /*recovery_time_limit*/{0, 0},
127 };
128
129 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
130         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
131         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
132         /*byte3*/0,
133         /*read_retry_count*/0,
134         /*correction_span*/0,
135         /*head_offset_count*/0,
136         /*data_strobe_offset_cnt*/0,
137         /*byte8*/0,
138         /*write_retry_count*/0,
139         /*reserved2*/0,
140         /*recovery_time_limit*/{0, 0},
141 };
142
143 const static struct scsi_format_page format_page_default = {
144         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
145         /*page_length*/sizeof(struct scsi_format_page) - 2,
146         /*tracks_per_zone*/ {0, 0},
147         /*alt_sectors_per_zone*/ {0, 0},
148         /*alt_tracks_per_zone*/ {0, 0},
149         /*alt_tracks_per_lun*/ {0, 0},
150         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
151                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
152         /*bytes_per_sector*/ {0, 0},
153         /*interleave*/ {0, 0},
154         /*track_skew*/ {0, 0},
155         /*cylinder_skew*/ {0, 0},
156         /*flags*/ SFP_HSEC,
157         /*reserved*/ {0, 0, 0}
158 };
159
160 const static struct scsi_format_page format_page_changeable = {
161         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
162         /*page_length*/sizeof(struct scsi_format_page) - 2,
163         /*tracks_per_zone*/ {0, 0},
164         /*alt_sectors_per_zone*/ {0, 0},
165         /*alt_tracks_per_zone*/ {0, 0},
166         /*alt_tracks_per_lun*/ {0, 0},
167         /*sectors_per_track*/ {0, 0},
168         /*bytes_per_sector*/ {0, 0},
169         /*interleave*/ {0, 0},
170         /*track_skew*/ {0, 0},
171         /*cylinder_skew*/ {0, 0},
172         /*flags*/ 0,
173         /*reserved*/ {0, 0, 0}
174 };
175
176 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
177         /*page_code*/SMS_RIGID_DISK_PAGE,
178         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
179         /*cylinders*/ {0, 0, 0},
180         /*heads*/ CTL_DEFAULT_HEADS,
181         /*start_write_precomp*/ {0, 0, 0},
182         /*start_reduced_current*/ {0, 0, 0},
183         /*step_rate*/ {0, 0},
184         /*landing_zone_cylinder*/ {0, 0, 0},
185         /*rpl*/ SRDP_RPL_DISABLED,
186         /*rotational_offset*/ 0,
187         /*reserved1*/ 0,
188         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
189                            CTL_DEFAULT_ROTATION_RATE & 0xff},
190         /*reserved2*/ {0, 0}
191 };
192
193 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
194         /*page_code*/SMS_RIGID_DISK_PAGE,
195         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196         /*cylinders*/ {0, 0, 0},
197         /*heads*/ 0,
198         /*start_write_precomp*/ {0, 0, 0},
199         /*start_reduced_current*/ {0, 0, 0},
200         /*step_rate*/ {0, 0},
201         /*landing_zone_cylinder*/ {0, 0, 0},
202         /*rpl*/ 0,
203         /*rotational_offset*/ 0,
204         /*reserved1*/ 0,
205         /*rotation_rate*/ {0, 0},
206         /*reserved2*/ {0, 0}
207 };
208
209 const static struct scsi_caching_page caching_page_default = {
210         /*page_code*/SMS_CACHING_PAGE,
211         /*page_length*/sizeof(struct scsi_caching_page) - 2,
212         /*flags1*/ SCP_DISC | SCP_WCE,
213         /*ret_priority*/ 0,
214         /*disable_pf_transfer_len*/ {0xff, 0xff},
215         /*min_prefetch*/ {0, 0},
216         /*max_prefetch*/ {0xff, 0xff},
217         /*max_pf_ceiling*/ {0xff, 0xff},
218         /*flags2*/ 0,
219         /*cache_segments*/ 0,
220         /*cache_seg_size*/ {0, 0},
221         /*reserved*/ 0,
222         /*non_cache_seg_size*/ {0, 0, 0}
223 };
224
225 const static struct scsi_caching_page caching_page_changeable = {
226         /*page_code*/SMS_CACHING_PAGE,
227         /*page_length*/sizeof(struct scsi_caching_page) - 2,
228         /*flags1*/ SCP_WCE | SCP_RCD,
229         /*ret_priority*/ 0,
230         /*disable_pf_transfer_len*/ {0, 0},
231         /*min_prefetch*/ {0, 0},
232         /*max_prefetch*/ {0, 0},
233         /*max_pf_ceiling*/ {0, 0},
234         /*flags2*/ 0,
235         /*cache_segments*/ 0,
236         /*cache_seg_size*/ {0, 0},
237         /*reserved*/ 0,
238         /*non_cache_seg_size*/ {0, 0, 0}
239 };
240
241 const static struct scsi_control_page control_page_default = {
242         /*page_code*/SMS_CONTROL_MODE_PAGE,
243         /*page_length*/sizeof(struct scsi_control_page) - 2,
244         /*rlec*/0,
245         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
246         /*eca_and_aen*/0,
247         /*flags4*/SCP_TAS,
248         /*aen_holdoff_period*/{0, 0},
249         /*busy_timeout_period*/{0, 0},
250         /*extended_selftest_completion_time*/{0, 0}
251 };
252
253 const static struct scsi_control_page control_page_changeable = {
254         /*page_code*/SMS_CONTROL_MODE_PAGE,
255         /*page_length*/sizeof(struct scsi_control_page) - 2,
256         /*rlec*/SCP_DSENSE,
257         /*queue_flags*/SCP_QUEUE_ALG_MASK,
258         /*eca_and_aen*/SCP_SWP,
259         /*flags4*/0,
260         /*aen_holdoff_period*/{0, 0},
261         /*busy_timeout_period*/{0, 0},
262         /*extended_selftest_completion_time*/{0, 0}
263 };
264
265 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
266
267 const static struct scsi_control_ext_page control_ext_page_default = {
268         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
269         /*subpage_code*/0x01,
270         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
271         /*flags*/0,
272         /*prio*/0,
273         /*max_sense*/0
274 };
275
276 const static struct scsi_control_ext_page control_ext_page_changeable = {
277         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
278         /*subpage_code*/0x01,
279         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
280         /*flags*/0,
281         /*prio*/0,
282         /*max_sense*/0
283 };
284
285 const static struct scsi_info_exceptions_page ie_page_default = {
286         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
287         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
288         /*info_flags*/SIEP_FLAGS_DEXCPT,
289         /*mrie*/0,
290         /*interval_timer*/{0, 0, 0, 0},
291         /*report_count*/{0, 0, 0, 0}
292 };
293
294 const static struct scsi_info_exceptions_page ie_page_changeable = {
295         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
296         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
297         /*info_flags*/0,
298         /*mrie*/0,
299         /*interval_timer*/{0, 0, 0, 0},
300         /*report_count*/{0, 0, 0, 0}
301 };
302
303 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307         /*subpage_code*/0x02,
308         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309         /*flags*/0,
310         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311         /*descr*/{}},
312         {{/*flags*/0,
313           /*resource*/0x01,
314           /*reserved*/{0, 0},
315           /*count*/{0, 0, 0, 0}},
316          {/*flags*/0,
317           /*resource*/0x02,
318           /*reserved*/{0, 0},
319           /*count*/{0, 0, 0, 0}},
320          {/*flags*/0,
321           /*resource*/0xf1,
322           /*reserved*/{0, 0},
323           /*count*/{0, 0, 0, 0}},
324          {/*flags*/0,
325           /*resource*/0xf2,
326           /*reserved*/{0, 0},
327           /*count*/{0, 0, 0, 0}}
328         }
329 };
330
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333         /*subpage_code*/0x02,
334         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335         /*flags*/0,
336         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337         /*descr*/{}},
338         {{/*flags*/0,
339           /*resource*/0,
340           /*reserved*/{0, 0},
341           /*count*/{0, 0, 0, 0}},
342          {/*flags*/0,
343           /*resource*/0,
344           /*reserved*/{0, 0},
345           /*count*/{0, 0, 0, 0}},
346          {/*flags*/0,
347           /*resource*/0,
348           /*reserved*/{0, 0},
349           /*count*/{0, 0, 0, 0}},
350          {/*flags*/0,
351           /*resource*/0,
352           /*reserved*/{0, 0},
353           /*count*/{0, 0, 0, 0}}
354         }
355 };
356
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358         /*page_code*/SMS_CDDVD_CAPS_PAGE,
359         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360         /*caps1*/0x3f,
361         /*caps2*/0x00,
362         /*caps3*/0xf0,
363         /*caps4*/0x00,
364         /*caps5*/0x29,
365         /*caps6*/0x00,
366         /*obsolete*/{0, 0},
367         /*nvol_levels*/{0, 0},
368         /*buffer_size*/{8, 0},
369         /*obsolete2*/{0, 0},
370         /*reserved*/0,
371         /*digital*/0,
372         /*obsolete3*/0,
373         /*copy_management*/0,
374         /*reserved2*/0,
375         /*rotation_control*/0,
376         /*cur_write_speed*/0,
377         /*num_speed_descr*/0,
378 };
379
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381         /*page_code*/SMS_CDDVD_CAPS_PAGE,
382         /*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383         /*caps1*/0,
384         /*caps2*/0,
385         /*caps3*/0,
386         /*caps4*/0,
387         /*caps5*/0,
388         /*caps6*/0,
389         /*obsolete*/{0, 0},
390         /*nvol_levels*/{0, 0},
391         /*buffer_size*/{0, 0},
392         /*obsolete2*/{0, 0},
393         /*reserved*/0,
394         /*digital*/0,
395         /*obsolete3*/0,
396         /*copy_management*/0,
397         /*reserved2*/0,
398         /*rotation_control*/0,
399         /*cur_write_speed*/0,
400         /*num_speed_descr*/0,
401 };
402
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 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
413 /*
414  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
415  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
416  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
417  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
418  */
419 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
420
421 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
422                                   int param);
423 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
424 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
425 static int ctl_init(void);
426 void ctl_shutdown(void);
427 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
428 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
429 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
430 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
431                               struct ctl_ooa *ooa_hdr,
432                               struct ctl_ooa_entry *kern_entries);
433 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
434                      struct thread *td);
435 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
436                          struct ctl_be_lun *be_lun);
437 static int ctl_free_lun(struct ctl_lun *lun);
438 static void ctl_create_lun(struct ctl_be_lun *be_lun);
439 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
440
441 static int ctl_do_mode_select(union ctl_io *io);
442 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443                            uint64_t res_key, uint64_t sa_res_key,
444                            uint8_t type, uint32_t residx,
445                            struct ctl_scsiio *ctsio,
446                            struct scsi_per_res_out *cdb,
447                            struct scsi_per_res_out_parms* param);
448 static void ctl_pro_preempt_other(struct ctl_lun *lun,
449                                   union ctl_ha_msg *msg);
450 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
451 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457                                          int alloc_len);
458 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459                                          int alloc_len);
460 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466     bool seq);
467 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469     union ctl_io *pending_io, union ctl_io *ooa_io);
470 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471                                 union ctl_io *starting_io);
472 static int ctl_check_blocked(struct ctl_lun *lun);
473 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474                                 const struct ctl_cmd_entry *entry,
475                                 struct ctl_scsiio *ctsio);
476 static void ctl_failover_lun(union ctl_io *io);
477 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478                                struct ctl_scsiio *ctsio);
479 static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483                             ctl_ua_type ua_type);
484 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485                          ctl_ua_type ua_type);
486 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487 static int ctl_abort_task(union ctl_io *io);
488 static int ctl_abort_task_set(union ctl_io *io);
489 static int ctl_query_task(union ctl_io *io, int task_set);
490 static int ctl_i_t_nexus_reset(union ctl_io *io);
491 static int ctl_query_async_event(union ctl_io *io);
492 static void ctl_run_task(union ctl_io *io);
493 #ifdef CTL_IO_DELAY
494 static void ctl_datamove_timer_wakeup(void *arg);
495 static void ctl_done_timer_wakeup(void *arg);
496 #endif /* CTL_IO_DELAY */
497
498 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501 static void ctl_datamove_remote_write(union ctl_io *io);
502 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506                                     ctl_ha_dt_cb callback);
507 static void ctl_datamove_remote_read(union ctl_io *io);
508 static void ctl_datamove_remote(union ctl_io *io);
509 static void ctl_process_done(union ctl_io *io);
510 static void ctl_lun_thread(void *arg);
511 static void ctl_thresh_thread(void *arg);
512 static void ctl_work_thread(void *arg);
513 static void ctl_enqueue_incoming(union ctl_io *io);
514 static void ctl_enqueue_rtr(union ctl_io *io);
515 static void ctl_enqueue_done(union ctl_io *io);
516 static void ctl_enqueue_isc(union ctl_io *io);
517 static const struct ctl_cmd_entry *
518     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519 static const struct ctl_cmd_entry *
520     ctl_validate_command(struct ctl_scsiio *ctsio);
521 static int ctl_cmd_applicable(uint8_t lun_type,
522     const struct ctl_cmd_entry *entry);
523
524 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528
529 /*
530  * Load the serialization table.  This isn't very pretty, but is probably
531  * the easiest way to do it.
532  */
533 #include "ctl_ser_table.c"
534
535 /*
536  * We only need to define open, close and ioctl routines for this driver.
537  */
538 static struct cdevsw ctl_cdevsw = {
539         .d_version =    D_VERSION,
540         .d_flags =      0,
541         .d_open =       ctl_open,
542         .d_close =      ctl_close,
543         .d_ioctl =      ctl_ioctl,
544         .d_name =       "ctl",
545 };
546
547
548 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549
550 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551
552 static moduledata_t ctl_moduledata = {
553         "ctl",
554         ctl_module_event_handler,
555         NULL
556 };
557
558 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559 MODULE_VERSION(ctl, 1);
560
561 static struct ctl_frontend ha_frontend =
562 {
563         .name = "ha",
564 };
565
566 static void
567 ctl_ha_datamove(union ctl_io *io)
568 {
569         struct ctl_lun *lun;
570         struct ctl_sg_entry *sgl;
571         union ctl_ha_msg msg;
572         uint32_t sg_entries_sent;
573         int do_sg_copy, i, j;
574
575         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
576         memset(&msg.dt, 0, sizeof(msg.dt));
577         msg.hdr.msg_type = CTL_MSG_DATAMOVE;
578         msg.hdr.original_sc = io->io_hdr.original_sc;
579         msg.hdr.serializing_sc = io;
580         msg.hdr.nexus = io->io_hdr.nexus;
581         msg.hdr.status = io->io_hdr.status;
582         msg.dt.flags = io->io_hdr.flags;
583
584         /*
585          * We convert everything into a S/G list here.  We can't
586          * pass by reference, only by value between controllers.
587          * So we can't pass a pointer to the S/G list, only as many
588          * S/G entries as we can fit in here.  If it's possible for
589          * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
590          * then we need to break this up into multiple transfers.
591          */
592         if (io->scsiio.kern_sg_entries == 0) {
593                 msg.dt.kern_sg_entries = 1;
594 #if 0
595                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
596                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
597                 } else {
598                         /* XXX KDM use busdma here! */
599                         msg.dt.sg_list[0].addr =
600                             (void *)vtophys(io->scsiio.kern_data_ptr);
601                 }
602 #else
603                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
604                     ("HA does not support BUS_ADDR"));
605                 msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
606 #endif
607                 msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
608                 do_sg_copy = 0;
609         } else {
610                 msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
611                 do_sg_copy = 1;
612         }
613
614         msg.dt.kern_data_len = io->scsiio.kern_data_len;
615         msg.dt.kern_total_len = io->scsiio.kern_total_len;
616         msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
617         msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
618         msg.dt.sg_sequence = 0;
619
620         /*
621          * Loop until we've sent all of the S/G entries.  On the
622          * other end, we'll recompose these S/G entries into one
623          * contiguous list before processing.
624          */
625         for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
626             msg.dt.sg_sequence++) {
627                 msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
628                     sizeof(msg.dt.sg_list[0])),
629                     msg.dt.kern_sg_entries - sg_entries_sent);
630                 if (do_sg_copy != 0) {
631                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
632                         for (i = sg_entries_sent, j = 0;
633                              i < msg.dt.cur_sg_entries; i++, j++) {
634 #if 0
635                                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
636                                         msg.dt.sg_list[j].addr = sgl[i].addr;
637                                 } else {
638                                         /* XXX KDM use busdma here! */
639                                         msg.dt.sg_list[j].addr =
640                                             (void *)vtophys(sgl[i].addr);
641                                 }
642 #else
643                                 KASSERT((io->io_hdr.flags &
644                                     CTL_FLAG_BUS_ADDR) == 0,
645                                     ("HA does not support BUS_ADDR"));
646                                 msg.dt.sg_list[j].addr = sgl[i].addr;
647 #endif
648                                 msg.dt.sg_list[j].len = sgl[i].len;
649                         }
650                 }
651
652                 sg_entries_sent += msg.dt.cur_sg_entries;
653                 msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
654                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
655                     sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
656                     sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
657                     M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
658                         io->io_hdr.port_status = 31341;
659                         io->scsiio.be_move_done(io);
660                         return;
661                 }
662                 msg.dt.sent_sg_entries = sg_entries_sent;
663         }
664
665         /*
666          * Officially handover the request from us to peer.
667          * If failover has just happened, then we must return error.
668          * If failover happen just after, then it is not our problem.
669          */
670         if (lun)
671                 mtx_lock(&lun->lun_lock);
672         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
673                 if (lun)
674                         mtx_unlock(&lun->lun_lock);
675                 io->io_hdr.port_status = 31342;
676                 io->scsiio.be_move_done(io);
677                 return;
678         }
679         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
680         io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
681         if (lun)
682                 mtx_unlock(&lun->lun_lock);
683 }
684
685 static void
686 ctl_ha_done(union ctl_io *io)
687 {
688         union ctl_ha_msg msg;
689
690         if (io->io_hdr.io_type == CTL_IO_SCSI) {
691                 memset(&msg, 0, sizeof(msg));
692                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
693                 msg.hdr.original_sc = io->io_hdr.original_sc;
694                 msg.hdr.nexus = io->io_hdr.nexus;
695                 msg.hdr.status = io->io_hdr.status;
696                 msg.scsi.scsi_status = io->scsiio.scsi_status;
697                 msg.scsi.tag_num = io->scsiio.tag_num;
698                 msg.scsi.tag_type = io->scsiio.tag_type;
699                 msg.scsi.sense_len = io->scsiio.sense_len;
700                 msg.scsi.sense_residual = io->scsiio.sense_residual;
701                 msg.scsi.residual = io->scsiio.residual;
702                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
703                     io->scsiio.sense_len);
704                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
705                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
706                     msg.scsi.sense_len, M_WAITOK);
707         }
708         ctl_free_io(io);
709 }
710
711 static void
712 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
713                             union ctl_ha_msg *msg_info)
714 {
715         struct ctl_scsiio *ctsio;
716
717         if (msg_info->hdr.original_sc == NULL) {
718                 printf("%s: original_sc == NULL!\n", __func__);
719                 /* XXX KDM now what? */
720                 return;
721         }
722
723         ctsio = &msg_info->hdr.original_sc->scsiio;
724         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
725         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
726         ctsio->io_hdr.status = msg_info->hdr.status;
727         ctsio->scsi_status = msg_info->scsi.scsi_status;
728         ctsio->sense_len = msg_info->scsi.sense_len;
729         ctsio->sense_residual = msg_info->scsi.sense_residual;
730         ctsio->residual = msg_info->scsi.residual;
731         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
732                msg_info->scsi.sense_len);
733         ctl_enqueue_isc((union ctl_io *)ctsio);
734 }
735
736 static void
737 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
738                                 union ctl_ha_msg *msg_info)
739 {
740         struct ctl_scsiio *ctsio;
741
742         if (msg_info->hdr.serializing_sc == NULL) {
743                 printf("%s: serializing_sc == NULL!\n", __func__);
744                 /* XXX KDM now what? */
745                 return;
746         }
747
748         ctsio = &msg_info->hdr.serializing_sc->scsiio;
749         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
750         ctl_enqueue_isc((union ctl_io *)ctsio);
751 }
752
753 void
754 ctl_isc_announce_lun(struct ctl_lun *lun)
755 {
756         struct ctl_softc *softc = lun->ctl_softc;
757         union ctl_ha_msg *msg;
758         struct ctl_ha_msg_lun_pr_key pr_key;
759         int i, k;
760
761         if (softc->ha_link != CTL_HA_LINK_ONLINE)
762                 return;
763         mtx_lock(&lun->lun_lock);
764         i = sizeof(msg->lun);
765         if (lun->lun_devid)
766                 i += lun->lun_devid->len;
767         i += sizeof(pr_key) * lun->pr_key_count;
768 alloc:
769         mtx_unlock(&lun->lun_lock);
770         msg = malloc(i, M_CTL, M_WAITOK);
771         mtx_lock(&lun->lun_lock);
772         k = sizeof(msg->lun);
773         if (lun->lun_devid)
774                 k += lun->lun_devid->len;
775         k += sizeof(pr_key) * lun->pr_key_count;
776         if (i < k) {
777                 free(msg, M_CTL);
778                 i = k;
779                 goto alloc;
780         }
781         bzero(&msg->lun, sizeof(msg->lun));
782         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
783         msg->hdr.nexus.targ_lun = lun->lun;
784         msg->hdr.nexus.targ_mapped_lun = lun->lun;
785         msg->lun.flags = lun->flags;
786         msg->lun.pr_generation = lun->pr_generation;
787         msg->lun.pr_res_idx = lun->pr_res_idx;
788         msg->lun.pr_res_type = lun->pr_res_type;
789         msg->lun.pr_key_count = lun->pr_key_count;
790         i = 0;
791         if (lun->lun_devid) {
792                 msg->lun.lun_devid_len = lun->lun_devid->len;
793                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
794                     msg->lun.lun_devid_len);
795                 i += msg->lun.lun_devid_len;
796         }
797         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
798                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
799                         continue;
800                 pr_key.pr_iid = k;
801                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
802                 i += sizeof(pr_key);
803         }
804         mtx_unlock(&lun->lun_lock);
805         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
806             M_WAITOK);
807         free(msg, M_CTL);
808
809         if (lun->flags & CTL_LUN_PRIMARY_SC) {
810                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
811                         ctl_isc_announce_mode(lun, -1,
812                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
813                             lun->mode_pages.index[i].subpage);
814                 }
815         }
816 }
817
818 void
819 ctl_isc_announce_port(struct ctl_port *port)
820 {
821         struct ctl_softc *softc = port->ctl_softc;
822         union ctl_ha_msg *msg;
823         int i;
824
825         if (port->targ_port < softc->port_min ||
826             port->targ_port >= softc->port_max ||
827             softc->ha_link != CTL_HA_LINK_ONLINE)
828                 return;
829         i = sizeof(msg->port) + strlen(port->port_name) + 1;
830         if (port->lun_map)
831                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
832         if (port->port_devid)
833                 i += port->port_devid->len;
834         if (port->target_devid)
835                 i += port->target_devid->len;
836         if (port->init_devid)
837                 i += port->init_devid->len;
838         msg = malloc(i, M_CTL, M_WAITOK);
839         bzero(&msg->port, sizeof(msg->port));
840         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
841         msg->hdr.nexus.targ_port = port->targ_port;
842         msg->port.port_type = port->port_type;
843         msg->port.physical_port = port->physical_port;
844         msg->port.virtual_port = port->virtual_port;
845         msg->port.status = port->status;
846         i = 0;
847         msg->port.name_len = sprintf(&msg->port.data[i],
848             "%d:%s", softc->ha_id, port->port_name) + 1;
849         i += msg->port.name_len;
850         if (port->lun_map) {
851                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
852                 memcpy(&msg->port.data[i], port->lun_map,
853                     msg->port.lun_map_len);
854                 i += msg->port.lun_map_len;
855         }
856         if (port->port_devid) {
857                 msg->port.port_devid_len = port->port_devid->len;
858                 memcpy(&msg->port.data[i], port->port_devid->data,
859                     msg->port.port_devid_len);
860                 i += msg->port.port_devid_len;
861         }
862         if (port->target_devid) {
863                 msg->port.target_devid_len = port->target_devid->len;
864                 memcpy(&msg->port.data[i], port->target_devid->data,
865                     msg->port.target_devid_len);
866                 i += msg->port.target_devid_len;
867         }
868         if (port->init_devid) {
869                 msg->port.init_devid_len = port->init_devid->len;
870                 memcpy(&msg->port.data[i], port->init_devid->data,
871                     msg->port.init_devid_len);
872                 i += msg->port.init_devid_len;
873         }
874         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
875             M_WAITOK);
876         free(msg, M_CTL);
877 }
878
879 void
880 ctl_isc_announce_iid(struct ctl_port *port, int iid)
881 {
882         struct ctl_softc *softc = port->ctl_softc;
883         union ctl_ha_msg *msg;
884         int i, l;
885
886         if (port->targ_port < softc->port_min ||
887             port->targ_port >= softc->port_max ||
888             softc->ha_link != CTL_HA_LINK_ONLINE)
889                 return;
890         mtx_lock(&softc->ctl_lock);
891         i = sizeof(msg->iid);
892         l = 0;
893         if (port->wwpn_iid[iid].name)
894                 l = strlen(port->wwpn_iid[iid].name) + 1;
895         i += l;
896         msg = malloc(i, M_CTL, M_NOWAIT);
897         if (msg == NULL) {
898                 mtx_unlock(&softc->ctl_lock);
899                 return;
900         }
901         bzero(&msg->iid, sizeof(msg->iid));
902         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
903         msg->hdr.nexus.targ_port = port->targ_port;
904         msg->hdr.nexus.initid = iid;
905         msg->iid.in_use = port->wwpn_iid[iid].in_use;
906         msg->iid.name_len = l;
907         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
908         if (port->wwpn_iid[iid].name)
909                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
910         mtx_unlock(&softc->ctl_lock);
911         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
912         free(msg, M_CTL);
913 }
914
915 void
916 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
917     uint8_t page, uint8_t subpage)
918 {
919         struct ctl_softc *softc = lun->ctl_softc;
920         union ctl_ha_msg msg;
921         int i;
922
923         if (softc->ha_link != CTL_HA_LINK_ONLINE)
924                 return;
925         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
926                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
927                     page && lun->mode_pages.index[i].subpage == subpage)
928                         break;
929         }
930         if (i == CTL_NUM_MODE_PAGES)
931                 return;
932
933         /* Don't try to replicate pages not present on this device. */
934         if (lun->mode_pages.index[i].page_data == NULL)
935                 return;
936
937         bzero(&msg.mode, sizeof(msg.mode));
938         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
939         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
940         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
941         msg.hdr.nexus.targ_lun = lun->lun;
942         msg.hdr.nexus.targ_mapped_lun = lun->lun;
943         msg.mode.page_code = page;
944         msg.mode.subpage = subpage;
945         msg.mode.page_len = lun->mode_pages.index[i].page_len;
946         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
947             msg.mode.page_len);
948         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
949             M_WAITOK);
950 }
951
952 static void
953 ctl_isc_ha_link_up(struct ctl_softc *softc)
954 {
955         struct ctl_port *port;
956         struct ctl_lun *lun;
957         union ctl_ha_msg msg;
958         int i;
959
960         /* Announce this node parameters to peer for validation. */
961         msg.login.msg_type = CTL_MSG_LOGIN;
962         msg.login.version = CTL_HA_VERSION;
963         msg.login.ha_mode = softc->ha_mode;
964         msg.login.ha_id = softc->ha_id;
965         msg.login.max_luns = CTL_MAX_LUNS;
966         msg.login.max_ports = CTL_MAX_PORTS;
967         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
968         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
969             M_WAITOK);
970
971         STAILQ_FOREACH(port, &softc->port_list, links) {
972                 ctl_isc_announce_port(port);
973                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
974                         if (port->wwpn_iid[i].in_use)
975                                 ctl_isc_announce_iid(port, i);
976                 }
977         }
978         STAILQ_FOREACH(lun, &softc->lun_list, links)
979                 ctl_isc_announce_lun(lun);
980 }
981
982 static void
983 ctl_isc_ha_link_down(struct ctl_softc *softc)
984 {
985         struct ctl_port *port;
986         struct ctl_lun *lun;
987         union ctl_io *io;
988         int i;
989
990         mtx_lock(&softc->ctl_lock);
991         STAILQ_FOREACH(lun, &softc->lun_list, links) {
992                 mtx_lock(&lun->lun_lock);
993                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
994                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
995                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
996                 }
997                 mtx_unlock(&lun->lun_lock);
998
999                 mtx_unlock(&softc->ctl_lock);
1000                 io = ctl_alloc_io(softc->othersc_pool);
1001                 mtx_lock(&softc->ctl_lock);
1002                 ctl_zero_io(io);
1003                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1004                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1005                 ctl_enqueue_isc(io);
1006         }
1007
1008         STAILQ_FOREACH(port, &softc->port_list, links) {
1009                 if (port->targ_port >= softc->port_min &&
1010                     port->targ_port < softc->port_max)
1011                         continue;
1012                 port->status &= ~CTL_PORT_STATUS_ONLINE;
1013                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1014                         port->wwpn_iid[i].in_use = 0;
1015                         free(port->wwpn_iid[i].name, M_CTL);
1016                         port->wwpn_iid[i].name = NULL;
1017                 }
1018         }
1019         mtx_unlock(&softc->ctl_lock);
1020 }
1021
1022 static void
1023 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1024 {
1025         struct ctl_lun *lun;
1026         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1027
1028         mtx_lock(&softc->ctl_lock);
1029         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1030             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1031                 mtx_lock(&lun->lun_lock);
1032                 mtx_unlock(&softc->ctl_lock);
1033                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1034                     msg->ua.ua_set)
1035                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1036                 if (msg->ua.ua_all) {
1037                         if (msg->ua.ua_set)
1038                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1039                         else
1040                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1041                 } else {
1042                         if (msg->ua.ua_set)
1043                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
1044                         else
1045                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
1046                 }
1047                 mtx_unlock(&lun->lun_lock);
1048         } else
1049                 mtx_unlock(&softc->ctl_lock);
1050 }
1051
1052 static void
1053 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1054 {
1055         struct ctl_lun *lun;
1056         struct ctl_ha_msg_lun_pr_key pr_key;
1057         int i, k;
1058         ctl_lun_flags oflags;
1059         uint32_t targ_lun;
1060
1061         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1062         mtx_lock(&softc->ctl_lock);
1063         if ((targ_lun >= CTL_MAX_LUNS) ||
1064             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1065                 mtx_unlock(&softc->ctl_lock);
1066                 return;
1067         }
1068         mtx_lock(&lun->lun_lock);
1069         mtx_unlock(&softc->ctl_lock);
1070         if (lun->flags & CTL_LUN_DISABLED) {
1071                 mtx_unlock(&lun->lun_lock);
1072                 return;
1073         }
1074         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1075         if (msg->lun.lun_devid_len != i || (i > 0 &&
1076             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1077                 mtx_unlock(&lun->lun_lock);
1078                 printf("%s: Received conflicting HA LUN %d\n",
1079                     __func__, msg->hdr.nexus.targ_lun);
1080                 return;
1081         } else {
1082                 /* Record whether peer is primary. */
1083                 oflags = lun->flags;
1084                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1085                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1086                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1087                 else
1088                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1089                 if (oflags != lun->flags)
1090                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1091
1092                 /* If peer is primary and we are not -- use data */
1093                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1094                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1095                         lun->pr_generation = msg->lun.pr_generation;
1096                         lun->pr_res_idx = msg->lun.pr_res_idx;
1097                         lun->pr_res_type = msg->lun.pr_res_type;
1098                         lun->pr_key_count = msg->lun.pr_key_count;
1099                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
1100                                 ctl_clr_prkey(lun, k);
1101                         for (k = 0; k < msg->lun.pr_key_count; k++) {
1102                                 memcpy(&pr_key, &msg->lun.data[i],
1103                                     sizeof(pr_key));
1104                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
1105                                 ctl_set_prkey(lun, pr_key.pr_iid,
1106                                     pr_key.pr_key);
1107                                 i += sizeof(pr_key);
1108                         }
1109                 }
1110
1111                 mtx_unlock(&lun->lun_lock);
1112                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1113                     __func__, msg->hdr.nexus.targ_lun,
1114                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1115                     "primary" : "secondary"));
1116
1117                 /* If we are primary but peer doesn't know -- notify */
1118                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1119                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1120                         ctl_isc_announce_lun(lun);
1121         }
1122 }
1123
1124 static void
1125 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1126 {
1127         struct ctl_port *port;
1128         struct ctl_lun *lun;
1129         int i, new;
1130
1131         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1132         if (port == NULL) {
1133                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1134                     msg->hdr.nexus.targ_port));
1135                 new = 1;
1136                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1137                 port->frontend = &ha_frontend;
1138                 port->targ_port = msg->hdr.nexus.targ_port;
1139                 port->fe_datamove = ctl_ha_datamove;
1140                 port->fe_done = ctl_ha_done;
1141         } else if (port->frontend == &ha_frontend) {
1142                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1143                     msg->hdr.nexus.targ_port));
1144                 new = 0;
1145         } else {
1146                 printf("%s: Received conflicting HA port %d\n",
1147                     __func__, msg->hdr.nexus.targ_port);
1148                 return;
1149         }
1150         port->port_type = msg->port.port_type;
1151         port->physical_port = msg->port.physical_port;
1152         port->virtual_port = msg->port.virtual_port;
1153         port->status = msg->port.status;
1154         i = 0;
1155         free(port->port_name, M_CTL);
1156         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1157             M_CTL);
1158         i += msg->port.name_len;
1159         if (msg->port.lun_map_len != 0) {
1160                 if (port->lun_map == NULL)
1161                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1162                             M_CTL, M_WAITOK);
1163                 memcpy(port->lun_map, &msg->port.data[i],
1164                     sizeof(uint32_t) * CTL_MAX_LUNS);
1165                 i += msg->port.lun_map_len;
1166         } else {
1167                 free(port->lun_map, M_CTL);
1168                 port->lun_map = NULL;
1169         }
1170         if (msg->port.port_devid_len != 0) {
1171                 if (port->port_devid == NULL ||
1172                     port->port_devid->len != msg->port.port_devid_len) {
1173                         free(port->port_devid, M_CTL);
1174                         port->port_devid = malloc(sizeof(struct ctl_devid) +
1175                             msg->port.port_devid_len, M_CTL, M_WAITOK);
1176                 }
1177                 memcpy(port->port_devid->data, &msg->port.data[i],
1178                     msg->port.port_devid_len);
1179                 port->port_devid->len = msg->port.port_devid_len;
1180                 i += msg->port.port_devid_len;
1181         } else {
1182                 free(port->port_devid, M_CTL);
1183                 port->port_devid = NULL;
1184         }
1185         if (msg->port.target_devid_len != 0) {
1186                 if (port->target_devid == NULL ||
1187                     port->target_devid->len != msg->port.target_devid_len) {
1188                         free(port->target_devid, M_CTL);
1189                         port->target_devid = malloc(sizeof(struct ctl_devid) +
1190                             msg->port.target_devid_len, M_CTL, M_WAITOK);
1191                 }
1192                 memcpy(port->target_devid->data, &msg->port.data[i],
1193                     msg->port.target_devid_len);
1194                 port->target_devid->len = msg->port.target_devid_len;
1195                 i += msg->port.target_devid_len;
1196         } else {
1197                 free(port->target_devid, M_CTL);
1198                 port->target_devid = NULL;
1199         }
1200         if (msg->port.init_devid_len != 0) {
1201                 if (port->init_devid == NULL ||
1202                     port->init_devid->len != msg->port.init_devid_len) {
1203                         free(port->init_devid, M_CTL);
1204                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1205                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1206                 }
1207                 memcpy(port->init_devid->data, &msg->port.data[i],
1208                     msg->port.init_devid_len);
1209                 port->init_devid->len = msg->port.init_devid_len;
1210                 i += msg->port.init_devid_len;
1211         } else {
1212                 free(port->init_devid, M_CTL);
1213                 port->init_devid = NULL;
1214         }
1215         if (new) {
1216                 if (ctl_port_register(port) != 0) {
1217                         printf("%s: ctl_port_register() failed with error\n",
1218                             __func__);
1219                 }
1220         }
1221         mtx_lock(&softc->ctl_lock);
1222         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1223                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1224                         continue;
1225                 mtx_lock(&lun->lun_lock);
1226                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1227                 mtx_unlock(&lun->lun_lock);
1228         }
1229         mtx_unlock(&softc->ctl_lock);
1230 }
1231
1232 static void
1233 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1234 {
1235         struct ctl_port *port;
1236         int iid;
1237
1238         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1239         if (port == NULL) {
1240                 printf("%s: Received IID for unknown port %d\n",
1241                     __func__, msg->hdr.nexus.targ_port);
1242                 return;
1243         }
1244         iid = msg->hdr.nexus.initid;
1245         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1246         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1247         free(port->wwpn_iid[iid].name, M_CTL);
1248         if (msg->iid.name_len) {
1249                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1250                     msg->iid.name_len, M_CTL);
1251         } else
1252                 port->wwpn_iid[iid].name = NULL;
1253 }
1254
1255 static void
1256 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1257 {
1258
1259         if (msg->login.version != CTL_HA_VERSION) {
1260                 printf("CTL HA peers have different versions %d != %d\n",
1261                     msg->login.version, CTL_HA_VERSION);
1262                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1263                 return;
1264         }
1265         if (msg->login.ha_mode != softc->ha_mode) {
1266                 printf("CTL HA peers have different ha_mode %d != %d\n",
1267                     msg->login.ha_mode, softc->ha_mode);
1268                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1269                 return;
1270         }
1271         if (msg->login.ha_id == softc->ha_id) {
1272                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1273                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274                 return;
1275         }
1276         if (msg->login.max_luns != CTL_MAX_LUNS ||
1277             msg->login.max_ports != CTL_MAX_PORTS ||
1278             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1279                 printf("CTL HA peers have different limits\n");
1280                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281                 return;
1282         }
1283 }
1284
1285 static void
1286 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1287 {
1288         struct ctl_lun *lun;
1289         int i;
1290         uint32_t initidx, targ_lun;
1291
1292         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1293         mtx_lock(&softc->ctl_lock);
1294         if ((targ_lun >= CTL_MAX_LUNS) ||
1295             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1296                 mtx_unlock(&softc->ctl_lock);
1297                 return;
1298         }
1299         mtx_lock(&lun->lun_lock);
1300         mtx_unlock(&softc->ctl_lock);
1301         if (lun->flags & CTL_LUN_DISABLED) {
1302                 mtx_unlock(&lun->lun_lock);
1303                 return;
1304         }
1305         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1306                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1307                     msg->mode.page_code &&
1308                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1309                         break;
1310         }
1311         if (i == CTL_NUM_MODE_PAGES) {
1312                 mtx_unlock(&lun->lun_lock);
1313                 return;
1314         }
1315         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1316             lun->mode_pages.index[i].page_len);
1317         initidx = ctl_get_initindex(&msg->hdr.nexus);
1318         if (initidx != -1)
1319                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1320         mtx_unlock(&lun->lun_lock);
1321 }
1322
1323 /*
1324  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1325  * subsystem come in here.
1326  */
1327 static void
1328 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1329 {
1330         struct ctl_softc *softc = control_softc;
1331         union ctl_io *io;
1332         struct ctl_prio *presio;
1333         ctl_ha_status isc_status;
1334
1335         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1336         if (event == CTL_HA_EVT_MSG_RECV) {
1337                 union ctl_ha_msg *msg, msgbuf;
1338
1339                 if (param > sizeof(msgbuf))
1340                         msg = malloc(param, M_CTL, M_WAITOK);
1341                 else
1342                         msg = &msgbuf;
1343                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1344                     M_WAITOK);
1345                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1346                         printf("%s: Error receiving message: %d\n",
1347                             __func__, isc_status);
1348                         if (msg != &msgbuf)
1349                                 free(msg, M_CTL);
1350                         return;
1351                 }
1352
1353                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1354                 switch (msg->hdr.msg_type) {
1355                 case CTL_MSG_SERIALIZE:
1356                         io = ctl_alloc_io(softc->othersc_pool);
1357                         ctl_zero_io(io);
1358                         // populate ctsio from msg
1359                         io->io_hdr.io_type = CTL_IO_SCSI;
1360                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1361                         io->io_hdr.original_sc = msg->hdr.original_sc;
1362                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1363                                             CTL_FLAG_IO_ACTIVE;
1364                         /*
1365                          * If we're in serialization-only mode, we don't
1366                          * want to go through full done processing.  Thus
1367                          * the COPY flag.
1368                          *
1369                          * XXX KDM add another flag that is more specific.
1370                          */
1371                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1372                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1373                         io->io_hdr.nexus = msg->hdr.nexus;
1374 #if 0
1375                         printf("port %u, iid %u, lun %u\n",
1376                                io->io_hdr.nexus.targ_port,
1377                                io->io_hdr.nexus.initid,
1378                                io->io_hdr.nexus.targ_lun);
1379 #endif
1380                         io->scsiio.tag_num = msg->scsi.tag_num;
1381                         io->scsiio.tag_type = msg->scsi.tag_type;
1382 #ifdef CTL_TIME_IO
1383                         io->io_hdr.start_time = time_uptime;
1384                         getbinuptime(&io->io_hdr.start_bt);
1385 #endif /* CTL_TIME_IO */
1386                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1387                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1388                                CTL_MAX_CDBLEN);
1389                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1390                                 const struct ctl_cmd_entry *entry;
1391
1392                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1393                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1394                                 io->io_hdr.flags |=
1395                                         entry->flags & CTL_FLAG_DATA_MASK;
1396                         }
1397                         ctl_enqueue_isc(io);
1398                         break;
1399
1400                 /* Performed on the Originating SC, XFER mode only */
1401                 case CTL_MSG_DATAMOVE: {
1402                         struct ctl_sg_entry *sgl;
1403                         int i, j;
1404
1405                         io = msg->hdr.original_sc;
1406                         if (io == NULL) {
1407                                 printf("%s: original_sc == NULL!\n", __func__);
1408                                 /* XXX KDM do something here */
1409                                 break;
1410                         }
1411                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1412                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1413                         /*
1414                          * Keep track of this, we need to send it back over
1415                          * when the datamove is complete.
1416                          */
1417                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1418                         if (msg->hdr.status == CTL_SUCCESS)
1419                                 io->io_hdr.status = msg->hdr.status;
1420
1421                         if (msg->dt.sg_sequence == 0) {
1422 #ifdef CTL_TIME_IO
1423                                 getbinuptime(&io->io_hdr.dma_start_bt);
1424 #endif
1425                                 i = msg->dt.kern_sg_entries +
1426                                     msg->dt.kern_data_len /
1427                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1428                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1429                                     M_WAITOK | M_ZERO);
1430                                 io->io_hdr.remote_sglist = sgl;
1431                                 io->io_hdr.local_sglist =
1432                                     &sgl[msg->dt.kern_sg_entries];
1433
1434                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1435
1436                                 io->scsiio.kern_sg_entries =
1437                                         msg->dt.kern_sg_entries;
1438                                 io->scsiio.rem_sg_entries =
1439                                         msg->dt.kern_sg_entries;
1440                                 io->scsiio.kern_data_len =
1441                                         msg->dt.kern_data_len;
1442                                 io->scsiio.kern_total_len =
1443                                         msg->dt.kern_total_len;
1444                                 io->scsiio.kern_data_resid =
1445                                         msg->dt.kern_data_resid;
1446                                 io->scsiio.kern_rel_offset =
1447                                         msg->dt.kern_rel_offset;
1448                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1449                                 io->io_hdr.flags |= msg->dt.flags &
1450                                     CTL_FLAG_BUS_ADDR;
1451                         } else
1452                                 sgl = (struct ctl_sg_entry *)
1453                                         io->scsiio.kern_data_ptr;
1454
1455                         for (i = msg->dt.sent_sg_entries, j = 0;
1456                              i < (msg->dt.sent_sg_entries +
1457                              msg->dt.cur_sg_entries); i++, j++) {
1458                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1459                                 sgl[i].len = msg->dt.sg_list[j].len;
1460
1461 #if 0
1462                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1463                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1464 #endif
1465                         }
1466
1467                         /*
1468                          * If this is the last piece of the I/O, we've got
1469                          * the full S/G list.  Queue processing in the thread.
1470                          * Otherwise wait for the next piece.
1471                          */
1472                         if (msg->dt.sg_last != 0)
1473                                 ctl_enqueue_isc(io);
1474                         break;
1475                 }
1476                 /* Performed on the Serializing (primary) SC, XFER mode only */
1477                 case CTL_MSG_DATAMOVE_DONE: {
1478                         if (msg->hdr.serializing_sc == NULL) {
1479                                 printf("%s: serializing_sc == NULL!\n",
1480                                        __func__);
1481                                 /* XXX KDM now what? */
1482                                 break;
1483                         }
1484                         /*
1485                          * We grab the sense information here in case
1486                          * there was a failure, so we can return status
1487                          * back to the initiator.
1488                          */
1489                         io = msg->hdr.serializing_sc;
1490                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1491                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1492                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1493                         io->io_hdr.port_status = msg->scsi.fetd_status;
1494                         io->scsiio.residual = msg->scsi.residual;
1495                         if (msg->hdr.status != CTL_STATUS_NONE) {
1496                                 io->io_hdr.status = msg->hdr.status;
1497                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1498                                 io->scsiio.sense_len = msg->scsi.sense_len;
1499                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1500                                 memcpy(&io->scsiio.sense_data,
1501                                     &msg->scsi.sense_data,
1502                                     msg->scsi.sense_len);
1503                                 if (msg->hdr.status == CTL_SUCCESS)
1504                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1505                         }
1506                         ctl_enqueue_isc(io);
1507                         break;
1508                 }
1509
1510                 /* Preformed on Originating SC, SER_ONLY mode */
1511                 case CTL_MSG_R2R:
1512                         io = msg->hdr.original_sc;
1513                         if (io == NULL) {
1514                                 printf("%s: original_sc == NULL!\n",
1515                                     __func__);
1516                                 break;
1517                         }
1518                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1519                         io->io_hdr.msg_type = CTL_MSG_R2R;
1520                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1521                         ctl_enqueue_isc(io);
1522                         break;
1523
1524                 /*
1525                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1526                  * mode.
1527                  * Performed on the Originating (i.e. secondary) SC in XFER
1528                  * mode
1529                  */
1530                 case CTL_MSG_FINISH_IO:
1531                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1532                                 ctl_isc_handler_finish_xfer(softc, msg);
1533                         else
1534                                 ctl_isc_handler_finish_ser_only(softc, msg);
1535                         break;
1536
1537                 /* Preformed on Originating SC */
1538                 case CTL_MSG_BAD_JUJU:
1539                         io = msg->hdr.original_sc;
1540                         if (io == NULL) {
1541                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1542                                        __func__);
1543                                 break;
1544                         }
1545                         ctl_copy_sense_data(msg, io);
1546                         /*
1547                          * IO should have already been cleaned up on other
1548                          * SC so clear this flag so we won't send a message
1549                          * back to finish the IO there.
1550                          */
1551                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1552                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1553
1554                         /* io = msg->hdr.serializing_sc; */
1555                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1556                         ctl_enqueue_isc(io);
1557                         break;
1558
1559                 /* Handle resets sent from the other side */
1560                 case CTL_MSG_MANAGE_TASKS: {
1561                         struct ctl_taskio *taskio;
1562                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1563                             softc->othersc_pool);
1564                         ctl_zero_io((union ctl_io *)taskio);
1565                         taskio->io_hdr.io_type = CTL_IO_TASK;
1566                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1567                         taskio->io_hdr.nexus = msg->hdr.nexus;
1568                         taskio->task_action = msg->task.task_action;
1569                         taskio->tag_num = msg->task.tag_num;
1570                         taskio->tag_type = msg->task.tag_type;
1571 #ifdef CTL_TIME_IO
1572                         taskio->io_hdr.start_time = time_uptime;
1573                         getbinuptime(&taskio->io_hdr.start_bt);
1574 #endif /* CTL_TIME_IO */
1575                         ctl_run_task((union ctl_io *)taskio);
1576                         break;
1577                 }
1578                 /* Persistent Reserve action which needs attention */
1579                 case CTL_MSG_PERS_ACTION:
1580                         presio = (struct ctl_prio *)ctl_alloc_io(
1581                             softc->othersc_pool);
1582                         ctl_zero_io((union ctl_io *)presio);
1583                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1584                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1585                         presio->io_hdr.nexus = msg->hdr.nexus;
1586                         presio->pr_msg = msg->pr;
1587                         ctl_enqueue_isc((union ctl_io *)presio);
1588                         break;
1589                 case CTL_MSG_UA:
1590                         ctl_isc_ua(softc, msg, param);
1591                         break;
1592                 case CTL_MSG_PORT_SYNC:
1593                         ctl_isc_port_sync(softc, msg, param);
1594                         break;
1595                 case CTL_MSG_LUN_SYNC:
1596                         ctl_isc_lun_sync(softc, msg, param);
1597                         break;
1598                 case CTL_MSG_IID_SYNC:
1599                         ctl_isc_iid_sync(softc, msg, param);
1600                         break;
1601                 case CTL_MSG_LOGIN:
1602                         ctl_isc_login(softc, msg, param);
1603                         break;
1604                 case CTL_MSG_MODE_SYNC:
1605                         ctl_isc_mode_sync(softc, msg, param);
1606                         break;
1607                 default:
1608                         printf("Received HA message of unknown type %d\n",
1609                             msg->hdr.msg_type);
1610                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1611                         break;
1612                 }
1613                 if (msg != &msgbuf)
1614                         free(msg, M_CTL);
1615         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1616                 printf("CTL: HA link status changed from %d to %d\n",
1617                     softc->ha_link, param);
1618                 if (param == softc->ha_link)
1619                         return;
1620                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1621                         softc->ha_link = param;
1622                         ctl_isc_ha_link_down(softc);
1623                 } else {
1624                         softc->ha_link = param;
1625                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1626                                 ctl_isc_ha_link_up(softc);
1627                 }
1628                 return;
1629         } else {
1630                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1631                 return;
1632         }
1633 }
1634
1635 static void
1636 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1637 {
1638
1639         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1640             src->scsi.sense_len);
1641         dest->scsiio.scsi_status = src->scsi.scsi_status;
1642         dest->scsiio.sense_len = src->scsi.sense_len;
1643         dest->io_hdr.status = src->hdr.status;
1644 }
1645
1646 static void
1647 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1648 {
1649
1650         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1651             src->scsiio.sense_len);
1652         dest->scsi.scsi_status = src->scsiio.scsi_status;
1653         dest->scsi.sense_len = src->scsiio.sense_len;
1654         dest->hdr.status = src->io_hdr.status;
1655 }
1656
1657 void
1658 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1659 {
1660         struct ctl_softc *softc = lun->ctl_softc;
1661         ctl_ua_type *pu;
1662
1663         if (initidx < softc->init_min || initidx >= softc->init_max)
1664                 return;
1665         mtx_assert(&lun->lun_lock, MA_OWNED);
1666         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1667         if (pu == NULL)
1668                 return;
1669         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1670 }
1671
1672 void
1673 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1674 {
1675         int i;
1676
1677         mtx_assert(&lun->lun_lock, MA_OWNED);
1678         if (lun->pending_ua[port] == NULL)
1679                 return;
1680         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1681                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1682                         continue;
1683                 lun->pending_ua[port][i] |= ua;
1684         }
1685 }
1686
1687 void
1688 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1689 {
1690         struct ctl_softc *softc = lun->ctl_softc;
1691         int i;
1692
1693         mtx_assert(&lun->lun_lock, MA_OWNED);
1694         for (i = softc->port_min; i < softc->port_max; i++)
1695                 ctl_est_ua_port(lun, i, except, ua);
1696 }
1697
1698 void
1699 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1700 {
1701         struct ctl_softc *softc = lun->ctl_softc;
1702         ctl_ua_type *pu;
1703
1704         if (initidx < softc->init_min || initidx >= softc->init_max)
1705                 return;
1706         mtx_assert(&lun->lun_lock, MA_OWNED);
1707         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1708         if (pu == NULL)
1709                 return;
1710         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1711 }
1712
1713 void
1714 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1715 {
1716         struct ctl_softc *softc = lun->ctl_softc;
1717         int i, j;
1718
1719         mtx_assert(&lun->lun_lock, MA_OWNED);
1720         for (i = softc->port_min; i < softc->port_max; i++) {
1721                 if (lun->pending_ua[i] == NULL)
1722                         continue;
1723                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1724                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1725                                 continue;
1726                         lun->pending_ua[i][j] &= ~ua;
1727                 }
1728         }
1729 }
1730
1731 void
1732 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1733     ctl_ua_type ua_type)
1734 {
1735         struct ctl_lun *lun;
1736
1737         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1738         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1739                 mtx_lock(&lun->lun_lock);
1740                 ctl_clr_ua(lun, initidx, ua_type);
1741                 mtx_unlock(&lun->lun_lock);
1742         }
1743 }
1744
1745 static int
1746 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1747 {
1748         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1749         struct ctl_lun *lun;
1750         struct ctl_lun_req ireq;
1751         int error, value;
1752
1753         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1754         error = sysctl_handle_int(oidp, &value, 0, req);
1755         if ((error != 0) || (req->newptr == NULL))
1756                 return (error);
1757
1758         mtx_lock(&softc->ctl_lock);
1759         if (value == 0)
1760                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1761         else
1762                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1763         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1764                 mtx_unlock(&softc->ctl_lock);
1765                 bzero(&ireq, sizeof(ireq));
1766                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1767                 ireq.reqdata.modify.lun_id = lun->lun;
1768                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1769                     curthread);
1770                 if (ireq.status != CTL_LUN_OK) {
1771                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1772                             __func__, ireq.status, ireq.error_str);
1773                 }
1774                 mtx_lock(&softc->ctl_lock);
1775         }
1776         mtx_unlock(&softc->ctl_lock);
1777         return (0);
1778 }
1779
1780 static int
1781 ctl_init(void)
1782 {
1783         struct ctl_softc *softc;
1784         void *other_pool;
1785         int i, error;
1786
1787         softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1788                                M_WAITOK | M_ZERO);
1789
1790         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1791                               "cam/ctl");
1792         softc->dev->si_drv1 = softc;
1793
1794         sysctl_ctx_init(&softc->sysctl_ctx);
1795         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1796                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1797                 CTLFLAG_RD, 0, "CAM Target Layer");
1798
1799         if (softc->sysctl_tree == NULL) {
1800                 printf("%s: unable to allocate sysctl tree\n", __func__);
1801                 destroy_dev(softc->dev);
1802                 free(control_softc, M_DEVBUF);
1803                 control_softc = NULL;
1804                 return (ENOMEM);
1805         }
1806
1807         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1808         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1809             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1810         softc->flags = 0;
1811
1812         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1813             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1814             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1815
1816         /*
1817          * In Copan's HA scheme, the "master" and "slave" roles are
1818          * figured out through the slot the controller is in.  Although it
1819          * is an active/active system, someone has to be in charge.
1820          */
1821         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1822             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1823             "HA head ID (0 - no HA)");
1824         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1825                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1826                 softc->is_single = 1;
1827                 softc->port_cnt = CTL_MAX_PORTS;
1828                 softc->port_min = 0;
1829         } else {
1830                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1831                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1832         }
1833         softc->port_max = softc->port_min + softc->port_cnt;
1834         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1835         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1836
1837         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1838             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1839             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1840
1841         STAILQ_INIT(&softc->lun_list);
1842         STAILQ_INIT(&softc->pending_lun_queue);
1843         STAILQ_INIT(&softc->fe_list);
1844         STAILQ_INIT(&softc->port_list);
1845         STAILQ_INIT(&softc->be_list);
1846         ctl_tpc_init(softc);
1847
1848         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1849                             &other_pool) != 0)
1850         {
1851                 printf("ctl: can't allocate %d entry other SC pool, "
1852                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1853                 return (ENOMEM);
1854         }
1855         softc->othersc_pool = other_pool;
1856
1857         if (worker_threads <= 0)
1858                 worker_threads = max(1, mp_ncpus / 4);
1859         if (worker_threads > CTL_MAX_THREADS)
1860                 worker_threads = CTL_MAX_THREADS;
1861
1862         for (i = 0; i < worker_threads; i++) {
1863                 struct ctl_thread *thr = &softc->threads[i];
1864
1865                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1866                 thr->ctl_softc = softc;
1867                 STAILQ_INIT(&thr->incoming_queue);
1868                 STAILQ_INIT(&thr->rtr_queue);
1869                 STAILQ_INIT(&thr->done_queue);
1870                 STAILQ_INIT(&thr->isc_queue);
1871
1872                 error = kproc_kthread_add(ctl_work_thread, thr,
1873                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1874                 if (error != 0) {
1875                         printf("error creating CTL work thread!\n");
1876                         ctl_pool_free(other_pool);
1877                         return (error);
1878                 }
1879         }
1880         error = kproc_kthread_add(ctl_lun_thread, softc,
1881             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1882         if (error != 0) {
1883                 printf("error creating CTL lun thread!\n");
1884                 ctl_pool_free(other_pool);
1885                 return (error);
1886         }
1887         error = kproc_kthread_add(ctl_thresh_thread, softc,
1888             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1889         if (error != 0) {
1890                 printf("error creating CTL threshold thread!\n");
1891                 ctl_pool_free(other_pool);
1892                 return (error);
1893         }
1894
1895         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1896             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1897             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1898
1899         if (softc->is_single == 0) {
1900                 ctl_frontend_register(&ha_frontend);
1901                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1902                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1903                         softc->is_single = 1;
1904                 } else
1905                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1906                     != CTL_HA_STATUS_SUCCESS) {
1907                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1908                         softc->is_single = 1;
1909                 }
1910         }
1911         return (0);
1912 }
1913
1914 void
1915 ctl_shutdown(void)
1916 {
1917         struct ctl_softc *softc = control_softc;
1918         struct ctl_lun *lun, *next_lun;
1919
1920         if (softc->is_single == 0) {
1921                 ctl_ha_msg_shutdown(softc);
1922                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1923                     != CTL_HA_STATUS_SUCCESS)
1924                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1925                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1926                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1927                 ctl_frontend_deregister(&ha_frontend);
1928         }
1929
1930         mtx_lock(&softc->ctl_lock);
1931
1932         STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1933                 ctl_free_lun(lun);
1934
1935         mtx_unlock(&softc->ctl_lock);
1936
1937 #if 0
1938         ctl_shutdown_thread(softc->work_thread);
1939         mtx_destroy(&softc->queue_lock);
1940 #endif
1941
1942         ctl_tpc_shutdown(softc);
1943         uma_zdestroy(softc->io_zone);
1944         mtx_destroy(&softc->ctl_lock);
1945
1946         destroy_dev(softc->dev);
1947
1948         sysctl_ctx_free(&softc->sysctl_ctx);
1949
1950         free(control_softc, M_DEVBUF);
1951         control_softc = NULL;
1952 }
1953
1954 static int
1955 ctl_module_event_handler(module_t mod, int what, void *arg)
1956 {
1957
1958         switch (what) {
1959         case MOD_LOAD:
1960                 return (ctl_init());
1961         case MOD_UNLOAD:
1962                 return (EBUSY);
1963         default:
1964                 return (EOPNOTSUPP);
1965         }
1966 }
1967
1968 /*
1969  * XXX KDM should we do some access checks here?  Bump a reference count to
1970  * prevent a CTL module from being unloaded while someone has it open?
1971  */
1972 static int
1973 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1974 {
1975         return (0);
1976 }
1977
1978 static int
1979 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1980 {
1981         return (0);
1982 }
1983
1984 /*
1985  * Remove an initiator by port number and initiator ID.
1986  * Returns 0 for success, -1 for failure.
1987  */
1988 int
1989 ctl_remove_initiator(struct ctl_port *port, int iid)
1990 {
1991         struct ctl_softc *softc = port->ctl_softc;
1992
1993         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1994
1995         if (iid > CTL_MAX_INIT_PER_PORT) {
1996                 printf("%s: initiator ID %u > maximun %u!\n",
1997                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1998                 return (-1);
1999         }
2000
2001         mtx_lock(&softc->ctl_lock);
2002         port->wwpn_iid[iid].in_use--;
2003         port->wwpn_iid[iid].last_use = time_uptime;
2004         mtx_unlock(&softc->ctl_lock);
2005         ctl_isc_announce_iid(port, iid);
2006
2007         return (0);
2008 }
2009
2010 /*
2011  * Add an initiator to the initiator map.
2012  * Returns iid for success, < 0 for failure.
2013  */
2014 int
2015 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2016 {
2017         struct ctl_softc *softc = port->ctl_softc;
2018         time_t best_time;
2019         int i, best;
2020
2021         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2022
2023         if (iid >= CTL_MAX_INIT_PER_PORT) {
2024                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2025                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2026                 free(name, M_CTL);
2027                 return (-1);
2028         }
2029
2030         mtx_lock(&softc->ctl_lock);
2031
2032         if (iid < 0 && (wwpn != 0 || name != NULL)) {
2033                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2034                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2035                                 iid = i;
2036                                 break;
2037                         }
2038                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
2039                             strcmp(name, port->wwpn_iid[i].name) == 0) {
2040                                 iid = i;
2041                                 break;
2042                         }
2043                 }
2044         }
2045
2046         if (iid < 0) {
2047                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2048                         if (port->wwpn_iid[i].in_use == 0 &&
2049                             port->wwpn_iid[i].wwpn == 0 &&
2050                             port->wwpn_iid[i].name == NULL) {
2051                                 iid = i;
2052                                 break;
2053                         }
2054                 }
2055         }
2056
2057         if (iid < 0) {
2058                 best = -1;
2059                 best_time = INT32_MAX;
2060                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2061                         if (port->wwpn_iid[i].in_use == 0) {
2062                                 if (port->wwpn_iid[i].last_use < best_time) {
2063                                         best = i;
2064                                         best_time = port->wwpn_iid[i].last_use;
2065                                 }
2066                         }
2067                 }
2068                 iid = best;
2069         }
2070
2071         if (iid < 0) {
2072                 mtx_unlock(&softc->ctl_lock);
2073                 free(name, M_CTL);
2074                 return (-2);
2075         }
2076
2077         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2078                 /*
2079                  * This is not an error yet.
2080                  */
2081                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2082 #if 0
2083                         printf("%s: port %d iid %u WWPN %#jx arrived"
2084                             " again\n", __func__, port->targ_port,
2085                             iid, (uintmax_t)wwpn);
2086 #endif
2087                         goto take;
2088                 }
2089                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2090                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
2091 #if 0
2092                         printf("%s: port %d iid %u name '%s' arrived"
2093                             " again\n", __func__, port->targ_port,
2094                             iid, name);
2095 #endif
2096                         goto take;
2097                 }
2098
2099                 /*
2100                  * This is an error, but what do we do about it?  The
2101                  * driver is telling us we have a new WWPN for this
2102                  * initiator ID, so we pretty much need to use it.
2103                  */
2104                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2105                     " but WWPN %#jx '%s' is still at that address\n",
2106                     __func__, port->targ_port, iid, wwpn, name,
2107                     (uintmax_t)port->wwpn_iid[iid].wwpn,
2108                     port->wwpn_iid[iid].name);
2109
2110                 /*
2111                  * XXX KDM clear have_ca and ua_pending on each LUN for
2112                  * this initiator.
2113                  */
2114         }
2115 take:
2116         free(port->wwpn_iid[iid].name, M_CTL);
2117         port->wwpn_iid[iid].name = name;
2118         port->wwpn_iid[iid].wwpn = wwpn;
2119         port->wwpn_iid[iid].in_use++;
2120         mtx_unlock(&softc->ctl_lock);
2121         ctl_isc_announce_iid(port, iid);
2122
2123         return (iid);
2124 }
2125
2126 static int
2127 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2128 {
2129         int len;
2130
2131         switch (port->port_type) {
2132         case CTL_PORT_FC:
2133         {
2134                 struct scsi_transportid_fcp *id =
2135                     (struct scsi_transportid_fcp *)buf;
2136                 if (port->wwpn_iid[iid].wwpn == 0)
2137                         return (0);
2138                 memset(id, 0, sizeof(*id));
2139                 id->format_protocol = SCSI_PROTO_FC;
2140                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2141                 return (sizeof(*id));
2142         }
2143         case CTL_PORT_ISCSI:
2144         {
2145                 struct scsi_transportid_iscsi_port *id =
2146                     (struct scsi_transportid_iscsi_port *)buf;
2147                 if (port->wwpn_iid[iid].name == NULL)
2148                         return (0);
2149                 memset(id, 0, 256);
2150                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2151                     SCSI_PROTO_ISCSI;
2152                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2153                 len = roundup2(min(len, 252), 4);
2154                 scsi_ulto2b(len, id->additional_length);
2155                 return (sizeof(*id) + len);
2156         }
2157         case CTL_PORT_SAS:
2158         {
2159                 struct scsi_transportid_sas *id =
2160                     (struct scsi_transportid_sas *)buf;
2161                 if (port->wwpn_iid[iid].wwpn == 0)
2162                         return (0);
2163                 memset(id, 0, sizeof(*id));
2164                 id->format_protocol = SCSI_PROTO_SAS;
2165                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2166                 return (sizeof(*id));
2167         }
2168         default:
2169         {
2170                 struct scsi_transportid_spi *id =
2171                     (struct scsi_transportid_spi *)buf;
2172                 memset(id, 0, sizeof(*id));
2173                 id->format_protocol = SCSI_PROTO_SPI;
2174                 scsi_ulto2b(iid, id->scsi_addr);
2175                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2176                 return (sizeof(*id));
2177         }
2178         }
2179 }
2180
2181 /*
2182  * Serialize a command that went down the "wrong" side, and so was sent to
2183  * this controller for execution.  The logic is a little different than the
2184  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2185  * sent back to the other side, but in the success case, we execute the
2186  * command on this side (XFER mode) or tell the other side to execute it
2187  * (SER_ONLY mode).
2188  */
2189 static int
2190 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2191 {
2192         struct ctl_softc *softc = control_softc;
2193         union ctl_ha_msg msg_info;
2194         struct ctl_port *port;
2195         struct ctl_lun *lun;
2196         const struct ctl_cmd_entry *entry;
2197         int retval = 0;
2198         uint32_t targ_lun;
2199
2200         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2201         mtx_lock(&softc->ctl_lock);
2202
2203         /* Make sure that we know about this port. */
2204         port = ctl_io_port(&ctsio->io_hdr);
2205         if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2206                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2207                                          /*retry_count*/ 1);
2208                 goto badjuju;
2209         }
2210
2211         /* Make sure that we know about this LUN. */
2212         if ((targ_lun < CTL_MAX_LUNS) &&
2213             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2214                 mtx_lock(&lun->lun_lock);
2215                 mtx_unlock(&softc->ctl_lock);
2216                 /*
2217                  * If the LUN is invalid, pretend that it doesn't exist.
2218                  * It will go away as soon as all pending I/O has been
2219                  * completed.
2220                  */
2221                 if (lun->flags & CTL_LUN_DISABLED) {
2222                         mtx_unlock(&lun->lun_lock);
2223                         lun = NULL;
2224                 }
2225         } else {
2226                 mtx_unlock(&softc->ctl_lock);
2227                 lun = NULL;
2228         }
2229         if (lun == NULL) {
2230                 /*
2231                  * The other node would not send this request to us unless
2232                  * received announce that we are primary node for this LUN.
2233                  * If this LUN does not exist now, it is probably result of
2234                  * a race, so respond to initiator in the most opaque way.
2235                  */
2236                 ctl_set_busy(ctsio);
2237                 goto badjuju;
2238         }
2239
2240         entry = ctl_get_cmd_entry(ctsio, NULL);
2241         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2242                 mtx_unlock(&lun->lun_lock);
2243                 goto badjuju;
2244         }
2245
2246         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2247         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2248
2249         /*
2250          * Every I/O goes into the OOA queue for a
2251          * particular LUN, and stays there until completion.
2252          */
2253 #ifdef CTL_TIME_IO
2254         if (TAILQ_EMPTY(&lun->ooa_queue))
2255                 lun->idle_time += getsbinuptime() - lun->last_busy;
2256 #endif
2257         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2258
2259         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2260                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2261                  ooa_links))) {
2262         case CTL_ACTION_BLOCK:
2263                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2264                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2265                                   blocked_links);
2266                 mtx_unlock(&lun->lun_lock);
2267                 break;
2268         case CTL_ACTION_PASS:
2269         case CTL_ACTION_SKIP:
2270                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2271                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2272                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2273                         mtx_unlock(&lun->lun_lock);
2274                 } else {
2275                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2276                         mtx_unlock(&lun->lun_lock);
2277
2278                         /* send msg back to other side */
2279                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2280                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2281                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2282                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2283                             sizeof(msg_info.hdr), M_WAITOK);
2284                 }
2285                 break;
2286         case CTL_ACTION_OVERLAP:
2287                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2288                 mtx_unlock(&lun->lun_lock);
2289                 ctl_set_overlapped_cmd(ctsio);
2290                 goto badjuju;
2291         case CTL_ACTION_OVERLAP_TAG:
2292                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2293                 mtx_unlock(&lun->lun_lock);
2294                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2295                 goto badjuju;
2296         case CTL_ACTION_ERROR:
2297         default:
2298                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2299                 mtx_unlock(&lun->lun_lock);
2300
2301                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2302                                          /*retry_count*/ 0);
2303 badjuju:
2304                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2305                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2306                 msg_info.hdr.serializing_sc = NULL;
2307                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2308                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2309                     sizeof(msg_info.scsi), M_WAITOK);
2310                 retval = 1;
2311                 break;
2312         }
2313         return (retval);
2314 }
2315
2316 /*
2317  * Returns 0 for success, errno for failure.
2318  */
2319 static void
2320 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2321                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2322 {
2323         union ctl_io *io;
2324
2325         mtx_lock(&lun->lun_lock);
2326         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2327              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2328              ooa_links)) {
2329                 struct ctl_ooa_entry *entry;
2330
2331                 /*
2332                  * If we've got more than we can fit, just count the
2333                  * remaining entries.
2334                  */
2335                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2336                         continue;
2337
2338                 entry = &kern_entries[*cur_fill_num];
2339
2340                 entry->tag_num = io->scsiio.tag_num;
2341                 entry->lun_num = lun->lun;
2342 #ifdef CTL_TIME_IO
2343                 entry->start_bt = io->io_hdr.start_bt;
2344 #endif
2345                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2346                 entry->cdb_len = io->scsiio.cdb_len;
2347                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2348                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2349
2350                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2351                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2352
2353                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2354                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2355
2356                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2357                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2358
2359                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2360                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2361         }
2362         mtx_unlock(&lun->lun_lock);
2363 }
2364
2365 static void *
2366 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2367                  size_t error_str_len)
2368 {
2369         void *kptr;
2370
2371         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2372
2373         if (copyin(user_addr, kptr, len) != 0) {
2374                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2375                          "from user address %p to kernel address %p", len,
2376                          user_addr, kptr);
2377                 free(kptr, M_CTL);
2378                 return (NULL);
2379         }
2380
2381         return (kptr);
2382 }
2383
2384 static void
2385 ctl_free_args(int num_args, struct ctl_be_arg *args)
2386 {
2387         int i;
2388
2389         if (args == NULL)
2390                 return;
2391
2392         for (i = 0; i < num_args; i++) {
2393                 free(args[i].kname, M_CTL);
2394                 free(args[i].kvalue, M_CTL);
2395         }
2396
2397         free(args, M_CTL);
2398 }
2399
2400 static struct ctl_be_arg *
2401 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2402                 char *error_str, size_t error_str_len)
2403 {
2404         struct ctl_be_arg *args;
2405         int i;
2406
2407         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2408                                 error_str, error_str_len);
2409
2410         if (args == NULL)
2411                 goto bailout;
2412
2413         for (i = 0; i < num_args; i++) {
2414                 args[i].kname = NULL;
2415                 args[i].kvalue = NULL;
2416         }
2417
2418         for (i = 0; i < num_args; i++) {
2419                 uint8_t *tmpptr;
2420
2421                 args[i].kname = ctl_copyin_alloc(args[i].name,
2422                         args[i].namelen, error_str, error_str_len);
2423                 if (args[i].kname == NULL)
2424                         goto bailout;
2425
2426                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2427                         snprintf(error_str, error_str_len, "Argument %d "
2428                                  "name is not NUL-terminated", i);
2429                         goto bailout;
2430                 }
2431
2432                 if (args[i].flags & CTL_BEARG_RD) {
2433                         tmpptr = ctl_copyin_alloc(args[i].value,
2434                                 args[i].vallen, error_str, error_str_len);
2435                         if (tmpptr == NULL)
2436                                 goto bailout;
2437                         if ((args[i].flags & CTL_BEARG_ASCII)
2438                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2439                                 snprintf(error_str, error_str_len, "Argument "
2440                                     "%d value is not NUL-terminated", i);
2441                                 goto bailout;
2442                         }
2443                         args[i].kvalue = tmpptr;
2444                 } else {
2445                         args[i].kvalue = malloc(args[i].vallen,
2446                             M_CTL, M_WAITOK | M_ZERO);
2447                 }
2448         }
2449
2450         return (args);
2451 bailout:
2452
2453         ctl_free_args(num_args, args);
2454
2455         return (NULL);
2456 }
2457
2458 static void
2459 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2460 {
2461         int i;
2462
2463         for (i = 0; i < num_args; i++) {
2464                 if (args[i].flags & CTL_BEARG_WR)
2465                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2466         }
2467 }
2468
2469 /*
2470  * Escape characters that are illegal or not recommended in XML.
2471  */
2472 int
2473 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2474 {
2475         char *end = str + size;
2476         int retval;
2477
2478         retval = 0;
2479
2480         for (; *str && str < end; str++) {
2481                 switch (*str) {
2482                 case '&':
2483                         retval = sbuf_printf(sb, "&amp;");
2484                         break;
2485                 case '>':
2486                         retval = sbuf_printf(sb, "&gt;");
2487                         break;
2488                 case '<':
2489                         retval = sbuf_printf(sb, "&lt;");
2490                         break;
2491                 default:
2492                         retval = sbuf_putc(sb, *str);
2493                         break;
2494                 }
2495
2496                 if (retval != 0)
2497                         break;
2498
2499         }
2500
2501         return (retval);
2502 }
2503
2504 static void
2505 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2506 {
2507         struct scsi_vpd_id_descriptor *desc;
2508         int i;
2509
2510         if (id == NULL || id->len < 4)
2511                 return;
2512         desc = (struct scsi_vpd_id_descriptor *)id->data;
2513         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2514         case SVPD_ID_TYPE_T10:
2515                 sbuf_printf(sb, "t10.");
2516                 break;
2517         case SVPD_ID_TYPE_EUI64:
2518                 sbuf_printf(sb, "eui.");
2519                 break;
2520         case SVPD_ID_TYPE_NAA:
2521                 sbuf_printf(sb, "naa.");
2522                 break;
2523         case SVPD_ID_TYPE_SCSI_NAME:
2524                 break;
2525         }
2526         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2527         case SVPD_ID_CODESET_BINARY:
2528                 for (i = 0; i < desc->length; i++)
2529                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2530                 break;
2531         case SVPD_ID_CODESET_ASCII:
2532                 sbuf_printf(sb, "%.*s", (int)desc->length,
2533                     (char *)desc->identifier);
2534                 break;
2535         case SVPD_ID_CODESET_UTF8:
2536                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2537                 break;
2538         }
2539 }
2540
2541 static int
2542 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2543           struct thread *td)
2544 {
2545         struct ctl_softc *softc = dev->si_drv1;
2546         struct ctl_lun *lun;
2547         int retval;
2548
2549         retval = 0;
2550
2551         switch (cmd) {
2552         case CTL_IO:
2553                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2554                 break;
2555         case CTL_ENABLE_PORT:
2556         case CTL_DISABLE_PORT:
2557         case CTL_SET_PORT_WWNS: {
2558                 struct ctl_port *port;
2559                 struct ctl_port_entry *entry;
2560
2561                 entry = (struct ctl_port_entry *)addr;
2562                 
2563                 mtx_lock(&softc->ctl_lock);
2564                 STAILQ_FOREACH(port, &softc->port_list, links) {
2565                         int action, done;
2566
2567                         if (port->targ_port < softc->port_min ||
2568                             port->targ_port >= softc->port_max)
2569                                 continue;
2570
2571                         action = 0;
2572                         done = 0;
2573                         if ((entry->port_type == CTL_PORT_NONE)
2574                          && (entry->targ_port == port->targ_port)) {
2575                                 /*
2576                                  * If the user only wants to enable or
2577                                  * disable or set WWNs on a specific port,
2578                                  * do the operation and we're done.
2579                                  */
2580                                 action = 1;
2581                                 done = 1;
2582                         } else if (entry->port_type & port->port_type) {
2583                                 /*
2584                                  * Compare the user's type mask with the
2585                                  * particular frontend type to see if we
2586                                  * have a match.
2587                                  */
2588                                 action = 1;
2589                                 done = 0;
2590
2591                                 /*
2592                                  * Make sure the user isn't trying to set
2593                                  * WWNs on multiple ports at the same time.
2594                                  */
2595                                 if (cmd == CTL_SET_PORT_WWNS) {
2596                                         printf("%s: Can't set WWNs on "
2597                                                "multiple ports\n", __func__);
2598                                         retval = EINVAL;
2599                                         break;
2600                                 }
2601                         }
2602                         if (action == 0)
2603                                 continue;
2604
2605                         /*
2606                          * XXX KDM we have to drop the lock here, because
2607                          * the online/offline operations can potentially
2608                          * block.  We need to reference count the frontends
2609                          * so they can't go away,
2610                          */
2611                         if (cmd == CTL_ENABLE_PORT) {
2612                                 mtx_unlock(&softc->ctl_lock);
2613                                 ctl_port_online(port);
2614                                 mtx_lock(&softc->ctl_lock);
2615                         } else if (cmd == CTL_DISABLE_PORT) {
2616                                 mtx_unlock(&softc->ctl_lock);
2617                                 ctl_port_offline(port);
2618                                 mtx_lock(&softc->ctl_lock);
2619                         } else if (cmd == CTL_SET_PORT_WWNS) {
2620                                 ctl_port_set_wwns(port,
2621                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2622                                     1 : 0, entry->wwnn,
2623                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2624                                     1 : 0, entry->wwpn);
2625                         }
2626                         if (done != 0)
2627                                 break;
2628                 }
2629                 mtx_unlock(&softc->ctl_lock);
2630                 break;
2631         }
2632         case CTL_GET_OOA: {
2633                 struct ctl_ooa *ooa_hdr;
2634                 struct ctl_ooa_entry *entries;
2635                 uint32_t cur_fill_num;
2636
2637                 ooa_hdr = (struct ctl_ooa *)addr;
2638
2639                 if ((ooa_hdr->alloc_len == 0)
2640                  || (ooa_hdr->alloc_num == 0)) {
2641                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2642                                "must be non-zero\n", __func__,
2643                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2644                         retval = EINVAL;
2645                         break;
2646                 }
2647
2648                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2649                     sizeof(struct ctl_ooa_entry))) {
2650                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2651                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2652                                __func__, ooa_hdr->alloc_len,
2653                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2654                         retval = EINVAL;
2655                         break;
2656                 }
2657
2658                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2659                 if (entries == NULL) {
2660                         printf("%s: could not allocate %d bytes for OOA "
2661                                "dump\n", __func__, ooa_hdr->alloc_len);
2662                         retval = ENOMEM;
2663                         break;
2664                 }
2665
2666                 mtx_lock(&softc->ctl_lock);
2667                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2668                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2669                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2670                         mtx_unlock(&softc->ctl_lock);
2671                         free(entries, M_CTL);
2672                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2673                                __func__, (uintmax_t)ooa_hdr->lun_num);
2674                         retval = EINVAL;
2675                         break;
2676                 }
2677
2678                 cur_fill_num = 0;
2679
2680                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2681                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2682                                 ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2683                                     ooa_hdr, entries);
2684                         }
2685                 } else {
2686                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2687                         ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2688                             entries);
2689                 }
2690                 mtx_unlock(&softc->ctl_lock);
2691
2692                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2693                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2694                         sizeof(struct ctl_ooa_entry);
2695                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2696                 if (retval != 0) {
2697                         printf("%s: error copying out %d bytes for OOA dump\n", 
2698                                __func__, ooa_hdr->fill_len);
2699                 }
2700
2701                 getbinuptime(&ooa_hdr->cur_bt);
2702
2703                 if (cur_fill_num > ooa_hdr->alloc_num) {
2704                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2705                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2706                 } else {
2707                         ooa_hdr->dropped_num = 0;
2708                         ooa_hdr->status = CTL_OOA_OK;
2709                 }
2710
2711                 free(entries, M_CTL);
2712                 break;
2713         }
2714         case CTL_DELAY_IO: {
2715                 struct ctl_io_delay_info *delay_info;
2716
2717                 delay_info = (struct ctl_io_delay_info *)addr;
2718
2719 #ifdef CTL_IO_DELAY
2720                 mtx_lock(&softc->ctl_lock);
2721
2722                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2723                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2724                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2725                 } else {
2726                         lun = softc->ctl_luns[delay_info->lun_id];
2727                         mtx_lock(&lun->lun_lock);
2728
2729                         delay_info->status = CTL_DELAY_STATUS_OK;
2730
2731                         switch (delay_info->delay_type) {
2732                         case CTL_DELAY_TYPE_CONT:
2733                                 break;
2734                         case CTL_DELAY_TYPE_ONESHOT:
2735                                 break;
2736                         default:
2737                                 delay_info->status =
2738                                         CTL_DELAY_STATUS_INVALID_TYPE;
2739                                 break;
2740                         }
2741
2742                         switch (delay_info->delay_loc) {
2743                         case CTL_DELAY_LOC_DATAMOVE:
2744                                 lun->delay_info.datamove_type =
2745                                         delay_info->delay_type;
2746                                 lun->delay_info.datamove_delay =
2747                                         delay_info->delay_secs;
2748                                 break;
2749                         case CTL_DELAY_LOC_DONE:
2750                                 lun->delay_info.done_type =
2751                                         delay_info->delay_type;
2752                                 lun->delay_info.done_delay =
2753                                         delay_info->delay_secs;
2754                                 break;
2755                         default:
2756                                 delay_info->status =
2757                                         CTL_DELAY_STATUS_INVALID_LOC;
2758                                 break;
2759                         }
2760                         mtx_unlock(&lun->lun_lock);
2761                 }
2762
2763                 mtx_unlock(&softc->ctl_lock);
2764 #else
2765                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2766 #endif /* CTL_IO_DELAY */
2767                 break;
2768         }
2769         case CTL_GETSTATS: {
2770                 struct ctl_stats *stats;
2771                 int i;
2772
2773                 stats = (struct ctl_stats *)addr;
2774
2775                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2776                      stats->alloc_len) {
2777                         stats->status = CTL_SS_NEED_MORE_SPACE;
2778                         stats->num_luns = softc->num_luns;
2779                         break;
2780                 }
2781                 /*
2782                  * XXX KDM no locking here.  If the LUN list changes,
2783                  * things can blow up.
2784                  */
2785                 i = 0;
2786                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2787                         retval = copyout(&lun->stats, &stats->lun_stats[i++],
2788                                          sizeof(lun->stats));
2789                         if (retval != 0)
2790                                 break;
2791                 }
2792                 stats->num_luns = softc->num_luns;
2793                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2794                                  softc->num_luns;
2795                 stats->status = CTL_SS_OK;
2796 #ifdef CTL_TIME_IO
2797                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2798 #else
2799                 stats->flags = CTL_STATS_FLAG_NONE;
2800 #endif
2801                 getnanouptime(&stats->timestamp);
2802                 break;
2803         }
2804         case CTL_ERROR_INJECT: {
2805                 struct ctl_error_desc *err_desc, *new_err_desc;
2806
2807                 err_desc = (struct ctl_error_desc *)addr;
2808
2809                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2810                                       M_WAITOK | M_ZERO);
2811                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2812
2813                 mtx_lock(&softc->ctl_lock);
2814                 lun = softc->ctl_luns[err_desc->lun_id];
2815                 if (lun == NULL) {
2816                         mtx_unlock(&softc->ctl_lock);
2817                         free(new_err_desc, M_CTL);
2818                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2819                                __func__, (uintmax_t)err_desc->lun_id);
2820                         retval = EINVAL;
2821                         break;
2822                 }
2823                 mtx_lock(&lun->lun_lock);
2824                 mtx_unlock(&softc->ctl_lock);
2825
2826                 /*
2827                  * We could do some checking here to verify the validity
2828                  * of the request, but given the complexity of error
2829                  * injection requests, the checking logic would be fairly
2830                  * complex.
2831                  *
2832                  * For now, if the request is invalid, it just won't get
2833                  * executed and might get deleted.
2834                  */
2835                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2836
2837                 /*
2838                  * XXX KDM check to make sure the serial number is unique,
2839                  * in case we somehow manage to wrap.  That shouldn't
2840                  * happen for a very long time, but it's the right thing to
2841                  * do.
2842                  */
2843                 new_err_desc->serial = lun->error_serial;
2844                 err_desc->serial = lun->error_serial;
2845                 lun->error_serial++;
2846
2847                 mtx_unlock(&lun->lun_lock);
2848                 break;
2849         }
2850         case CTL_ERROR_INJECT_DELETE: {
2851                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2852                 int delete_done;
2853
2854                 delete_desc = (struct ctl_error_desc *)addr;
2855                 delete_done = 0;
2856
2857                 mtx_lock(&softc->ctl_lock);
2858                 lun = softc->ctl_luns[delete_desc->lun_id];
2859                 if (lun == NULL) {
2860                         mtx_unlock(&softc->ctl_lock);
2861                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2862                                __func__, (uintmax_t)delete_desc->lun_id);
2863                         retval = EINVAL;
2864                         break;
2865                 }
2866                 mtx_lock(&lun->lun_lock);
2867                 mtx_unlock(&softc->ctl_lock);
2868                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2869                         if (desc->serial != delete_desc->serial)
2870                                 continue;
2871
2872                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2873                                       links);
2874                         free(desc, M_CTL);
2875                         delete_done = 1;
2876                 }
2877                 mtx_unlock(&lun->lun_lock);
2878                 if (delete_done == 0) {
2879                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2880                                "error serial %ju on LUN %u\n", __func__, 
2881                                delete_desc->serial, delete_desc->lun_id);
2882                         retval = EINVAL;
2883                         break;
2884                 }
2885                 break;
2886         }
2887         case CTL_DUMP_STRUCTS: {
2888                 int i, j, k;
2889                 struct ctl_port *port;
2890                 struct ctl_frontend *fe;
2891
2892                 mtx_lock(&softc->ctl_lock);
2893                 printf("CTL Persistent Reservation information start:\n");
2894                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2895                         lun = softc->ctl_luns[i];
2896
2897                         if ((lun == NULL)
2898                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2899                                 continue;
2900
2901                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2902                                 if (lun->pr_keys[j] == NULL)
2903                                         continue;
2904                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2905                                         if (lun->pr_keys[j][k] == 0)
2906                                                 continue;
2907                                         printf("  LUN %d port %d iid %d key "
2908                                                "%#jx\n", i, j, k,
2909                                                (uintmax_t)lun->pr_keys[j][k]);
2910                                 }
2911                         }
2912                 }
2913                 printf("CTL Persistent Reservation information end\n");
2914                 printf("CTL Ports:\n");
2915                 STAILQ_FOREACH(port, &softc->port_list, links) {
2916                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2917                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2918                                port->frontend->name, port->port_type,
2919                                port->physical_port, port->virtual_port,
2920                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2921                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2922                                 if (port->wwpn_iid[j].in_use == 0 &&
2923                                     port->wwpn_iid[j].wwpn == 0 &&
2924                                     port->wwpn_iid[j].name == NULL)
2925                                         continue;
2926
2927                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2928                                     j, port->wwpn_iid[j].in_use,
2929                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2930                                     port->wwpn_iid[j].name);
2931                         }
2932                 }
2933                 printf("CTL Port information end\n");
2934                 mtx_unlock(&softc->ctl_lock);
2935                 /*
2936                  * XXX KDM calling this without a lock.  We'd likely want
2937                  * to drop the lock before calling the frontend's dump
2938                  * routine anyway.
2939                  */
2940                 printf("CTL Frontends:\n");
2941                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2942                         printf("  Frontend '%s'\n", fe->name);
2943                         if (fe->fe_dump != NULL)
2944                                 fe->fe_dump();
2945                 }
2946                 printf("CTL Frontend information end\n");
2947                 break;
2948         }
2949         case CTL_LUN_REQ: {
2950                 struct ctl_lun_req *lun_req;
2951                 struct ctl_backend_driver *backend;
2952
2953                 lun_req = (struct ctl_lun_req *)addr;
2954
2955                 backend = ctl_backend_find(lun_req->backend);
2956                 if (backend == NULL) {
2957                         lun_req->status = CTL_LUN_ERROR;
2958                         snprintf(lun_req->error_str,
2959                                  sizeof(lun_req->error_str),
2960                                  "Backend \"%s\" not found.",
2961                                  lun_req->backend);
2962                         break;
2963                 }
2964                 if (lun_req->num_be_args > 0) {
2965                         lun_req->kern_be_args = ctl_copyin_args(
2966                                 lun_req->num_be_args,
2967                                 lun_req->be_args,
2968                                 lun_req->error_str,
2969                                 sizeof(lun_req->error_str));
2970                         if (lun_req->kern_be_args == NULL) {
2971                                 lun_req->status = CTL_LUN_ERROR;
2972                                 break;
2973                         }
2974                 }
2975
2976                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2977
2978                 if (lun_req->num_be_args > 0) {
2979                         ctl_copyout_args(lun_req->num_be_args,
2980                                       lun_req->kern_be_args);
2981                         ctl_free_args(lun_req->num_be_args,
2982                                       lun_req->kern_be_args);
2983                 }
2984                 break;
2985         }
2986         case CTL_LUN_LIST: {
2987                 struct sbuf *sb;
2988                 struct ctl_lun_list *list;
2989                 struct ctl_option *opt;
2990
2991                 list = (struct ctl_lun_list *)addr;
2992
2993                 /*
2994                  * Allocate a fixed length sbuf here, based on the length
2995                  * of the user's buffer.  We could allocate an auto-extending
2996                  * buffer, and then tell the user how much larger our
2997                  * amount of data is than his buffer, but that presents
2998                  * some problems:
2999                  *
3000                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3001                  *     we can't hold a lock while calling them with an
3002                  *     auto-extending buffer.
3003                  *
3004                  * 2.  There is not currently a LUN reference counting
3005                  *     mechanism, outside of outstanding transactions on
3006                  *     the LUN's OOA queue.  So a LUN could go away on us
3007                  *     while we're getting the LUN number, backend-specific
3008                  *     information, etc.  Thus, given the way things
3009                  *     currently work, we need to hold the CTL lock while
3010                  *     grabbing LUN information.
3011                  *
3012                  * So, from the user's standpoint, the best thing to do is
3013                  * allocate what he thinks is a reasonable buffer length,
3014                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3015                  * double the buffer length and try again.  (And repeat
3016                  * that until he succeeds.)
3017                  */
3018                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3019                 if (sb == NULL) {
3020                         list->status = CTL_LUN_LIST_ERROR;
3021                         snprintf(list->error_str, sizeof(list->error_str),
3022                                  "Unable to allocate %d bytes for LUN list",
3023                                  list->alloc_len);
3024                         break;
3025                 }
3026
3027                 sbuf_printf(sb, "<ctllunlist>\n");
3028
3029                 mtx_lock(&softc->ctl_lock);
3030                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3031                         mtx_lock(&lun->lun_lock);
3032                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3033                                              (uintmax_t)lun->lun);
3034
3035                         /*
3036                          * Bail out as soon as we see that we've overfilled
3037                          * the buffer.
3038                          */
3039                         if (retval != 0)
3040                                 break;
3041
3042                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3043                                              "</backend_type>\n",
3044                                              (lun->backend == NULL) ?  "none" :
3045                                              lun->backend->name);
3046
3047                         if (retval != 0)
3048                                 break;
3049
3050                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3051                                              lun->be_lun->lun_type);
3052
3053                         if (retval != 0)
3054                                 break;
3055
3056                         if (lun->backend == NULL) {
3057                                 retval = sbuf_printf(sb, "</lun>\n");
3058                                 if (retval != 0)
3059                                         break;
3060                                 continue;
3061                         }
3062
3063                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3064                                              (lun->be_lun->maxlba > 0) ?
3065                                              lun->be_lun->maxlba + 1 : 0);
3066
3067                         if (retval != 0)
3068                                 break;
3069
3070                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3071                                              lun->be_lun->blocksize);
3072
3073                         if (retval != 0)
3074                                 break;
3075
3076                         retval = sbuf_printf(sb, "\t<serial_number>");
3077
3078                         if (retval != 0)
3079                                 break;
3080
3081                         retval = ctl_sbuf_printf_esc(sb,
3082                             lun->be_lun->serial_num,
3083                             sizeof(lun->be_lun->serial_num));
3084
3085                         if (retval != 0)
3086                                 break;
3087
3088                         retval = sbuf_printf(sb, "</serial_number>\n");
3089                 
3090                         if (retval != 0)
3091                                 break;
3092
3093                         retval = sbuf_printf(sb, "\t<device_id>");
3094
3095                         if (retval != 0)
3096                                 break;
3097
3098                         retval = ctl_sbuf_printf_esc(sb,
3099                             lun->be_lun->device_id,
3100                             sizeof(lun->be_lun->device_id));
3101
3102                         if (retval != 0)
3103                                 break;
3104
3105                         retval = sbuf_printf(sb, "</device_id>\n");
3106
3107                         if (retval != 0)
3108                                 break;
3109
3110                         if (lun->backend->lun_info != NULL) {
3111                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3112                                 if (retval != 0)
3113                                         break;
3114                         }
3115                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3116                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3117                                     opt->name, opt->value, opt->name);
3118                                 if (retval != 0)
3119                                         break;
3120                         }
3121
3122                         retval = sbuf_printf(sb, "</lun>\n");
3123
3124                         if (retval != 0)
3125                                 break;
3126                         mtx_unlock(&lun->lun_lock);
3127                 }
3128                 if (lun != NULL)
3129                         mtx_unlock(&lun->lun_lock);
3130                 mtx_unlock(&softc->ctl_lock);
3131
3132                 if ((retval != 0)
3133                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3134                         retval = 0;
3135                         sbuf_delete(sb);
3136                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3137                         snprintf(list->error_str, sizeof(list->error_str),
3138                                  "Out of space, %d bytes is too small",
3139                                  list->alloc_len);
3140                         break;
3141                 }
3142
3143                 sbuf_finish(sb);
3144
3145                 retval = copyout(sbuf_data(sb), list->lun_xml,
3146                                  sbuf_len(sb) + 1);
3147
3148                 list->fill_len = sbuf_len(sb) + 1;
3149                 list->status = CTL_LUN_LIST_OK;
3150                 sbuf_delete(sb);
3151                 break;
3152         }
3153         case CTL_ISCSI: {
3154                 struct ctl_iscsi *ci;
3155                 struct ctl_frontend *fe;
3156
3157                 ci = (struct ctl_iscsi *)addr;
3158
3159                 fe = ctl_frontend_find("iscsi");
3160                 if (fe == NULL) {
3161                         ci->status = CTL_ISCSI_ERROR;
3162                         snprintf(ci->error_str, sizeof(ci->error_str),
3163                             "Frontend \"iscsi\" not found.");
3164                         break;
3165                 }
3166
3167                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3168                 break;
3169         }
3170         case CTL_PORT_REQ: {
3171                 struct ctl_req *req;
3172                 struct ctl_frontend *fe;
3173
3174                 req = (struct ctl_req *)addr;
3175
3176                 fe = ctl_frontend_find(req->driver);
3177                 if (fe == NULL) {
3178                         req->status = CTL_LUN_ERROR;
3179                         snprintf(req->error_str, sizeof(req->error_str),
3180                             "Frontend \"%s\" not found.", req->driver);
3181                         break;
3182                 }
3183                 if (req->num_args > 0) {
3184                         req->kern_args = ctl_copyin_args(req->num_args,
3185                             req->args, req->error_str, sizeof(req->error_str));
3186                         if (req->kern_args == NULL) {
3187                                 req->status = CTL_LUN_ERROR;
3188                                 break;
3189                         }
3190                 }
3191
3192                 if (fe->ioctl)
3193                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3194                 else
3195                         retval = ENODEV;
3196
3197                 if (req->num_args > 0) {
3198                         ctl_copyout_args(req->num_args, req->kern_args);
3199                         ctl_free_args(req->num_args, req->kern_args);
3200                 }
3201                 break;
3202         }
3203         case CTL_PORT_LIST: {
3204                 struct sbuf *sb;
3205                 struct ctl_port *port;
3206                 struct ctl_lun_list *list;
3207                 struct ctl_option *opt;
3208                 int j;
3209                 uint32_t plun;
3210
3211                 list = (struct ctl_lun_list *)addr;
3212
3213                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3214                 if (sb == NULL) {
3215                         list->status = CTL_LUN_LIST_ERROR;
3216                         snprintf(list->error_str, sizeof(list->error_str),
3217                                  "Unable to allocate %d bytes for LUN list",
3218                                  list->alloc_len);
3219                         break;
3220                 }
3221
3222                 sbuf_printf(sb, "<ctlportlist>\n");
3223
3224                 mtx_lock(&softc->ctl_lock);
3225                 STAILQ_FOREACH(port, &softc->port_list, links) {
3226                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3227                                              (uintmax_t)port->targ_port);
3228
3229                         /*
3230                          * Bail out as soon as we see that we've overfilled
3231                          * the buffer.
3232                          */
3233                         if (retval != 0)
3234                                 break;
3235
3236                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3237                             "</frontend_type>\n", port->frontend->name);
3238                         if (retval != 0)
3239                                 break;
3240
3241                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3242                                              port->port_type);
3243                         if (retval != 0)
3244                                 break;
3245
3246                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3247                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3248                         if (retval != 0)
3249                                 break;
3250
3251                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3252                             port->port_name);
3253                         if (retval != 0)
3254                                 break;
3255
3256                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3257                             port->physical_port);
3258                         if (retval != 0)
3259                                 break;
3260
3261                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3262                             port->virtual_port);
3263                         if (retval != 0)
3264                                 break;
3265
3266                         if (port->target_devid != NULL) {
3267                                 sbuf_printf(sb, "\t<target>");
3268                                 ctl_id_sbuf(port->target_devid, sb);
3269                                 sbuf_printf(sb, "</target>\n");
3270                         }
3271
3272                         if (port->port_devid != NULL) {
3273                                 sbuf_printf(sb, "\t<port>");
3274                                 ctl_id_sbuf(port->port_devid, sb);
3275                                 sbuf_printf(sb, "</port>\n");
3276                         }
3277
3278                         if (port->port_info != NULL) {
3279                                 retval = port->port_info(port->onoff_arg, sb);
3280                                 if (retval != 0)
3281                                         break;
3282                         }
3283                         STAILQ_FOREACH(opt, &port->options, links) {
3284                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3285                                     opt->name, opt->value, opt->name);
3286                                 if (retval != 0)
3287                                         break;
3288                         }
3289
3290                         if (port->lun_map != NULL) {
3291                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3292                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3293                                         plun = ctl_lun_map_from_port(port, j);
3294                                         if (plun >= CTL_MAX_LUNS)
3295                                                 continue;
3296                                         sbuf_printf(sb,
3297                                             "\t<lun id=\"%u\">%u</lun>\n",
3298                                             j, plun);
3299                                 }
3300                         }
3301
3302                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3303                                 if (port->wwpn_iid[j].in_use == 0 ||
3304                                     (port->wwpn_iid[j].wwpn == 0 &&
3305                                      port->wwpn_iid[j].name == NULL))
3306                                         continue;
3307
3308                                 if (port->wwpn_iid[j].name != NULL)
3309                                         retval = sbuf_printf(sb,
3310                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3311                                             j, port->wwpn_iid[j].name);
3312                                 else
3313                                         retval = sbuf_printf(sb,
3314                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3315                                             j, port->wwpn_iid[j].wwpn);
3316                                 if (retval != 0)
3317                                         break;
3318                         }
3319                         if (retval != 0)
3320                                 break;
3321
3322                         retval = sbuf_printf(sb, "</targ_port>\n");
3323                         if (retval != 0)
3324                                 break;
3325                 }
3326                 mtx_unlock(&softc->ctl_lock);
3327
3328                 if ((retval != 0)
3329                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3330                         retval = 0;
3331                         sbuf_delete(sb);
3332                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3333                         snprintf(list->error_str, sizeof(list->error_str),
3334                                  "Out of space, %d bytes is too small",
3335                                  list->alloc_len);
3336                         break;
3337                 }
3338
3339                 sbuf_finish(sb);
3340
3341                 retval = copyout(sbuf_data(sb), list->lun_xml,
3342                                  sbuf_len(sb) + 1);
3343
3344                 list->fill_len = sbuf_len(sb) + 1;
3345                 list->status = CTL_LUN_LIST_OK;
3346                 sbuf_delete(sb);
3347                 break;
3348         }
3349         case CTL_LUN_MAP: {
3350                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3351                 struct ctl_port *port;
3352
3353                 mtx_lock(&softc->ctl_lock);
3354                 if (lm->port < softc->port_min ||
3355                     lm->port >= softc->port_max ||
3356                     (port = softc->ctl_ports[lm->port]) == NULL) {
3357                         mtx_unlock(&softc->ctl_lock);
3358                         return (ENXIO);
3359                 }
3360                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3361                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3362                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3363                                     CTL_MAX_LUNS)
3364                                         continue;
3365                                 mtx_lock(&lun->lun_lock);
3366                                 ctl_est_ua_port(lun, lm->port, -1,
3367                                     CTL_UA_LUN_CHANGE);
3368                                 mtx_unlock(&lun->lun_lock);
3369                         }
3370                 }
3371                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3372                 if (lm->plun < CTL_MAX_LUNS) {
3373                         if (lm->lun == UINT32_MAX)
3374                                 retval = ctl_lun_map_unset(port, lm->plun);
3375                         else if (lm->lun < CTL_MAX_LUNS &&
3376                             softc->ctl_luns[lm->lun] != NULL)
3377                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3378                         else
3379                                 return (ENXIO);
3380                 } else if (lm->plun == UINT32_MAX) {
3381                         if (lm->lun == UINT32_MAX)
3382                                 retval = ctl_lun_map_deinit(port);
3383                         else
3384                                 retval = ctl_lun_map_init(port);
3385                 } else
3386                         return (ENXIO);
3387                 if (port->status & CTL_PORT_STATUS_ONLINE)
3388                         ctl_isc_announce_port(port);
3389                 break;
3390         }
3391         default: {
3392                 /* XXX KDM should we fix this? */
3393 #if 0
3394                 struct ctl_backend_driver *backend;
3395                 unsigned int type;
3396                 int found;
3397
3398                 found = 0;
3399
3400                 /*
3401                  * We encode the backend type as the ioctl type for backend
3402                  * ioctls.  So parse it out here, and then search for a
3403                  * backend of this type.
3404                  */
3405                 type = _IOC_TYPE(cmd);
3406
3407                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3408                         if (backend->type == type) {
3409                                 found = 1;
3410                                 break;
3411                         }
3412                 }
3413                 if (found == 0) {
3414                         printf("ctl: unknown ioctl command %#lx or backend "
3415                                "%d\n", cmd, type);
3416                         retval = EINVAL;
3417                         break;
3418                 }
3419                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3420 #endif
3421                 retval = ENOTTY;
3422                 break;
3423         }
3424         }
3425         return (retval);
3426 }
3427
3428 uint32_t
3429 ctl_get_initindex(struct ctl_nexus *nexus)
3430 {
3431         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3432 }
3433
3434 int
3435 ctl_lun_map_init(struct ctl_port *port)
3436 {
3437         struct ctl_softc *softc = port->ctl_softc;
3438         struct ctl_lun *lun;
3439         uint32_t i;
3440
3441         if (port->lun_map == NULL)
3442                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3443                     M_CTL, M_NOWAIT);
3444         if (port->lun_map == NULL)
3445                 return (ENOMEM);
3446         for (i = 0; i < CTL_MAX_LUNS; i++)
3447                 port->lun_map[i] = UINT32_MAX;
3448         if (port->status & CTL_PORT_STATUS_ONLINE) {
3449                 if (port->lun_disable != NULL) {
3450                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3451                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3452                 }
3453                 ctl_isc_announce_port(port);
3454         }
3455         return (0);
3456 }
3457
3458 int
3459 ctl_lun_map_deinit(struct ctl_port *port)
3460 {
3461         struct ctl_softc *softc = port->ctl_softc;
3462         struct ctl_lun *lun;
3463
3464         if (port->lun_map == NULL)
3465                 return (0);
3466         free(port->lun_map, M_CTL);
3467         port->lun_map = NULL;
3468         if (port->status & CTL_PORT_STATUS_ONLINE) {
3469                 if (port->lun_enable != NULL) {
3470                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3471                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3472                 }
3473                 ctl_isc_announce_port(port);
3474         }
3475         return (0);
3476 }
3477
3478 int
3479 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3480 {
3481         int status;
3482         uint32_t old;
3483
3484         if (port->lun_map == NULL) {
3485                 status = ctl_lun_map_init(port);
3486                 if (status != 0)
3487                         return (status);
3488         }
3489         old = port->lun_map[plun];
3490         port->lun_map[plun] = glun;
3491         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3492                 if (port->lun_enable != NULL)
3493                         port->lun_enable(port->targ_lun_arg, plun);
3494                 ctl_isc_announce_port(port);
3495         }
3496         return (0);
3497 }
3498
3499 int
3500 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3501 {
3502         uint32_t old;
3503
3504         if (port->lun_map == NULL)
3505                 return (0);
3506         old = port->lun_map[plun];
3507         port->lun_map[plun] = UINT32_MAX;
3508         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3509                 if (port->lun_disable != NULL)
3510                         port->lun_disable(port->targ_lun_arg, plun);
3511                 ctl_isc_announce_port(port);
3512         }
3513         return (0);
3514 }
3515
3516 uint32_t
3517 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3518 {
3519
3520         if (port == NULL)
3521                 return (UINT32_MAX);
3522         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3523                 return (lun_id);
3524         return (port->lun_map[lun_id]);
3525 }
3526
3527 uint32_t
3528 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3529 {
3530         uint32_t i;
3531
3532         if (port == NULL)
3533                 return (UINT32_MAX);
3534         if (port->lun_map == NULL)
3535                 return (lun_id);
3536         for (i = 0; i < CTL_MAX_LUNS; i++) {
3537                 if (port->lun_map[i] == lun_id)
3538                         return (i);
3539         }
3540         return (UINT32_MAX);
3541 }
3542
3543 uint32_t
3544 ctl_decode_lun(uint64_t encoded)
3545 {
3546         uint8_t lun[8];
3547         uint32_t result = 0xffffffff;
3548
3549         be64enc(lun, encoded);
3550         switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3551         case RPL_LUNDATA_ATYP_PERIPH:
3552                 if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3553                     lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3554                         result = lun[1];
3555                 break;
3556         case RPL_LUNDATA_ATYP_FLAT:
3557                 if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3558                     lun[6] == 0 && lun[7] == 0)
3559                         result = ((lun[0] & 0x3f) << 8) + lun[1];
3560                 break;
3561         case RPL_LUNDATA_ATYP_EXTLUN:
3562                 switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3563                 case 0x02:
3564                         switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3565                         case 0x00:
3566                                 result = lun[1];
3567                                 break;
3568                         case 0x10:
3569                                 result = (lun[1] << 16) + (lun[2] << 8) +
3570                                     lun[3];
3571                                 break;
3572                         case 0x20:
3573                                 if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3574                                         result = (lun[2] << 24) +
3575                                             (lun[3] << 16) + (lun[4] << 8) +
3576                                             lun[5];
3577                                 break;
3578                         }
3579                         break;
3580                 case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3581                         result = 0xffffffff;
3582                         break;
3583                 }
3584                 break;
3585         }
3586         return (result);
3587 }
3588
3589 uint64_t
3590 ctl_encode_lun(uint32_t decoded)
3591 {
3592         uint64_t l = decoded;
3593
3594         if (l <= 0xff)
3595                 return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3596         if (l <= 0x3fff)
3597                 return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3598         if (l <= 0xffffff)
3599                 return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3600                     (l << 32));
3601         return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3602 }
3603
3604 static struct ctl_port *
3605 ctl_io_port(struct ctl_io_hdr *io_hdr)
3606 {
3607
3608         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3609 }
3610
3611 int
3612 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3613 {
3614         int i;
3615
3616         for (i = first; i < last; i++) {
3617                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3618                         return (i);
3619         }
3620         return (-1);
3621 }
3622
3623 int
3624 ctl_set_mask(uint32_t *mask, uint32_t bit)
3625 {
3626         uint32_t chunk, piece;
3627
3628         chunk = bit >> 5;
3629         piece = bit % (sizeof(uint32_t) * 8);
3630
3631         if ((mask[chunk] & (1 << piece)) != 0)
3632                 return (-1);
3633         else
3634                 mask[chunk] |= (1 << piece);
3635
3636         return (0);
3637 }
3638
3639 int
3640 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3641 {
3642         uint32_t chunk, piece;
3643
3644         chunk = bit >> 5;
3645         piece = bit % (sizeof(uint32_t) * 8);
3646
3647         if ((mask[chunk] & (1 << piece)) == 0)
3648                 return (-1);
3649         else
3650                 mask[chunk] &= ~(1 << piece);
3651
3652         return (0);
3653 }
3654
3655 int
3656 ctl_is_set(uint32_t *mask, uint32_t bit)
3657 {
3658         uint32_t chunk, piece;
3659
3660         chunk = bit >> 5;
3661         piece = bit % (sizeof(uint32_t) * 8);
3662
3663         if ((mask[chunk] & (1 << piece)) == 0)
3664                 return (0);
3665         else
3666                 return (1);
3667 }
3668
3669 static uint64_t
3670 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3671 {
3672         uint64_t *t;
3673
3674         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3675         if (t == NULL)
3676                 return (0);
3677         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3678 }
3679
3680 static void
3681 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3682 {
3683         uint64_t *t;
3684
3685         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3686         if (t == NULL)
3687                 return;
3688         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3689 }
3690
3691 static void
3692 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3693 {
3694         uint64_t *p;
3695         u_int i;
3696
3697         i = residx/CTL_MAX_INIT_PER_PORT;
3698         if (lun->pr_keys[i] != NULL)
3699                 return;
3700         mtx_unlock(&lun->lun_lock);
3701         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3702             M_WAITOK | M_ZERO);
3703         mtx_lock(&lun->lun_lock);
3704         if (lun->pr_keys[i] == NULL)
3705                 lun->pr_keys[i] = p;
3706         else
3707                 free(p, M_CTL);
3708 }
3709
3710 static void
3711 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3712 {
3713         uint64_t *t;
3714
3715         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3716         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3717         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3718 }
3719
3720 /*
3721  * ctl_softc, pool_name, total_ctl_io are passed in.
3722  * npool is passed out.
3723  */
3724 int
3725 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3726                 uint32_t total_ctl_io, void **npool)
3727 {
3728 #ifdef IO_POOLS
3729         struct ctl_io_pool *pool;
3730
3731         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3732                                             M_NOWAIT | M_ZERO);
3733         if (pool == NULL)
3734                 return (ENOMEM);
3735
3736         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3737         pool->ctl_softc = ctl_softc;
3738         pool->zone = uma_zsecond_create(pool->name, NULL,
3739             NULL, NULL, NULL, ctl_softc->io_zone);
3740         /* uma_prealloc(pool->zone, total_ctl_io); */
3741
3742         *npool = pool;
3743 #else
3744         *npool = ctl_softc->io_zone;
3745 #endif
3746         return (0);
3747 }
3748
3749 void
3750 ctl_pool_free(struct ctl_io_pool *pool)
3751 {
3752
3753         if (pool == NULL)
3754                 return;
3755
3756 #ifdef IO_POOLS
3757         uma_zdestroy(pool->zone);
3758         free(pool, M_CTL);
3759 #endif
3760 }
3761
3762 union ctl_io *
3763 ctl_alloc_io(void *pool_ref)
3764 {
3765         union ctl_io *io;
3766 #ifdef IO_POOLS
3767         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3768
3769         io = uma_zalloc(pool->zone, M_WAITOK);
3770 #else
3771         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3772 #endif
3773         if (io != NULL)
3774                 io->io_hdr.pool = pool_ref;
3775         return (io);
3776 }
3777
3778 union ctl_io *
3779 ctl_alloc_io_nowait(void *pool_ref)
3780 {
3781         union ctl_io *io;
3782 #ifdef IO_POOLS
3783         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3784
3785         io = uma_zalloc(pool->zone, M_NOWAIT);
3786 #else
3787         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3788 #endif
3789         if (io != NULL)
3790                 io->io_hdr.pool = pool_ref;
3791         return (io);
3792 }
3793
3794 void
3795 ctl_free_io(union ctl_io *io)
3796 {
3797 #ifdef IO_POOLS
3798         struct ctl_io_pool *pool;
3799 #endif
3800
3801         if (io == NULL)
3802                 return;
3803
3804 #ifdef IO_POOLS
3805         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3806         uma_zfree(pool->zone, io);
3807 #else
3808         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3809 #endif
3810 }
3811
3812 void
3813 ctl_zero_io(union ctl_io *io)
3814 {
3815         void *pool_ref;
3816
3817         if (io == NULL)
3818                 return;
3819
3820         /*
3821          * May need to preserve linked list pointers at some point too.
3822          */
3823         pool_ref = io->io_hdr.pool;
3824         memset(io, 0, sizeof(*io));
3825         io->io_hdr.pool = pool_ref;
3826 }
3827
3828 int
3829 ctl_expand_number(const char *buf, uint64_t *num)
3830 {
3831         char *endptr;
3832         uint64_t number;
3833         unsigned shift;
3834
3835         number = strtoq(buf, &endptr, 0);
3836
3837         switch (tolower((unsigned char)*endptr)) {
3838         case 'e':
3839                 shift = 60;
3840                 break;
3841         case 'p':
3842                 shift = 50;
3843                 break;
3844         case 't':
3845                 shift = 40;
3846                 break;
3847         case 'g':
3848                 shift = 30;
3849                 break;
3850         case 'm':
3851                 shift = 20;
3852                 break;
3853         case 'k':
3854                 shift = 10;
3855                 break;
3856         case 'b':
3857         case '\0': /* No unit. */
3858                 *num = number;
3859                 return (0);
3860         default:
3861                 /* Unrecognized unit. */
3862                 return (-1);
3863         }
3864
3865         if ((number << shift) >> shift != number) {
3866                 /* Overflow */
3867                 return (-1);
3868         }
3869         *num = number << shift;
3870         return (0);
3871 }
3872
3873
3874 /*
3875  * This routine could be used in the future to load default and/or saved
3876  * mode page parameters for a particuar lun.
3877  */
3878 static int
3879 ctl_init_page_index(struct ctl_lun *lun)
3880 {
3881         int i, page_code;
3882         struct ctl_page_index *page_index;
3883         const char *value;
3884         uint64_t ival;
3885
3886         memcpy(&lun->mode_pages.index, page_index_template,
3887                sizeof(page_index_template));
3888
3889         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3890
3891                 page_index = &lun->mode_pages.index[i];
3892                 if (lun->be_lun->lun_type == T_DIRECT &&
3893                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3894                         continue;
3895                 if (lun->be_lun->lun_type == T_PROCESSOR &&
3896                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3897                         continue;
3898                 if (lun->be_lun->lun_type == T_CDROM &&
3899                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3900                         continue;
3901
3902                 page_code = page_index->page_code & SMPH_PC_MASK;
3903                 switch (page_code) {
3904                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3905                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3906                             ("subpage %#x for page %#x is incorrect!",
3907                             page_index->subpage, page_code));
3908                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3909                                &rw_er_page_default,
3910                                sizeof(rw_er_page_default));
3911                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3912                                &rw_er_page_changeable,
3913                                sizeof(rw_er_page_changeable));
3914                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3915                                &rw_er_page_default,
3916                                sizeof(rw_er_page_default));
3917                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3918                                &rw_er_page_default,
3919                                sizeof(rw_er_page_default));
3920                         page_index->page_data =
3921                                 (uint8_t *)lun->mode_pages.rw_er_page;
3922                         break;
3923                 }
3924                 case SMS_FORMAT_DEVICE_PAGE: {
3925                         struct scsi_format_page *format_page;
3926
3927                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3928                             ("subpage %#x for page %#x is incorrect!",
3929                             page_index->subpage, page_code));
3930
3931                         /*
3932                          * Sectors per track are set above.  Bytes per
3933                          * sector need to be set here on a per-LUN basis.
3934                          */
3935                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3936                                &format_page_default,
3937                                sizeof(format_page_default));
3938                         memcpy(&lun->mode_pages.format_page[
3939                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3940                                sizeof(format_page_changeable));
3941                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3942                                &format_page_default,
3943                                sizeof(format_page_default));
3944                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3945                                &format_page_default,
3946                                sizeof(format_page_default));
3947
3948                         format_page = &lun->mode_pages.format_page[
3949                                 CTL_PAGE_CURRENT];
3950                         scsi_ulto2b(lun->be_lun->blocksize,
3951                                     format_page->bytes_per_sector);
3952
3953                         format_page = &lun->mode_pages.format_page[
3954                                 CTL_PAGE_DEFAULT];
3955                         scsi_ulto2b(lun->be_lun->blocksize,
3956                                     format_page->bytes_per_sector);
3957
3958                         format_page = &lun->mode_pages.format_page[
3959                                 CTL_PAGE_SAVED];
3960                         scsi_ulto2b(lun->be_lun->blocksize,
3961                                     format_page->bytes_per_sector);
3962
3963                         page_index->page_data =
3964                                 (uint8_t *)lun->mode_pages.format_page;
3965                         break;
3966                 }
3967                 case SMS_RIGID_DISK_PAGE: {
3968                         struct scsi_rigid_disk_page *rigid_disk_page;
3969                         uint32_t sectors_per_cylinder;
3970                         uint64_t cylinders;
3971 #ifndef __XSCALE__
3972                         int shift;
3973 #endif /* !__XSCALE__ */
3974
3975                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3976                             ("subpage %#x for page %#x is incorrect!",
3977                             page_index->subpage, page_code));
3978
3979                         /*
3980                          * Rotation rate and sectors per track are set
3981                          * above.  We calculate the cylinders here based on
3982                          * capacity.  Due to the number of heads and
3983                          * sectors per track we're using, smaller arrays
3984                          * may turn out to have 0 cylinders.  Linux and
3985                          * FreeBSD don't pay attention to these mode pages
3986                          * to figure out capacity, but Solaris does.  It
3987                          * seems to deal with 0 cylinders just fine, and
3988                          * works out a fake geometry based on the capacity.
3989                          */
3990                         memcpy(&lun->mode_pages.rigid_disk_page[
3991                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3992                                sizeof(rigid_disk_page_default));
3993                         memcpy(&lun->mode_pages.rigid_disk_page[
3994                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3995                                sizeof(rigid_disk_page_changeable));
3996
3997                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3998                                 CTL_DEFAULT_HEADS;
3999
4000                         /*
4001                          * The divide method here will be more accurate,
4002                          * probably, but results in floating point being
4003                          * used in the kernel on i386 (__udivdi3()).  On the
4004                          * XScale, though, __udivdi3() is implemented in
4005                          * software.
4006                          *
4007                          * The shift method for cylinder calculation is
4008                          * accurate if sectors_per_cylinder is a power of
4009                          * 2.  Otherwise it might be slightly off -- you
4010                          * might have a bit of a truncation problem.
4011                          */
4012 #ifdef  __XSCALE__
4013                         cylinders = (lun->be_lun->maxlba + 1) /
4014                                 sectors_per_cylinder;
4015 #else
4016                         for (shift = 31; shift > 0; shift--) {
4017                                 if (sectors_per_cylinder & (1 << shift))
4018                                         break;
4019                         }
4020                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4021 #endif
4022
4023                         /*
4024                          * We've basically got 3 bytes, or 24 bits for the
4025                          * cylinder size in the mode page.  If we're over,
4026                          * just round down to 2^24.
4027                          */
4028                         if (cylinders > 0xffffff)
4029                                 cylinders = 0xffffff;
4030
4031                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4032                                 CTL_PAGE_DEFAULT];
4033                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4034
4035                         if ((value = ctl_get_opt(&lun->be_lun->options,
4036                             "rpm")) != NULL) {
4037                                 scsi_ulto2b(strtol(value, NULL, 0),
4038                                      rigid_disk_page->rotation_rate);
4039                         }
4040
4041                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4042                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4043                                sizeof(rigid_disk_page_default));
4044                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4045                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4046                                sizeof(rigid_disk_page_default));
4047
4048                         page_index->page_data =
4049                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4050                         break;
4051                 }
4052                 case SMS_CACHING_PAGE: {
4053                         struct scsi_caching_page *caching_page;
4054
4055                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4056                             ("subpage %#x for page %#x is incorrect!",
4057                             page_index->subpage, page_code));
4058                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4059                                &caching_page_default,
4060                                sizeof(caching_page_default));
4061                         memcpy(&lun->mode_pages.caching_page[
4062                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4063                                sizeof(caching_page_changeable));
4064                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4065                                &caching_page_default,
4066                                sizeof(caching_page_default));
4067                         caching_page = &lun->mode_pages.caching_page[
4068                             CTL_PAGE_SAVED];
4069                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4070                         if (value != NULL && strcmp(value, "off") == 0)
4071                                 caching_page->flags1 &= ~SCP_WCE;
4072                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4073                         if (value != NULL && strcmp(value, "off") == 0)
4074                                 caching_page->flags1 |= SCP_RCD;
4075                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4076                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4077                                sizeof(caching_page_default));
4078                         page_index->page_data =
4079                                 (uint8_t *)lun->mode_pages.caching_page;
4080                         break;
4081                 }
4082                 case SMS_CONTROL_MODE_PAGE: {
4083                         switch (page_index->subpage) {
4084                         case SMS_SUBPAGE_PAGE_0: {
4085                                 struct scsi_control_page *control_page;
4086
4087                                 memcpy(&lun->mode_pages.control_page[
4088                                     CTL_PAGE_DEFAULT],
4089                                        &control_page_default,
4090                                        sizeof(control_page_default));
4091                                 memcpy(&lun->mode_pages.control_page[
4092                                     CTL_PAGE_CHANGEABLE],
4093                                        &control_page_changeable,
4094                                        sizeof(control_page_changeable));
4095                                 memcpy(&lun->mode_pages.control_page[
4096                                     CTL_PAGE_SAVED],
4097                                        &control_page_default,
4098                                        sizeof(control_page_default));
4099                                 control_page = &lun->mode_pages.control_page[
4100                                     CTL_PAGE_SAVED];
4101                                 value = ctl_get_opt(&lun->be_lun->options,
4102                                     "reordering");
4103                                 if (value != NULL &&
4104                                     strcmp(value, "unrestricted") == 0) {
4105                                         control_page->queue_flags &=
4106                                             ~SCP_QUEUE_ALG_MASK;
4107                                         control_page->queue_flags |=
4108                                             SCP_QUEUE_ALG_UNRESTRICTED;
4109                                 }
4110                                 memcpy(&lun->mode_pages.control_page[
4111                                     CTL_PAGE_CURRENT],
4112                                        &lun->mode_pages.control_page[
4113                                     CTL_PAGE_SAVED],
4114                                        sizeof(control_page_default));
4115                                 page_index->page_data =
4116                                     (uint8_t *)lun->mode_pages.control_page;
4117                                 break;
4118                         }
4119                         case 0x01:
4120                                 memcpy(&lun->mode_pages.control_ext_page[
4121                                     CTL_PAGE_DEFAULT],
4122                                        &control_ext_page_default,
4123                                        sizeof(control_ext_page_default));
4124                                 memcpy(&lun->mode_pages.control_ext_page[
4125                                     CTL_PAGE_CHANGEABLE],
4126                                        &control_ext_page_changeable,
4127                                        sizeof(control_ext_page_changeable));
4128                                 memcpy(&lun->mode_pages.control_ext_page[
4129                                     CTL_PAGE_SAVED],
4130                                        &control_ext_page_default,
4131                                        sizeof(control_ext_page_default));
4132                                 memcpy(&lun->mode_pages.control_ext_page[
4133                                     CTL_PAGE_CURRENT],
4134                                        &lun->mode_pages.control_ext_page[
4135                                     CTL_PAGE_SAVED],
4136                                        sizeof(control_ext_page_default));
4137                                 page_index->page_data =
4138                                     (uint8_t *)lun->mode_pages.control_ext_page;
4139                                 break;
4140                         default:
4141                                 panic("subpage %#x for page %#x is incorrect!",
4142                                       page_index->subpage, page_code);
4143                         }
4144                         break;
4145                 }
4146                 case SMS_INFO_EXCEPTIONS_PAGE: {
4147                         switch (page_index->subpage) {
4148                         case SMS_SUBPAGE_PAGE_0:
4149                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4150                                        &ie_page_default,
4151                                        sizeof(ie_page_default));
4152                                 memcpy(&lun->mode_pages.ie_page[
4153                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4154                                        sizeof(ie_page_changeable));
4155                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4156                                        &ie_page_default,
4157                                        sizeof(ie_page_default));
4158                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4159                                        &ie_page_default,
4160                                        sizeof(ie_page_default));
4161                                 page_index->page_data =
4162                                         (uint8_t *)lun->mode_pages.ie_page;
4163                                 break;
4164                         case 0x02: {
4165                                 struct ctl_logical_block_provisioning_page *page;
4166
4167                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4168                                        &lbp_page_default,
4169                                        sizeof(lbp_page_default));
4170                                 memcpy(&lun->mode_pages.lbp_page[
4171                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4172                                        sizeof(lbp_page_changeable));
4173                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4174                                        &lbp_page_default,
4175                                        sizeof(lbp_page_default));
4176                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4177                                 value = ctl_get_opt(&lun->be_lun->options,
4178                                     "avail-threshold");
4179                                 if (value != NULL &&
4180                                     ctl_expand_number(value, &ival) == 0) {
4181                                         page->descr[0].flags |= SLBPPD_ENABLED |
4182                                             SLBPPD_ARMING_DEC;
4183                                         if (lun->be_lun->blocksize)
4184                                                 ival /= lun->be_lun->blocksize;
4185                                         else
4186                                                 ival /= 512;
4187                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4188                                             page->descr[0].count);
4189                                 }
4190                                 value = ctl_get_opt(&lun->be_lun->options,
4191                                     "used-threshold");
4192                                 if (value != NULL &&
4193                                     ctl_expand_number(value, &ival) == 0) {
4194                                         page->descr[1].flags |= SLBPPD_ENABLED |
4195                                             SLBPPD_ARMING_INC;
4196                                         if (lun->be_lun->blocksize)
4197                                                 ival /= lun->be_lun->blocksize;
4198                                         else
4199                                                 ival /= 512;
4200                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4201                                             page->descr[1].count);
4202                                 }
4203                                 value = ctl_get_opt(&lun->be_lun->options,
4204                                     "pool-avail-threshold");
4205                                 if (value != NULL &&
4206                                     ctl_expand_number(value, &ival) == 0) {
4207                                         page->descr[2].flags |= SLBPPD_ENABLED |
4208                                             SLBPPD_ARMING_DEC;
4209                                         if (lun->be_lun->blocksize)
4210                                                 ival /= lun->be_lun->blocksize;
4211                                         else
4212                                                 ival /= 512;
4213                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4214                                             page->descr[2].count);
4215                                 }
4216                                 value = ctl_get_opt(&lun->be_lun->options,
4217                                     "pool-used-threshold");
4218                                 if (value != NULL &&
4219                                     ctl_expand_number(value, &ival) == 0) {
4220                                         page->descr[3].flags |= SLBPPD_ENABLED |
4221                                             SLBPPD_ARMING_INC;
4222                                         if (lun->be_lun->blocksize)
4223                                                 ival /= lun->be_lun->blocksize;
4224                                         else
4225                                                 ival /= 512;
4226                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4227                                             page->descr[3].count);
4228                                 }
4229                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4230                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4231                                        sizeof(lbp_page_default));
4232                                 page_index->page_data =
4233                                         (uint8_t *)lun->mode_pages.lbp_page;
4234                                 break;
4235                         }
4236                         default:
4237                                 panic("subpage %#x for page %#x is incorrect!",
4238                                       page_index->subpage, page_code);
4239                         }
4240                         break;
4241                 }
4242                 case SMS_CDDVD_CAPS_PAGE:{
4243                         KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4244                             ("subpage %#x for page %#x is incorrect!",
4245                             page_index->subpage, page_code));
4246                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4247                                &cddvd_page_default,
4248                                sizeof(cddvd_page_default));
4249                         memcpy(&lun->mode_pages.cddvd_page[
4250                                CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4251                                sizeof(cddvd_page_changeable));
4252                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4253                                &cddvd_page_default,
4254                                sizeof(cddvd_page_default));
4255                         memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4256                                &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4257                                sizeof(cddvd_page_default));
4258                         page_index->page_data =
4259                                 (uint8_t *)lun->mode_pages.cddvd_page;
4260                         break;
4261                 }
4262                 case SMS_VENDOR_SPECIFIC_PAGE:{
4263                         switch (page_index->subpage) {
4264                         case DBGCNF_SUBPAGE_CODE: {
4265                                 memcpy(&lun->mode_pages.debugconf_subpage[
4266                                        CTL_PAGE_CURRENT],
4267                                        &debugconf_page_default,
4268                                        sizeof(debugconf_page_default));
4269                                 memcpy(&lun->mode_pages.debugconf_subpage[
4270                                        CTL_PAGE_CHANGEABLE],
4271                                        &debugconf_page_changeable,
4272                                        sizeof(debugconf_page_changeable));
4273                                 memcpy(&lun->mode_pages.debugconf_subpage[
4274                                        CTL_PAGE_DEFAULT],
4275                                        &debugconf_page_default,
4276                                        sizeof(debugconf_page_default));
4277                                 memcpy(&lun->mode_pages.debugconf_subpage[
4278                                        CTL_PAGE_SAVED],
4279                                        &debugconf_page_default,
4280                                        sizeof(debugconf_page_default));
4281                                 page_index->page_data =
4282                                     (uint8_t *)lun->mode_pages.debugconf_subpage;
4283                                 break;
4284                         }
4285                         default:
4286                                 panic("subpage %#x for page %#x is incorrect!",
4287                                       page_index->subpage, page_code);
4288                         }
4289                         break;
4290                 }
4291                 default:
4292                         panic("invalid page code value %#x", page_code);
4293                 }
4294         }
4295
4296         return (CTL_RETVAL_COMPLETE);
4297 }
4298
4299 static int
4300 ctl_init_log_page_index(struct ctl_lun *lun)
4301 {
4302         struct ctl_page_index *page_index;
4303         int i, j, k, prev;
4304
4305         memcpy(&lun->log_pages.index, log_page_index_template,
4306                sizeof(log_page_index_template));
4307
4308         prev = -1;
4309         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4310
4311                 page_index = &lun->log_pages.index[i];
4312                 if (lun->be_lun->lun_type == T_DIRECT &&
4313                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4314                         continue;
4315                 if (lun->be_lun->lun_type == T_PROCESSOR &&
4316                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4317                         continue;
4318                 if (lun->be_lun->lun_type == T_CDROM &&
4319                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4320                         continue;
4321
4322                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4323                     lun->backend->lun_attr == NULL)
4324                         continue;
4325
4326                 if (page_index->page_code != prev) {
4327                         lun->log_pages.pages_page[j] = page_index->page_code;
4328                         prev = page_index->page_code;
4329                         j++;
4330                 }
4331                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4332                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4333                 k++;
4334         }
4335         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4336         lun->log_pages.index[0].page_len = j;
4337         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4338         lun->log_pages.index[1].page_len = k * 2;
4339         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4340         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4341         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4342         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4343
4344         return (CTL_RETVAL_COMPLETE);
4345 }
4346
4347 static int
4348 hex2bin(const char *str, uint8_t *buf, int buf_size)
4349 {
4350         int i;
4351         u_char c;
4352
4353         memset(buf, 0, buf_size);
4354         while (isspace(str[0]))
4355                 str++;
4356         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4357                 str += 2;
4358         buf_size *= 2;
4359         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4360                 c = str[i];
4361                 if (isdigit(c))
4362                         c -= '0';
4363                 else if (isalpha(c))
4364                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4365                 else
4366                         break;
4367                 if (c >= 16)
4368                         break;
4369                 if ((i & 1) == 0)
4370                         buf[i / 2] |= (c << 4);
4371                 else
4372                         buf[i / 2] |= c;
4373         }
4374         return ((i + 1) / 2);
4375 }
4376
4377 /*
4378  * LUN allocation.
4379  *
4380  * Requirements:
4381  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4382  *   wants us to allocate the LUN and he can block.
4383  * - ctl_softc is always set
4384  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4385  *
4386  * Returns 0 for success, non-zero (errno) for failure.
4387  */
4388 static int
4389 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4390               struct ctl_be_lun *const be_lun)
4391 {
4392         struct ctl_lun *nlun, *lun;
4393         struct scsi_vpd_id_descriptor *desc;
4394         struct scsi_vpd_id_t10 *t10id;
4395         const char *eui, *naa, *scsiname, *vendor, *value;
4396         int lun_number, i, lun_malloced;
4397         int devidlen, idlen1, idlen2 = 0, len;
4398
4399         if (be_lun == NULL)
4400                 return (EINVAL);
4401
4402         /*
4403          * We currently only support Direct Access or Processor LUN types.
4404          */
4405         switch (be_lun->lun_type) {
4406         case T_DIRECT:
4407         case T_PROCESSOR:
4408         case T_CDROM:
4409                 break;
4410         case T_SEQUENTIAL:
4411         case T_CHANGER:
4412         default:
4413                 be_lun->lun_config_status(be_lun->be_lun,
4414                                           CTL_LUN_CONFIG_FAILURE);
4415                 break;
4416         }
4417         if (ctl_lun == NULL) {
4418                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4419                 lun_malloced = 1;
4420         } else {
4421                 lun_malloced = 0;
4422                 lun = ctl_lun;
4423         }
4424
4425         memset(lun, 0, sizeof(*lun));
4426         if (lun_malloced)
4427                 lun->flags = CTL_LUN_MALLOCED;
4428
4429         /* Generate LUN ID. */
4430         devidlen = max(CTL_DEVID_MIN_LEN,
4431             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4432         idlen1 = sizeof(*t10id) + devidlen;
4433         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4434         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4435         if (scsiname != NULL) {
4436                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4437                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4438         }
4439         eui = ctl_get_opt(&be_lun->options, "eui");
4440         if (eui != NULL) {
4441                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4442         }
4443         naa = ctl_get_opt(&be_lun->options, "naa");
4444         if (naa != NULL) {
4445                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4446         }
4447         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4448             M_CTL, M_WAITOK | M_ZERO);
4449         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4450         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4451         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4452         desc->length = idlen1;
4453         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4454         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4455         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4456                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4457         } else {
4458                 strncpy(t10id->vendor, vendor,
4459                     min(sizeof(t10id->vendor), strlen(vendor)));
4460         }
4461         strncpy((char *)t10id->vendor_spec_id,
4462             (char *)be_lun->device_id, devidlen);
4463         if (scsiname != NULL) {
4464                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4465                     desc->length);
4466                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4467                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4468                     SVPD_ID_TYPE_SCSI_NAME;
4469                 desc->length = idlen2;
4470                 strlcpy(desc->identifier, scsiname, idlen2);
4471         }
4472         if (eui != NULL) {
4473                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4474                     desc->length);
4475                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4476                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4477                     SVPD_ID_TYPE_EUI64;
4478                 desc->length = hex2bin(eui, desc->identifier, 16);
4479                 desc->length = desc->length > 12 ? 16 :
4480                     (desc->length > 8 ? 12 : 8);
4481                 len -= 16 - desc->length;
4482         }
4483         if (naa != NULL) {
4484                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4485                     desc->length);
4486                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4487                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4488                     SVPD_ID_TYPE_NAA;
4489                 desc->length = hex2bin(naa, desc->identifier, 16);
4490                 desc->length = desc->length > 8 ? 16 : 8;
4491                 len -= 16 - desc->length;
4492         }
4493         lun->lun_devid->len = len;
4494
4495         mtx_lock(&ctl_softc->ctl_lock);
4496         /*
4497          * See if the caller requested a particular LUN number.  If so, see
4498          * if it is available.  Otherwise, allocate the first available LUN.
4499          */
4500         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4501                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4502                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4503                         mtx_unlock(&ctl_softc->ctl_lock);
4504                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4505                                 printf("ctl: requested LUN ID %d is higher "
4506                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4507                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4508                         } else {
4509                                 /*
4510                                  * XXX KDM return an error, or just assign
4511                                  * another LUN ID in this case??
4512                                  */
4513                                 printf("ctl: requested LUN ID %d is already "
4514                                        "in use\n", be_lun->req_lun_id);
4515                         }
4516                         if (lun->flags & CTL_LUN_MALLOCED)
4517                                 free(lun, M_CTL);
4518                         be_lun->lun_config_status(be_lun->be_lun,
4519                                                   CTL_LUN_CONFIG_FAILURE);
4520                         return (ENOSPC);
4521                 }
4522                 lun_number = be_lun->req_lun_id;
4523         } else {
4524                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4525                 if (lun_number == -1) {
4526                         mtx_unlock(&ctl_softc->ctl_lock);
4527                         printf("ctl: can't allocate LUN, out of LUNs\n");
4528                         if (lun->flags & CTL_LUN_MALLOCED)
4529                                 free(lun, M_CTL);
4530                         be_lun->lun_config_status(be_lun->be_lun,
4531                                                   CTL_LUN_CONFIG_FAILURE);
4532                         return (ENOSPC);
4533                 }
4534         }
4535         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4536
4537         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4538         lun->lun = lun_number;
4539         lun->be_lun = be_lun;
4540         /*
4541          * The processor LUN is always enabled.  Disk LUNs come on line
4542          * disabled, and must be enabled by the backend.
4543          */
4544         lun->flags |= CTL_LUN_DISABLED;
4545         lun->backend = be_lun->be;
4546         be_lun->ctl_lun = lun;
4547         be_lun->lun_id = lun_number;
4548         atomic_add_int(&be_lun->be->num_luns, 1);
4549         if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4550                 lun->flags |= CTL_LUN_EJECTED;
4551         if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4552                 lun->flags |= CTL_LUN_NO_MEDIA;
4553         if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4554                 lun->flags |= CTL_LUN_STOPPED;
4555
4556         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4557                 lun->flags |= CTL_LUN_PRIMARY_SC;
4558
4559         value = ctl_get_opt(&be_lun->options, "removable");
4560         if (value != NULL) {
4561                 if (strcmp(value, "on") == 0)
4562                         lun->flags |= CTL_LUN_REMOVABLE;
4563         } else if (be_lun->lun_type == T_CDROM)
4564                 lun->flags |= CTL_LUN_REMOVABLE;
4565
4566         lun->ctl_softc = ctl_softc;
4567 #ifdef CTL_TIME_IO
4568         lun->last_busy = getsbinuptime();
4569 #endif
4570         TAILQ_INIT(&lun->ooa_queue);
4571         TAILQ_INIT(&lun->blocked_queue);
4572         STAILQ_INIT(&lun->error_list);
4573         ctl_tpc_lun_init(lun);
4574
4575         /*
4576          * Initialize the mode and log page index.
4577          */
4578         ctl_init_page_index(lun);
4579         ctl_init_log_page_index(lun);
4580
4581         /*
4582          * Now, before we insert this lun on the lun list, set the lun
4583          * inventory changed UA for all other luns.
4584          */
4585         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4586                 mtx_lock(&nlun->lun_lock);
4587                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4588                 mtx_unlock(&nlun->lun_lock);
4589         }
4590
4591         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4592
4593         ctl_softc->ctl_luns[lun_number] = lun;
4594
4595         ctl_softc->num_luns++;
4596
4597         /* Setup statistics gathering */
4598         lun->stats.device_type = be_lun->lun_type;
4599         lun->stats.lun_number = lun_number;
4600         lun->stats.blocksize = be_lun->blocksize;
4601         if (be_lun->blocksize == 0)
4602                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4603         for (i = 0;i < CTL_MAX_PORTS;i++)
4604                 lun->stats.ports[i].targ_port = i;
4605
4606         mtx_unlock(&ctl_softc->ctl_lock);
4607
4608         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4609         return (0);
4610 }
4611
4612 /*
4613  * Delete a LUN.
4614  * Assumptions:
4615  * - LUN has already been marked invalid and any pending I/O has been taken
4616  *   care of.
4617  */
4618 static int
4619 ctl_free_lun(struct ctl_lun *lun)
4620 {
4621         struct ctl_softc *softc;
4622         struct ctl_lun *nlun;
4623         int i;
4624
4625         softc = lun->ctl_softc;
4626
4627         mtx_assert(&softc->ctl_lock, MA_OWNED);
4628
4629         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4630
4631         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4632
4633         softc->ctl_luns[lun->lun] = NULL;
4634
4635         if (!TAILQ_EMPTY(&lun->ooa_queue))
4636                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4637
4638         softc->num_luns--;
4639
4640         /*
4641          * Tell the backend to free resources, if this LUN has a backend.
4642          */
4643         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4644         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4645
4646         ctl_tpc_lun_shutdown(lun);
4647         mtx_destroy(&lun->lun_lock);
4648         free(lun->lun_devid, M_CTL);
4649         for (i = 0; i < CTL_MAX_PORTS; i++)
4650                 free(lun->pending_ua[i], M_CTL);
4651         for (i = 0; i < CTL_MAX_PORTS; i++)
4652                 free(lun->pr_keys[i], M_CTL);
4653         free(lun->write_buffer, M_CTL);
4654         if (lun->flags & CTL_LUN_MALLOCED)
4655                 free(lun, M_CTL);
4656
4657         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4658                 mtx_lock(&nlun->lun_lock);
4659                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4660                 mtx_unlock(&nlun->lun_lock);
4661         }
4662
4663         return (0);
4664 }
4665
4666 static void
4667 ctl_create_lun(struct ctl_be_lun *be_lun)
4668 {
4669
4670         /*
4671          * ctl_alloc_lun() should handle all potential failure cases.
4672          */
4673         ctl_alloc_lun(control_softc, NULL, be_lun);
4674 }
4675
4676 int
4677 ctl_add_lun(struct ctl_be_lun *be_lun)
4678 {
4679         struct ctl_softc *softc = control_softc;
4680
4681         mtx_lock(&softc->ctl_lock);
4682         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4683         mtx_unlock(&softc->ctl_lock);
4684         wakeup(&softc->pending_lun_queue);
4685
4686         return (0);
4687 }
4688
4689 int
4690 ctl_enable_lun(struct ctl_be_lun *be_lun)
4691 {
4692         struct ctl_softc *softc;
4693         struct ctl_port *port, *nport;
4694         struct ctl_lun *lun;
4695         int retval;
4696
4697         lun = (struct ctl_lun *)be_lun->ctl_lun;
4698         softc = lun->ctl_softc;
4699
4700         mtx_lock(&softc->ctl_lock);
4701         mtx_lock(&lun->lun_lock);
4702         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4703                 /*
4704                  * eh?  Why did we get called if the LUN is already
4705                  * enabled?
4706                  */
4707                 mtx_unlock(&lun->lun_lock);
4708                 mtx_unlock(&softc->ctl_lock);
4709                 return (0);
4710         }
4711         lun->flags &= ~CTL_LUN_DISABLED;
4712         mtx_unlock(&lun->lun_lock);
4713
4714         STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4715                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4716                     port->lun_map != NULL || port->lun_enable == NULL)
4717                         continue;
4718
4719                 /*
4720                  * Drop the lock while we call the FETD's enable routine.
4721                  * This can lead to a callback into CTL (at least in the
4722                  * case of the internal initiator frontend.
4723                  */
4724                 mtx_unlock(&softc->ctl_lock);
4725                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4726                 mtx_lock(&softc->ctl_lock);
4727                 if (retval != 0) {
4728                         printf("%s: FETD %s port %d returned error "
4729                                "%d for lun_enable on lun %jd\n",
4730                                __func__, port->port_name, port->targ_port,
4731                                retval, (intmax_t)lun->lun);
4732                 }
4733         }
4734
4735         mtx_unlock(&softc->ctl_lock);
4736         ctl_isc_announce_lun(lun);
4737
4738         return (0);
4739 }
4740
4741 int
4742 ctl_disable_lun(struct ctl_be_lun *be_lun)
4743 {
4744         struct ctl_softc *softc;
4745         struct ctl_port *port;
4746         struct ctl_lun *lun;
4747         int retval;
4748
4749         lun = (struct ctl_lun *)be_lun->ctl_lun;
4750         softc = lun->ctl_softc;
4751
4752         mtx_lock(&softc->ctl_lock);
4753         mtx_lock(&lun->lun_lock);
4754         if (lun->flags & CTL_LUN_DISABLED) {
4755                 mtx_unlock(&lun->lun_lock);
4756                 mtx_unlock(&softc->ctl_lock);
4757                 return (0);
4758         }
4759         lun->flags |= CTL_LUN_DISABLED;
4760         mtx_unlock(&lun->lun_lock);
4761
4762         STAILQ_FOREACH(port, &softc->port_list, links) {
4763                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4764                     port->lun_map != NULL || port->lun_disable == NULL)
4765                         continue;
4766
4767                 /*
4768                  * Drop the lock before we call the frontend's disable
4769                  * routine, to avoid lock order reversals.
4770                  *
4771                  * XXX KDM what happens if the frontend list changes while
4772                  * we're traversing it?  It's unlikely, but should be handled.
4773                  */
4774                 mtx_unlock(&softc->ctl_lock);
4775                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4776                 mtx_lock(&softc->ctl_lock);
4777                 if (retval != 0) {
4778                         printf("%s: FETD %s port %d returned error "
4779                                "%d for lun_disable on lun %jd\n",
4780                                __func__, port->port_name, port->targ_port,
4781                                retval, (intmax_t)lun->lun);
4782                 }
4783         }
4784
4785         mtx_unlock(&softc->ctl_lock);
4786         ctl_isc_announce_lun(lun);
4787
4788         return (0);
4789 }
4790
4791 int
4792 ctl_start_lun(struct ctl_be_lun *be_lun)
4793 {
4794         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4795
4796         mtx_lock(&lun->lun_lock);
4797         lun->flags &= ~CTL_LUN_STOPPED;
4798         mtx_unlock(&lun->lun_lock);
4799         return (0);
4800 }
4801
4802 int
4803 ctl_stop_lun(struct ctl_be_lun *be_lun)
4804 {
4805         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4806
4807         mtx_lock(&lun->lun_lock);
4808         lun->flags |= CTL_LUN_STOPPED;
4809         mtx_unlock(&lun->lun_lock);
4810         return (0);
4811 }
4812
4813 int
4814 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4815 {
4816         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4817
4818         mtx_lock(&lun->lun_lock);
4819         lun->flags |= CTL_LUN_NO_MEDIA;
4820         mtx_unlock(&lun->lun_lock);
4821         return (0);
4822 }
4823
4824 int
4825 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4826 {
4827         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4828         union ctl_ha_msg msg;
4829
4830         mtx_lock(&lun->lun_lock);
4831         lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4832         if (lun->flags & CTL_LUN_REMOVABLE)
4833                 ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4834         mtx_unlock(&lun->lun_lock);
4835         if ((lun->flags & CTL_LUN_REMOVABLE) &&
4836             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4837                 bzero(&msg.ua, sizeof(msg.ua));
4838                 msg.hdr.msg_type = CTL_MSG_UA;
4839                 msg.hdr.nexus.initid = -1;
4840                 msg.hdr.nexus.targ_port = -1;
4841                 msg.hdr.nexus.targ_lun = lun->lun;
4842                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4843                 msg.ua.ua_all = 1;
4844                 msg.ua.ua_set = 1;
4845                 msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4846                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4847                     M_WAITOK);
4848         }
4849         return (0);
4850 }
4851
4852 int
4853 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4854 {
4855         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4856
4857         mtx_lock(&lun->lun_lock);
4858         lun->flags |= CTL_LUN_EJECTED;
4859         mtx_unlock(&lun->lun_lock);
4860         return (0);
4861 }
4862
4863 int
4864 ctl_lun_primary(struct ctl_be_lun *be_lun)
4865 {
4866         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4867
4868         mtx_lock(&lun->lun_lock);
4869         lun->flags |= CTL_LUN_PRIMARY_SC;
4870         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4871         mtx_unlock(&lun->lun_lock);
4872         ctl_isc_announce_lun(lun);
4873         return (0);
4874 }
4875
4876 int
4877 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4878 {
4879         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4880
4881         mtx_lock(&lun->lun_lock);
4882         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4883         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4884         mtx_unlock(&lun->lun_lock);
4885         ctl_isc_announce_lun(lun);
4886         return (0);
4887 }
4888
4889 int
4890 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4891 {
4892         struct ctl_softc *softc;
4893         struct ctl_lun *lun;
4894
4895         lun = (struct ctl_lun *)be_lun->ctl_lun;
4896         softc = lun->ctl_softc;
4897
4898         mtx_lock(&lun->lun_lock);
4899
4900         /*
4901          * The LUN needs to be disabled before it can be marked invalid.
4902          */
4903         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4904                 mtx_unlock(&lun->lun_lock);
4905                 return (-1);
4906         }
4907         /*
4908          * Mark the LUN invalid.
4909          */
4910         lun->flags |= CTL_LUN_INVALID;
4911
4912         /*
4913          * If there is nothing in the OOA queue, go ahead and free the LUN.
4914          * If we have something in the OOA queue, we'll free it when the
4915          * last I/O completes.
4916          */
4917         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4918                 mtx_unlock(&lun->lun_lock);
4919                 mtx_lock(&softc->ctl_lock);
4920                 ctl_free_lun(lun);
4921                 mtx_unlock(&softc->ctl_lock);
4922         } else
4923                 mtx_unlock(&lun->lun_lock);
4924
4925         return (0);
4926 }
4927
4928 void
4929 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4930 {
4931         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4932         union ctl_ha_msg msg;
4933
4934         mtx_lock(&lun->lun_lock);
4935         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4936         mtx_unlock(&lun->lun_lock);
4937         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4938                 /* Send msg to other side. */
4939                 bzero(&msg.ua, sizeof(msg.ua));
4940                 msg.hdr.msg_type = CTL_MSG_UA;
4941                 msg.hdr.nexus.initid = -1;
4942                 msg.hdr.nexus.targ_port = -1;
4943                 msg.hdr.nexus.targ_lun = lun->lun;
4944                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4945                 msg.ua.ua_all = 1;
4946                 msg.ua.ua_set = 1;
4947                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4948                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4949                     M_WAITOK);
4950         }
4951 }
4952
4953 /*
4954  * Backend "memory move is complete" callback for requests that never
4955  * make it down to say RAIDCore's configuration code.
4956  */
4957 int
4958 ctl_config_move_done(union ctl_io *io)
4959 {
4960         int retval;
4961
4962         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4963         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4964             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4965
4966         if ((io->io_hdr.port_status != 0) &&
4967             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4968              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4969                 /*
4970                  * For hardware error sense keys, the sense key
4971                  * specific value is defined to be a retry count,
4972                  * but we use it to pass back an internal FETD
4973                  * error code.  XXX KDM  Hopefully the FETD is only
4974                  * using 16 bits for an error code, since that's
4975                  * all the space we have in the sks field.
4976                  */
4977                 ctl_set_internal_failure(&io->scsiio,
4978                                          /*sks_valid*/ 1,
4979                                          /*retry_count*/
4980                                          io->io_hdr.port_status);
4981         }
4982
4983         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4984                 ctl_data_print(io);
4985         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4986             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4987              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4988             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4989                 /*
4990                  * XXX KDM just assuming a single pointer here, and not a
4991                  * S/G list.  If we start using S/G lists for config data,
4992                  * we'll need to know how to clean them up here as well.
4993                  */
4994                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4995                         free(io->scsiio.kern_data_ptr, M_CTL);
4996                 ctl_done(io);
4997                 retval = CTL_RETVAL_COMPLETE;
4998         } else {
4999                 /*
5000                  * XXX KDM now we need to continue data movement.  Some
5001                  * options:
5002                  * - call ctl_scsiio() again?  We don't do this for data
5003                  *   writes, because for those at least we know ahead of
5004                  *   time where the write will go and how long it is.  For
5005                  *   config writes, though, that information is largely
5006                  *   contained within the write itself, thus we need to
5007                  *   parse out the data again.
5008                  *
5009                  * - Call some other function once the data is in?
5010                  */
5011
5012                 /*
5013                  * XXX KDM call ctl_scsiio() again for now, and check flag
5014                  * bits to see whether we're allocated or not.
5015                  */
5016                 retval = ctl_scsiio(&io->scsiio);
5017         }
5018         return (retval);
5019 }
5020
5021 /*
5022  * This gets called by a backend driver when it is done with a
5023  * data_submit method.
5024  */
5025 void
5026 ctl_data_submit_done(union ctl_io *io)
5027 {
5028         /*
5029          * If the IO_CONT flag is set, we need to call the supplied
5030          * function to continue processing the I/O, instead of completing
5031          * the I/O just yet.
5032          *
5033          * If there is an error, though, we don't want to keep processing.
5034          * Instead, just send status back to the initiator.
5035          */
5036         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5037             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5038             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5039              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5040                 io->scsiio.io_cont(io);
5041                 return;
5042         }
5043         ctl_done(io);
5044 }
5045
5046 /*
5047  * This gets called by a backend driver when it is done with a
5048  * configuration write.
5049  */
5050 void
5051 ctl_config_write_done(union ctl_io *io)
5052 {
5053         uint8_t *buf;
5054
5055         /*
5056          * If the IO_CONT flag is set, we need to call the supplied
5057          * function to continue processing the I/O, instead of completing
5058          * the I/O just yet.
5059          *
5060          * If there is an error, though, we don't want to keep processing.
5061          * Instead, just send status back to the initiator.
5062          */
5063         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5064             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5065             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5066              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5067                 io->scsiio.io_cont(io);
5068                 return;
5069         }
5070         /*
5071          * Since a configuration write can be done for commands that actually
5072          * have data allocated, like write buffer, and commands that have
5073          * no data, like start/stop unit, we need to check here.
5074          */
5075         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5076                 buf = io->scsiio.kern_data_ptr;
5077         else
5078                 buf = NULL;
5079         ctl_done(io);
5080         if (buf)
5081                 free(buf, M_CTL);
5082 }
5083
5084 void
5085 ctl_config_read_done(union ctl_io *io)
5086 {
5087         uint8_t *buf;
5088
5089         /*
5090          * If there is some error -- we are done, skip data transfer.
5091          */
5092         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5093             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5094              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5095                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5096                         buf = io->scsiio.kern_data_ptr;
5097                 else
5098                         buf = NULL;
5099                 ctl_done(io);
5100                 if (buf)
5101                         free(buf, M_CTL);
5102                 return;
5103         }
5104
5105         /*
5106          * If the IO_CONT flag is set, we need to call the supplied
5107          * function to continue processing the I/O, instead of completing
5108          * the I/O just yet.
5109          */
5110         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5111                 io->scsiio.io_cont(io);
5112                 return;
5113         }
5114
5115         ctl_datamove(io);
5116 }
5117
5118 /*
5119  * SCSI release command.
5120  */
5121 int
5122 ctl_scsi_release(struct ctl_scsiio *ctsio)
5123 {
5124         struct ctl_lun *lun;
5125         uint32_t residx;
5126
5127         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5128
5129         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5130         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5131
5132         /*
5133          * XXX KDM right now, we only support LUN reservation.  We don't
5134          * support 3rd party reservations, or extent reservations, which
5135          * might actually need the parameter list.  If we've gotten this
5136          * far, we've got a LUN reservation.  Anything else got kicked out
5137          * above.  So, according to SPC, ignore the length.
5138          */
5139
5140         mtx_lock(&lun->lun_lock);
5141
5142         /*
5143          * According to SPC, it is not an error for an intiator to attempt
5144          * to release a reservation on a LUN that isn't reserved, or that
5145          * is reserved by another initiator.  The reservation can only be
5146          * released, though, by the initiator who made it or by one of
5147          * several reset type events.
5148          */
5149         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5150                         lun->flags &= ~CTL_LUN_RESERVED;
5151
5152         mtx_unlock(&lun->lun_lock);
5153
5154         ctl_set_success(ctsio);
5155         ctl_done((union ctl_io *)ctsio);
5156         return (CTL_RETVAL_COMPLETE);
5157 }
5158
5159 int
5160 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5161 {
5162         struct ctl_lun *lun;
5163         uint32_t residx;
5164
5165         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5166
5167         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5168         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5169
5170         /*
5171          * XXX KDM right now, we only support LUN reservation.  We don't
5172          * support 3rd party reservations, or extent reservations, which
5173          * might actually need the parameter list.  If we've gotten this
5174          * far, we've got a LUN reservation.  Anything else got kicked out
5175          * above.  So, according to SPC, ignore the length.
5176          */
5177
5178         mtx_lock(&lun->lun_lock);
5179         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5180                 ctl_set_reservation_conflict(ctsio);
5181                 goto bailout;
5182         }
5183
5184         /* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5185         if (lun->flags & CTL_LUN_PR_RESERVED) {
5186                 ctl_set_success(ctsio);
5187                 goto bailout;
5188         }
5189
5190         lun->flags |= CTL_LUN_RESERVED;
5191         lun->res_idx = residx;
5192         ctl_set_success(ctsio);
5193
5194 bailout:
5195         mtx_unlock(&lun->lun_lock);
5196         ctl_done((union ctl_io *)ctsio);
5197         return (CTL_RETVAL_COMPLETE);
5198 }
5199
5200 int
5201 ctl_start_stop(struct ctl_scsiio *ctsio)
5202 {
5203         struct scsi_start_stop_unit *cdb;
5204         struct ctl_lun *lun;
5205         int retval;
5206
5207         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5208
5209         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5210         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5211
5212         if ((cdb->how & SSS_PC_MASK) == 0) {
5213                 if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5214                     (cdb->how & SSS_START) == 0) {
5215                         uint32_t residx;
5216
5217                         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5218                         if (ctl_get_prkey(lun, residx) == 0 ||
5219                             (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5220
5221                                 ctl_set_reservation_conflict(ctsio);
5222                                 ctl_done((union ctl_io *)ctsio);
5223                                 return (CTL_RETVAL_COMPLETE);
5224                         }
5225                 }
5226
5227                 if ((cdb->how & SSS_LOEJ) &&
5228                     (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5229                         ctl_set_invalid_field(ctsio,
5230                                               /*sks_valid*/ 1,
5231                                               /*command*/ 1,
5232                                               /*field*/ 4,
5233                                               /*bit_valid*/ 1,
5234                                               /*bit*/ 1);
5235                         ctl_done((union ctl_io *)ctsio);
5236                         return (CTL_RETVAL_COMPLETE);
5237                 }
5238
5239                 if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5240                     lun->prevent_count > 0) {
5241                         /* "Medium removal prevented" */
5242                         ctl_set_sense(ctsio, /*current_error*/ 1,
5243                             /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5244                              SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5245                             /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5246                         ctl_done((union ctl_io *)ctsio);
5247                         return (CTL_RETVAL_COMPLETE);
5248                 }
5249         }
5250
5251         retval = lun->backend->config_write((union ctl_io *)ctsio);
5252         return (retval);
5253 }
5254
5255 int
5256 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5257 {
5258         struct ctl_lun *lun;
5259         struct scsi_prevent *cdb;
5260         int retval;
5261         uint32_t initidx;
5262
5263         CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5264
5265         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5266         cdb = (struct scsi_prevent *)ctsio->cdb;
5267
5268         if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5269                 ctl_set_invalid_opcode(ctsio);
5270                 ctl_done((union ctl_io *)ctsio);
5271                 return (CTL_RETVAL_COMPLETE);
5272         }
5273
5274         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5275         mtx_lock(&lun->lun_lock);
5276         if ((cdb->how & PR_PREVENT) &&
5277             ctl_is_set(lun->prevent, initidx) == 0) {
5278                 ctl_set_mask(lun->prevent, initidx);
5279                 lun->prevent_count++;
5280         } else if ((cdb->how & PR_PREVENT) == 0 &&
5281             ctl_is_set(lun->prevent, initidx)) {
5282                 ctl_clear_mask(lun->prevent, initidx);
5283                 lun->prevent_count--;
5284         }
5285         mtx_unlock(&lun->lun_lock);
5286         retval = lun->backend->config_write((union ctl_io *)ctsio);
5287         return (retval);
5288 }
5289
5290 /*
5291  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5292  * we don't really do anything with the LBA and length fields if the user
5293  * passes them in.  Instead we'll just flush out the cache for the entire
5294  * LUN.
5295  */
5296 int
5297 ctl_sync_cache(struct ctl_scsiio *ctsio)
5298 {
5299         struct ctl_lun *lun;
5300         struct ctl_softc *softc;
5301         struct ctl_lba_len_flags *lbalen;
5302         uint64_t starting_lba;
5303         uint32_t block_count;
5304         int retval;
5305         uint8_t byte2;
5306
5307         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5308
5309         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5310         softc = lun->ctl_softc;
5311         retval = 0;
5312
5313         switch (ctsio->cdb[0]) {
5314         case SYNCHRONIZE_CACHE: {
5315                 struct scsi_sync_cache *cdb;
5316                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5317
5318                 starting_lba = scsi_4btoul(cdb->begin_lba);
5319                 block_count = scsi_2btoul(cdb->lb_count);
5320                 byte2 = cdb->byte2;
5321                 break;
5322         }
5323         case SYNCHRONIZE_CACHE_16: {
5324                 struct scsi_sync_cache_16 *cdb;
5325                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5326
5327                 starting_lba = scsi_8btou64(cdb->begin_lba);
5328                 block_count = scsi_4btoul(cdb->lb_count);
5329                 byte2 = cdb->byte2;
5330                 break;
5331         }
5332         default:
5333                 ctl_set_invalid_opcode(ctsio);
5334                 ctl_done((union ctl_io *)ctsio);
5335                 goto bailout;
5336                 break; /* NOTREACHED */
5337         }
5338
5339         /*
5340          * We check the LBA and length, but don't do anything with them.
5341          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5342          * get flushed.  This check will just help satisfy anyone who wants
5343          * to see an error for an out of range LBA.
5344          */
5345         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5346                 ctl_set_lba_out_of_range(ctsio);
5347                 ctl_done((union ctl_io *)ctsio);
5348                 goto bailout;
5349         }
5350
5351         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5352         lbalen->lba = starting_lba;
5353         lbalen->len = block_count;
5354         lbalen->flags = byte2;
5355         retval = lun->backend->config_write((union ctl_io *)ctsio);
5356
5357 bailout:
5358         return (retval);
5359 }
5360
5361 int
5362 ctl_format(struct ctl_scsiio *ctsio)
5363 {
5364         struct scsi_format *cdb;
5365         struct ctl_lun *lun;
5366         int length, defect_list_len;
5367
5368         CTL_DEBUG_PRINT(("ctl_format\n"));
5369
5370         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
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;
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         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
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 ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5485             (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5486             (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5487                 ctl_set_invalid_field(ctsio,
5488                                       /*sks_valid*/ 1,
5489                                       /*command*/ 1,
5490                                       /*field*/ 1,
5491                                       /*bit_valid*/ 1,
5492                                       /*bit*/ 4);
5493                 ctl_done((union ctl_io *)ctsio);
5494                 return (CTL_RETVAL_COMPLETE);
5495         }
5496
5497         if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5498             buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5499                 ctl_set_invalid_field(ctsio,
5500                                       /*sks_valid*/ 1,
5501                                       /*command*/ 1,
5502                                       /*field*/ 6,
5503                                       /*bit_valid*/ 0,
5504                                       /*bit*/ 0);
5505                 ctl_done((union ctl_io *)ctsio);
5506                 return (CTL_RETVAL_COMPLETE);
5507         }
5508
5509         if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5510                 descr[0] = 0;
5511                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5512                 ctsio->kern_data_ptr = descr;
5513                 len = min(len, sizeof(descr));
5514         } else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5515                 ctsio->kern_data_ptr = echo_descr;
5516                 len = min(len, sizeof(echo_descr));
5517         } else {
5518                 if (lun->write_buffer == NULL) {
5519                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5520                             M_CTL, M_WAITOK);
5521                 }
5522                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5523         }
5524         ctsio->kern_data_len = len;
5525         ctsio->kern_total_len = len;
5526         ctsio->kern_data_resid = 0;
5527         ctsio->kern_rel_offset = 0;
5528         ctsio->kern_sg_entries = 0;
5529         ctl_set_success(ctsio);
5530         ctsio->be_move_done = ctl_config_move_done;
5531         ctl_datamove((union ctl_io *)ctsio);
5532         return (CTL_RETVAL_COMPLETE);
5533 }
5534
5535 int
5536 ctl_write_buffer(struct ctl_scsiio *ctsio)
5537 {
5538         struct scsi_write_buffer *cdb;
5539         struct ctl_lun *lun;
5540         int buffer_offset, len;
5541
5542         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5543
5544         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5545         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5546
5547         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5548                 ctl_set_invalid_field(ctsio,
5549                                       /*sks_valid*/ 1,
5550                                       /*command*/ 1,
5551                                       /*field*/ 1,
5552                                       /*bit_valid*/ 1,
5553                                       /*bit*/ 4);
5554                 ctl_done((union ctl_io *)ctsio);
5555                 return (CTL_RETVAL_COMPLETE);
5556         }
5557
5558         len = scsi_3btoul(cdb->length);
5559         buffer_offset = scsi_3btoul(cdb->offset);
5560
5561         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5562                 ctl_set_invalid_field(ctsio,
5563                                       /*sks_valid*/ 1,
5564                                       /*command*/ 1,
5565                                       /*field*/ 6,
5566                                       /*bit_valid*/ 0,
5567                                       /*bit*/ 0);
5568                 ctl_done((union ctl_io *)ctsio);
5569                 return (CTL_RETVAL_COMPLETE);
5570         }
5571
5572         /*
5573          * If we've got a kernel request that hasn't been malloced yet,
5574          * malloc it and tell the caller the data buffer is here.
5575          */
5576         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5577                 if (lun->write_buffer == NULL) {
5578                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5579                             M_CTL, M_WAITOK);
5580                 }
5581                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5582                 ctsio->kern_data_len = len;
5583                 ctsio->kern_total_len = len;
5584                 ctsio->kern_data_resid = 0;
5585                 ctsio->kern_rel_offset = 0;
5586                 ctsio->kern_sg_entries = 0;
5587                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5588                 ctsio->be_move_done = ctl_config_move_done;
5589                 ctl_datamove((union ctl_io *)ctsio);
5590
5591                 return (CTL_RETVAL_COMPLETE);
5592         }
5593
5594         ctl_set_success(ctsio);
5595         ctl_done((union ctl_io *)ctsio);
5596         return (CTL_RETVAL_COMPLETE);
5597 }
5598
5599 int
5600 ctl_write_same(struct ctl_scsiio *ctsio)
5601 {
5602         struct ctl_lun *lun;
5603         struct ctl_lba_len_flags *lbalen;
5604         uint64_t lba;
5605         uint32_t num_blocks;
5606         int len, retval;
5607         uint8_t byte2;
5608
5609         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5610
5611         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5612
5613         switch (ctsio->cdb[0]) {
5614         case WRITE_SAME_10: {
5615                 struct scsi_write_same_10 *cdb;
5616
5617                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5618
5619                 lba = scsi_4btoul(cdb->addr);
5620                 num_blocks = scsi_2btoul(cdb->length);
5621                 byte2 = cdb->byte2;
5622                 break;
5623         }
5624         case WRITE_SAME_16: {
5625                 struct scsi_write_same_16 *cdb;
5626
5627                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5628
5629                 lba = scsi_8btou64(cdb->addr);
5630                 num_blocks = scsi_4btoul(cdb->length);
5631                 byte2 = cdb->byte2;
5632                 break;
5633         }
5634         default:
5635                 /*
5636                  * We got a command we don't support.  This shouldn't
5637                  * happen, commands should be filtered out above us.
5638                  */
5639                 ctl_set_invalid_opcode(ctsio);
5640                 ctl_done((union ctl_io *)ctsio);
5641
5642                 return (CTL_RETVAL_COMPLETE);
5643                 break; /* NOTREACHED */
5644         }
5645
5646         /* ANCHOR flag can be used only together with UNMAP */
5647         if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5648                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5649                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5650                 ctl_done((union ctl_io *)ctsio);
5651                 return (CTL_RETVAL_COMPLETE);
5652         }
5653
5654         /*
5655          * The first check is to make sure we're in bounds, the second
5656          * check is to catch wrap-around problems.  If the lba + num blocks
5657          * is less than the lba, then we've wrapped around and the block
5658          * range is invalid anyway.
5659          */
5660         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5661          || ((lba + num_blocks) < lba)) {
5662                 ctl_set_lba_out_of_range(ctsio);
5663                 ctl_done((union ctl_io *)ctsio);
5664                 return (CTL_RETVAL_COMPLETE);
5665         }
5666
5667         /* Zero number of blocks means "to the last logical block" */
5668         if (num_blocks == 0) {
5669                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5670                         ctl_set_invalid_field(ctsio,
5671                                               /*sks_valid*/ 0,
5672                                               /*command*/ 1,
5673                                               /*field*/ 0,
5674                                               /*bit_valid*/ 0,
5675                                               /*bit*/ 0);
5676                         ctl_done((union ctl_io *)ctsio);
5677                         return (CTL_RETVAL_COMPLETE);
5678                 }
5679                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5680         }
5681
5682         len = lun->be_lun->blocksize;
5683
5684         /*
5685          * If we've got a kernel request that hasn't been malloced yet,
5686          * malloc it and tell the caller the data buffer is here.
5687          */
5688         if ((byte2 & SWS_NDOB) == 0 &&
5689             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5690                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5691                 ctsio->kern_data_len = len;
5692                 ctsio->kern_total_len = len;
5693                 ctsio->kern_data_resid = 0;
5694                 ctsio->kern_rel_offset = 0;
5695                 ctsio->kern_sg_entries = 0;
5696                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5697                 ctsio->be_move_done = ctl_config_move_done;
5698                 ctl_datamove((union ctl_io *)ctsio);
5699
5700                 return (CTL_RETVAL_COMPLETE);
5701         }
5702
5703         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5704         lbalen->lba = lba;
5705         lbalen->len = num_blocks;
5706         lbalen->flags = byte2;
5707         retval = lun->backend->config_write((union ctl_io *)ctsio);
5708
5709         return (retval);
5710 }
5711
5712 int
5713 ctl_unmap(struct ctl_scsiio *ctsio)
5714 {
5715         struct ctl_lun *lun;
5716         struct scsi_unmap *cdb;
5717         struct ctl_ptr_len_flags *ptrlen;
5718         struct scsi_unmap_header *hdr;
5719         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5720         uint64_t lba;
5721         uint32_t num_blocks;
5722         int len, retval;
5723         uint8_t byte2;
5724
5725         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5726
5727         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5728         cdb = (struct scsi_unmap *)ctsio->cdb;
5729
5730         len = scsi_2btoul(cdb->length);
5731         byte2 = cdb->byte2;
5732
5733         /*
5734          * If we've got a kernel request that hasn't been malloced yet,
5735          * malloc it and tell the caller the data buffer is here.
5736          */
5737         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5738                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5739                 ctsio->kern_data_len = len;
5740                 ctsio->kern_total_len = len;
5741                 ctsio->kern_data_resid = 0;
5742                 ctsio->kern_rel_offset = 0;
5743                 ctsio->kern_sg_entries = 0;
5744                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5745                 ctsio->be_move_done = ctl_config_move_done;
5746                 ctl_datamove((union ctl_io *)ctsio);
5747
5748                 return (CTL_RETVAL_COMPLETE);
5749         }
5750
5751         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5752         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5753         if (len < sizeof (*hdr) ||
5754             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5755             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5756             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5757                 ctl_set_invalid_field(ctsio,
5758                                       /*sks_valid*/ 0,
5759                                       /*command*/ 0,
5760                                       /*field*/ 0,
5761                                       /*bit_valid*/ 0,
5762                                       /*bit*/ 0);
5763                 goto done;
5764         }
5765         len = scsi_2btoul(hdr->desc_length);
5766         buf = (struct scsi_unmap_desc *)(hdr + 1);
5767         end = buf + len / sizeof(*buf);
5768
5769         endnz = buf;
5770         for (range = buf; range < end; range++) {
5771                 lba = scsi_8btou64(range->lba);
5772                 num_blocks = scsi_4btoul(range->length);
5773                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5774                  || ((lba + num_blocks) < lba)) {
5775                         ctl_set_lba_out_of_range(ctsio);
5776                         ctl_done((union ctl_io *)ctsio);
5777                         return (CTL_RETVAL_COMPLETE);
5778                 }
5779                 if (num_blocks != 0)
5780                         endnz = range + 1;
5781         }
5782
5783         /*
5784          * Block backend can not handle zero last range.
5785          * Filter it out and return if there is nothing left.
5786          */
5787         len = (uint8_t *)endnz - (uint8_t *)buf;
5788         if (len == 0) {
5789                 ctl_set_success(ctsio);
5790                 goto done;
5791         }
5792
5793         mtx_lock(&lun->lun_lock);
5794         ptrlen = (struct ctl_ptr_len_flags *)
5795             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5796         ptrlen->ptr = (void *)buf;
5797         ptrlen->len = len;
5798         ptrlen->flags = byte2;
5799         ctl_check_blocked(lun);
5800         mtx_unlock(&lun->lun_lock);
5801
5802         retval = lun->backend->config_write((union ctl_io *)ctsio);
5803         return (retval);
5804
5805 done:
5806         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5807                 free(ctsio->kern_data_ptr, M_CTL);
5808                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5809         }
5810         ctl_done((union ctl_io *)ctsio);
5811         return (CTL_RETVAL_COMPLETE);
5812 }
5813
5814 /*
5815  * Note that this function currently doesn't actually do anything inside
5816  * CTL to enforce things if the DQue bit is turned on.
5817  *
5818  * Also note that this function can't be used in the default case, because
5819  * the DQue bit isn't set in the changeable mask for the control mode page
5820  * anyway.  This is just here as an example for how to implement a page
5821  * handler, and a placeholder in case we want to allow the user to turn
5822  * tagged queueing on and off.
5823  *
5824  * The D_SENSE bit handling is functional, however, and will turn
5825  * descriptor sense on and off for a given LUN.
5826  */
5827 int
5828 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5829                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5830 {
5831         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5832         struct ctl_lun *lun;
5833         int set_ua;
5834         uint32_t initidx;
5835
5836         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5837         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5838         set_ua = 0;
5839
5840         user_cp = (struct scsi_control_page *)page_ptr;
5841         current_cp = (struct scsi_control_page *)
5842                 (page_index->page_data + (page_index->page_len *
5843                 CTL_PAGE_CURRENT));
5844         saved_cp = (struct scsi_control_page *)
5845                 (page_index->page_data + (page_index->page_len *
5846                 CTL_PAGE_SAVED));
5847
5848         mtx_lock(&lun->lun_lock);
5849         if (((current_cp->rlec & SCP_DSENSE) == 0)
5850          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5851                 /*
5852                  * Descriptor sense is currently turned off and the user
5853                  * wants to turn it on.
5854                  */
5855                 current_cp->rlec |= SCP_DSENSE;
5856                 saved_cp->rlec |= SCP_DSENSE;
5857                 lun->flags |= CTL_LUN_SENSE_DESC;
5858                 set_ua = 1;
5859         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5860                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5861                 /*
5862                  * Descriptor sense is currently turned on, and the user
5863                  * wants to turn it off.
5864                  */
5865                 current_cp->rlec &= ~SCP_DSENSE;
5866                 saved_cp->rlec &= ~SCP_DSENSE;
5867                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5868                 set_ua = 1;
5869         }
5870         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5871             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5872                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5873                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5874                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5875                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5876                 set_ua = 1;
5877         }
5878         if ((current_cp->eca_and_aen & SCP_SWP) !=
5879             (user_cp->eca_and_aen & SCP_SWP)) {
5880                 current_cp->eca_and_aen &= ~SCP_SWP;
5881                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5882                 saved_cp->eca_and_aen &= ~SCP_SWP;
5883                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5884                 set_ua = 1;
5885         }
5886         if (set_ua != 0)
5887                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5888         mtx_unlock(&lun->lun_lock);
5889         if (set_ua) {
5890                 ctl_isc_announce_mode(lun,
5891                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5892                     page_index->page_code, page_index->subpage);
5893         }
5894         return (0);
5895 }
5896
5897 int
5898 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5899                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5900 {
5901         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5902         struct ctl_lun *lun;
5903         int set_ua;
5904         uint32_t initidx;
5905
5906         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5907         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5908         set_ua = 0;
5909
5910         user_cp = (struct scsi_caching_page *)page_ptr;
5911         current_cp = (struct scsi_caching_page *)
5912                 (page_index->page_data + (page_index->page_len *
5913                 CTL_PAGE_CURRENT));
5914         saved_cp = (struct scsi_caching_page *)
5915                 (page_index->page_data + (page_index->page_len *
5916                 CTL_PAGE_SAVED));
5917
5918         mtx_lock(&lun->lun_lock);
5919         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5920             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5921                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5922                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5923                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5924                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5925                 set_ua = 1;
5926         }
5927         if (set_ua != 0)
5928                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5929         mtx_unlock(&lun->lun_lock);
5930         if (set_ua) {
5931                 ctl_isc_announce_mode(lun,
5932                     ctl_get_initindex(&ctsio->io_hdr.nexus),
5933                     page_index->page_code, page_index->subpage);
5934         }
5935         return (0);
5936 }
5937
5938 int
5939 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5940                                 struct ctl_page_index *page_index,
5941                                 uint8_t *page_ptr)
5942 {
5943         uint8_t *c;
5944         int i;
5945
5946         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5947         ctl_time_io_secs =
5948                 (c[0] << 8) |
5949                 (c[1] << 0) |
5950                 0;
5951         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5952         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5953         printf("page data:");
5954         for (i=0; i<8; i++)
5955                 printf(" %.2x",page_ptr[i]);
5956         printf("\n");
5957         return (0);
5958 }
5959
5960 int
5961 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5962                                struct ctl_page_index *page_index,
5963                                int pc)
5964 {
5965         struct copan_debugconf_subpage *page;
5966
5967         page = (struct copan_debugconf_subpage *)page_index->page_data +
5968                 (page_index->page_len * pc);
5969
5970         switch (pc) {
5971         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5972         case SMS_PAGE_CTRL_DEFAULT >> 6:
5973         case SMS_PAGE_CTRL_SAVED >> 6:
5974                 /*
5975                  * We don't update the changable or default bits for this page.
5976                  */
5977                 break;
5978         case SMS_PAGE_CTRL_CURRENT >> 6:
5979                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5980                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5981                 break;
5982         default:
5983                 break;
5984         }
5985         return (0);
5986 }
5987
5988
5989 static int
5990 ctl_do_mode_select(union ctl_io *io)
5991 {
5992         struct scsi_mode_page_header *page_header;
5993         struct ctl_page_index *page_index;
5994         struct ctl_scsiio *ctsio;
5995         int page_len, page_len_offset, page_len_size;
5996         union ctl_modepage_info *modepage_info;
5997         struct ctl_lun *lun;
5998         int *len_left, *len_used;
5999         int retval, i;
6000
6001         ctsio = &io->scsiio;
6002         page_index = NULL;
6003         page_len = 0;
6004         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6005
6006         modepage_info = (union ctl_modepage_info *)
6007                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6008         len_left = &modepage_info->header.len_left;
6009         len_used = &modepage_info->header.len_used;
6010
6011 do_next_page:
6012
6013         page_header = (struct scsi_mode_page_header *)
6014                 (ctsio->kern_data_ptr + *len_used);
6015
6016         if (*len_left == 0) {
6017                 free(ctsio->kern_data_ptr, M_CTL);
6018                 ctl_set_success(ctsio);
6019                 ctl_done((union ctl_io *)ctsio);
6020                 return (CTL_RETVAL_COMPLETE);
6021         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6022
6023                 free(ctsio->kern_data_ptr, M_CTL);
6024                 ctl_set_param_len_error(ctsio);
6025                 ctl_done((union ctl_io *)ctsio);
6026                 return (CTL_RETVAL_COMPLETE);
6027
6028         } else if ((page_header->page_code & SMPH_SPF)
6029                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6030
6031                 free(ctsio->kern_data_ptr, M_CTL);
6032                 ctl_set_param_len_error(ctsio);
6033                 ctl_done((union ctl_io *)ctsio);
6034                 return (CTL_RETVAL_COMPLETE);
6035         }
6036
6037
6038         /*
6039          * XXX KDM should we do something with the block descriptor?
6040          */
6041         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6042                 page_index = &lun->mode_pages.index[i];
6043                 if (lun->be_lun->lun_type == T_DIRECT &&
6044                     (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6045                         continue;
6046                 if (lun->be_lun->lun_type == T_PROCESSOR &&
6047                     (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6048                         continue;
6049                 if (lun->be_lun->lun_type == T_CDROM &&
6050                     (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6051                         continue;
6052
6053                 if ((page_index->page_code & SMPH_PC_MASK) !=
6054                     (page_header->page_code & SMPH_PC_MASK))
6055                         continue;
6056
6057                 /*
6058                  * If neither page has a subpage code, then we've got a
6059                  * match.
6060                  */
6061                 if (((page_index->page_code & SMPH_SPF) == 0)
6062                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6063                         page_len = page_header->page_length;
6064                         break;
6065                 }
6066
6067                 /*
6068                  * If both pages have subpages, then the subpage numbers
6069                  * have to match.
6070                  */
6071                 if ((page_index->page_code & SMPH_SPF)
6072                   && (page_header->page_code & SMPH_SPF)) {
6073                         struct scsi_mode_page_header_sp *sph;
6074
6075                         sph = (struct scsi_mode_page_header_sp *)page_header;
6076                         if (page_index->subpage == sph->subpage) {
6077                                 page_len = scsi_2btoul(sph->page_length);
6078                                 break;
6079                         }
6080                 }
6081         }
6082
6083         /*
6084          * If we couldn't find the page, or if we don't have a mode select
6085          * handler for it, send back an error to the user.
6086          */
6087         if ((i >= CTL_NUM_MODE_PAGES)
6088          || (page_index->select_handler == NULL)) {
6089                 ctl_set_invalid_field(ctsio,
6090                                       /*sks_valid*/ 1,
6091                                       /*command*/ 0,
6092                                       /*field*/ *len_used,
6093                                       /*bit_valid*/ 0,
6094                                       /*bit*/ 0);
6095                 free(ctsio->kern_data_ptr, M_CTL);
6096                 ctl_done((union ctl_io *)ctsio);
6097                 return (CTL_RETVAL_COMPLETE);
6098         }
6099
6100         if (page_index->page_code & SMPH_SPF) {
6101                 page_len_offset = 2;
6102                 page_len_size = 2;
6103         } else {
6104                 page_len_size = 1;
6105                 page_len_offset = 1;
6106         }
6107
6108         /*
6109          * If the length the initiator gives us isn't the one we specify in
6110          * the mode page header, or if they didn't specify enough data in
6111          * the CDB to avoid truncating this page, kick out the request.
6112          */
6113         if ((page_len != (page_index->page_len - page_len_offset -
6114                           page_len_size))
6115          || (*len_left < page_index->page_len)) {
6116
6117
6118                 ctl_set_invalid_field(ctsio,
6119                                       /*sks_valid*/ 1,
6120                                       /*command*/ 0,
6121                                       /*field*/ *len_used + page_len_offset,
6122                                       /*bit_valid*/ 0,
6123                                       /*bit*/ 0);
6124                 free(ctsio->kern_data_ptr, M_CTL);
6125                 ctl_done((union ctl_io *)ctsio);
6126                 return (CTL_RETVAL_COMPLETE);
6127         }
6128
6129         /*
6130          * Run through the mode page, checking to make sure that the bits
6131          * the user changed are actually legal for him to change.
6132          */
6133         for (i = 0; i < page_index->page_len; i++) {
6134                 uint8_t *user_byte, *change_mask, *current_byte;
6135                 int bad_bit;
6136                 int j;
6137
6138                 user_byte = (uint8_t *)page_header + i;
6139                 change_mask = page_index->page_data +
6140                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6141                 current_byte = page_index->page_data +
6142                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6143
6144                 /*
6145                  * Check to see whether the user set any bits in this byte
6146                  * that he is not allowed to set.
6147                  */
6148                 if ((*user_byte & ~(*change_mask)) ==
6149                     (*current_byte & ~(*change_mask)))
6150                         continue;
6151
6152                 /*
6153                  * Go through bit by bit to determine which one is illegal.
6154                  */
6155                 bad_bit = 0;
6156                 for (j = 7; j >= 0; j--) {
6157                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6158                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6159                                 bad_bit = i;
6160                                 break;
6161                         }
6162                 }
6163                 ctl_set_invalid_field(ctsio,
6164                                       /*sks_valid*/ 1,
6165                                       /*command*/ 0,
6166                                       /*field*/ *len_used + i,
6167                                       /*bit_valid*/ 1,
6168                                       /*bit*/ bad_bit);
6169                 free(ctsio->kern_data_ptr, M_CTL);
6170                 ctl_done((union ctl_io *)ctsio);
6171                 return (CTL_RETVAL_COMPLETE);
6172         }
6173
6174         /*
6175          * Decrement these before we call the page handler, since we may
6176          * end up getting called back one way or another before the handler
6177          * returns to this context.
6178          */
6179         *len_left -= page_index->page_len;
6180         *len_used += page_index->page_len;
6181
6182         retval = page_index->select_handler(ctsio, page_index,
6183                                             (uint8_t *)page_header);
6184
6185         /*
6186          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6187          * wait until this queued command completes to finish processing
6188          * the mode page.  If it returns anything other than
6189          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6190          * already set the sense information, freed the data pointer, and
6191          * completed the io for us.
6192          */
6193         if (retval != CTL_RETVAL_COMPLETE)
6194                 goto bailout_no_done;
6195
6196         /*
6197          * If the initiator sent us more than one page, parse the next one.
6198          */
6199         if (*len_left > 0)
6200                 goto do_next_page;
6201
6202         ctl_set_success(ctsio);
6203         free(ctsio->kern_data_ptr, M_CTL);
6204         ctl_done((union ctl_io *)ctsio);
6205
6206 bailout_no_done:
6207
6208         return (CTL_RETVAL_COMPLETE);
6209
6210 }
6211
6212 int
6213 ctl_mode_select(struct ctl_scsiio *ctsio)
6214 {
6215         int param_len, pf, sp;
6216         int header_size, bd_len;
6217         union ctl_modepage_info *modepage_info;
6218
6219         switch (ctsio->cdb[0]) {
6220         case MODE_SELECT_6: {
6221                 struct scsi_mode_select_6 *cdb;
6222
6223                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6224
6225                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6226                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6227                 param_len = cdb->length;
6228                 header_size = sizeof(struct scsi_mode_header_6);
6229                 break;
6230         }
6231         case MODE_SELECT_10: {
6232                 struct scsi_mode_select_10 *cdb;
6233
6234                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6235
6236                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6237                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6238                 param_len = scsi_2btoul(cdb->length);
6239                 header_size = sizeof(struct scsi_mode_header_10);
6240                 break;
6241         }
6242         default:
6243                 ctl_set_invalid_opcode(ctsio);
6244                 ctl_done((union ctl_io *)ctsio);
6245                 return (CTL_RETVAL_COMPLETE);
6246         }
6247
6248         /*
6249          * From SPC-3:
6250          * "A parameter list length of zero indicates that the Data-Out Buffer
6251          * shall be empty. This condition shall not be considered as an error."
6252          */
6253         if (param_len == 0) {
6254                 ctl_set_success(ctsio);
6255                 ctl_done((union ctl_io *)ctsio);
6256                 return (CTL_RETVAL_COMPLETE);
6257         }
6258
6259         /*
6260          * Since we'll hit this the first time through, prior to
6261          * allocation, we don't need to free a data buffer here.
6262          */
6263         if (param_len < header_size) {
6264                 ctl_set_param_len_error(ctsio);
6265                 ctl_done((union ctl_io *)ctsio);
6266                 return (CTL_RETVAL_COMPLETE);
6267         }
6268
6269         /*
6270          * Allocate the data buffer and grab the user's data.  In theory,
6271          * we shouldn't have to sanity check the parameter list length here
6272          * because the maximum size is 64K.  We should be able to malloc
6273          * that much without too many problems.
6274          */
6275         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6276                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6277                 ctsio->kern_data_len = param_len;
6278                 ctsio->kern_total_len = param_len;
6279                 ctsio->kern_data_resid = 0;
6280                 ctsio->kern_rel_offset = 0;
6281                 ctsio->kern_sg_entries = 0;
6282                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6283                 ctsio->be_move_done = ctl_config_move_done;
6284                 ctl_datamove((union ctl_io *)ctsio);
6285
6286                 return (CTL_RETVAL_COMPLETE);
6287         }
6288
6289         switch (ctsio->cdb[0]) {
6290         case MODE_SELECT_6: {
6291                 struct scsi_mode_header_6 *mh6;
6292
6293                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6294                 bd_len = mh6->blk_desc_len;
6295                 break;
6296         }
6297         case MODE_SELECT_10: {
6298                 struct scsi_mode_header_10 *mh10;
6299
6300                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6301                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6302                 break;
6303         }
6304         default:
6305                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6306         }
6307
6308         if (param_len < (header_size + bd_len)) {
6309                 free(ctsio->kern_data_ptr, M_CTL);
6310                 ctl_set_param_len_error(ctsio);
6311                 ctl_done((union ctl_io *)ctsio);
6312                 return (CTL_RETVAL_COMPLETE);
6313         }
6314
6315         /*
6316          * Set the IO_CONT flag, so that if this I/O gets passed to
6317          * ctl_config_write_done(), it'll get passed back to
6318          * ctl_do_mode_select() for further processing, or completion if
6319          * we're all done.
6320          */
6321         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6322         ctsio->io_cont = ctl_do_mode_select;
6323
6324         modepage_info = (union ctl_modepage_info *)
6325                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6326         memset(modepage_info, 0, sizeof(*modepage_info));
6327         modepage_info->header.len_left = param_len - header_size - bd_len;
6328         modepage_info->header.len_used = header_size + bd_len;
6329
6330         return (ctl_do_mode_select((union ctl_io *)ctsio));
6331 }
6332
6333 int
6334 ctl_mode_sense(struct ctl_scsiio *ctsio)
6335 {
6336         struct ctl_lun *lun;
6337         int pc, page_code, dbd, llba, subpage;
6338         int alloc_len, page_len, header_len, total_len;
6339         struct scsi_mode_block_descr *block_desc;
6340         struct ctl_page_index *page_index;
6341
6342         dbd = 0;
6343         llba = 0;
6344         block_desc = NULL;
6345
6346         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6347
6348         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6349         switch (ctsio->cdb[0]) {
6350         case MODE_SENSE_6: {
6351                 struct scsi_mode_sense_6 *cdb;
6352
6353                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6354
6355                 header_len = sizeof(struct scsi_mode_hdr_6);
6356                 if (cdb->byte2 & SMS_DBD)
6357                         dbd = 1;
6358                 else
6359                         header_len += sizeof(struct scsi_mode_block_descr);
6360
6361                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6362                 page_code = cdb->page & SMS_PAGE_CODE;
6363                 subpage = cdb->subpage;
6364                 alloc_len = cdb->length;
6365                 break;
6366         }
6367         case MODE_SENSE_10: {
6368                 struct scsi_mode_sense_10 *cdb;
6369
6370                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6371
6372                 header_len = sizeof(struct scsi_mode_hdr_10);
6373
6374                 if (cdb->byte2 & SMS_DBD)
6375                         dbd = 1;
6376                 else
6377                         header_len += sizeof(struct scsi_mode_block_descr);
6378                 if (cdb->byte2 & SMS10_LLBAA)
6379                         llba = 1;
6380                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6381                 page_code = cdb->page & SMS_PAGE_CODE;
6382                 subpage = cdb->subpage;
6383                 alloc_len = scsi_2btoul(cdb->length);
6384                 break;
6385         }
6386         default:
6387                 ctl_set_invalid_opcode(ctsio);
6388                 ctl_done((union ctl_io *)ctsio);
6389                 return (CTL_RETVAL_COMPLETE);
6390                 break; /* NOTREACHED */
6391         }
6392
6393         /*
6394          * We have to make a first pass through to calculate the size of
6395          * the pages that match the user's query.  Then we allocate enough
6396          * memory to hold it, and actually copy the data into the buffer.
6397          */
6398         switch (page_code) {
6399         case SMS_ALL_PAGES_PAGE: {
6400                 int i;
6401
6402                 page_len = 0;
6403
6404                 /*
6405                  * At the moment, values other than 0 and 0xff here are
6406                  * reserved according to SPC-3.
6407                  */
6408                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6409                  && (subpage != SMS_SUBPAGE_ALL)) {
6410                         ctl_set_invalid_field(ctsio,
6411                                               /*sks_valid*/ 1,
6412                                               /*command*/ 1,
6413                                               /*field*/ 3,
6414                                               /*bit_valid*/ 0,
6415                                               /*bit*/ 0);
6416                         ctl_done((union ctl_io *)ctsio);
6417                         return (CTL_RETVAL_COMPLETE);
6418                 }
6419
6420                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6421                         page_index = &lun->mode_pages.index[i];
6422
6423                         /* Make sure the page is supported for this dev type */
6424                         if (lun->be_lun->lun_type == T_DIRECT &&
6425                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6426                                 continue;
6427                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6428                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6429                                 continue;
6430                         if (lun->be_lun->lun_type == T_CDROM &&
6431                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6432                                 continue;
6433
6434                         /*
6435                          * We don't use this subpage if the user didn't
6436                          * request all subpages.
6437                          */
6438                         if ((page_index->subpage != 0)
6439                          && (subpage == SMS_SUBPAGE_PAGE_0))
6440                                 continue;
6441
6442 #if 0
6443                         printf("found page %#x len %d\n",
6444                                page_index->page_code & SMPH_PC_MASK,
6445                                page_index->page_len);
6446 #endif
6447                         page_len += page_index->page_len;
6448                 }
6449                 break;
6450         }
6451         default: {
6452                 int i;
6453
6454                 page_len = 0;
6455
6456                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6457                         page_index = &lun->mode_pages.index[i];
6458
6459                         /* Make sure the page is supported for this dev type */
6460                         if (lun->be_lun->lun_type == T_DIRECT &&
6461                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6462                                 continue;
6463                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6464                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6465                                 continue;
6466                         if (lun->be_lun->lun_type == T_CDROM &&
6467                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6468                                 continue;
6469
6470                         /* Look for the right page code */
6471                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6472                                 continue;
6473
6474                         /* Look for the right subpage or the subpage wildcard*/
6475                         if ((page_index->subpage != subpage)
6476                          && (subpage != SMS_SUBPAGE_ALL))
6477                                 continue;
6478
6479 #if 0
6480                         printf("found page %#x len %d\n",
6481                                page_index->page_code & SMPH_PC_MASK,
6482                                page_index->page_len);
6483 #endif
6484
6485                         page_len += page_index->page_len;
6486                 }
6487
6488                 if (page_len == 0) {
6489                         ctl_set_invalid_field(ctsio,
6490                                               /*sks_valid*/ 1,
6491                                               /*command*/ 1,
6492                                               /*field*/ 2,
6493                                               /*bit_valid*/ 1,
6494                                               /*bit*/ 5);
6495                         ctl_done((union ctl_io *)ctsio);
6496                         return (CTL_RETVAL_COMPLETE);
6497                 }
6498                 break;
6499         }
6500         }
6501
6502         total_len = header_len + page_len;
6503 #if 0
6504         printf("header_len = %d, page_len = %d, total_len = %d\n",
6505                header_len, page_len, total_len);
6506 #endif
6507
6508         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6509         ctsio->kern_sg_entries = 0;
6510         ctsio->kern_data_resid = 0;
6511         ctsio->kern_rel_offset = 0;
6512         if (total_len < alloc_len) {
6513                 ctsio->residual = alloc_len - total_len;
6514                 ctsio->kern_data_len = total_len;
6515                 ctsio->kern_total_len = total_len;
6516         } else {
6517                 ctsio->residual = 0;
6518                 ctsio->kern_data_len = alloc_len;
6519                 ctsio->kern_total_len = alloc_len;
6520         }
6521
6522         switch (ctsio->cdb[0]) {
6523         case MODE_SENSE_6: {
6524                 struct scsi_mode_hdr_6 *header;
6525
6526                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6527
6528                 header->datalen = MIN(total_len - 1, 254);
6529                 if (lun->be_lun->lun_type == T_DIRECT) {
6530                         header->dev_specific = 0x10; /* DPOFUA */
6531                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6532                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6533                             .eca_and_aen & SCP_SWP) != 0)
6534                                     header->dev_specific |= 0x80; /* WP */
6535                 }
6536                 if (dbd)
6537                         header->block_descr_len = 0;
6538                 else
6539                         header->block_descr_len =
6540                                 sizeof(struct scsi_mode_block_descr);
6541                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6542                 break;
6543         }
6544         case MODE_SENSE_10: {
6545                 struct scsi_mode_hdr_10 *header;
6546                 int datalen;
6547
6548                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6549
6550                 datalen = MIN(total_len - 2, 65533);
6551                 scsi_ulto2b(datalen, header->datalen);
6552                 if (lun->be_lun->lun_type == T_DIRECT) {
6553                         header->dev_specific = 0x10; /* DPOFUA */
6554                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6555                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6556                             .eca_and_aen & SCP_SWP) != 0)
6557                                     header->dev_specific |= 0x80; /* WP */
6558                 }
6559                 if (dbd)
6560                         scsi_ulto2b(0, header->block_descr_len);
6561                 else
6562                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6563                                     header->block_descr_len);
6564                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6565                 break;
6566         }
6567         default:
6568                 panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6569         }
6570
6571         /*
6572          * If we've got a disk, use its blocksize in the block
6573          * descriptor.  Otherwise, just set it to 0.
6574          */
6575         if (dbd == 0) {
6576                 if (lun->be_lun->lun_type == T_DIRECT)
6577                         scsi_ulto3b(lun->be_lun->blocksize,
6578                                     block_desc->block_len);
6579                 else
6580                         scsi_ulto3b(0, block_desc->block_len);
6581         }
6582
6583         switch (page_code) {
6584         case SMS_ALL_PAGES_PAGE: {
6585                 int i, data_used;
6586
6587                 data_used = header_len;
6588                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6589                         struct ctl_page_index *page_index;
6590
6591                         page_index = &lun->mode_pages.index[i];
6592                         if (lun->be_lun->lun_type == T_DIRECT &&
6593                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6594                                 continue;
6595                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6596                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6597                                 continue;
6598                         if (lun->be_lun->lun_type == T_CDROM &&
6599                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6600                                 continue;
6601
6602                         /*
6603                          * We don't use this subpage if the user didn't
6604                          * request all subpages.  We already checked (above)
6605                          * to make sure the user only specified a subpage
6606                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6607                          */
6608                         if ((page_index->subpage != 0)
6609                          && (subpage == SMS_SUBPAGE_PAGE_0))
6610                                 continue;
6611
6612                         /*
6613                          * Call the handler, if it exists, to update the
6614                          * page to the latest values.
6615                          */
6616                         if (page_index->sense_handler != NULL)
6617                                 page_index->sense_handler(ctsio, page_index,pc);
6618
6619                         memcpy(ctsio->kern_data_ptr + data_used,
6620                                page_index->page_data +
6621                                (page_index->page_len * pc),
6622                                page_index->page_len);
6623                         data_used += page_index->page_len;
6624                 }
6625                 break;
6626         }
6627         default: {
6628                 int i, data_used;
6629
6630                 data_used = header_len;
6631
6632                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6633                         struct ctl_page_index *page_index;
6634
6635                         page_index = &lun->mode_pages.index[i];
6636
6637                         /* Look for the right page code */
6638                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6639                                 continue;
6640
6641                         /* Look for the right subpage or the subpage wildcard*/
6642                         if ((page_index->subpage != subpage)
6643                          && (subpage != SMS_SUBPAGE_ALL))
6644                                 continue;
6645
6646                         /* Make sure the page is supported for this dev type */
6647                         if (lun->be_lun->lun_type == T_DIRECT &&
6648                             (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6649                                 continue;
6650                         if (lun->be_lun->lun_type == T_PROCESSOR &&
6651                             (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6652                                 continue;
6653                         if (lun->be_lun->lun_type == T_CDROM &&
6654                             (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6655                                 continue;
6656
6657                         /*
6658                          * Call the handler, if it exists, to update the
6659                          * page to the latest values.
6660                          */
6661                         if (page_index->sense_handler != NULL)
6662                                 page_index->sense_handler(ctsio, page_index,pc);
6663
6664                         memcpy(ctsio->kern_data_ptr + data_used,
6665                                page_index->page_data +
6666                                (page_index->page_len * pc),
6667                                page_index->page_len);
6668                         data_used += page_index->page_len;
6669                 }
6670                 break;
6671         }
6672         }
6673
6674         ctl_set_success(ctsio);
6675         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6676         ctsio->be_move_done = ctl_config_move_done;
6677         ctl_datamove((union ctl_io *)ctsio);
6678         return (CTL_RETVAL_COMPLETE);
6679 }
6680
6681 int
6682 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6683                                struct ctl_page_index *page_index,
6684                                int pc)
6685 {
6686         struct ctl_lun *lun;
6687         struct scsi_log_param_header *phdr;
6688         uint8_t *data;
6689         uint64_t val;
6690
6691         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6692         data = page_index->page_data;
6693
6694         if (lun->backend->lun_attr != NULL &&
6695             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6696              != UINT64_MAX) {
6697                 phdr = (struct scsi_log_param_header *)data;
6698                 scsi_ulto2b(0x0001, phdr->param_code);
6699                 phdr->param_control = SLP_LBIN | SLP_LP;
6700                 phdr->param_len = 8;
6701                 data = (uint8_t *)(phdr + 1);
6702                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6703                 data[4] = 0x02; /* per-pool */
6704                 data += phdr->param_len;
6705         }
6706
6707         if (lun->backend->lun_attr != NULL &&
6708             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6709              != UINT64_MAX) {
6710                 phdr = (struct scsi_log_param_header *)data;
6711                 scsi_ulto2b(0x0002, phdr->param_code);
6712                 phdr->param_control = SLP_LBIN | SLP_LP;
6713                 phdr->param_len = 8;
6714                 data = (uint8_t *)(phdr + 1);
6715                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6716                 data[4] = 0x01; /* per-LUN */
6717                 data += phdr->param_len;
6718         }
6719
6720         if (lun->backend->lun_attr != NULL &&
6721             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6722              != UINT64_MAX) {
6723                 phdr = (struct scsi_log_param_header *)data;
6724                 scsi_ulto2b(0x00f1, phdr->param_code);
6725                 phdr->param_control = SLP_LBIN | SLP_LP;
6726                 phdr->param_len = 8;
6727                 data = (uint8_t *)(phdr + 1);
6728                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6729                 data[4] = 0x02; /* per-pool */
6730                 data += phdr->param_len;
6731         }
6732
6733         if (lun->backend->lun_attr != NULL &&
6734             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6735              != UINT64_MAX) {
6736                 phdr = (struct scsi_log_param_header *)data;
6737                 scsi_ulto2b(0x00f2, phdr->param_code);
6738                 phdr->param_control = SLP_LBIN | SLP_LP;
6739                 phdr->param_len = 8;
6740                 data = (uint8_t *)(phdr + 1);
6741                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6742                 data[4] = 0x02; /* per-pool */
6743                 data += phdr->param_len;
6744         }
6745
6746         page_index->page_len = data - page_index->page_data;
6747         return (0);
6748 }
6749
6750 int
6751 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6752                                struct ctl_page_index *page_index,
6753                                int pc)
6754 {
6755         struct ctl_lun *lun;
6756         struct stat_page *data;
6757         uint64_t rn, wn, rb, wb;
6758         struct bintime rt, wt;
6759         int i;
6760
6761         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6762         data = (struct stat_page *)page_index->page_data;
6763
6764         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6765         data->sap.hdr.param_control = SLP_LBIN;
6766         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6767             sizeof(struct scsi_log_param_header);
6768         rn = wn = rb = wb = 0;
6769         bintime_clear(&rt);
6770         bintime_clear(&wt);
6771         for (i = 0; i < CTL_MAX_PORTS; i++) {
6772                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6773                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6774                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6775                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6776                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6777                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6778         }
6779         scsi_u64to8b(rn, data->sap.read_num);
6780         scsi_u64to8b(wn, data->sap.write_num);
6781         if (lun->stats.blocksize > 0) {
6782                 scsi_u64to8b(wb / lun->stats.blocksize,
6783                     data->sap.recvieved_lba);
6784                 scsi_u64to8b(rb / lun->stats.blocksize,
6785                     data->sap.transmitted_lba);
6786         }
6787         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6788             data->sap.read_int);
6789         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6790             data->sap.write_int);
6791         scsi_u64to8b(0, data->sap.weighted_num);
6792         scsi_u64to8b(0, data->sap.weighted_int);
6793         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6794         data->it.hdr.param_control = SLP_LBIN;
6795         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6796             sizeof(struct scsi_log_param_header);
6797 #ifdef CTL_TIME_IO
6798         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6799 #endif
6800         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6801         data->it.hdr.param_control = SLP_LBIN;
6802         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6803             sizeof(struct scsi_log_param_header);
6804         scsi_ulto4b(3, data->ti.exponent);
6805         scsi_ulto4b(1, data->ti.integer);
6806
6807         page_index->page_len = sizeof(*data);
6808         return (0);
6809 }
6810
6811 int
6812 ctl_log_sense(struct ctl_scsiio *ctsio)
6813 {
6814         struct ctl_lun *lun;
6815         int i, pc, page_code, subpage;
6816         int alloc_len, total_len;
6817         struct ctl_page_index *page_index;
6818         struct scsi_log_sense *cdb;
6819         struct scsi_log_header *header;
6820
6821         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6822
6823         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6824         cdb = (struct scsi_log_sense *)ctsio->cdb;
6825         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6826         page_code = cdb->page & SLS_PAGE_CODE;
6827         subpage = cdb->subpage;
6828         alloc_len = scsi_2btoul(cdb->length);
6829
6830         page_index = NULL;
6831         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6832                 page_index = &lun->log_pages.index[i];
6833
6834                 /* Look for the right page code */
6835                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6836                         continue;
6837
6838                 /* Look for the right subpage or the subpage wildcard*/
6839                 if (page_index->subpage != subpage)
6840                         continue;
6841
6842                 break;
6843         }
6844         if (i >= CTL_NUM_LOG_PAGES) {
6845                 ctl_set_invalid_field(ctsio,
6846                                       /*sks_valid*/ 1,
6847                                       /*command*/ 1,
6848                                       /*field*/ 2,
6849                                       /*bit_valid*/ 0,
6850                                       /*bit*/ 0);
6851                 ctl_done((union ctl_io *)ctsio);
6852                 return (CTL_RETVAL_COMPLETE);
6853         }
6854
6855         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6856
6857         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6858         ctsio->kern_sg_entries = 0;
6859         ctsio->kern_data_resid = 0;
6860         ctsio->kern_rel_offset = 0;
6861         if (total_len < alloc_len) {
6862                 ctsio->residual = alloc_len - total_len;
6863                 ctsio->kern_data_len = total_len;
6864                 ctsio->kern_total_len = total_len;
6865         } else {
6866                 ctsio->residual = 0;
6867                 ctsio->kern_data_len = alloc_len;
6868                 ctsio->kern_total_len = alloc_len;
6869         }
6870
6871         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6872         header->page = page_index->page_code;
6873         if (page_index->subpage) {
6874                 header->page |= SL_SPF;
6875                 header->subpage = page_index->subpage;
6876         }
6877         scsi_ulto2b(page_index->page_len, header->datalen);
6878
6879         /*
6880          * Call the handler, if it exists, to update the
6881          * page to the latest values.
6882          */
6883         if (page_index->sense_handler != NULL)
6884                 page_index->sense_handler(ctsio, page_index, pc);
6885
6886         memcpy(header + 1, page_index->page_data, page_index->page_len);
6887
6888         ctl_set_success(ctsio);
6889         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6890         ctsio->be_move_done = ctl_config_move_done;
6891         ctl_datamove((union ctl_io *)ctsio);
6892         return (CTL_RETVAL_COMPLETE);
6893 }
6894
6895 int
6896 ctl_read_capacity(struct ctl_scsiio *ctsio)
6897 {
6898         struct scsi_read_capacity *cdb;
6899         struct scsi_read_capacity_data *data;
6900         struct ctl_lun *lun;
6901         uint32_t lba;
6902
6903         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6904
6905         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6906
6907         lba = scsi_4btoul(cdb->addr);
6908         if (((cdb->pmi & SRC_PMI) == 0)
6909          && (lba != 0)) {
6910                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6911                                       /*sks_valid*/ 1,
6912                                       /*command*/ 1,
6913                                       /*field*/ 2,
6914                                       /*bit_valid*/ 0,
6915                                       /*bit*/ 0);
6916                 ctl_done((union ctl_io *)ctsio);
6917                 return (CTL_RETVAL_COMPLETE);
6918         }
6919
6920         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6921
6922         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6923         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6924         ctsio->residual = 0;
6925         ctsio->kern_data_len = sizeof(*data);
6926         ctsio->kern_total_len = sizeof(*data);
6927         ctsio->kern_data_resid = 0;
6928         ctsio->kern_rel_offset = 0;
6929         ctsio->kern_sg_entries = 0;
6930
6931         /*
6932          * If the maximum LBA is greater than 0xfffffffe, the user must
6933          * issue a SERVICE ACTION IN (16) command, with the read capacity
6934          * serivce action set.
6935          */
6936         if (lun->be_lun->maxlba > 0xfffffffe)
6937                 scsi_ulto4b(0xffffffff, data->addr);
6938         else
6939                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6940
6941         /*
6942          * XXX KDM this may not be 512 bytes...
6943          */
6944         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6945
6946         ctl_set_success(ctsio);
6947         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6948         ctsio->be_move_done = ctl_config_move_done;
6949         ctl_datamove((union ctl_io *)ctsio);
6950         return (CTL_RETVAL_COMPLETE);
6951 }
6952
6953 int
6954 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6955 {
6956         struct scsi_read_capacity_16 *cdb;
6957         struct scsi_read_capacity_data_long *data;
6958         struct ctl_lun *lun;
6959         uint64_t lba;
6960         uint32_t alloc_len;
6961
6962         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6963
6964         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6965
6966         alloc_len = scsi_4btoul(cdb->alloc_len);
6967         lba = scsi_8btou64(cdb->addr);
6968
6969         if ((cdb->reladr & SRC16_PMI)
6970          && (lba != 0)) {
6971                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6972                                       /*sks_valid*/ 1,
6973                                       /*command*/ 1,
6974                                       /*field*/ 2,
6975                                       /*bit_valid*/ 0,
6976                                       /*bit*/ 0);
6977                 ctl_done((union ctl_io *)ctsio);
6978                 return (CTL_RETVAL_COMPLETE);
6979         }
6980
6981         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6982
6983         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6984         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6985
6986         if (sizeof(*data) < alloc_len) {
6987                 ctsio->residual = alloc_len - sizeof(*data);
6988                 ctsio->kern_data_len = sizeof(*data);
6989                 ctsio->kern_total_len = sizeof(*data);
6990         } else {
6991                 ctsio->residual = 0;
6992                 ctsio->kern_data_len = alloc_len;
6993                 ctsio->kern_total_len = alloc_len;
6994         }
6995         ctsio->kern_data_resid = 0;
6996         ctsio->kern_rel_offset = 0;
6997         ctsio->kern_sg_entries = 0;
6998
6999         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7000         /* XXX KDM this may not be 512 bytes... */
7001         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7002         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7003         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7004         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7005                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7006
7007         ctl_set_success(ctsio);
7008         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7009         ctsio->be_move_done = ctl_config_move_done;
7010         ctl_datamove((union ctl_io *)ctsio);
7011         return (CTL_RETVAL_COMPLETE);
7012 }
7013
7014 int
7015 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7016 {
7017         struct scsi_get_lba_status *cdb;
7018         struct scsi_get_lba_status_data *data;
7019         struct ctl_lun *lun;
7020         struct ctl_lba_len_flags *lbalen;
7021         uint64_t lba;
7022         uint32_t alloc_len, total_len;
7023         int retval;
7024
7025         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7026
7027         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7028         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7029         lba = scsi_8btou64(cdb->addr);
7030         alloc_len = scsi_4btoul(cdb->alloc_len);
7031
7032         if (lba > lun->be_lun->maxlba) {
7033                 ctl_set_lba_out_of_range(ctsio);
7034                 ctl_done((union ctl_io *)ctsio);
7035                 return (CTL_RETVAL_COMPLETE);
7036         }
7037
7038         total_len = sizeof(*data) + sizeof(data->descr[0]);
7039         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7040         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7041
7042         if (total_len < alloc_len) {
7043                 ctsio->residual = alloc_len - total_len;
7044                 ctsio->kern_data_len = total_len;
7045                 ctsio->kern_total_len = total_len;
7046         } else {
7047                 ctsio->residual = 0;
7048                 ctsio->kern_data_len = alloc_len;
7049                 ctsio->kern_total_len = alloc_len;
7050         }
7051         ctsio->kern_data_resid = 0;
7052         ctsio->kern_rel_offset = 0;
7053         ctsio->kern_sg_entries = 0;
7054
7055         /* Fill dummy data in case backend can't tell anything. */
7056         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7057         scsi_u64to8b(lba, data->descr[0].addr);
7058         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7059             data->descr[0].length);
7060         data->descr[0].status = 0; /* Mapped or unknown. */
7061
7062         ctl_set_success(ctsio);
7063         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7064         ctsio->be_move_done = ctl_config_move_done;
7065
7066         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7067         lbalen->lba = lba;
7068         lbalen->len = total_len;
7069         lbalen->flags = 0;
7070         retval = lun->backend->config_read((union ctl_io *)ctsio);
7071         return (CTL_RETVAL_COMPLETE);
7072 }
7073
7074 int
7075 ctl_read_defect(struct ctl_scsiio *ctsio)
7076 {
7077         struct scsi_read_defect_data_10 *ccb10;
7078         struct scsi_read_defect_data_12 *ccb12;
7079         struct scsi_read_defect_data_hdr_10 *data10;
7080         struct scsi_read_defect_data_hdr_12 *data12;
7081         uint32_t alloc_len, data_len;
7082         uint8_t format;
7083
7084         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7085
7086         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7087                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7088                 format = ccb10->format;
7089                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7090                 data_len = sizeof(*data10);
7091         } else {
7092                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7093                 format = ccb12->format;
7094                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7095                 data_len = sizeof(*data12);
7096         }
7097         if (alloc_len == 0) {
7098                 ctl_set_success(ctsio);
7099                 ctl_done((union ctl_io *)ctsio);
7100                 return (CTL_RETVAL_COMPLETE);
7101         }
7102
7103         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7104         if (data_len < alloc_len) {
7105                 ctsio->residual = alloc_len - data_len;
7106                 ctsio->kern_data_len = data_len;
7107                 ctsio->kern_total_len = data_len;
7108         } else {
7109                 ctsio->residual = 0;
7110                 ctsio->kern_data_len = alloc_len;
7111                 ctsio->kern_total_len = alloc_len;
7112         }
7113         ctsio->kern_data_resid = 0;
7114         ctsio->kern_rel_offset = 0;
7115         ctsio->kern_sg_entries = 0;
7116
7117         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7118                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7119                     ctsio->kern_data_ptr;
7120                 data10->format = format;
7121                 scsi_ulto2b(0, data10->length);
7122         } else {
7123                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7124                     ctsio->kern_data_ptr;
7125                 data12->format = format;
7126                 scsi_ulto2b(0, data12->generation);
7127                 scsi_ulto4b(0, data12->length);
7128         }
7129
7130         ctl_set_success(ctsio);
7131         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7132         ctsio->be_move_done = ctl_config_move_done;
7133         ctl_datamove((union ctl_io *)ctsio);
7134         return (CTL_RETVAL_COMPLETE);
7135 }
7136
7137 int
7138 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7139 {
7140         struct scsi_maintenance_in *cdb;
7141         int retval;
7142         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7143         int num_target_port_groups, num_target_ports;
7144         struct ctl_lun *lun;
7145         struct ctl_softc *softc;
7146         struct ctl_port *port;
7147         struct scsi_target_group_data *rtg_ptr;
7148         struct scsi_target_group_data_extended *rtg_ext_ptr;
7149         struct scsi_target_port_group_descriptor *tpg_desc;
7150
7151         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7152
7153         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7154         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7155         softc = lun->ctl_softc;
7156
7157         retval = CTL_RETVAL_COMPLETE;
7158
7159         switch (cdb->byte2 & STG_PDF_MASK) {
7160         case STG_PDF_LENGTH:
7161                 ext = 0;
7162                 break;
7163         case STG_PDF_EXTENDED:
7164                 ext = 1;
7165                 break;
7166         default:
7167                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7168                                       /*sks_valid*/ 1,
7169                                       /*command*/ 1,
7170                                       /*field*/ 2,
7171                                       /*bit_valid*/ 1,
7172                                       /*bit*/ 5);
7173                 ctl_done((union ctl_io *)ctsio);
7174                 return(retval);
7175         }
7176
7177         if (softc->is_single)
7178                 num_target_port_groups = 1;
7179         else
7180                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7181         num_target_ports = 0;
7182         mtx_lock(&softc->ctl_lock);
7183         STAILQ_FOREACH(port, &softc->port_list, links) {
7184                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7185                         continue;
7186                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7187                         continue;
7188                 num_target_ports++;
7189         }
7190         mtx_unlock(&softc->ctl_lock);
7191
7192         if (ext)
7193                 total_len = sizeof(struct scsi_target_group_data_extended);
7194         else
7195                 total_len = sizeof(struct scsi_target_group_data);
7196         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7197                 num_target_port_groups +
7198             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7199
7200         alloc_len = scsi_4btoul(cdb->length);
7201
7202         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7203
7204         ctsio->kern_sg_entries = 0;
7205
7206         if (total_len < alloc_len) {
7207                 ctsio->residual = alloc_len - total_len;
7208                 ctsio->kern_data_len = total_len;
7209                 ctsio->kern_total_len = total_len;
7210         } else {
7211                 ctsio->residual = 0;
7212                 ctsio->kern_data_len = alloc_len;
7213                 ctsio->kern_total_len = alloc_len;
7214         }
7215         ctsio->kern_data_resid = 0;
7216         ctsio->kern_rel_offset = 0;
7217
7218         if (ext) {
7219                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7220                     ctsio->kern_data_ptr;
7221                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7222                 rtg_ext_ptr->format_type = 0x10;
7223                 rtg_ext_ptr->implicit_transition_time = 0;
7224                 tpg_desc = &rtg_ext_ptr->groups[0];
7225         } else {
7226                 rtg_ptr = (struct scsi_target_group_data *)
7227                     ctsio->kern_data_ptr;
7228                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7229                 tpg_desc = &rtg_ptr->groups[0];
7230         }
7231
7232         mtx_lock(&softc->ctl_lock);
7233         pg = softc->port_min / softc->port_cnt;
7234         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7235                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7236         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7237                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7238         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7239                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7240         else
7241                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7242         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7243                 os = gs;
7244                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7245         } else
7246                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7247         for (g = 0; g < num_target_port_groups; g++) {
7248                 tpg_desc->pref_state = (g == pg) ? gs : os;
7249                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7250                     TPG_U_SUP | TPG_T_SUP;
7251                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7252                 tpg_desc->status = TPG_IMPLICIT;
7253                 pc = 0;
7254                 STAILQ_FOREACH(port, &softc->port_list, links) {
7255                         if (port->targ_port < g * softc->port_cnt ||
7256                             port->targ_port >= (g + 1) * softc->port_cnt)
7257                                 continue;
7258                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7259                                 continue;
7260                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7261                                 continue;
7262                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7263                             relative_target_port_identifier);
7264                         pc++;
7265                 }
7266                 tpg_desc->target_port_count = pc;
7267                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7268                     &tpg_desc->descriptors[pc];
7269         }
7270         mtx_unlock(&softc->ctl_lock);
7271
7272         ctl_set_success(ctsio);
7273         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7274         ctsio->be_move_done = ctl_config_move_done;
7275         ctl_datamove((union ctl_io *)ctsio);
7276         return(retval);
7277 }
7278
7279 int
7280 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7281 {
7282         struct ctl_lun *lun;
7283         struct scsi_report_supported_opcodes *cdb;
7284         const struct ctl_cmd_entry *entry, *sentry;
7285         struct scsi_report_supported_opcodes_all *all;
7286         struct scsi_report_supported_opcodes_descr *descr;
7287         struct scsi_report_supported_opcodes_one *one;
7288         int retval;
7289         int alloc_len, total_len;
7290         int opcode, service_action, i, j, num;
7291
7292         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7293
7294         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7295         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7296
7297         retval = CTL_RETVAL_COMPLETE;
7298
7299         opcode = cdb->requested_opcode;
7300         service_action = scsi_2btoul(cdb->requested_service_action);
7301         switch (cdb->options & RSO_OPTIONS_MASK) {
7302         case RSO_OPTIONS_ALL:
7303                 num = 0;
7304                 for (i = 0; i < 256; i++) {
7305                         entry = &ctl_cmd_table[i];
7306                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7307                                 for (j = 0; j < 32; j++) {
7308                                         sentry = &((const struct ctl_cmd_entry *)
7309                                             entry->execute)[j];
7310                                         if (ctl_cmd_applicable(
7311                                             lun->be_lun->lun_type, sentry))
7312                                                 num++;
7313                                 }
7314                         } else {
7315                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7316                                     entry))
7317                                         num++;
7318                         }
7319                 }
7320                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7321                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7322                 break;
7323         case RSO_OPTIONS_OC:
7324                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7325                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7326                                               /*sks_valid*/ 1,
7327                                               /*command*/ 1,
7328                                               /*field*/ 2,
7329                                               /*bit_valid*/ 1,
7330                                               /*bit*/ 2);
7331                         ctl_done((union ctl_io *)ctsio);
7332                         return (CTL_RETVAL_COMPLETE);
7333                 }
7334                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7335                 break;
7336         case RSO_OPTIONS_OC_SA:
7337                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7338                     service_action >= 32) {
7339                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7340                                               /*sks_valid*/ 1,
7341                                               /*command*/ 1,
7342                                               /*field*/ 2,
7343                                               /*bit_valid*/ 1,
7344                                               /*bit*/ 2);
7345                         ctl_done((union ctl_io *)ctsio);
7346                         return (CTL_RETVAL_COMPLETE);
7347                 }
7348                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7349                 break;
7350         default:
7351                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7352                                       /*sks_valid*/ 1,
7353                                       /*command*/ 1,
7354                                       /*field*/ 2,
7355                                       /*bit_valid*/ 1,
7356                                       /*bit*/ 2);
7357                 ctl_done((union ctl_io *)ctsio);
7358                 return (CTL_RETVAL_COMPLETE);
7359         }
7360
7361         alloc_len = scsi_4btoul(cdb->length);
7362
7363         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7364
7365         ctsio->kern_sg_entries = 0;
7366
7367         if (total_len < alloc_len) {
7368                 ctsio->residual = alloc_len - total_len;
7369                 ctsio->kern_data_len = total_len;
7370                 ctsio->kern_total_len = total_len;
7371         } else {
7372                 ctsio->residual = 0;
7373                 ctsio->kern_data_len = alloc_len;
7374                 ctsio->kern_total_len = alloc_len;
7375         }
7376         ctsio->kern_data_resid = 0;
7377         ctsio->kern_rel_offset = 0;
7378
7379         switch (cdb->options & RSO_OPTIONS_MASK) {
7380         case RSO_OPTIONS_ALL:
7381                 all = (struct scsi_report_supported_opcodes_all *)
7382                     ctsio->kern_data_ptr;
7383                 num = 0;
7384                 for (i = 0; i < 256; i++) {
7385                         entry = &ctl_cmd_table[i];
7386                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7387                                 for (j = 0; j < 32; j++) {
7388                                         sentry = &((const struct ctl_cmd_entry *)
7389                                             entry->execute)[j];
7390                                         if (!ctl_cmd_applicable(
7391                                             lun->be_lun->lun_type, sentry))
7392                                                 continue;
7393                                         descr = &all->descr[num++];
7394                                         descr->opcode = i;
7395                                         scsi_ulto2b(j, descr->service_action);
7396                                         descr->flags = RSO_SERVACTV;
7397                                         scsi_ulto2b(sentry->length,
7398                                             descr->cdb_length);
7399                                 }
7400                         } else {
7401                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7402                                     entry))
7403                                         continue;
7404                                 descr = &all->descr[num++];
7405                                 descr->opcode = i;
7406                                 scsi_ulto2b(0, descr->service_action);
7407                                 descr->flags = 0;
7408                                 scsi_ulto2b(entry->length, descr->cdb_length);
7409                         }
7410                 }
7411                 scsi_ulto4b(
7412                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7413                     all->length);
7414                 break;
7415         case RSO_OPTIONS_OC:
7416                 one = (struct scsi_report_supported_opcodes_one *)
7417                     ctsio->kern_data_ptr;
7418                 entry = &ctl_cmd_table[opcode];
7419                 goto fill_one;
7420         case RSO_OPTIONS_OC_SA:
7421                 one = (struct scsi_report_supported_opcodes_one *)
7422                     ctsio->kern_data_ptr;
7423                 entry = &ctl_cmd_table[opcode];
7424                 entry = &((const struct ctl_cmd_entry *)
7425                     entry->execute)[service_action];
7426 fill_one:
7427                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7428                         one->support = 3;
7429                         scsi_ulto2b(entry->length, one->cdb_length);
7430                         one->cdb_usage[0] = opcode;
7431                         memcpy(&one->cdb_usage[1], entry->usage,
7432                             entry->length - 1);
7433                 } else
7434                         one->support = 1;
7435                 break;
7436         }
7437
7438         ctl_set_success(ctsio);
7439         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7440         ctsio->be_move_done = ctl_config_move_done;
7441         ctl_datamove((union ctl_io *)ctsio);
7442         return(retval);
7443 }
7444
7445 int
7446 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7447 {
7448         struct scsi_report_supported_tmf *cdb;
7449         struct scsi_report_supported_tmf_data *data;
7450         int retval;
7451         int alloc_len, total_len;
7452
7453         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7454
7455         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7456
7457         retval = CTL_RETVAL_COMPLETE;
7458
7459         total_len = sizeof(struct scsi_report_supported_tmf_data);
7460         alloc_len = scsi_4btoul(cdb->length);
7461
7462         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7463
7464         ctsio->kern_sg_entries = 0;
7465
7466         if (total_len < alloc_len) {
7467                 ctsio->residual = alloc_len - total_len;
7468                 ctsio->kern_data_len = total_len;
7469                 ctsio->kern_total_len = total_len;
7470         } else {
7471                 ctsio->residual = 0;
7472                 ctsio->kern_data_len = alloc_len;
7473                 ctsio->kern_total_len = alloc_len;
7474         }
7475         ctsio->kern_data_resid = 0;
7476         ctsio->kern_rel_offset = 0;
7477
7478         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7479         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7480             RST_TRS;
7481         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7482
7483         ctl_set_success(ctsio);
7484         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7485         ctsio->be_move_done = ctl_config_move_done;
7486         ctl_datamove((union ctl_io *)ctsio);
7487         return (retval);
7488 }
7489
7490 int
7491 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7492 {
7493         struct scsi_report_timestamp *cdb;
7494         struct scsi_report_timestamp_data *data;
7495         struct timeval tv;
7496         int64_t timestamp;
7497         int retval;
7498         int alloc_len, total_len;
7499
7500         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7501
7502         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7503
7504         retval = CTL_RETVAL_COMPLETE;
7505
7506         total_len = sizeof(struct scsi_report_timestamp_data);
7507         alloc_len = scsi_4btoul(cdb->length);
7508
7509         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7510
7511         ctsio->kern_sg_entries = 0;
7512
7513         if (total_len < alloc_len) {
7514                 ctsio->residual = alloc_len - total_len;
7515                 ctsio->kern_data_len = total_len;
7516                 ctsio->kern_total_len = total_len;
7517         } else {
7518                 ctsio->residual = 0;
7519                 ctsio->kern_data_len = alloc_len;
7520                 ctsio->kern_total_len = alloc_len;
7521         }
7522         ctsio->kern_data_resid = 0;
7523         ctsio->kern_rel_offset = 0;
7524
7525         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7526         scsi_ulto2b(sizeof(*data) - 2, data->length);
7527         data->origin = RTS_ORIG_OUTSIDE;
7528         getmicrotime(&tv);
7529         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7530         scsi_ulto4b(timestamp >> 16, data->timestamp);
7531         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7532
7533         ctl_set_success(ctsio);
7534         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7535         ctsio->be_move_done = ctl_config_move_done;
7536         ctl_datamove((union ctl_io *)ctsio);
7537         return (retval);
7538 }
7539
7540 int
7541 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7542 {
7543         struct scsi_per_res_in *cdb;
7544         int alloc_len, total_len = 0;
7545         /* struct scsi_per_res_in_rsrv in_data; */
7546         struct ctl_lun *lun;
7547         struct ctl_softc *softc;
7548         uint64_t key;
7549
7550         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7551
7552         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7553
7554         alloc_len = scsi_2btoul(cdb->length);
7555
7556         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7557         softc = lun->ctl_softc;
7558
7559 retry:
7560         mtx_lock(&lun->lun_lock);
7561         switch (cdb->action) {
7562         case SPRI_RK: /* read keys */
7563                 total_len = sizeof(struct scsi_per_res_in_keys) +
7564                         lun->pr_key_count *
7565                         sizeof(struct scsi_per_res_key);
7566                 break;
7567         case SPRI_RR: /* read reservation */
7568                 if (lun->flags & CTL_LUN_PR_RESERVED)
7569                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7570                 else
7571                         total_len = sizeof(struct scsi_per_res_in_header);
7572                 break;
7573         case SPRI_RC: /* report capabilities */
7574                 total_len = sizeof(struct scsi_per_res_cap);
7575                 break;
7576         case SPRI_RS: /* read full status */
7577                 total_len = sizeof(struct scsi_per_res_in_header) +
7578                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7579                     lun->pr_key_count;
7580                 break;
7581         default:
7582                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7583         }
7584         mtx_unlock(&lun->lun_lock);
7585
7586         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7587
7588         if (total_len < alloc_len) {
7589                 ctsio->residual = alloc_len - total_len;
7590                 ctsio->kern_data_len = total_len;
7591                 ctsio->kern_total_len = total_len;
7592         } else {
7593                 ctsio->residual = 0;
7594                 ctsio->kern_data_len = alloc_len;
7595                 ctsio->kern_total_len = alloc_len;
7596         }
7597
7598         ctsio->kern_data_resid = 0;
7599         ctsio->kern_rel_offset = 0;
7600         ctsio->kern_sg_entries = 0;
7601
7602         mtx_lock(&lun->lun_lock);
7603         switch (cdb->action) {
7604         case SPRI_RK: { // read keys
7605         struct scsi_per_res_in_keys *res_keys;
7606                 int i, key_count;
7607
7608                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7609
7610                 /*
7611                  * We had to drop the lock to allocate our buffer, which
7612                  * leaves time for someone to come in with another
7613                  * persistent reservation.  (That is unlikely, though,
7614                  * since this should be the only persistent reservation
7615                  * command active right now.)
7616                  */
7617                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7618                     (lun->pr_key_count *
7619                      sizeof(struct scsi_per_res_key)))){
7620                         mtx_unlock(&lun->lun_lock);
7621                         free(ctsio->kern_data_ptr, M_CTL);
7622                         printf("%s: reservation length changed, retrying\n",
7623                                __func__);
7624                         goto retry;
7625                 }
7626
7627                 scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7628
7629                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7630                              lun->pr_key_count, res_keys->header.length);
7631
7632                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7633                         if ((key = ctl_get_prkey(lun, i)) == 0)
7634                                 continue;
7635
7636                         /*
7637                          * We used lun->pr_key_count to calculate the
7638                          * size to allocate.  If it turns out the number of
7639                          * initiators with the registered flag set is
7640                          * larger than that (i.e. they haven't been kept in
7641                          * sync), we've got a problem.
7642                          */
7643                         if (key_count >= lun->pr_key_count) {
7644                                 key_count++;
7645                                 continue;
7646                         }
7647                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7648                         key_count++;
7649                 }
7650                 break;
7651         }
7652         case SPRI_RR: { // read reservation
7653                 struct scsi_per_res_in_rsrv *res;
7654                 int tmp_len, header_only;
7655
7656                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7657
7658                 scsi_ulto4b(lun->pr_generation, res->header.generation);
7659
7660                 if (lun->flags & CTL_LUN_PR_RESERVED)
7661                 {
7662                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7663                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7664                                     res->header.length);
7665                         header_only = 0;
7666                 } else {
7667                         tmp_len = sizeof(struct scsi_per_res_in_header);
7668                         scsi_ulto4b(0, res->header.length);
7669                         header_only = 1;
7670                 }
7671
7672                 /*
7673                  * We had to drop the lock to allocate our buffer, which
7674                  * leaves time for someone to come in with another
7675                  * persistent reservation.  (That is unlikely, though,
7676                  * since this should be the only persistent reservation
7677                  * command active right now.)
7678                  */
7679                 if (tmp_len != total_len) {
7680                         mtx_unlock(&lun->lun_lock);
7681                         free(ctsio->kern_data_ptr, M_CTL);
7682                         printf("%s: reservation status changed, retrying\n",
7683                                __func__);
7684                         goto retry;
7685                 }
7686
7687                 /*
7688                  * No reservation held, so we're done.
7689                  */
7690                 if (header_only != 0)
7691                         break;
7692
7693                 /*
7694                  * If the registration is an All Registrants type, the key
7695                  * is 0, since it doesn't really matter.
7696                  */
7697                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7698                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7699                             res->data.reservation);
7700                 }
7701                 res->data.scopetype = lun->pr_res_type;
7702                 break;
7703         }
7704         case SPRI_RC:     //report capabilities
7705         {
7706                 struct scsi_per_res_cap *res_cap;
7707                 uint16_t type_mask;
7708
7709                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7710                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7711                 res_cap->flags1 = SPRI_CRH;
7712                 res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7713                 type_mask = SPRI_TM_WR_EX_AR |
7714                             SPRI_TM_EX_AC_RO |
7715                             SPRI_TM_WR_EX_RO |
7716                             SPRI_TM_EX_AC |
7717                             SPRI_TM_WR_EX |
7718                             SPRI_TM_EX_AC_AR;
7719                 scsi_ulto2b(type_mask, res_cap->type_mask);
7720                 break;
7721         }
7722         case SPRI_RS: { // read full status
7723                 struct scsi_per_res_in_full *res_status;
7724                 struct scsi_per_res_in_full_desc *res_desc;
7725                 struct ctl_port *port;
7726                 int i, len;
7727
7728                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7729
7730                 /*
7731                  * We had to drop the lock to allocate our buffer, which
7732                  * leaves time for someone to come in with another
7733                  * persistent reservation.  (That is unlikely, though,
7734                  * since this should be the only persistent reservation
7735                  * command active right now.)
7736                  */
7737                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7738                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7739                      lun->pr_key_count)){
7740                         mtx_unlock(&lun->lun_lock);
7741                         free(ctsio->kern_data_ptr, M_CTL);
7742                         printf("%s: reservation length changed, retrying\n",
7743                                __func__);
7744                         goto retry;
7745                 }
7746
7747                 scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7748
7749                 res_desc = &res_status->desc[0];
7750                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7751                         if ((key = ctl_get_prkey(lun, i)) == 0)
7752                                 continue;
7753
7754                         scsi_u64to8b(key, res_desc->res_key.key);
7755                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7756                             (lun->pr_res_idx == i ||
7757                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7758                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7759                                 res_desc->scopetype = lun->pr_res_type;
7760                         }
7761                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7762                             res_desc->rel_trgt_port_id);
7763                         len = 0;
7764                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7765                         if (port != NULL)
7766                                 len = ctl_create_iid(port,
7767                                     i % CTL_MAX_INIT_PER_PORT,
7768                                     res_desc->transport_id);
7769                         scsi_ulto4b(len, res_desc->additional_length);
7770                         res_desc = (struct scsi_per_res_in_full_desc *)
7771                             &res_desc->transport_id[len];
7772                 }
7773                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7774                     res_status->header.length);
7775                 break;
7776         }
7777         default:
7778                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
7779         }
7780         mtx_unlock(&lun->lun_lock);
7781
7782         ctl_set_success(ctsio);
7783         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7784         ctsio->be_move_done = ctl_config_move_done;
7785         ctl_datamove((union ctl_io *)ctsio);
7786         return (CTL_RETVAL_COMPLETE);
7787 }
7788
7789 /*
7790  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7791  * it should return.
7792  */
7793 static int
7794 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7795                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7796                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7797                 struct scsi_per_res_out_parms* param)
7798 {
7799         union ctl_ha_msg persis_io;
7800         int i;
7801
7802         mtx_lock(&lun->lun_lock);
7803         if (sa_res_key == 0) {
7804                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7805                         /* validate scope and type */
7806                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7807                              SPR_LU_SCOPE) {
7808                                 mtx_unlock(&lun->lun_lock);
7809                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7810                                                       /*sks_valid*/ 1,
7811                                                       /*command*/ 1,
7812                                                       /*field*/ 2,
7813                                                       /*bit_valid*/ 1,
7814                                                       /*bit*/ 4);
7815                                 ctl_done((union ctl_io *)ctsio);
7816                                 return (1);
7817                         }
7818
7819                         if (type>8 || type==2 || type==4 || type==0) {
7820                                 mtx_unlock(&lun->lun_lock);
7821                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7822                                                       /*sks_valid*/ 1,
7823                                                       /*command*/ 1,
7824                                                       /*field*/ 2,
7825                                                       /*bit_valid*/ 1,
7826                                                       /*bit*/ 0);
7827                                 ctl_done((union ctl_io *)ctsio);
7828                                 return (1);
7829                         }
7830
7831                         /*
7832                          * Unregister everybody else and build UA for
7833                          * them
7834                          */
7835                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7836                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7837                                         continue;
7838
7839                                 ctl_clr_prkey(lun, i);
7840                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7841                         }
7842                         lun->pr_key_count = 1;
7843                         lun->pr_res_type = type;
7844                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7845                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7846                                 lun->pr_res_idx = residx;
7847                         lun->pr_generation++;
7848                         mtx_unlock(&lun->lun_lock);
7849
7850                         /* send msg to other side */
7851                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7852                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7853                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7854                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7855                         persis_io.pr.pr_info.res_type = type;
7856                         memcpy(persis_io.pr.pr_info.sa_res_key,
7857                                param->serv_act_res_key,
7858                                sizeof(param->serv_act_res_key));
7859                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7860                             sizeof(persis_io.pr), M_WAITOK);
7861                 } else {
7862                         /* not all registrants */
7863                         mtx_unlock(&lun->lun_lock);
7864                         free(ctsio->kern_data_ptr, M_CTL);
7865                         ctl_set_invalid_field(ctsio,
7866                                               /*sks_valid*/ 1,
7867                                               /*command*/ 0,
7868                                               /*field*/ 8,
7869                                               /*bit_valid*/ 0,
7870                                               /*bit*/ 0);
7871                         ctl_done((union ctl_io *)ctsio);
7872                         return (1);
7873                 }
7874         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7875                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7876                 int found = 0;
7877
7878                 if (res_key == sa_res_key) {
7879                         /* special case */
7880                         /*
7881                          * The spec implies this is not good but doesn't
7882                          * say what to do. There are two choices either
7883                          * generate a res conflict or check condition
7884                          * with illegal field in parameter data. Since
7885                          * that is what is done when the sa_res_key is
7886                          * zero I'll take that approach since this has
7887                          * to do with the sa_res_key.
7888                          */
7889                         mtx_unlock(&lun->lun_lock);
7890                         free(ctsio->kern_data_ptr, M_CTL);
7891                         ctl_set_invalid_field(ctsio,
7892                                               /*sks_valid*/ 1,
7893                                               /*command*/ 0,
7894                                               /*field*/ 8,
7895                                               /*bit_valid*/ 0,
7896                                               /*bit*/ 0);
7897                         ctl_done((union ctl_io *)ctsio);
7898                         return (1);
7899                 }
7900
7901                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7902                         if (ctl_get_prkey(lun, i) != sa_res_key)
7903                                 continue;
7904
7905                         found = 1;
7906                         ctl_clr_prkey(lun, i);
7907                         lun->pr_key_count--;
7908                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7909                 }
7910                 if (!found) {
7911                         mtx_unlock(&lun->lun_lock);
7912                         free(ctsio->kern_data_ptr, M_CTL);
7913                         ctl_set_reservation_conflict(ctsio);
7914                         ctl_done((union ctl_io *)ctsio);
7915                         return (CTL_RETVAL_COMPLETE);
7916                 }
7917                 lun->pr_generation++;
7918                 mtx_unlock(&lun->lun_lock);
7919
7920                 /* send msg to other side */
7921                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7922                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7923                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7924                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7925                 persis_io.pr.pr_info.res_type = type;
7926                 memcpy(persis_io.pr.pr_info.sa_res_key,
7927                        param->serv_act_res_key,
7928                        sizeof(param->serv_act_res_key));
7929                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7930                     sizeof(persis_io.pr), M_WAITOK);
7931         } else {
7932                 /* Reserved but not all registrants */
7933                 /* sa_res_key is res holder */
7934                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7935                         /* validate scope and type */
7936                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7937                              SPR_LU_SCOPE) {
7938                                 mtx_unlock(&lun->lun_lock);
7939                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7940                                                       /*sks_valid*/ 1,
7941                                                       /*command*/ 1,
7942                                                       /*field*/ 2,
7943                                                       /*bit_valid*/ 1,
7944                                                       /*bit*/ 4);
7945                                 ctl_done((union ctl_io *)ctsio);
7946                                 return (1);
7947                         }
7948
7949                         if (type>8 || type==2 || type==4 || type==0) {
7950                                 mtx_unlock(&lun->lun_lock);
7951                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7952                                                       /*sks_valid*/ 1,
7953                                                       /*command*/ 1,
7954                                                       /*field*/ 2,
7955                                                       /*bit_valid*/ 1,
7956                                                       /*bit*/ 0);
7957                                 ctl_done((union ctl_io *)ctsio);
7958                                 return (1);
7959                         }
7960
7961                         /*
7962                          * Do the following:
7963                          * if sa_res_key != res_key remove all
7964                          * registrants w/sa_res_key and generate UA
7965                          * for these registrants(Registrations
7966                          * Preempted) if it wasn't an exclusive
7967                          * reservation generate UA(Reservations
7968                          * Preempted) for all other registered nexuses
7969                          * if the type has changed. Establish the new
7970                          * reservation and holder. If res_key and
7971                          * sa_res_key are the same do the above
7972                          * except don't unregister the res holder.
7973                          */
7974
7975                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7976                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7977                                         continue;
7978
7979                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7980                                         ctl_clr_prkey(lun, i);
7981                                         lun->pr_key_count--;
7982                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7983                                 } else if (type != lun->pr_res_type &&
7984                                     (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7985                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7986                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7987                                 }
7988                         }
7989                         lun->pr_res_type = type;
7990                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7991                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7992                                 lun->pr_res_idx = residx;
7993                         else
7994                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7995                         lun->pr_generation++;
7996                         mtx_unlock(&lun->lun_lock);
7997
7998                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7999                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8000                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8001                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8002                         persis_io.pr.pr_info.res_type = type;
8003                         memcpy(persis_io.pr.pr_info.sa_res_key,
8004                                param->serv_act_res_key,
8005                                sizeof(param->serv_act_res_key));
8006                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8007                             sizeof(persis_io.pr), M_WAITOK);
8008                 } else {
8009                         /*
8010                          * sa_res_key is not the res holder just
8011                          * remove registrants
8012                          */
8013                         int found=0;
8014
8015                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8016                                 if (sa_res_key != ctl_get_prkey(lun, i))
8017                                         continue;
8018
8019                                 found = 1;
8020                                 ctl_clr_prkey(lun, i);
8021                                 lun->pr_key_count--;
8022                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8023                         }
8024
8025                         if (!found) {
8026                                 mtx_unlock(&lun->lun_lock);
8027                                 free(ctsio->kern_data_ptr, M_CTL);
8028                                 ctl_set_reservation_conflict(ctsio);
8029                                 ctl_done((union ctl_io *)ctsio);
8030                                 return (1);
8031                         }
8032                         lun->pr_generation++;
8033                         mtx_unlock(&lun->lun_lock);
8034
8035                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8036                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8037                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8038                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8039                         persis_io.pr.pr_info.res_type = type;
8040                         memcpy(persis_io.pr.pr_info.sa_res_key,
8041                                param->serv_act_res_key,
8042                                sizeof(param->serv_act_res_key));
8043                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8044                             sizeof(persis_io.pr), M_WAITOK);
8045                 }
8046         }
8047         return (0);
8048 }
8049
8050 static void
8051 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8052 {
8053         uint64_t sa_res_key;
8054         int i;
8055
8056         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8057
8058         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8059          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8060          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8061                 if (sa_res_key == 0) {
8062                         /*
8063                          * Unregister everybody else and build UA for
8064                          * them
8065                          */
8066                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8067                                 if (i == msg->pr.pr_info.residx ||
8068                                     ctl_get_prkey(lun, i) == 0)
8069                                         continue;
8070
8071                                 ctl_clr_prkey(lun, i);
8072                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8073                         }
8074
8075                         lun->pr_key_count = 1;
8076                         lun->pr_res_type = msg->pr.pr_info.res_type;
8077                         if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8078                             lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8079                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8080                 } else {
8081                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8082                                 if (sa_res_key == ctl_get_prkey(lun, i))
8083                                         continue;
8084
8085                                 ctl_clr_prkey(lun, i);
8086                                 lun->pr_key_count--;
8087                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8088                         }
8089                 }
8090         } else {
8091                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8092                         if (i == msg->pr.pr_info.residx ||
8093                             ctl_get_prkey(lun, i) == 0)
8094                                 continue;
8095
8096                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8097                                 ctl_clr_prkey(lun, i);
8098                                 lun->pr_key_count--;
8099                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8100                         } else if (msg->pr.pr_info.res_type != lun->pr_res_type
8101                             && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8102                              lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8103                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8104                         }
8105                 }
8106                 lun->pr_res_type = msg->pr.pr_info.res_type;
8107                 if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8108                     lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8109                         lun->pr_res_idx = msg->pr.pr_info.residx;
8110                 else
8111                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8112         }
8113         lun->pr_generation++;
8114
8115 }
8116
8117
8118 int
8119 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8120 {
8121         int retval;
8122         u_int32_t param_len;
8123         struct scsi_per_res_out *cdb;
8124         struct ctl_lun *lun;
8125         struct scsi_per_res_out_parms* param;
8126         struct ctl_softc *softc;
8127         uint32_t residx;
8128         uint64_t res_key, sa_res_key, key;
8129         uint8_t type;
8130         union ctl_ha_msg persis_io;
8131         int    i;
8132
8133         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8134
8135         retval = CTL_RETVAL_COMPLETE;
8136
8137         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8138         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8139         softc = lun->ctl_softc;
8140
8141         /*
8142          * We only support whole-LUN scope.  The scope & type are ignored for
8143          * register, register and ignore existing key and clear.
8144          * We sometimes ignore scope and type on preempts too!!
8145          * Verify reservation type here as well.
8146          */
8147         type = cdb->scope_type & SPR_TYPE_MASK;
8148         if ((cdb->action == SPRO_RESERVE)
8149          || (cdb->action == SPRO_RELEASE)) {
8150                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8151                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8152                                               /*sks_valid*/ 1,
8153                                               /*command*/ 1,
8154                                               /*field*/ 2,
8155                                               /*bit_valid*/ 1,
8156                                               /*bit*/ 4);
8157                         ctl_done((union ctl_io *)ctsio);
8158                         return (CTL_RETVAL_COMPLETE);
8159                 }
8160
8161                 if (type>8 || type==2 || type==4 || type==0) {
8162                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8163                                               /*sks_valid*/ 1,
8164                                               /*command*/ 1,
8165                                               /*field*/ 2,
8166                                               /*bit_valid*/ 1,
8167                                               /*bit*/ 0);
8168                         ctl_done((union ctl_io *)ctsio);
8169                         return (CTL_RETVAL_COMPLETE);
8170                 }
8171         }
8172
8173         param_len = scsi_4btoul(cdb->length);
8174
8175         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8176                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8177                 ctsio->kern_data_len = param_len;
8178                 ctsio->kern_total_len = param_len;
8179                 ctsio->kern_data_resid = 0;
8180                 ctsio->kern_rel_offset = 0;
8181                 ctsio->kern_sg_entries = 0;
8182                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8183                 ctsio->be_move_done = ctl_config_move_done;
8184                 ctl_datamove((union ctl_io *)ctsio);
8185
8186                 return (CTL_RETVAL_COMPLETE);
8187         }
8188
8189         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8190
8191         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8192         res_key = scsi_8btou64(param->res_key.key);
8193         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8194
8195         /*
8196          * Validate the reservation key here except for SPRO_REG_IGNO
8197          * This must be done for all other service actions
8198          */
8199         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8200                 mtx_lock(&lun->lun_lock);
8201                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8202                         if (res_key != key) {
8203                                 /*
8204                                  * The current key passed in doesn't match
8205                                  * the one the initiator previously
8206                                  * registered.
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                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8215                         /*
8216                          * We are not registered
8217                          */
8218                         mtx_unlock(&lun->lun_lock);
8219                         free(ctsio->kern_data_ptr, M_CTL);
8220                         ctl_set_reservation_conflict(ctsio);
8221                         ctl_done((union ctl_io *)ctsio);
8222                         return (CTL_RETVAL_COMPLETE);
8223                 } else if (res_key != 0) {
8224                         /*
8225                          * We are not registered and trying to register but
8226                          * the register key isn't zero.
8227                          */
8228                         mtx_unlock(&lun->lun_lock);
8229                         free(ctsio->kern_data_ptr, M_CTL);
8230                         ctl_set_reservation_conflict(ctsio);
8231                         ctl_done((union ctl_io *)ctsio);
8232                         return (CTL_RETVAL_COMPLETE);
8233                 }
8234                 mtx_unlock(&lun->lun_lock);
8235         }
8236
8237         switch (cdb->action & SPRO_ACTION_MASK) {
8238         case SPRO_REGISTER:
8239         case SPRO_REG_IGNO: {
8240
8241 #if 0
8242                 printf("Registration received\n");
8243 #endif
8244
8245                 /*
8246                  * We don't support any of these options, as we report in
8247                  * the read capabilities request (see
8248                  * ctl_persistent_reserve_in(), above).
8249                  */
8250                 if ((param->flags & SPR_SPEC_I_PT)
8251                  || (param->flags & SPR_ALL_TG_PT)
8252                  || (param->flags & SPR_APTPL)) {
8253                         int bit_ptr;
8254
8255                         if (param->flags & SPR_APTPL)
8256                                 bit_ptr = 0;
8257                         else if (param->flags & SPR_ALL_TG_PT)
8258                                 bit_ptr = 2;
8259                         else /* SPR_SPEC_I_PT */
8260                                 bit_ptr = 3;
8261
8262                         free(ctsio->kern_data_ptr, M_CTL);
8263                         ctl_set_invalid_field(ctsio,
8264                                               /*sks_valid*/ 1,
8265                                               /*command*/ 0,
8266                                               /*field*/ 20,
8267                                               /*bit_valid*/ 1,
8268                                               /*bit*/ bit_ptr);
8269                         ctl_done((union ctl_io *)ctsio);
8270                         return (CTL_RETVAL_COMPLETE);
8271                 }
8272
8273                 mtx_lock(&lun->lun_lock);
8274
8275                 /*
8276                  * The initiator wants to clear the
8277                  * key/unregister.
8278                  */
8279                 if (sa_res_key == 0) {
8280                         if ((res_key == 0
8281                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8282                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8283                           && ctl_get_prkey(lun, residx) == 0)) {
8284                                 mtx_unlock(&lun->lun_lock);
8285                                 goto done;
8286                         }
8287
8288                         ctl_clr_prkey(lun, residx);
8289                         lun->pr_key_count--;
8290
8291                         if (residx == lun->pr_res_idx) {
8292                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8293                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8294
8295                                 if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8296                                      lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8297                                     lun->pr_key_count) {
8298                                         /*
8299                                          * If the reservation is a registrants
8300                                          * only type we need to generate a UA
8301                                          * for other registered inits.  The
8302                                          * sense code should be RESERVATIONS
8303                                          * RELEASED
8304                                          */
8305
8306                                         for (i = softc->init_min; i < softc->init_max; i++){
8307                                                 if (ctl_get_prkey(lun, i) == 0)
8308                                                         continue;
8309                                                 ctl_est_ua(lun, i,
8310                                                     CTL_UA_RES_RELEASE);
8311                                         }
8312                                 }
8313                                 lun->pr_res_type = 0;
8314                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8315                                 if (lun->pr_key_count==0) {
8316                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8317                                         lun->pr_res_type = 0;
8318                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8319                                 }
8320                         }
8321                         lun->pr_generation++;
8322                         mtx_unlock(&lun->lun_lock);
8323
8324                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8325                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8326                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8327                         persis_io.pr.pr_info.residx = residx;
8328                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8329                             sizeof(persis_io.pr), M_WAITOK);
8330                 } else /* sa_res_key != 0 */ {
8331
8332                         /*
8333                          * If we aren't registered currently then increment
8334                          * the key count and set the registered flag.
8335                          */
8336                         ctl_alloc_prkey(lun, residx);
8337                         if (ctl_get_prkey(lun, residx) == 0)
8338                                 lun->pr_key_count++;
8339                         ctl_set_prkey(lun, residx, sa_res_key);
8340                         lun->pr_generation++;
8341                         mtx_unlock(&lun->lun_lock);
8342
8343                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8344                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8345                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8346                         persis_io.pr.pr_info.residx = residx;
8347                         memcpy(persis_io.pr.pr_info.sa_res_key,
8348                                param->serv_act_res_key,
8349                                sizeof(param->serv_act_res_key));
8350                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8351                             sizeof(persis_io.pr), M_WAITOK);
8352                 }
8353
8354                 break;
8355         }
8356         case SPRO_RESERVE:
8357 #if 0
8358                 printf("Reserve executed type %d\n", type);
8359 #endif
8360                 mtx_lock(&lun->lun_lock);
8361                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8362                         /*
8363                          * if this isn't the reservation holder and it's
8364                          * not a "all registrants" type or if the type is
8365                          * different then we have a conflict
8366                          */
8367                         if ((lun->pr_res_idx != residx
8368                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8369                          || lun->pr_res_type != type) {
8370                                 mtx_unlock(&lun->lun_lock);
8371                                 free(ctsio->kern_data_ptr, M_CTL);
8372                                 ctl_set_reservation_conflict(ctsio);
8373                                 ctl_done((union ctl_io *)ctsio);
8374                                 return (CTL_RETVAL_COMPLETE);
8375                         }
8376                         mtx_unlock(&lun->lun_lock);
8377                 } else /* create a reservation */ {
8378                         /*
8379                          * If it's not an "all registrants" type record
8380                          * reservation holder
8381                          */
8382                         if (type != SPR_TYPE_WR_EX_AR
8383                          && type != SPR_TYPE_EX_AC_AR)
8384                                 lun->pr_res_idx = residx; /* Res holder */
8385                         else
8386                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8387
8388                         lun->flags |= CTL_LUN_PR_RESERVED;
8389                         lun->pr_res_type = type;
8390
8391                         mtx_unlock(&lun->lun_lock);
8392
8393                         /* send msg to other side */
8394                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8395                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8396                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8397                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8398                         persis_io.pr.pr_info.res_type = type;
8399                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8400                             sizeof(persis_io.pr), M_WAITOK);
8401                 }
8402                 break;
8403
8404         case SPRO_RELEASE:
8405                 mtx_lock(&lun->lun_lock);
8406                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8407                         /* No reservation exists return good status */
8408                         mtx_unlock(&lun->lun_lock);
8409                         goto done;
8410                 }
8411                 /*
8412                  * Is this nexus a reservation holder?
8413                  */
8414                 if (lun->pr_res_idx != residx
8415                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8416                         /*
8417                          * not a res holder return good status but
8418                          * do nothing
8419                          */
8420                         mtx_unlock(&lun->lun_lock);
8421                         goto done;
8422                 }
8423
8424                 if (lun->pr_res_type != type) {
8425                         mtx_unlock(&lun->lun_lock);
8426                         free(ctsio->kern_data_ptr, M_CTL);
8427                         ctl_set_illegal_pr_release(ctsio);
8428                         ctl_done((union ctl_io *)ctsio);
8429                         return (CTL_RETVAL_COMPLETE);
8430                 }
8431
8432                 /* okay to release */
8433                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8434                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8435                 lun->pr_res_type = 0;
8436
8437                 /*
8438                  * if this isn't an exclusive access
8439                  * res generate UA for all other
8440                  * registrants.
8441                  */
8442                 if (type != SPR_TYPE_EX_AC
8443                  && type != SPR_TYPE_WR_EX) {
8444                         for (i = softc->init_min; i < softc->init_max; i++) {
8445                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8446                                         continue;
8447                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8448                         }
8449                 }
8450                 mtx_unlock(&lun->lun_lock);
8451
8452                 /* Send msg to other side */
8453                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8454                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8455                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8456                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8457                      sizeof(persis_io.pr), M_WAITOK);
8458                 break;
8459
8460         case SPRO_CLEAR:
8461                 /* send msg to other side */
8462
8463                 mtx_lock(&lun->lun_lock);
8464                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8465                 lun->pr_res_type = 0;
8466                 lun->pr_key_count = 0;
8467                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8468
8469                 ctl_clr_prkey(lun, residx);
8470                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8471                         if (ctl_get_prkey(lun, i) != 0) {
8472                                 ctl_clr_prkey(lun, i);
8473                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8474                         }
8475                 lun->pr_generation++;
8476                 mtx_unlock(&lun->lun_lock);
8477
8478                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8479                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8480                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8481                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8482                      sizeof(persis_io.pr), M_WAITOK);
8483                 break;
8484
8485         case SPRO_PREEMPT:
8486         case SPRO_PRE_ABO: {
8487                 int nretval;
8488
8489                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8490                                           residx, ctsio, cdb, param);
8491                 if (nretval != 0)
8492                         return (CTL_RETVAL_COMPLETE);
8493                 break;
8494         }
8495         default:
8496                 panic("%s: Invalid PR type %#x", __func__, cdb->action);
8497         }
8498
8499 done:
8500         free(ctsio->kern_data_ptr, M_CTL);
8501         ctl_set_success(ctsio);
8502         ctl_done((union ctl_io *)ctsio);
8503
8504         return (retval);
8505 }
8506
8507 /*
8508  * This routine is for handling a message from the other SC pertaining to
8509  * persistent reserve out. All the error checking will have been done
8510  * so only perorming the action need be done here to keep the two
8511  * in sync.
8512  */
8513 static void
8514 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8515 {
8516         struct ctl_softc *softc = control_softc;
8517         struct ctl_lun *lun;
8518         int i;
8519         uint32_t residx, targ_lun;
8520
8521         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8522         mtx_lock(&softc->ctl_lock);
8523         if ((targ_lun >= CTL_MAX_LUNS) ||
8524             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8525                 mtx_unlock(&softc->ctl_lock);
8526                 return;
8527         }
8528         mtx_lock(&lun->lun_lock);
8529         mtx_unlock(&softc->ctl_lock);
8530         if (lun->flags & CTL_LUN_DISABLED) {
8531                 mtx_unlock(&lun->lun_lock);
8532                 return;
8533         }
8534         residx = ctl_get_initindex(&msg->hdr.nexus);
8535         switch(msg->pr.pr_info.action) {
8536         case CTL_PR_REG_KEY:
8537                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8538                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8539                         lun->pr_key_count++;
8540                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8541                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8542                 lun->pr_generation++;
8543                 break;
8544
8545         case CTL_PR_UNREG_KEY:
8546                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8547                 lun->pr_key_count--;
8548
8549                 /* XXX Need to see if the reservation has been released */
8550                 /* if so do we need to generate UA? */
8551                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8552                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8553                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8554
8555                         if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8556                              lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8557                             lun->pr_key_count) {
8558                                 /*
8559                                  * If the reservation is a registrants
8560                                  * only type we need to generate a UA
8561                                  * for other registered inits.  The
8562                                  * sense code should be RESERVATIONS
8563                                  * RELEASED
8564                                  */
8565
8566                                 for (i = softc->init_min; i < softc->init_max; i++) {
8567                                         if (ctl_get_prkey(lun, i) == 0)
8568                                                 continue;
8569
8570                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8571                                 }
8572                         }
8573                         lun->pr_res_type = 0;
8574                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8575                         if (lun->pr_key_count==0) {
8576                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8577                                 lun->pr_res_type = 0;
8578                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8579                         }
8580                 }
8581                 lun->pr_generation++;
8582                 break;
8583
8584         case CTL_PR_RESERVE:
8585                 lun->flags |= CTL_LUN_PR_RESERVED;
8586                 lun->pr_res_type = msg->pr.pr_info.res_type;
8587                 lun->pr_res_idx = msg->pr.pr_info.residx;
8588
8589                 break;
8590
8591         case CTL_PR_RELEASE:
8592                 /*
8593                  * if this isn't an exclusive access res generate UA for all
8594                  * other registrants.
8595                  */
8596                 if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8597                     lun->pr_res_type != SPR_TYPE_WR_EX) {
8598                         for (i = softc->init_min; i < softc->init_max; i++)
8599                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8600                                         continue;
8601                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8602                 }
8603
8604                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8605                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8606                 lun->pr_res_type = 0;
8607                 break;
8608
8609         case CTL_PR_PREEMPT:
8610                 ctl_pro_preempt_other(lun, msg);
8611                 break;
8612         case CTL_PR_CLEAR:
8613                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8614                 lun->pr_res_type = 0;
8615                 lun->pr_key_count = 0;
8616                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8617
8618                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8619                         if (ctl_get_prkey(lun, i) == 0)
8620                                 continue;
8621                         ctl_clr_prkey(lun, i);
8622                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8623                 }
8624                 lun->pr_generation++;
8625                 break;
8626         }
8627
8628         mtx_unlock(&lun->lun_lock);
8629 }
8630
8631 int
8632 ctl_read_write(struct ctl_scsiio *ctsio)
8633 {
8634         struct ctl_lun *lun;
8635         struct ctl_lba_len_flags *lbalen;
8636         uint64_t lba;
8637         uint32_t num_blocks;
8638         int flags, retval;
8639         int isread;
8640
8641         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8642
8643         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8644
8645         flags = 0;
8646         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8647               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8648         switch (ctsio->cdb[0]) {
8649         case READ_6:
8650         case WRITE_6: {
8651                 struct scsi_rw_6 *cdb;
8652
8653                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8654
8655                 lba = scsi_3btoul(cdb->addr);
8656                 /* only 5 bits are valid in the most significant address byte */
8657                 lba &= 0x1fffff;
8658                 num_blocks = cdb->length;
8659                 /*
8660                  * This is correct according to SBC-2.
8661                  */
8662                 if (num_blocks == 0)
8663                         num_blocks = 256;
8664                 break;
8665         }
8666         case READ_10:
8667         case WRITE_10: {
8668                 struct scsi_rw_10 *cdb;
8669
8670                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8671                 if (cdb->byte2 & SRW10_FUA)
8672                         flags |= CTL_LLF_FUA;
8673                 if (cdb->byte2 & SRW10_DPO)
8674                         flags |= CTL_LLF_DPO;
8675                 lba = scsi_4btoul(cdb->addr);
8676                 num_blocks = scsi_2btoul(cdb->length);
8677                 break;
8678         }
8679         case WRITE_VERIFY_10: {
8680                 struct scsi_write_verify_10 *cdb;
8681
8682                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8683                 flags |= CTL_LLF_FUA;
8684                 if (cdb->byte2 & SWV_DPO)
8685                         flags |= CTL_LLF_DPO;
8686                 lba = scsi_4btoul(cdb->addr);
8687                 num_blocks = scsi_2btoul(cdb->length);
8688                 break;
8689         }
8690         case READ_12:
8691         case WRITE_12: {
8692                 struct scsi_rw_12 *cdb;
8693
8694                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8695                 if (cdb->byte2 & SRW12_FUA)
8696                         flags |= CTL_LLF_FUA;
8697                 if (cdb->byte2 & SRW12_DPO)
8698                         flags |= CTL_LLF_DPO;
8699                 lba = scsi_4btoul(cdb->addr);
8700                 num_blocks = scsi_4btoul(cdb->length);
8701                 break;
8702         }
8703         case WRITE_VERIFY_12: {
8704                 struct scsi_write_verify_12 *cdb;
8705
8706                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8707                 flags |= CTL_LLF_FUA;
8708                 if (cdb->byte2 & SWV_DPO)
8709                         flags |= CTL_LLF_DPO;
8710                 lba = scsi_4btoul(cdb->addr);
8711                 num_blocks = scsi_4btoul(cdb->length);
8712                 break;
8713         }
8714         case READ_16:
8715         case WRITE_16: {
8716                 struct scsi_rw_16 *cdb;
8717
8718                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8719                 if (cdb->byte2 & SRW12_FUA)
8720                         flags |= CTL_LLF_FUA;
8721                 if (cdb->byte2 & SRW12_DPO)
8722                         flags |= CTL_LLF_DPO;
8723                 lba = scsi_8btou64(cdb->addr);
8724                 num_blocks = scsi_4btoul(cdb->length);
8725                 break;
8726         }
8727         case WRITE_ATOMIC_16: {
8728                 struct scsi_write_atomic_16 *cdb;
8729
8730                 if (lun->be_lun->atomicblock == 0) {
8731                         ctl_set_invalid_opcode(ctsio);
8732                         ctl_done((union ctl_io *)ctsio);
8733                         return (CTL_RETVAL_COMPLETE);
8734                 }
8735
8736                 cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8737                 if (cdb->byte2 & SRW12_FUA)
8738                         flags |= CTL_LLF_FUA;
8739                 if (cdb->byte2 & SRW12_DPO)
8740                         flags |= CTL_LLF_DPO;
8741                 lba = scsi_8btou64(cdb->addr);
8742                 num_blocks = scsi_2btoul(cdb->length);
8743                 if (num_blocks > lun->be_lun->atomicblock) {
8744                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8745                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8746                             /*bit*/ 0);
8747                         ctl_done((union ctl_io *)ctsio);
8748                         return (CTL_RETVAL_COMPLETE);
8749                 }
8750                 break;
8751         }
8752         case WRITE_VERIFY_16: {
8753                 struct scsi_write_verify_16 *cdb;
8754
8755                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8756                 flags |= CTL_LLF_FUA;
8757                 if (cdb->byte2 & SWV_DPO)
8758                         flags |= CTL_LLF_DPO;
8759                 lba = scsi_8btou64(cdb->addr);
8760                 num_blocks = scsi_4btoul(cdb->length);
8761                 break;
8762         }
8763         default:
8764                 /*
8765                  * We got a command we don't support.  This shouldn't
8766                  * happen, commands should be filtered out above us.
8767                  */
8768                 ctl_set_invalid_opcode(ctsio);
8769                 ctl_done((union ctl_io *)ctsio);
8770
8771                 return (CTL_RETVAL_COMPLETE);
8772                 break; /* NOTREACHED */
8773         }
8774
8775         /*
8776          * The first check is to make sure we're in bounds, the second
8777          * check is to catch wrap-around problems.  If the lba + num blocks
8778          * is less than the lba, then we've wrapped around and the block
8779          * range is invalid anyway.
8780          */
8781         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8782          || ((lba + num_blocks) < lba)) {
8783                 ctl_set_lba_out_of_range(ctsio);
8784                 ctl_done((union ctl_io *)ctsio);
8785                 return (CTL_RETVAL_COMPLETE);
8786         }
8787
8788         /*
8789          * According to SBC-3, a transfer length of 0 is not an error.
8790          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8791          * translates to 256 blocks for those commands.
8792          */
8793         if (num_blocks == 0) {
8794                 ctl_set_success(ctsio);
8795                 ctl_done((union ctl_io *)ctsio);
8796                 return (CTL_RETVAL_COMPLETE);
8797         }
8798
8799         /* Set FUA and/or DPO if caches are disabled. */
8800         if (isread) {
8801                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8802                     SCP_RCD) != 0)
8803                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8804         } else {
8805                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8806                     SCP_WCE) == 0)
8807                         flags |= CTL_LLF_FUA;
8808         }
8809
8810         lbalen = (struct ctl_lba_len_flags *)
8811             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8812         lbalen->lba = lba;
8813         lbalen->len = num_blocks;
8814         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8815
8816         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8817         ctsio->kern_rel_offset = 0;
8818
8819         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8820
8821         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8822         return (retval);
8823 }
8824
8825 static int
8826 ctl_cnw_cont(union ctl_io *io)
8827 {
8828         struct ctl_scsiio *ctsio;
8829         struct ctl_lun *lun;
8830         struct ctl_lba_len_flags *lbalen;
8831         int retval;
8832
8833         ctsio = &io->scsiio;
8834         ctsio->io_hdr.status = CTL_STATUS_NONE;
8835         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8836         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8837         lbalen = (struct ctl_lba_len_flags *)
8838             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8839         lbalen->flags &= ~CTL_LLF_COMPARE;
8840         lbalen->flags |= CTL_LLF_WRITE;
8841
8842         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8843         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8844         return (retval);
8845 }
8846
8847 int
8848 ctl_cnw(struct ctl_scsiio *ctsio)
8849 {
8850         struct ctl_lun *lun;
8851         struct ctl_lba_len_flags *lbalen;
8852         uint64_t lba;
8853         uint32_t num_blocks;
8854         int flags, retval;
8855
8856         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8857
8858         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8859
8860         flags = 0;
8861         switch (ctsio->cdb[0]) {
8862         case COMPARE_AND_WRITE: {
8863                 struct scsi_compare_and_write *cdb;
8864
8865                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8866                 if (cdb->byte2 & SRW10_FUA)
8867                         flags |= CTL_LLF_FUA;
8868                 if (cdb->byte2 & SRW10_DPO)
8869                         flags |= CTL_LLF_DPO;
8870                 lba = scsi_8btou64(cdb->addr);
8871                 num_blocks = cdb->length;
8872                 break;
8873         }
8874         default:
8875                 /*
8876                  * We got a command we don't support.  This shouldn't
8877                  * happen, commands should be filtered out above us.
8878                  */
8879                 ctl_set_invalid_opcode(ctsio);
8880                 ctl_done((union ctl_io *)ctsio);
8881
8882                 return (CTL_RETVAL_COMPLETE);
8883                 break; /* NOTREACHED */
8884         }
8885
8886         /*
8887          * The first check is to make sure we're in bounds, the second
8888          * check is to catch wrap-around problems.  If the lba + num blocks
8889          * is less than the lba, then we've wrapped around and the block
8890          * range is invalid anyway.
8891          */
8892         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8893          || ((lba + num_blocks) < lba)) {
8894                 ctl_set_lba_out_of_range(ctsio);
8895                 ctl_done((union ctl_io *)ctsio);
8896                 return (CTL_RETVAL_COMPLETE);
8897         }
8898
8899         /*
8900          * According to SBC-3, a transfer length of 0 is not an error.
8901          */
8902         if (num_blocks == 0) {
8903                 ctl_set_success(ctsio);
8904                 ctl_done((union ctl_io *)ctsio);
8905                 return (CTL_RETVAL_COMPLETE);
8906         }
8907
8908         /* Set FUA if write cache is disabled. */
8909         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8910             SCP_WCE) == 0)
8911                 flags |= CTL_LLF_FUA;
8912
8913         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8914         ctsio->kern_rel_offset = 0;
8915
8916         /*
8917          * Set the IO_CONT flag, so that if this I/O gets passed to
8918          * ctl_data_submit_done(), it'll get passed back to
8919          * ctl_ctl_cnw_cont() for further processing.
8920          */
8921         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8922         ctsio->io_cont = ctl_cnw_cont;
8923
8924         lbalen = (struct ctl_lba_len_flags *)
8925             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8926         lbalen->lba = lba;
8927         lbalen->len = num_blocks;
8928         lbalen->flags = CTL_LLF_COMPARE | flags;
8929
8930         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8931         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8932         return (retval);
8933 }
8934
8935 int
8936 ctl_verify(struct ctl_scsiio *ctsio)
8937 {
8938         struct ctl_lun *lun;
8939         struct ctl_lba_len_flags *lbalen;
8940         uint64_t lba;
8941         uint32_t num_blocks;
8942         int bytchk, flags;
8943         int retval;
8944
8945         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8946
8947         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8948
8949         bytchk = 0;
8950         flags = CTL_LLF_FUA;
8951         switch (ctsio->cdb[0]) {
8952         case VERIFY_10: {
8953                 struct scsi_verify_10 *cdb;
8954
8955                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8956                 if (cdb->byte2 & SVFY_BYTCHK)
8957                         bytchk = 1;
8958                 if (cdb->byte2 & SVFY_DPO)
8959                         flags |= CTL_LLF_DPO;
8960                 lba = scsi_4btoul(cdb->addr);
8961                 num_blocks = scsi_2btoul(cdb->length);
8962                 break;
8963         }
8964         case VERIFY_12: {
8965                 struct scsi_verify_12 *cdb;
8966
8967                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8968                 if (cdb->byte2 & SVFY_BYTCHK)
8969                         bytchk = 1;
8970                 if (cdb->byte2 & SVFY_DPO)
8971                         flags |= CTL_LLF_DPO;
8972                 lba = scsi_4btoul(cdb->addr);
8973                 num_blocks = scsi_4btoul(cdb->length);
8974                 break;
8975         }
8976         case VERIFY_16: {
8977                 struct scsi_rw_16 *cdb;
8978
8979                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8980                 if (cdb->byte2 & SVFY_BYTCHK)
8981                         bytchk = 1;
8982                 if (cdb->byte2 & SVFY_DPO)
8983                         flags |= CTL_LLF_DPO;
8984                 lba = scsi_8btou64(cdb->addr);
8985                 num_blocks = scsi_4btoul(cdb->length);
8986                 break;
8987         }
8988         default:
8989                 /*
8990                  * We got a command we don't support.  This shouldn't
8991                  * happen, commands should be filtered out above us.
8992                  */
8993                 ctl_set_invalid_opcode(ctsio);
8994                 ctl_done((union ctl_io *)ctsio);
8995                 return (CTL_RETVAL_COMPLETE);
8996         }
8997
8998         /*
8999          * The first check is to make sure we're in bounds, the second
9000          * check is to catch wrap-around problems.  If the lba + num blocks
9001          * is less than the lba, then we've wrapped around and the block
9002          * range is invalid anyway.
9003          */
9004         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9005          || ((lba + num_blocks) < lba)) {
9006                 ctl_set_lba_out_of_range(ctsio);
9007                 ctl_done((union ctl_io *)ctsio);
9008                 return (CTL_RETVAL_COMPLETE);
9009         }
9010
9011         /*
9012          * According to SBC-3, a transfer length of 0 is not an error.
9013          */
9014         if (num_blocks == 0) {
9015                 ctl_set_success(ctsio);
9016                 ctl_done((union ctl_io *)ctsio);
9017                 return (CTL_RETVAL_COMPLETE);
9018         }
9019
9020         lbalen = (struct ctl_lba_len_flags *)
9021             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9022         lbalen->lba = lba;
9023         lbalen->len = num_blocks;
9024         if (bytchk) {
9025                 lbalen->flags = CTL_LLF_COMPARE | flags;
9026                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9027         } else {
9028                 lbalen->flags = CTL_LLF_VERIFY | flags;
9029                 ctsio->kern_total_len = 0;
9030         }
9031         ctsio->kern_rel_offset = 0;
9032
9033         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9034         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9035         return (retval);
9036 }
9037
9038 int
9039 ctl_report_luns(struct ctl_scsiio *ctsio)
9040 {
9041         struct ctl_softc *softc;
9042         struct scsi_report_luns *cdb;
9043         struct scsi_report_luns_data *lun_data;
9044         struct ctl_lun *lun, *request_lun;
9045         struct ctl_port *port;
9046         int num_luns, retval;
9047         uint32_t alloc_len, lun_datalen;
9048         int num_filled;
9049         uint32_t initidx, targ_lun_id, lun_id;
9050
9051         retval = CTL_RETVAL_COMPLETE;
9052         cdb = (struct scsi_report_luns *)ctsio->cdb;
9053         port = ctl_io_port(&ctsio->io_hdr);
9054         softc = port->ctl_softc;
9055
9056         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9057
9058         mtx_lock(&softc->ctl_lock);
9059         num_luns = 0;
9060         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9061                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9062                         num_luns++;
9063         }
9064         mtx_unlock(&softc->ctl_lock);
9065
9066         switch (cdb->select_report) {
9067         case RPL_REPORT_DEFAULT:
9068         case RPL_REPORT_ALL:
9069         case RPL_REPORT_NONSUBSID:
9070                 break;
9071         case RPL_REPORT_WELLKNOWN:
9072         case RPL_REPORT_ADMIN:
9073         case RPL_REPORT_CONGLOM:
9074                 num_luns = 0;
9075                 break;
9076         default:
9077                 ctl_set_invalid_field(ctsio,
9078                                       /*sks_valid*/ 1,
9079                                       /*command*/ 1,
9080                                       /*field*/ 2,
9081                                       /*bit_valid*/ 0,
9082                                       /*bit*/ 0);
9083                 ctl_done((union ctl_io *)ctsio);
9084                 return (retval);
9085                 break; /* NOTREACHED */
9086         }
9087
9088         alloc_len = scsi_4btoul(cdb->length);
9089         /*
9090          * The initiator has to allocate at least 16 bytes for this request,
9091          * so he can at least get the header and the first LUN.  Otherwise
9092          * we reject the request (per SPC-3 rev 14, section 6.21).
9093          */
9094         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9095             sizeof(struct scsi_report_luns_lundata))) {
9096                 ctl_set_invalid_field(ctsio,
9097                                       /*sks_valid*/ 1,
9098                                       /*command*/ 1,
9099                                       /*field*/ 6,
9100                                       /*bit_valid*/ 0,
9101                                       /*bit*/ 0);
9102                 ctl_done((union ctl_io *)ctsio);
9103                 return (retval);
9104         }
9105
9106         request_lun = (struct ctl_lun *)
9107                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9108
9109         lun_datalen = sizeof(*lun_data) +
9110                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9111
9112         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9113         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9114         ctsio->kern_sg_entries = 0;
9115
9116         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9117
9118         mtx_lock(&softc->ctl_lock);
9119         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9120                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9121                 if (lun_id >= CTL_MAX_LUNS)
9122                         continue;
9123                 lun = softc->ctl_luns[lun_id];
9124                 if (lun == NULL)
9125                         continue;
9126
9127                 be64enc(lun_data->luns[num_filled++].lundata,
9128                     ctl_encode_lun(targ_lun_id));
9129
9130                 /*
9131                  * According to SPC-3, rev 14 section 6.21:
9132                  *
9133                  * "The execution of a REPORT LUNS command to any valid and
9134                  * installed logical unit shall clear the REPORTED LUNS DATA
9135                  * HAS CHANGED unit attention condition for all logical
9136                  * units of that target with respect to the requesting
9137                  * initiator. A valid and installed logical unit is one
9138                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9139                  * INQUIRY data (see 6.4.2)."
9140                  *
9141                  * If request_lun is NULL, the LUN this report luns command
9142                  * was issued to is either disabled or doesn't exist. In that
9143                  * case, we shouldn't clear any pending lun change unit
9144                  * attention.
9145                  */
9146                 if (request_lun != NULL) {
9147                         mtx_lock(&lun->lun_lock);
9148                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9149                         mtx_unlock(&lun->lun_lock);
9150                 }
9151         }
9152         mtx_unlock(&softc->ctl_lock);
9153
9154         /*
9155          * It's quite possible that we've returned fewer LUNs than we allocated
9156          * space for.  Trim it.
9157          */
9158         lun_datalen = sizeof(*lun_data) +
9159                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9160
9161         if (lun_datalen < alloc_len) {
9162                 ctsio->residual = alloc_len - lun_datalen;
9163                 ctsio->kern_data_len = lun_datalen;
9164                 ctsio->kern_total_len = lun_datalen;
9165         } else {
9166                 ctsio->residual = 0;
9167                 ctsio->kern_data_len = alloc_len;
9168                 ctsio->kern_total_len = alloc_len;
9169         }
9170         ctsio->kern_data_resid = 0;
9171         ctsio->kern_rel_offset = 0;
9172         ctsio->kern_sg_entries = 0;
9173
9174         /*
9175          * We set this to the actual data length, regardless of how much
9176          * space we actually have to return results.  If the user looks at
9177          * this value, he'll know whether or not he allocated enough space
9178          * and reissue the command if necessary.  We don't support well
9179          * known logical units, so if the user asks for that, return none.
9180          */
9181         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9182
9183         /*
9184          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9185          * this request.
9186          */
9187         ctl_set_success(ctsio);
9188         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9189         ctsio->be_move_done = ctl_config_move_done;
9190         ctl_datamove((union ctl_io *)ctsio);
9191         return (retval);
9192 }
9193
9194 int
9195 ctl_request_sense(struct ctl_scsiio *ctsio)
9196 {
9197         struct scsi_request_sense *cdb;
9198         struct scsi_sense_data *sense_ptr;
9199         struct ctl_softc *ctl_softc;
9200         struct ctl_lun *lun;
9201         uint32_t initidx;
9202         int have_error;
9203         scsi_sense_data_type sense_format;
9204         ctl_ua_type ua_type;
9205
9206         cdb = (struct scsi_request_sense *)ctsio->cdb;
9207
9208         ctl_softc = control_softc;
9209         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9210
9211         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9212
9213         /*
9214          * Determine which sense format the user wants.
9215          */
9216         if (cdb->byte2 & SRS_DESC)
9217                 sense_format = SSD_TYPE_DESC;
9218         else
9219                 sense_format = SSD_TYPE_FIXED;
9220
9221         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9222         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9223         ctsio->kern_sg_entries = 0;
9224
9225         /*
9226          * struct scsi_sense_data, which is currently set to 256 bytes, is
9227          * larger than the largest allowed value for the length field in the
9228          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9229          */
9230         ctsio->residual = 0;
9231         ctsio->kern_data_len = cdb->length;
9232         ctsio->kern_total_len = cdb->length;
9233
9234         ctsio->kern_data_resid = 0;
9235         ctsio->kern_rel_offset = 0;
9236         ctsio->kern_sg_entries = 0;
9237
9238         /*
9239          * If we don't have a LUN, we don't have any pending sense.
9240          */
9241         if (lun == NULL)
9242                 goto no_sense;
9243
9244         have_error = 0;
9245         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9246         /*
9247          * Check for pending sense, and then for pending unit attentions.
9248          * Pending sense gets returned first, then pending unit attentions.
9249          */
9250         mtx_lock(&lun->lun_lock);
9251 #ifdef CTL_WITH_CA
9252         if (ctl_is_set(lun->have_ca, initidx)) {
9253                 scsi_sense_data_type stored_format;
9254
9255                 /*
9256                  * Check to see which sense format was used for the stored
9257                  * sense data.
9258                  */
9259                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9260
9261                 /*
9262                  * If the user requested a different sense format than the
9263                  * one we stored, then we need to convert it to the other
9264                  * format.  If we're going from descriptor to fixed format
9265                  * sense data, we may lose things in translation, depending
9266                  * on what options were used.
9267                  *
9268                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9269                  * for some reason we'll just copy it out as-is.
9270                  */
9271                 if ((stored_format == SSD_TYPE_FIXED)
9272                  && (sense_format == SSD_TYPE_DESC))
9273                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9274                             &lun->pending_sense[initidx],
9275                             (struct scsi_sense_data_desc *)sense_ptr);
9276                 else if ((stored_format == SSD_TYPE_DESC)
9277                       && (sense_format == SSD_TYPE_FIXED))
9278                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9279                             &lun->pending_sense[initidx],
9280                             (struct scsi_sense_data_fixed *)sense_ptr);
9281                 else
9282                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9283                                MIN(sizeof(*sense_ptr),
9284                                sizeof(lun->pending_sense[initidx])));
9285
9286                 ctl_clear_mask(lun->have_ca, initidx);
9287                 have_error = 1;
9288         } else
9289 #endif
9290         {
9291                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9292                 if (ua_type != CTL_UA_NONE)
9293                         have_error = 1;
9294                 if (ua_type == CTL_UA_LUN_CHANGE) {
9295                         mtx_unlock(&lun->lun_lock);
9296                         mtx_lock(&ctl_softc->ctl_lock);
9297                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9298                         mtx_unlock(&ctl_softc->ctl_lock);
9299                         mtx_lock(&lun->lun_lock);
9300                 }
9301
9302         }
9303         mtx_unlock(&lun->lun_lock);
9304
9305         /*
9306          * We already have a pending error, return it.
9307          */
9308         if (have_error != 0) {
9309                 /*
9310                  * We report the SCSI status as OK, since the status of the
9311                  * request sense command itself is OK.
9312                  * We report 0 for the sense length, because we aren't doing
9313                  * autosense in this case.  We're reporting sense as
9314                  * parameter data.
9315                  */
9316                 ctl_set_success(ctsio);
9317                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9318                 ctsio->be_move_done = ctl_config_move_done;
9319                 ctl_datamove((union ctl_io *)ctsio);
9320                 return (CTL_RETVAL_COMPLETE);
9321         }
9322
9323 no_sense:
9324
9325         /*
9326          * No sense information to report, so we report that everything is
9327          * okay.
9328          */
9329         ctl_set_sense_data(sense_ptr,
9330                            lun,
9331                            sense_format,
9332                            /*current_error*/ 1,
9333                            /*sense_key*/ SSD_KEY_NO_SENSE,
9334                            /*asc*/ 0x00,
9335                            /*ascq*/ 0x00,
9336                            SSD_ELEM_NONE);
9337
9338         /*
9339          * We report 0 for the sense length, because we aren't doing
9340          * autosense in this case.  We're reporting sense as parameter data.
9341          */
9342         ctl_set_success(ctsio);
9343         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9344         ctsio->be_move_done = ctl_config_move_done;
9345         ctl_datamove((union ctl_io *)ctsio);
9346         return (CTL_RETVAL_COMPLETE);
9347 }
9348
9349 int
9350 ctl_tur(struct ctl_scsiio *ctsio)
9351 {
9352
9353         CTL_DEBUG_PRINT(("ctl_tur\n"));
9354
9355         ctl_set_success(ctsio);
9356         ctl_done((union ctl_io *)ctsio);
9357
9358         return (CTL_RETVAL_COMPLETE);
9359 }
9360
9361 /*
9362  * SCSI VPD page 0x00, the Supported VPD Pages page.
9363  */
9364 static int
9365 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9366 {
9367         struct scsi_vpd_supported_pages *pages;
9368         int sup_page_size;
9369         struct ctl_lun *lun;
9370         int p;
9371
9372         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9373
9374         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9375             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9376         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9377         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9378         ctsio->kern_sg_entries = 0;
9379
9380         if (sup_page_size < alloc_len) {
9381                 ctsio->residual = alloc_len - sup_page_size;
9382                 ctsio->kern_data_len = sup_page_size;
9383                 ctsio->kern_total_len = sup_page_size;
9384         } else {
9385                 ctsio->residual = 0;
9386                 ctsio->kern_data_len = alloc_len;
9387                 ctsio->kern_total_len = alloc_len;
9388         }
9389         ctsio->kern_data_resid = 0;
9390         ctsio->kern_rel_offset = 0;
9391         ctsio->kern_sg_entries = 0;
9392
9393         /*
9394          * The control device is always connected.  The disk device, on the
9395          * other hand, may not be online all the time.  Need to change this
9396          * to figure out whether the disk device is actually online or not.
9397          */
9398         if (lun != NULL)
9399                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9400                                 lun->be_lun->lun_type;
9401         else
9402                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9403
9404         p = 0;
9405         /* Supported VPD pages */
9406         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9407         /* Serial Number */
9408         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9409         /* Device Identification */
9410         pages->page_list[p++] = SVPD_DEVICE_ID;
9411         /* Extended INQUIRY Data */
9412         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9413         /* Mode Page Policy */
9414         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9415         /* SCSI Ports */
9416         pages->page_list[p++] = SVPD_SCSI_PORTS;
9417         /* Third-party Copy */
9418         pages->page_list[p++] = SVPD_SCSI_TPC;
9419         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9420                 /* Block limits */
9421                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9422                 /* Block Device Characteristics */
9423                 pages->page_list[p++] = SVPD_BDC;
9424                 /* Logical Block Provisioning */
9425                 pages->page_list[p++] = SVPD_LBP;
9426         }
9427         pages->length = p;
9428
9429         ctl_set_success(ctsio);
9430         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9431         ctsio->be_move_done = ctl_config_move_done;
9432         ctl_datamove((union ctl_io *)ctsio);
9433         return (CTL_RETVAL_COMPLETE);
9434 }
9435
9436 /*
9437  * SCSI VPD page 0x80, the Unit Serial Number page.
9438  */
9439 static int
9440 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9441 {
9442         struct scsi_vpd_unit_serial_number *sn_ptr;
9443         struct ctl_lun *lun;
9444         int data_len;
9445
9446         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9447
9448         data_len = 4 + CTL_SN_LEN;
9449         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9450         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9451         if (data_len < alloc_len) {
9452                 ctsio->residual = alloc_len - data_len;
9453                 ctsio->kern_data_len = data_len;
9454                 ctsio->kern_total_len = data_len;
9455         } else {
9456                 ctsio->residual = 0;
9457                 ctsio->kern_data_len = alloc_len;
9458                 ctsio->kern_total_len = alloc_len;
9459         }
9460         ctsio->kern_data_resid = 0;
9461         ctsio->kern_rel_offset = 0;
9462         ctsio->kern_sg_entries = 0;
9463
9464         /*
9465          * The control device is always connected.  The disk device, on the
9466          * other hand, may not be online all the time.  Need to change this
9467          * to figure out whether the disk device is actually online or not.
9468          */
9469         if (lun != NULL)
9470                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9471                                   lun->be_lun->lun_type;
9472         else
9473                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9474
9475         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9476         sn_ptr->length = CTL_SN_LEN;
9477         /*
9478          * If we don't have a LUN, we just leave the serial number as
9479          * all spaces.
9480          */
9481         if (lun != NULL) {
9482                 strncpy((char *)sn_ptr->serial_num,
9483                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9484         } else
9485                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9486
9487         ctl_set_success(ctsio);
9488         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9489         ctsio->be_move_done = ctl_config_move_done;
9490         ctl_datamove((union ctl_io *)ctsio);
9491         return (CTL_RETVAL_COMPLETE);
9492 }
9493
9494
9495 /*
9496  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9497  */
9498 static int
9499 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9500 {
9501         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9502         struct ctl_lun *lun;
9503         int data_len;
9504
9505         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9506
9507         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9508         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9509         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9510         ctsio->kern_sg_entries = 0;
9511
9512         if (data_len < alloc_len) {
9513                 ctsio->residual = alloc_len - data_len;
9514                 ctsio->kern_data_len = data_len;
9515                 ctsio->kern_total_len = data_len;
9516         } else {
9517                 ctsio->residual = 0;
9518                 ctsio->kern_data_len = alloc_len;
9519                 ctsio->kern_total_len = alloc_len;
9520         }
9521         ctsio->kern_data_resid = 0;
9522         ctsio->kern_rel_offset = 0;
9523         ctsio->kern_sg_entries = 0;
9524
9525         /*
9526          * The control device is always connected.  The disk device, on the
9527          * other hand, may not be online all the time.
9528          */
9529         if (lun != NULL)
9530                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9531                                      lun->be_lun->lun_type;
9532         else
9533                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9534         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9535         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9536         /*
9537          * We support head of queue, ordered and simple tags.
9538          */
9539         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9540         /*
9541          * Volatile cache supported.
9542          */
9543         eid_ptr->flags3 = SVPD_EID_V_SUP;
9544
9545         /*
9546          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9547          * attention for a particular IT nexus on all LUNs once we report
9548          * it to that nexus once.  This bit is required as of SPC-4.
9549          */
9550         eid_ptr->flags4 = SVPD_EID_LUICLT;
9551
9552         /*
9553          * XXX KDM in order to correctly answer this, we would need
9554          * information from the SIM to determine how much sense data it
9555          * can send.  So this would really be a path inquiry field, most
9556          * likely.  This can be set to a maximum of 252 according to SPC-4,
9557          * but the hardware may or may not be able to support that much.
9558          * 0 just means that the maximum sense data length is not reported.
9559          */
9560         eid_ptr->max_sense_length = 0;
9561
9562         ctl_set_success(ctsio);
9563         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9564         ctsio->be_move_done = ctl_config_move_done;
9565         ctl_datamove((union ctl_io *)ctsio);
9566         return (CTL_RETVAL_COMPLETE);
9567 }
9568
9569 static int
9570 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9571 {
9572         struct scsi_vpd_mode_page_policy *mpp_ptr;
9573         struct ctl_lun *lun;
9574         int data_len;
9575
9576         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9577
9578         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9579             sizeof(struct scsi_vpd_mode_page_policy_descr);
9580
9581         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9582         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9583         ctsio->kern_sg_entries = 0;
9584
9585         if (data_len < alloc_len) {
9586                 ctsio->residual = alloc_len - data_len;
9587                 ctsio->kern_data_len = data_len;
9588                 ctsio->kern_total_len = data_len;
9589         } else {
9590                 ctsio->residual = 0;
9591                 ctsio->kern_data_len = alloc_len;
9592                 ctsio->kern_total_len = alloc_len;
9593         }
9594         ctsio->kern_data_resid = 0;
9595         ctsio->kern_rel_offset = 0;
9596         ctsio->kern_sg_entries = 0;
9597
9598         /*
9599          * The control device is always connected.  The disk device, on the
9600          * other hand, may not be online all the time.
9601          */
9602         if (lun != NULL)
9603                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9604                                      lun->be_lun->lun_type;
9605         else
9606                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9607         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9608         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9609         mpp_ptr->descr[0].page_code = 0x3f;
9610         mpp_ptr->descr[0].subpage_code = 0xff;
9611         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9612
9613         ctl_set_success(ctsio);
9614         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9615         ctsio->be_move_done = ctl_config_move_done;
9616         ctl_datamove((union ctl_io *)ctsio);
9617         return (CTL_RETVAL_COMPLETE);
9618 }
9619
9620 /*
9621  * SCSI VPD page 0x83, the Device Identification page.
9622  */
9623 static int
9624 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9625 {
9626         struct scsi_vpd_device_id *devid_ptr;
9627         struct scsi_vpd_id_descriptor *desc;
9628         struct ctl_softc *softc;
9629         struct ctl_lun *lun;
9630         struct ctl_port *port;
9631         int data_len;
9632         uint8_t proto;
9633
9634         softc = control_softc;
9635
9636         port = ctl_io_port(&ctsio->io_hdr);
9637         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9638
9639         data_len = sizeof(struct scsi_vpd_device_id) +
9640             sizeof(struct scsi_vpd_id_descriptor) +
9641                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9642             sizeof(struct scsi_vpd_id_descriptor) +
9643                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9644         if (lun && lun->lun_devid)
9645                 data_len += lun->lun_devid->len;
9646         if (port && port->port_devid)
9647                 data_len += port->port_devid->len;
9648         if (port && port->target_devid)
9649                 data_len += port->target_devid->len;
9650
9651         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9652         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9653         ctsio->kern_sg_entries = 0;
9654
9655         if (data_len < alloc_len) {
9656                 ctsio->residual = alloc_len - data_len;
9657                 ctsio->kern_data_len = data_len;
9658                 ctsio->kern_total_len = data_len;
9659         } else {
9660                 ctsio->residual = 0;
9661                 ctsio->kern_data_len = alloc_len;
9662                 ctsio->kern_total_len = alloc_len;
9663         }
9664         ctsio->kern_data_resid = 0;
9665         ctsio->kern_rel_offset = 0;
9666         ctsio->kern_sg_entries = 0;
9667
9668         /*
9669          * The control device is always connected.  The disk device, on the
9670          * other hand, may not be online all the time.
9671          */
9672         if (lun != NULL)
9673                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9674                                      lun->be_lun->lun_type;
9675         else
9676                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9677         devid_ptr->page_code = SVPD_DEVICE_ID;
9678         scsi_ulto2b(data_len - 4, devid_ptr->length);
9679
9680         if (port && port->port_type == CTL_PORT_FC)
9681                 proto = SCSI_PROTO_FC << 4;
9682         else if (port && port->port_type == CTL_PORT_ISCSI)
9683                 proto = SCSI_PROTO_ISCSI << 4;
9684         else
9685                 proto = SCSI_PROTO_SPI << 4;
9686         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9687
9688         /*
9689          * We're using a LUN association here.  i.e., this device ID is a
9690          * per-LUN identifier.
9691          */
9692         if (lun && lun->lun_devid) {
9693                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9694                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9695                     lun->lun_devid->len);
9696         }
9697
9698         /*
9699          * This is for the WWPN which is a port association.
9700          */
9701         if (port && port->port_devid) {
9702                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9703                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9704                     port->port_devid->len);
9705         }
9706
9707         /*
9708          * This is for the Relative Target Port(type 4h) identifier
9709          */
9710         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9711         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9712             SVPD_ID_TYPE_RELTARG;
9713         desc->length = 4;
9714         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9715         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9716             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9717
9718         /*
9719          * This is for the Target Port Group(type 5h) identifier
9720          */
9721         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9722         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9723             SVPD_ID_TYPE_TPORTGRP;
9724         desc->length = 4;
9725         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9726             &desc->identifier[2]);
9727         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9728             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9729
9730         /*
9731          * This is for the Target identifier
9732          */
9733         if (port && port->target_devid) {
9734                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9735         }
9736
9737         ctl_set_success(ctsio);
9738         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9739         ctsio->be_move_done = ctl_config_move_done;
9740         ctl_datamove((union ctl_io *)ctsio);
9741         return (CTL_RETVAL_COMPLETE);
9742 }
9743
9744 static int
9745 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9746 {
9747         struct ctl_softc *softc = control_softc;
9748         struct scsi_vpd_scsi_ports *sp;
9749         struct scsi_vpd_port_designation *pd;
9750         struct scsi_vpd_port_designation_cont *pdc;
9751         struct ctl_lun *lun;
9752         struct ctl_port *port;
9753         int data_len, num_target_ports, iid_len, id_len;
9754
9755         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9756
9757         num_target_ports = 0;
9758         iid_len = 0;
9759         id_len = 0;
9760         mtx_lock(&softc->ctl_lock);
9761         STAILQ_FOREACH(port, &softc->port_list, links) {
9762                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9763                         continue;
9764                 if (lun != NULL &&
9765                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9766                         continue;
9767                 num_target_ports++;
9768                 if (port->init_devid)
9769                         iid_len += port->init_devid->len;
9770                 if (port->port_devid)
9771                         id_len += port->port_devid->len;
9772         }
9773         mtx_unlock(&softc->ctl_lock);
9774
9775         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9776             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9777              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9778         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9779         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9780         ctsio->kern_sg_entries = 0;
9781
9782         if (data_len < alloc_len) {
9783                 ctsio->residual = alloc_len - data_len;
9784                 ctsio->kern_data_len = data_len;
9785                 ctsio->kern_total_len = data_len;
9786         } else {
9787                 ctsio->residual = 0;
9788                 ctsio->kern_data_len = alloc_len;
9789                 ctsio->kern_total_len = alloc_len;
9790         }
9791         ctsio->kern_data_resid = 0;
9792         ctsio->kern_rel_offset = 0;
9793         ctsio->kern_sg_entries = 0;
9794
9795         /*
9796          * The control device is always connected.  The disk device, on the
9797          * other hand, may not be online all the time.  Need to change this
9798          * to figure out whether the disk device is actually online or not.
9799          */
9800         if (lun != NULL)
9801                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9802                                   lun->be_lun->lun_type;
9803         else
9804                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9805
9806         sp->page_code = SVPD_SCSI_PORTS;
9807         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9808             sp->page_length);
9809         pd = &sp->design[0];
9810
9811         mtx_lock(&softc->ctl_lock);
9812         STAILQ_FOREACH(port, &softc->port_list, links) {
9813                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9814                         continue;
9815                 if (lun != NULL &&
9816                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9817                         continue;
9818                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9819                 if (port->init_devid) {
9820                         iid_len = port->init_devid->len;
9821                         memcpy(pd->initiator_transportid,
9822                             port->init_devid->data, port->init_devid->len);
9823                 } else
9824                         iid_len = 0;
9825                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9826                 pdc = (struct scsi_vpd_port_designation_cont *)
9827                     (&pd->initiator_transportid[iid_len]);
9828                 if (port->port_devid) {
9829                         id_len = port->port_devid->len;
9830                         memcpy(pdc->target_port_descriptors,
9831                             port->port_devid->data, port->port_devid->len);
9832                 } else
9833                         id_len = 0;
9834                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9835                 pd = (struct scsi_vpd_port_designation *)
9836                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9837         }
9838         mtx_unlock(&softc->ctl_lock);
9839
9840         ctl_set_success(ctsio);
9841         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9842         ctsio->be_move_done = ctl_config_move_done;
9843         ctl_datamove((union ctl_io *)ctsio);
9844         return (CTL_RETVAL_COMPLETE);
9845 }
9846
9847 static int
9848 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9849 {
9850         struct scsi_vpd_block_limits *bl_ptr;
9851         struct ctl_lun *lun;
9852
9853         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9854
9855         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9856         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9857         ctsio->kern_sg_entries = 0;
9858
9859         if (sizeof(*bl_ptr) < alloc_len) {
9860                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9861                 ctsio->kern_data_len = sizeof(*bl_ptr);
9862                 ctsio->kern_total_len = sizeof(*bl_ptr);
9863         } else {
9864                 ctsio->residual = 0;
9865                 ctsio->kern_data_len = alloc_len;
9866                 ctsio->kern_total_len = alloc_len;
9867         }
9868         ctsio->kern_data_resid = 0;
9869         ctsio->kern_rel_offset = 0;
9870         ctsio->kern_sg_entries = 0;
9871
9872         /*
9873          * The control device is always connected.  The disk device, on the
9874          * other hand, may not be online all the time.  Need to change this
9875          * to figure out whether the disk device is actually online or not.
9876          */
9877         if (lun != NULL)
9878                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9879                                   lun->be_lun->lun_type;
9880         else
9881                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9882
9883         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9884         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9885         bl_ptr->max_cmp_write_len = 0xff;
9886         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9887         if (lun != NULL) {
9888                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9889                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9890                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9891                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9892                         if (lun->be_lun->ublockexp != 0) {
9893                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9894                                     bl_ptr->opt_unmap_grain);
9895                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9896                                     bl_ptr->unmap_grain_align);
9897                         }
9898                 }
9899                 scsi_ulto4b(lun->be_lun->atomicblock,
9900                     bl_ptr->max_atomic_transfer_length);
9901                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9902                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9903                 scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9904                 scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9905         }
9906         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9907
9908         ctl_set_success(ctsio);
9909         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9910         ctsio->be_move_done = ctl_config_move_done;
9911         ctl_datamove((union ctl_io *)ctsio);
9912         return (CTL_RETVAL_COMPLETE);
9913 }
9914
9915 static int
9916 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9917 {
9918         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9919         struct ctl_lun *lun;
9920         const char *value;
9921         u_int i;
9922
9923         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9924
9925         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9926         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9927         ctsio->kern_sg_entries = 0;
9928
9929         if (sizeof(*bdc_ptr) < alloc_len) {
9930                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9931                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9932                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9933         } else {
9934                 ctsio->residual = 0;
9935                 ctsio->kern_data_len = alloc_len;
9936                 ctsio->kern_total_len = alloc_len;
9937         }
9938         ctsio->kern_data_resid = 0;
9939         ctsio->kern_rel_offset = 0;
9940         ctsio->kern_sg_entries = 0;
9941
9942         /*
9943          * The control device is always connected.  The disk device, on the
9944          * other hand, may not be online all the time.  Need to change this
9945          * to figure out whether the disk device is actually online or not.
9946          */
9947         if (lun != NULL)
9948                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9949                                   lun->be_lun->lun_type;
9950         else
9951                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9952         bdc_ptr->page_code = SVPD_BDC;
9953         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9954         if (lun != NULL &&
9955             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9956                 i = strtol(value, NULL, 0);
9957         else
9958                 i = CTL_DEFAULT_ROTATION_RATE;
9959         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9960         if (lun != NULL &&
9961             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9962                 i = strtol(value, NULL, 0);
9963         else
9964                 i = 0;
9965         bdc_ptr->wab_wac_ff = (i & 0x0f);
9966         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9967
9968         ctl_set_success(ctsio);
9969         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9970         ctsio->be_move_done = ctl_config_move_done;
9971         ctl_datamove((union ctl_io *)ctsio);
9972         return (CTL_RETVAL_COMPLETE);
9973 }
9974
9975 static int
9976 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9977 {
9978         struct scsi_vpd_logical_block_prov *lbp_ptr;
9979         struct ctl_lun *lun;
9980
9981         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9982
9983         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9984         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9985         ctsio->kern_sg_entries = 0;
9986
9987         if (sizeof(*lbp_ptr) < alloc_len) {
9988                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9989                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9990                 ctsio->kern_total_len = sizeof(*lbp_ptr);
9991         } else {
9992                 ctsio->residual = 0;
9993                 ctsio->kern_data_len = alloc_len;
9994                 ctsio->kern_total_len = alloc_len;
9995         }
9996         ctsio->kern_data_resid = 0;
9997         ctsio->kern_rel_offset = 0;
9998         ctsio->kern_sg_entries = 0;
9999
10000         /*
10001          * The control device is always connected.  The disk device, on the
10002          * other hand, may not be online all the time.  Need to change this
10003          * to figure out whether the disk device is actually online or not.
10004          */
10005         if (lun != NULL)
10006                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10007                                   lun->be_lun->lun_type;
10008         else
10009                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10010
10011         lbp_ptr->page_code = SVPD_LBP;
10012         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10013         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10014         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10015                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10016                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10017                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10018         }
10019
10020         ctl_set_success(ctsio);
10021         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10022         ctsio->be_move_done = ctl_config_move_done;
10023         ctl_datamove((union ctl_io *)ctsio);
10024         return (CTL_RETVAL_COMPLETE);
10025 }
10026
10027 /*
10028  * INQUIRY with the EVPD bit set.
10029  */
10030 static int
10031 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10032 {
10033         struct ctl_lun *lun;
10034         struct scsi_inquiry *cdb;
10035         int alloc_len, retval;
10036
10037         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10038         cdb = (struct scsi_inquiry *)ctsio->cdb;
10039         alloc_len = scsi_2btoul(cdb->length);
10040
10041         switch (cdb->page_code) {
10042         case SVPD_SUPPORTED_PAGES:
10043                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10044                 break;
10045         case SVPD_UNIT_SERIAL_NUMBER:
10046                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10047                 break;
10048         case SVPD_DEVICE_ID:
10049                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10050                 break;
10051         case SVPD_EXTENDED_INQUIRY_DATA:
10052                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10053                 break;
10054         case SVPD_MODE_PAGE_POLICY:
10055                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10056                 break;
10057         case SVPD_SCSI_PORTS:
10058                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10059                 break;
10060         case SVPD_SCSI_TPC:
10061                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10062                 break;
10063         case SVPD_BLOCK_LIMITS:
10064                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10065                         goto err;
10066                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10067                 break;
10068         case SVPD_BDC:
10069                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10070                         goto err;
10071                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10072                 break;
10073         case SVPD_LBP:
10074                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10075                         goto err;
10076                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10077                 break;
10078         default:
10079 err:
10080                 ctl_set_invalid_field(ctsio,
10081                                       /*sks_valid*/ 1,
10082                                       /*command*/ 1,
10083                                       /*field*/ 2,
10084                                       /*bit_valid*/ 0,
10085                                       /*bit*/ 0);
10086                 ctl_done((union ctl_io *)ctsio);
10087                 retval = CTL_RETVAL_COMPLETE;
10088                 break;
10089         }
10090
10091         return (retval);
10092 }
10093
10094 /*
10095  * Standard INQUIRY data.
10096  */
10097 static int
10098 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10099 {
10100         struct scsi_inquiry_data *inq_ptr;
10101         struct scsi_inquiry *cdb;
10102         struct ctl_softc *softc = control_softc;
10103         struct ctl_port *port;
10104         struct ctl_lun *lun;
10105         char *val;
10106         uint32_t alloc_len, data_len;
10107         ctl_port_type port_type;
10108
10109         port = ctl_io_port(&ctsio->io_hdr);
10110         port_type = port->port_type;
10111         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10112                 port_type = CTL_PORT_SCSI;
10113
10114         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10115         cdb = (struct scsi_inquiry *)ctsio->cdb;
10116         alloc_len = scsi_2btoul(cdb->length);
10117
10118         /*
10119          * We malloc the full inquiry data size here and fill it
10120          * in.  If the user only asks for less, we'll give him
10121          * that much.
10122          */
10123         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10124         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10125         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10126         ctsio->kern_sg_entries = 0;
10127         ctsio->kern_data_resid = 0;
10128         ctsio->kern_rel_offset = 0;
10129
10130         if (data_len < alloc_len) {
10131                 ctsio->residual = alloc_len - data_len;
10132                 ctsio->kern_data_len = data_len;
10133                 ctsio->kern_total_len = data_len;
10134         } else {
10135                 ctsio->residual = 0;
10136                 ctsio->kern_data_len = alloc_len;
10137                 ctsio->kern_total_len = alloc_len;
10138         }
10139
10140         if (lun != NULL) {
10141                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10142                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10143                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10144                             lun->be_lun->lun_type;
10145                 } else {
10146                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10147                             lun->be_lun->lun_type;
10148                 }
10149                 if (lun->flags & CTL_LUN_REMOVABLE)
10150                         inq_ptr->dev_qual2 |= SID_RMB;
10151         } else
10152                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10153
10154         /* RMB in byte 2 is 0 */
10155         inq_ptr->version = SCSI_REV_SPC4;
10156
10157         /*
10158          * According to SAM-3, even if a device only supports a single
10159          * level of LUN addressing, it should still set the HISUP bit:
10160          *
10161          * 4.9.1 Logical unit numbers overview
10162          *
10163          * All logical unit number formats described in this standard are
10164          * hierarchical in structure even when only a single level in that
10165          * hierarchy is used. The HISUP bit shall be set to one in the
10166          * standard INQUIRY data (see SPC-2) when any logical unit number
10167          * format described in this standard is used.  Non-hierarchical
10168          * formats are outside the scope of this standard.
10169          *
10170          * Therefore we set the HiSup bit here.
10171          *
10172          * The reponse format is 2, per SPC-3.
10173          */
10174         inq_ptr->response_format = SID_HiSup | 2;
10175
10176         inq_ptr->additional_length = data_len -
10177             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10178         CTL_DEBUG_PRINT(("additional_length = %d\n",
10179                          inq_ptr->additional_length));
10180
10181         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10182         if (port_type == CTL_PORT_SCSI)
10183                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10184         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10185         inq_ptr->flags = SID_CmdQue;
10186         if (port_type == CTL_PORT_SCSI)
10187                 inq_ptr->flags |= SID_WBus16 | SID_Sync;
10188
10189         /*
10190          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10191          * We have 8 bytes for the vendor name, and 16 bytes for the device
10192          * name and 4 bytes for the revision.
10193          */
10194         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10195             "vendor")) == NULL) {
10196                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10197         } else {
10198                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10199                 strncpy(inq_ptr->vendor, val,
10200                     min(sizeof(inq_ptr->vendor), strlen(val)));
10201         }
10202         if (lun == NULL) {
10203                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10204                     sizeof(inq_ptr->product));
10205         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10206                 switch (lun->be_lun->lun_type) {
10207                 case T_DIRECT:
10208                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10209                             sizeof(inq_ptr->product));
10210                         break;
10211                 case T_PROCESSOR:
10212                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10213                             sizeof(inq_ptr->product));
10214                         break;
10215                 case T_CDROM:
10216                         strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10217                             sizeof(inq_ptr->product));
10218                         break;
10219                 default:
10220                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10221                             sizeof(inq_ptr->product));
10222                         break;
10223                 }
10224         } else {
10225                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10226                 strncpy(inq_ptr->product, val,
10227                     min(sizeof(inq_ptr->product), strlen(val)));
10228         }
10229
10230         /*
10231          * XXX make this a macro somewhere so it automatically gets
10232          * incremented when we make changes.
10233          */
10234         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10235             "revision")) == NULL) {
10236                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10237         } else {
10238                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10239                 strncpy(inq_ptr->revision, val,
10240                     min(sizeof(inq_ptr->revision), strlen(val)));
10241         }
10242
10243         /*
10244          * For parallel SCSI, we support double transition and single
10245          * transition clocking.  We also support QAS (Quick Arbitration
10246          * and Selection) and Information Unit transfers on both the
10247          * control and array devices.
10248          */
10249         if (port_type == CTL_PORT_SCSI)
10250                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10251                                     SID_SPI_IUS;
10252
10253         /* SAM-5 (no version claimed) */
10254         scsi_ulto2b(0x00A0, inq_ptr->version1);
10255         /* SPC-4 (no version claimed) */
10256         scsi_ulto2b(0x0460, inq_ptr->version2);
10257         if (port_type == CTL_PORT_FC) {
10258                 /* FCP-2 ANSI INCITS.350:2003 */
10259                 scsi_ulto2b(0x0917, inq_ptr->version3);
10260         } else if (port_type == CTL_PORT_SCSI) {
10261                 /* SPI-4 ANSI INCITS.362:200x */
10262                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10263         } else if (port_type == CTL_PORT_ISCSI) {
10264                 /* iSCSI (no version claimed) */
10265                 scsi_ulto2b(0x0960, inq_ptr->version3);
10266         } else if (port_type == CTL_PORT_SAS) {
10267                 /* SAS (no version claimed) */
10268                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10269         }
10270
10271         if (lun == NULL) {
10272                 /* SBC-4 (no version claimed) */
10273                 scsi_ulto2b(0x0600, inq_ptr->version4);
10274         } else {
10275                 switch (lun->be_lun->lun_type) {
10276                 case T_DIRECT:
10277                         /* SBC-4 (no version claimed) */
10278                         scsi_ulto2b(0x0600, inq_ptr->version4);
10279                         break;
10280                 case T_PROCESSOR:
10281                         break;
10282                 case T_CDROM:
10283                         /* MMC-6 (no version claimed) */
10284                         scsi_ulto2b(0x04E0, inq_ptr->version4);
10285                         break;
10286                 default:
10287                         break;
10288                 }
10289         }
10290
10291         ctl_set_success(ctsio);
10292         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10293         ctsio->be_move_done = ctl_config_move_done;
10294         ctl_datamove((union ctl_io *)ctsio);
10295         return (CTL_RETVAL_COMPLETE);
10296 }
10297
10298 int
10299 ctl_inquiry(struct ctl_scsiio *ctsio)
10300 {
10301         struct scsi_inquiry *cdb;
10302         int retval;
10303
10304         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10305
10306         cdb = (struct scsi_inquiry *)ctsio->cdb;
10307         if (cdb->byte2 & SI_EVPD)
10308                 retval = ctl_inquiry_evpd(ctsio);
10309         else if (cdb->page_code == 0)
10310                 retval = ctl_inquiry_std(ctsio);
10311         else {
10312                 ctl_set_invalid_field(ctsio,
10313                                       /*sks_valid*/ 1,
10314                                       /*command*/ 1,
10315                                       /*field*/ 2,
10316                                       /*bit_valid*/ 0,
10317                                       /*bit*/ 0);
10318                 ctl_done((union ctl_io *)ctsio);
10319                 return (CTL_RETVAL_COMPLETE);
10320         }
10321
10322         return (retval);
10323 }
10324
10325 int
10326 ctl_get_config(struct ctl_scsiio *ctsio)
10327 {
10328         struct scsi_get_config_header *hdr;
10329         struct scsi_get_config_feature *feature;
10330         struct scsi_get_config *cdb;
10331         struct ctl_lun *lun;
10332         uint32_t alloc_len, data_len;
10333         int rt, starting;
10334
10335         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10336         cdb = (struct scsi_get_config *)ctsio->cdb;
10337         rt = (cdb->rt & SGC_RT_MASK);
10338         starting = scsi_2btoul(cdb->starting_feature);
10339         alloc_len = scsi_2btoul(cdb->length);
10340
10341         data_len = sizeof(struct scsi_get_config_header) +
10342             sizeof(struct scsi_get_config_feature) + 8 +
10343             sizeof(struct scsi_get_config_feature) + 8 +
10344             sizeof(struct scsi_get_config_feature) + 4 +
10345             sizeof(struct scsi_get_config_feature) + 4 +
10346             sizeof(struct scsi_get_config_feature) + 8 +
10347             sizeof(struct scsi_get_config_feature) +
10348             sizeof(struct scsi_get_config_feature) + 4 +
10349             sizeof(struct scsi_get_config_feature) + 4 +
10350             sizeof(struct scsi_get_config_feature) + 4 +
10351             sizeof(struct scsi_get_config_feature) + 4 +
10352             sizeof(struct scsi_get_config_feature) + 4 +
10353             sizeof(struct scsi_get_config_feature) + 4;
10354         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10355         ctsio->kern_sg_entries = 0;
10356         ctsio->kern_data_resid = 0;
10357         ctsio->kern_rel_offset = 0;
10358
10359         hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10360         if (lun->flags & CTL_LUN_NO_MEDIA)
10361                 scsi_ulto2b(0x0000, hdr->current_profile);
10362         else
10363                 scsi_ulto2b(0x0010, hdr->current_profile);
10364         feature = (struct scsi_get_config_feature *)(hdr + 1);
10365
10366         if (starting > 0x003b)
10367                 goto done;
10368         if (starting > 0x003a)
10369                 goto f3b;
10370         if (starting > 0x002b)
10371                 goto f3a;
10372         if (starting > 0x002a)
10373                 goto f2b;
10374         if (starting > 0x001f)
10375                 goto f2a;
10376         if (starting > 0x001e)
10377                 goto f1f;
10378         if (starting > 0x001d)
10379                 goto f1e;
10380         if (starting > 0x0010)
10381                 goto f1d;
10382         if (starting > 0x0003)
10383                 goto f10;
10384         if (starting > 0x0002)
10385                 goto f3;
10386         if (starting > 0x0001)
10387                 goto f2;
10388         if (starting > 0x0000)
10389                 goto f1;
10390
10391         /* Profile List */
10392         scsi_ulto2b(0x0000, feature->feature_code);
10393         feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10394         feature->add_length = 8;
10395         scsi_ulto2b(0x0008, &feature->feature_data[0]); /* CD-ROM */
10396         feature->feature_data[2] = 0x00;
10397         scsi_ulto2b(0x0010, &feature->feature_data[4]); /* DVD-ROM */
10398         feature->feature_data[6] = 0x01;
10399         feature = (struct scsi_get_config_feature *)
10400             &feature->feature_data[feature->add_length];
10401
10402 f1:     /* Core */
10403         scsi_ulto2b(0x0001, feature->feature_code);
10404         feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10405         feature->add_length = 8;
10406         scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10407         feature->feature_data[4] = 0x03;
10408         feature = (struct scsi_get_config_feature *)
10409             &feature->feature_data[feature->add_length];
10410
10411 f2:     /* Morphing */
10412         scsi_ulto2b(0x0002, feature->feature_code);
10413         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10414         feature->add_length = 4;
10415         feature->feature_data[0] = 0x02;
10416         feature = (struct scsi_get_config_feature *)
10417             &feature->feature_data[feature->add_length];
10418
10419 f3:     /* Removable Medium */
10420         scsi_ulto2b(0x0003, feature->feature_code);
10421         feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10422         feature->add_length = 4;
10423         feature->feature_data[0] = 0x39;
10424         feature = (struct scsi_get_config_feature *)
10425             &feature->feature_data[feature->add_length];
10426
10427         if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10428                 goto done;
10429
10430 f10:    /* Random Read */
10431         scsi_ulto2b(0x0010, feature->feature_code);
10432         feature->flags = 0x00;
10433         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10434                 feature->flags |= SGC_F_CURRENT;
10435         feature->add_length = 8;
10436         scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10437         scsi_ulto2b(1, &feature->feature_data[4]);
10438         feature->feature_data[6] = 0x00;
10439         feature = (struct scsi_get_config_feature *)
10440             &feature->feature_data[feature->add_length];
10441
10442 f1d:    /* Multi-Read */
10443         scsi_ulto2b(0x001D, feature->feature_code);
10444         feature->flags = 0x00;
10445         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10446                 feature->flags |= SGC_F_CURRENT;
10447         feature->add_length = 0;
10448         feature = (struct scsi_get_config_feature *)
10449             &feature->feature_data[feature->add_length];
10450
10451 f1e:    /* CD Read */
10452         scsi_ulto2b(0x001E, feature->feature_code);
10453         feature->flags = 0x00;
10454         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10455                 feature->flags |= SGC_F_CURRENT;
10456         feature->add_length = 4;
10457         feature->feature_data[0] = 0x00;
10458         feature = (struct scsi_get_config_feature *)
10459             &feature->feature_data[feature->add_length];
10460
10461 f1f:    /* DVD Read */
10462         scsi_ulto2b(0x001F, feature->feature_code);
10463         feature->flags = 0x08;
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] = 0x01;
10468         feature->feature_data[2] = 0x03;
10469         feature = (struct scsi_get_config_feature *)
10470             &feature->feature_data[feature->add_length];
10471
10472 f2a:    /* DVD+RW */
10473         scsi_ulto2b(0x002A, feature->feature_code);
10474         feature->flags = 0x04;
10475         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10476                 feature->flags |= SGC_F_CURRENT;
10477         feature->add_length = 4;
10478         feature->feature_data[0] = 0x00;
10479         feature->feature_data[1] = 0x00;
10480         feature = (struct scsi_get_config_feature *)
10481             &feature->feature_data[feature->add_length];
10482
10483 f2b:    /* DVD+R */
10484         scsi_ulto2b(0x002B, feature->feature_code);
10485         feature->flags = 0x00;
10486         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10487                 feature->flags |= SGC_F_CURRENT;
10488         feature->add_length = 4;
10489         feature->feature_data[0] = 0x00;
10490         feature = (struct scsi_get_config_feature *)
10491             &feature->feature_data[feature->add_length];
10492
10493 f3a:    /* DVD+RW Dual Layer */
10494         scsi_ulto2b(0x003A, feature->feature_code);
10495         feature->flags = 0x00;
10496         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10497                 feature->flags |= SGC_F_CURRENT;
10498         feature->add_length = 4;
10499         feature->feature_data[0] = 0x00;
10500         feature->feature_data[1] = 0x00;
10501         feature = (struct scsi_get_config_feature *)
10502             &feature->feature_data[feature->add_length];
10503
10504 f3b:    /* DVD+R Dual Layer */
10505         scsi_ulto2b(0x003B, feature->feature_code);
10506         feature->flags = 0x00;
10507         if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10508                 feature->flags |= SGC_F_CURRENT;
10509         feature->add_length = 4;
10510         feature->feature_data[0] = 0x00;
10511         feature = (struct scsi_get_config_feature *)
10512             &feature->feature_data[feature->add_length];
10513
10514 done:
10515         data_len = (uint8_t *)feature - (uint8_t *)hdr;
10516         if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10517                 feature = (struct scsi_get_config_feature *)(hdr + 1);
10518                 if (scsi_2btoul(feature->feature_code) == starting)
10519                         feature = (struct scsi_get_config_feature *)
10520                             &feature->feature_data[feature->add_length];
10521                 data_len = (uint8_t *)feature - (uint8_t *)hdr;
10522         }
10523         scsi_ulto4b(data_len - 4, hdr->data_length);
10524         if (data_len < alloc_len) {
10525                 ctsio->residual = alloc_len - data_len;
10526                 ctsio->kern_data_len = data_len;
10527                 ctsio->kern_total_len = data_len;
10528         } else {
10529                 ctsio->residual = 0;
10530                 ctsio->kern_data_len = alloc_len;
10531                 ctsio->kern_total_len = alloc_len;
10532         }
10533
10534         ctl_set_success(ctsio);
10535         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10536         ctsio->be_move_done = ctl_config_move_done;
10537         ctl_datamove((union ctl_io *)ctsio);
10538         return (CTL_RETVAL_COMPLETE);
10539 }
10540
10541 int
10542 ctl_get_event_status(struct ctl_scsiio *ctsio)
10543 {
10544         struct scsi_get_event_status_header *hdr;
10545         struct scsi_get_event_status *cdb;
10546         struct ctl_lun *lun;
10547         uint32_t alloc_len, data_len;
10548         int notif_class;
10549
10550         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10551         cdb = (struct scsi_get_event_status *)ctsio->cdb;
10552         if ((cdb->byte2 & SGESN_POLLED) == 0) {
10553                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10554                     /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10555                 ctl_done((union ctl_io *)ctsio);
10556                 return (CTL_RETVAL_COMPLETE);
10557         }
10558         notif_class = cdb->notif_class;
10559         alloc_len = scsi_2btoul(cdb->length);
10560
10561         data_len = sizeof(struct scsi_get_event_status_header);
10562         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10563         ctsio->kern_sg_entries = 0;
10564         ctsio->kern_data_resid = 0;
10565         ctsio->kern_rel_offset = 0;
10566
10567         if (data_len < alloc_len) {
10568                 ctsio->residual = alloc_len - data_len;
10569                 ctsio->kern_data_len = data_len;
10570                 ctsio->kern_total_len = data_len;
10571         } else {
10572                 ctsio->residual = 0;
10573                 ctsio->kern_data_len = alloc_len;
10574                 ctsio->kern_total_len = alloc_len;
10575         }
10576
10577         hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10578         scsi_ulto2b(0, hdr->descr_length);
10579         hdr->nea_class = SGESN_NEA;
10580         hdr->supported_class = 0;
10581
10582         ctl_set_success(ctsio);
10583         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10584         ctsio->be_move_done = ctl_config_move_done;
10585         ctl_datamove((union ctl_io *)ctsio);
10586         return (CTL_RETVAL_COMPLETE);
10587 }
10588
10589 int
10590 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10591 {
10592         struct scsi_mechanism_status_header *hdr;
10593         struct scsi_mechanism_status *cdb;
10594         struct ctl_lun *lun;
10595         uint32_t alloc_len, data_len;
10596
10597         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10598         cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10599         alloc_len = scsi_2btoul(cdb->length);
10600
10601         data_len = sizeof(struct scsi_mechanism_status_header);
10602         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10603         ctsio->kern_sg_entries = 0;
10604         ctsio->kern_data_resid = 0;
10605         ctsio->kern_rel_offset = 0;
10606
10607         if (data_len < alloc_len) {
10608                 ctsio->residual = alloc_len - data_len;
10609                 ctsio->kern_data_len = data_len;
10610                 ctsio->kern_total_len = data_len;
10611         } else {
10612                 ctsio->residual = 0;
10613                 ctsio->kern_data_len = alloc_len;
10614                 ctsio->kern_total_len = alloc_len;
10615         }
10616
10617         hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10618         hdr->state1 = 0x00;
10619         hdr->state2 = 0xe0;
10620         scsi_ulto3b(0, hdr->lba);
10621         hdr->slots_num = 0;
10622         scsi_ulto2b(0, hdr->slots_length);
10623
10624         ctl_set_success(ctsio);
10625         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10626         ctsio->be_move_done = ctl_config_move_done;
10627         ctl_datamove((union ctl_io *)ctsio);
10628         return (CTL_RETVAL_COMPLETE);
10629 }
10630
10631 static void
10632 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10633 {
10634
10635         lba += 150;
10636         buf[0] = 0;
10637         buf[1] = bin2bcd((lba / 75) / 60);
10638         buf[2] = bin2bcd((lba / 75) % 60);
10639         buf[3] = bin2bcd(lba % 75);
10640 }
10641
10642 int
10643 ctl_read_toc(struct ctl_scsiio *ctsio)
10644 {
10645         struct scsi_read_toc_hdr *hdr;
10646         struct scsi_read_toc_type01_descr *descr;
10647         struct scsi_read_toc *cdb;
10648         struct ctl_lun *lun;
10649         uint32_t alloc_len, data_len;
10650         int format, msf;
10651
10652         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10653         cdb = (struct scsi_read_toc *)ctsio->cdb;
10654         msf = (cdb->byte2 & CD_MSF) != 0;
10655         format = cdb->format;
10656         alloc_len = scsi_2btoul(cdb->data_len);
10657
10658         data_len = sizeof(struct scsi_read_toc_hdr);
10659         if (format == 0)
10660                 data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10661         else
10662                 data_len += sizeof(struct scsi_read_toc_type01_descr);
10663         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10664         ctsio->kern_sg_entries = 0;
10665         ctsio->kern_data_resid = 0;
10666         ctsio->kern_rel_offset = 0;
10667
10668         if (data_len < alloc_len) {
10669                 ctsio->residual = alloc_len - data_len;
10670                 ctsio->kern_data_len = data_len;
10671                 ctsio->kern_total_len = data_len;
10672         } else {
10673                 ctsio->residual = 0;
10674                 ctsio->kern_data_len = alloc_len;
10675                 ctsio->kern_total_len = alloc_len;
10676         }
10677
10678         hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10679         if (format == 0) {
10680                 scsi_ulto2b(0x12, hdr->data_length);
10681                 hdr->first = 1;
10682                 hdr->last = 1;
10683                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10684                 descr->addr_ctl = 0x14;
10685                 descr->track_number = 1;
10686                 if (msf)
10687                         ctl_ultomsf(0, descr->track_start);
10688                 else
10689                         scsi_ulto4b(0, descr->track_start);
10690                 descr++;
10691                 descr->addr_ctl = 0x14;
10692                 descr->track_number = 0xaa;
10693                 if (msf)
10694                         ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10695                 else
10696                         scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10697         } else {
10698                 scsi_ulto2b(0x0a, hdr->data_length);
10699                 hdr->first = 1;
10700                 hdr->last = 1;
10701                 descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10702                 descr->addr_ctl = 0x14;
10703                 descr->track_number = 1;
10704                 if (msf)
10705                         ctl_ultomsf(0, descr->track_start);
10706                 else
10707                         scsi_ulto4b(0, descr->track_start);
10708         }
10709
10710         ctl_set_success(ctsio);
10711         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10712         ctsio->be_move_done = ctl_config_move_done;
10713         ctl_datamove((union ctl_io *)ctsio);
10714         return (CTL_RETVAL_COMPLETE);
10715 }
10716
10717 /*
10718  * For known CDB types, parse the LBA and length.
10719  */
10720 static int
10721 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10722 {
10723         if (io->io_hdr.io_type != CTL_IO_SCSI)
10724                 return (1);
10725
10726         switch (io->scsiio.cdb[0]) {
10727         case COMPARE_AND_WRITE: {
10728                 struct scsi_compare_and_write *cdb;
10729
10730                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10731
10732                 *lba = scsi_8btou64(cdb->addr);
10733                 *len = cdb->length;
10734                 break;
10735         }
10736         case READ_6:
10737         case WRITE_6: {
10738                 struct scsi_rw_6 *cdb;
10739
10740                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10741
10742                 *lba = scsi_3btoul(cdb->addr);
10743                 /* only 5 bits are valid in the most significant address byte */
10744                 *lba &= 0x1fffff;
10745                 *len = cdb->length;
10746                 break;
10747         }
10748         case READ_10:
10749         case WRITE_10: {
10750                 struct scsi_rw_10 *cdb;
10751
10752                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10753
10754                 *lba = scsi_4btoul(cdb->addr);
10755                 *len = scsi_2btoul(cdb->length);
10756                 break;
10757         }
10758         case WRITE_VERIFY_10: {
10759                 struct scsi_write_verify_10 *cdb;
10760
10761                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10762
10763                 *lba = scsi_4btoul(cdb->addr);
10764                 *len = scsi_2btoul(cdb->length);
10765                 break;
10766         }
10767         case READ_12:
10768         case WRITE_12: {
10769                 struct scsi_rw_12 *cdb;
10770
10771                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10772
10773                 *lba = scsi_4btoul(cdb->addr);
10774                 *len = scsi_4btoul(cdb->length);
10775                 break;
10776         }
10777         case WRITE_VERIFY_12: {
10778                 struct scsi_write_verify_12 *cdb;
10779
10780                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10781
10782                 *lba = scsi_4btoul(cdb->addr);
10783                 *len = scsi_4btoul(cdb->length);
10784                 break;
10785         }
10786         case READ_16:
10787         case WRITE_16: {
10788                 struct scsi_rw_16 *cdb;
10789
10790                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10791
10792                 *lba = scsi_8btou64(cdb->addr);
10793                 *len = scsi_4btoul(cdb->length);
10794                 break;
10795         }
10796         case WRITE_ATOMIC_16: {
10797                 struct scsi_write_atomic_16 *cdb;
10798
10799                 cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10800
10801                 *lba = scsi_8btou64(cdb->addr);
10802                 *len = scsi_2btoul(cdb->length);
10803                 break;
10804         }
10805         case WRITE_VERIFY_16: {
10806                 struct scsi_write_verify_16 *cdb;
10807
10808                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10809
10810                 *lba = scsi_8btou64(cdb->addr);
10811                 *len = scsi_4btoul(cdb->length);
10812                 break;
10813         }
10814         case WRITE_SAME_10: {
10815                 struct scsi_write_same_10 *cdb;
10816
10817                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10818
10819                 *lba = scsi_4btoul(cdb->addr);
10820                 *len = scsi_2btoul(cdb->length);
10821                 break;
10822         }
10823         case WRITE_SAME_16: {
10824                 struct scsi_write_same_16 *cdb;
10825
10826                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10827
10828                 *lba = scsi_8btou64(cdb->addr);
10829                 *len = scsi_4btoul(cdb->length);
10830                 break;
10831         }
10832         case VERIFY_10: {
10833                 struct scsi_verify_10 *cdb;
10834
10835                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10836
10837                 *lba = scsi_4btoul(cdb->addr);
10838                 *len = scsi_2btoul(cdb->length);
10839                 break;
10840         }
10841         case VERIFY_12: {
10842                 struct scsi_verify_12 *cdb;
10843
10844                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10845
10846                 *lba = scsi_4btoul(cdb->addr);
10847                 *len = scsi_4btoul(cdb->length);
10848                 break;
10849         }
10850         case VERIFY_16: {
10851                 struct scsi_verify_16 *cdb;
10852
10853                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10854
10855                 *lba = scsi_8btou64(cdb->addr);
10856                 *len = scsi_4btoul(cdb->length);
10857                 break;
10858         }
10859         case UNMAP: {
10860                 *lba = 0;
10861                 *len = UINT64_MAX;
10862                 break;
10863         }
10864         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10865                 struct scsi_get_lba_status *cdb;
10866
10867                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10868                 *lba = scsi_8btou64(cdb->addr);
10869                 *len = UINT32_MAX;
10870                 break;
10871         }
10872         default:
10873                 return (1);
10874                 break; /* NOTREACHED */
10875         }
10876
10877         return (0);
10878 }
10879
10880 static ctl_action
10881 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10882     bool seq)
10883 {
10884         uint64_t endlba1, endlba2;
10885
10886         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10887         endlba2 = lba2 + len2 - 1;
10888
10889         if ((endlba1 < lba2) || (endlba2 < lba1))
10890                 return (CTL_ACTION_PASS);
10891         else
10892                 return (CTL_ACTION_BLOCK);
10893 }
10894
10895 static int
10896 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10897 {
10898         struct ctl_ptr_len_flags *ptrlen;
10899         struct scsi_unmap_desc *buf, *end, *range;
10900         uint64_t lba;
10901         uint32_t len;
10902
10903         /* If not UNMAP -- go other way. */
10904         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10905             io->scsiio.cdb[0] != UNMAP)
10906                 return (CTL_ACTION_ERROR);
10907
10908         /* If UNMAP without data -- block and wait for data. */
10909         ptrlen = (struct ctl_ptr_len_flags *)
10910             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10911         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10912             ptrlen->ptr == NULL)
10913                 return (CTL_ACTION_BLOCK);
10914
10915         /* UNMAP with data -- check for collision. */
10916         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10917         end = buf + ptrlen->len / sizeof(*buf);
10918         for (range = buf; range < end; range++) {
10919                 lba = scsi_8btou64(range->lba);
10920                 len = scsi_4btoul(range->length);
10921                 if ((lba < lba2 + len2) && (lba + len > lba2))
10922                         return (CTL_ACTION_BLOCK);
10923         }
10924         return (CTL_ACTION_PASS);
10925 }
10926
10927 static ctl_action
10928 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10929 {
10930         uint64_t lba1, lba2;
10931         uint64_t len1, len2;
10932         int retval;
10933
10934         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10935                 return (CTL_ACTION_ERROR);
10936
10937         retval = ctl_extent_check_unmap(io1, lba2, len2);
10938         if (retval != CTL_ACTION_ERROR)
10939                 return (retval);
10940
10941         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10942                 return (CTL_ACTION_ERROR);
10943
10944         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10945                 seq = FALSE;
10946         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10947 }
10948
10949 static ctl_action
10950 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10951 {
10952         uint64_t lba1, lba2;
10953         uint64_t len1, len2;
10954
10955         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10956                 return (CTL_ACTION_PASS);
10957         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10958                 return (CTL_ACTION_ERROR);
10959         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10960                 return (CTL_ACTION_ERROR);
10961
10962         if (lba1 + len1 == lba2)
10963                 return (CTL_ACTION_BLOCK);
10964         return (CTL_ACTION_PASS);
10965 }
10966
10967 static ctl_action
10968 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10969     union ctl_io *ooa_io)
10970 {
10971         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10972         const ctl_serialize_action *serialize_row;
10973
10974         /*
10975          * The initiator attempted multiple untagged commands at the same
10976          * time.  Can't do that.
10977          */
10978         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10979          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10980          && ((pending_io->io_hdr.nexus.targ_port ==
10981               ooa_io->io_hdr.nexus.targ_port)
10982           && (pending_io->io_hdr.nexus.initid ==
10983               ooa_io->io_hdr.nexus.initid))
10984          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10985               CTL_FLAG_STATUS_SENT)) == 0))
10986                 return (CTL_ACTION_OVERLAP);
10987
10988         /*
10989          * The initiator attempted to send multiple tagged commands with
10990          * the same ID.  (It's fine if different initiators have the same
10991          * tag ID.)
10992          *
10993          * Even if all of those conditions are true, we don't kill the I/O
10994          * if the command ahead of us has been aborted.  We won't end up
10995          * sending it to the FETD, and it's perfectly legal to resend a
10996          * command with the same tag number as long as the previous
10997          * instance of this tag number has been aborted somehow.
10998          */
10999         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11000          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11001          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11002          && ((pending_io->io_hdr.nexus.targ_port ==
11003               ooa_io->io_hdr.nexus.targ_port)
11004           && (pending_io->io_hdr.nexus.initid ==
11005               ooa_io->io_hdr.nexus.initid))
11006          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11007               CTL_FLAG_STATUS_SENT)) == 0))
11008                 return (CTL_ACTION_OVERLAP_TAG);
11009
11010         /*
11011          * If we get a head of queue tag, SAM-3 says that we should
11012          * immediately execute it.
11013          *
11014          * What happens if this command would normally block for some other
11015          * reason?  e.g. a request sense with a head of queue tag
11016          * immediately after a write.  Normally that would block, but this
11017          * will result in its getting executed immediately...
11018          *
11019          * We currently return "pass" instead of "skip", so we'll end up
11020          * going through the rest of the queue to check for overlapped tags.
11021          *
11022          * XXX KDM check for other types of blockage first??
11023          */
11024         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11025                 return (CTL_ACTION_PASS);
11026
11027         /*
11028          * Ordered tags have to block until all items ahead of them
11029          * have completed.  If we get called with an ordered tag, we always
11030          * block, if something else is ahead of us in the queue.
11031          */
11032         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11033                 return (CTL_ACTION_BLOCK);
11034
11035         /*
11036          * Simple tags get blocked until all head of queue and ordered tags
11037          * ahead of them have completed.  I'm lumping untagged commands in
11038          * with simple tags here.  XXX KDM is that the right thing to do?
11039          */
11040         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11041           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11042          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11043           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11044                 return (CTL_ACTION_BLOCK);
11045
11046         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11047         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11048
11049         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11050
11051         switch (serialize_row[pending_entry->seridx]) {
11052         case CTL_SER_BLOCK:
11053                 return (CTL_ACTION_BLOCK);
11054         case CTL_SER_EXTENT:
11055                 return (ctl_extent_check(ooa_io, pending_io,
11056                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11057         case CTL_SER_EXTENTOPT:
11058                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11059                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11060                         return (ctl_extent_check(ooa_io, pending_io,
11061                             (lun->be_lun &&
11062                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11063                 return (CTL_ACTION_PASS);
11064         case CTL_SER_EXTENTSEQ:
11065                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11066                         return (ctl_extent_check_seq(ooa_io, pending_io));
11067                 return (CTL_ACTION_PASS);
11068         case CTL_SER_PASS:
11069                 return (CTL_ACTION_PASS);
11070         case CTL_SER_BLOCKOPT:
11071                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11072                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11073                         return (CTL_ACTION_BLOCK);
11074                 return (CTL_ACTION_PASS);
11075         case CTL_SER_SKIP:
11076                 return (CTL_ACTION_SKIP);
11077         default:
11078                 panic("%s: Invalid serialization value %d for %d => %d",
11079                     __func__, serialize_row[pending_entry->seridx],
11080                     pending_entry->seridx, ooa_entry->seridx);
11081         }
11082
11083         return (CTL_ACTION_ERROR);
11084 }
11085
11086 /*
11087  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11088  * Assumptions:
11089  * - pending_io is generally either incoming, or on the blocked queue
11090  * - starting I/O is the I/O we want to start the check with.
11091  */
11092 static ctl_action
11093 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11094               union ctl_io *starting_io)
11095 {
11096         union ctl_io *ooa_io;
11097         ctl_action action;
11098
11099         mtx_assert(&lun->lun_lock, MA_OWNED);
11100
11101         /*
11102          * Run back along the OOA queue, starting with the current
11103          * blocked I/O and going through every I/O before it on the
11104          * queue.  If starting_io is NULL, we'll just end up returning
11105          * CTL_ACTION_PASS.
11106          */
11107         for (ooa_io = starting_io; ooa_io != NULL;
11108              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11109              ooa_links)){
11110
11111                 /*
11112                  * This routine just checks to see whether
11113                  * cur_blocked is blocked by ooa_io, which is ahead
11114                  * of it in the queue.  It doesn't queue/dequeue
11115                  * cur_blocked.
11116                  */
11117                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11118                 switch (action) {
11119                 case CTL_ACTION_BLOCK:
11120                 case CTL_ACTION_OVERLAP:
11121                 case CTL_ACTION_OVERLAP_TAG:
11122                 case CTL_ACTION_SKIP:
11123                 case CTL_ACTION_ERROR:
11124                         return (action);
11125                         break; /* NOTREACHED */
11126                 case CTL_ACTION_PASS:
11127                         break;
11128                 default:
11129                         panic("%s: Invalid action %d\n", __func__, action);
11130                 }
11131         }
11132
11133         return (CTL_ACTION_PASS);
11134 }
11135
11136 /*
11137  * Assumptions:
11138  * - An I/O has just completed, and has been removed from the per-LUN OOA
11139  *   queue, so some items on the blocked queue may now be unblocked.
11140  */
11141 static int
11142 ctl_check_blocked(struct ctl_lun *lun)
11143 {
11144         struct ctl_softc *softc = lun->ctl_softc;
11145         union ctl_io *cur_blocked, *next_blocked;
11146
11147         mtx_assert(&lun->lun_lock, MA_OWNED);
11148
11149         /*
11150          * Run forward from the head of the blocked queue, checking each
11151          * entry against the I/Os prior to it on the OOA queue to see if
11152          * there is still any blockage.
11153          *
11154          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11155          * with our removing a variable on it while it is traversing the
11156          * list.
11157          */
11158         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11159              cur_blocked != NULL; cur_blocked = next_blocked) {
11160                 union ctl_io *prev_ooa;
11161                 ctl_action action;
11162
11163                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11164                                                           blocked_links);
11165
11166                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11167                                                       ctl_ooaq, ooa_links);
11168
11169                 /*
11170                  * If cur_blocked happens to be the first item in the OOA
11171                  * queue now, prev_ooa will be NULL, and the action
11172                  * returned will just be CTL_ACTION_PASS.
11173                  */
11174                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11175
11176                 switch (action) {
11177                 case CTL_ACTION_BLOCK:
11178                         /* Nothing to do here, still blocked */
11179                         break;
11180                 case CTL_ACTION_OVERLAP:
11181                 case CTL_ACTION_OVERLAP_TAG:
11182                         /*
11183                          * This shouldn't happen!  In theory we've already
11184                          * checked this command for overlap...
11185                          */
11186                         break;
11187                 case CTL_ACTION_PASS:
11188                 case CTL_ACTION_SKIP: {
11189                         const struct ctl_cmd_entry *entry;
11190
11191                         /*
11192                          * The skip case shouldn't happen, this transaction
11193                          * should have never made it onto the blocked queue.
11194                          */
11195                         /*
11196                          * This I/O is no longer blocked, we can remove it
11197                          * from the blocked queue.  Since this is a TAILQ
11198                          * (doubly linked list), we can do O(1) removals
11199                          * from any place on the list.
11200                          */
11201                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11202                                      blocked_links);
11203                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11204
11205                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11206                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11207                                 /*
11208                                  * Need to send IO back to original side to
11209                                  * run
11210                                  */
11211                                 union ctl_ha_msg msg_info;
11212
11213                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11214                                 msg_info.hdr.original_sc =
11215                                         cur_blocked->io_hdr.original_sc;
11216                                 msg_info.hdr.serializing_sc = cur_blocked;
11217                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11218                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11219                                     sizeof(msg_info.hdr), M_NOWAIT);
11220                                 break;
11221                         }
11222                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11223
11224                         /*
11225                          * Check this I/O for LUN state changes that may
11226                          * have happened while this command was blocked.
11227                          * The LUN state may have been changed by a command
11228                          * ahead of us in the queue, so we need to re-check
11229                          * for any states that can be caused by SCSI
11230                          * commands.
11231                          */
11232                         if (ctl_scsiio_lun_check(lun, entry,
11233                                                  &cur_blocked->scsiio) == 0) {
11234                                 cur_blocked->io_hdr.flags |=
11235                                                       CTL_FLAG_IS_WAS_ON_RTR;
11236                                 ctl_enqueue_rtr(cur_blocked);
11237                         } else
11238                                 ctl_done(cur_blocked);
11239                         break;
11240                 }
11241                 default:
11242                         /*
11243                          * This probably shouldn't happen -- we shouldn't
11244                          * get CTL_ACTION_ERROR, or anything else.
11245                          */
11246                         break;
11247                 }
11248         }
11249
11250         return (CTL_RETVAL_COMPLETE);
11251 }
11252
11253 /*
11254  * This routine (with one exception) checks LUN flags that can be set by
11255  * commands ahead of us in the OOA queue.  These flags have to be checked
11256  * when a command initially comes in, and when we pull a command off the
11257  * blocked queue and are preparing to execute it.  The reason we have to
11258  * check these flags for commands on the blocked queue is that the LUN
11259  * state may have been changed by a command ahead of us while we're on the
11260  * blocked queue.
11261  *
11262  * Ordering is somewhat important with these checks, so please pay
11263  * careful attention to the placement of any new checks.
11264  */
11265 static int
11266 ctl_scsiio_lun_check(struct ctl_lun *lun,
11267     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11268 {
11269         struct ctl_softc *softc = lun->ctl_softc;
11270         int retval;
11271         uint32_t residx;
11272
11273         retval = 0;
11274
11275         mtx_assert(&lun->lun_lock, MA_OWNED);
11276
11277         /*
11278          * If this shelf is a secondary shelf controller, we may have to
11279          * reject some commands disallowed by HA mode and link state.
11280          */
11281         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11282                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11283                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11284                         ctl_set_lun_unavail(ctsio);
11285                         retval = 1;
11286                         goto bailout;
11287                 }
11288                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11289                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11290                         ctl_set_lun_transit(ctsio);
11291                         retval = 1;
11292                         goto bailout;
11293                 }
11294                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11295                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11296                         ctl_set_lun_standby(ctsio);
11297                         retval = 1;
11298                         goto bailout;
11299                 }
11300
11301                 /* The rest of checks are only done on executing side */
11302                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11303                         goto bailout;
11304         }
11305
11306         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11307                 if (lun->be_lun &&
11308                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11309                         ctl_set_hw_write_protected(ctsio);
11310                         retval = 1;
11311                         goto bailout;
11312                 }
11313                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11314                     .eca_and_aen & SCP_SWP) != 0) {
11315                         ctl_set_sense(ctsio, /*current_error*/ 1,
11316                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11317                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11318                         retval = 1;
11319                         goto bailout;
11320                 }
11321         }
11322
11323         /*
11324          * Check for a reservation conflict.  If this command isn't allowed
11325          * even on reserved LUNs, and if this initiator isn't the one who
11326          * reserved us, reject the command with a reservation conflict.
11327          */
11328         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11329         if ((lun->flags & CTL_LUN_RESERVED)
11330          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11331                 if (lun->res_idx != residx) {
11332                         ctl_set_reservation_conflict(ctsio);
11333                         retval = 1;
11334                         goto bailout;
11335                 }
11336         }
11337
11338         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11339             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11340                 /* No reservation or command is allowed. */;
11341         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11342             (lun->pr_res_type == SPR_TYPE_WR_EX ||
11343              lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11344              lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11345                 /* The command is allowed for Write Exclusive resv. */;
11346         } else {
11347                 /*
11348                  * if we aren't registered or it's a res holder type
11349                  * reservation and this isn't the res holder then set a
11350                  * conflict.
11351                  */
11352                 if (ctl_get_prkey(lun, residx) == 0 ||
11353                     (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11354                         ctl_set_reservation_conflict(ctsio);
11355                         retval = 1;
11356                         goto bailout;
11357                 }
11358         }
11359
11360         if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11361                 if (lun->flags & CTL_LUN_EJECTED)
11362                         ctl_set_lun_ejected(ctsio);
11363                 else if (lun->flags & CTL_LUN_NO_MEDIA) {
11364                         if (lun->flags & CTL_LUN_REMOVABLE)
11365                                 ctl_set_lun_no_media(ctsio);
11366                         else
11367                                 ctl_set_lun_int_reqd(ctsio);
11368                 } else if (lun->flags & CTL_LUN_STOPPED)
11369                         ctl_set_lun_stopped(ctsio);
11370                 else
11371                         goto bailout;
11372                 retval = 1;
11373                 goto bailout;
11374         }
11375
11376 bailout:
11377         return (retval);
11378 }
11379
11380 static void
11381 ctl_failover_io(union ctl_io *io, int have_lock)
11382 {
11383         ctl_set_busy(&io->scsiio);
11384         ctl_done(io);
11385 }
11386
11387 static void
11388 ctl_failover_lun(union ctl_io *rio)
11389 {
11390         struct ctl_softc *softc = control_softc;
11391         struct ctl_lun *lun;
11392         struct ctl_io_hdr *io, *next_io;
11393         uint32_t targ_lun;
11394
11395         targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11396         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11397
11398         /* Find and lock the LUN. */
11399         mtx_lock(&softc->ctl_lock);
11400         if ((targ_lun < CTL_MAX_LUNS) &&
11401             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11402                 mtx_lock(&lun->lun_lock);
11403                 mtx_unlock(&softc->ctl_lock);
11404                 if (lun->flags & CTL_LUN_DISABLED) {
11405                         mtx_unlock(&lun->lun_lock);
11406                         return;
11407                 }
11408         } else {
11409                 mtx_unlock(&softc->ctl_lock);
11410                 return;
11411         }
11412
11413         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11414                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11415                         /* We are master */
11416                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11417                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11418                                         io->flags |= CTL_FLAG_ABORT;
11419                                         io->flags |= CTL_FLAG_FAILOVER;
11420                                 } else { /* This can be only due to DATAMOVE */
11421                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11422                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11423                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11424                                         io->port_status = 31340;
11425                                         ctl_enqueue_isc((union ctl_io *)io);
11426                                 }
11427                         }
11428                         /* We are slave */
11429                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11430                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11431                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11432                                         io->flags |= CTL_FLAG_FAILOVER;
11433                                 } else {
11434                                         ctl_set_busy(&((union ctl_io *)io)->
11435                                             scsiio);
11436                                         ctl_done((union ctl_io *)io);
11437                                 }
11438                         }
11439                 }
11440         } else { /* SERIALIZE modes */
11441                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11442                     next_io) {
11443                         /* We are master */
11444                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11445                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11446                                     blocked_links);
11447                                 io->flags &= ~CTL_FLAG_BLOCKED;
11448                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11449                                 ctl_free_io((union ctl_io *)io);
11450                         }
11451                 }
11452                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11453                         /* We are master */
11454                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11455                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11456                                 ctl_free_io((union ctl_io *)io);
11457                         }
11458                         /* We are slave */
11459                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11460                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11461                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11462                                         ctl_set_busy(&((union ctl_io *)io)->
11463                                             scsiio);
11464                                         ctl_done((union ctl_io *)io);
11465                                 }
11466                         }
11467                 }
11468                 ctl_check_blocked(lun);
11469         }
11470         mtx_unlock(&lun->lun_lock);
11471 }
11472
11473 static int
11474 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11475 {
11476         struct ctl_lun *lun;
11477         const struct ctl_cmd_entry *entry;
11478         uint32_t initidx, targ_lun;
11479         int retval;
11480
11481         retval = 0;
11482
11483         lun = NULL;
11484
11485         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11486         if ((targ_lun < CTL_MAX_LUNS)
11487          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11488                 /*
11489                  * If the LUN is invalid, pretend that it doesn't exist.
11490                  * It will go away as soon as all pending I/O has been
11491                  * completed.
11492                  */
11493                 mtx_lock(&lun->lun_lock);
11494                 if (lun->flags & CTL_LUN_DISABLED) {
11495                         mtx_unlock(&lun->lun_lock);
11496                         lun = NULL;
11497                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11498                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11499                 } else {
11500                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11501                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11502                                 lun->be_lun;
11503
11504                         /*
11505                          * Every I/O goes into the OOA queue for a
11506                          * particular LUN, and stays there until completion.
11507                          */
11508 #ifdef CTL_TIME_IO
11509                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11510                                 lun->idle_time += getsbinuptime() -
11511                                     lun->last_busy;
11512                         }
11513 #endif
11514                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11515                             ooa_links);
11516                 }
11517         } else {
11518                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11519                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11520         }
11521
11522         /* Get command entry and return error if it is unsuppotyed. */
11523         entry = ctl_validate_command(ctsio);
11524         if (entry == NULL) {
11525                 if (lun)
11526                         mtx_unlock(&lun->lun_lock);
11527                 return (retval);
11528         }
11529
11530         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11531         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11532
11533         /*
11534          * Check to see whether we can send this command to LUNs that don't
11535          * exist.  This should pretty much only be the case for inquiry
11536          * and request sense.  Further checks, below, really require having
11537          * a LUN, so we can't really check the command anymore.  Just put
11538          * it on the rtr queue.
11539          */
11540         if (lun == NULL) {
11541                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11542                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11543                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11544                         return (retval);
11545                 }
11546
11547                 ctl_set_unsupported_lun(ctsio);
11548                 ctl_done((union ctl_io *)ctsio);
11549                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11550                 return (retval);
11551         } else {
11552                 /*
11553                  * Make sure we support this particular command on this LUN.
11554                  * e.g., we don't support writes to the control LUN.
11555                  */
11556                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11557                         mtx_unlock(&lun->lun_lock);
11558                         ctl_set_invalid_opcode(ctsio);
11559                         ctl_done((union ctl_io *)ctsio);
11560                         return (retval);
11561                 }
11562         }
11563
11564         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11565
11566 #ifdef CTL_WITH_CA
11567         /*
11568          * If we've got a request sense, it'll clear the contingent
11569          * allegiance condition.  Otherwise, if we have a CA condition for
11570          * this initiator, clear it, because it sent down a command other
11571          * than request sense.
11572          */
11573         if ((ctsio->cdb[0] != REQUEST_SENSE)
11574          && (ctl_is_set(lun->have_ca, initidx)))
11575                 ctl_clear_mask(lun->have_ca, initidx);
11576 #endif
11577
11578         /*
11579          * If the command has this flag set, it handles its own unit
11580          * attention reporting, we shouldn't do anything.  Otherwise we
11581          * check for any pending unit attentions, and send them back to the
11582          * initiator.  We only do this when a command initially comes in,
11583          * not when we pull it off the blocked queue.
11584          *
11585          * According to SAM-3, section 5.3.2, the order that things get
11586          * presented back to the host is basically unit attentions caused
11587          * by some sort of reset event, busy status, reservation conflicts
11588          * or task set full, and finally any other status.
11589          *
11590          * One issue here is that some of the unit attentions we report
11591          * don't fall into the "reset" category (e.g. "reported luns data
11592          * has changed").  So reporting it here, before the reservation
11593          * check, may be technically wrong.  I guess the only thing to do
11594          * would be to check for and report the reset events here, and then
11595          * check for the other unit attention types after we check for a
11596          * reservation conflict.
11597          *
11598          * XXX KDM need to fix this
11599          */
11600         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11601                 ctl_ua_type ua_type;
11602
11603                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11604                     SSD_TYPE_NONE);
11605                 if (ua_type != CTL_UA_NONE) {
11606                         mtx_unlock(&lun->lun_lock);
11607                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11608                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11609                         ctsio->sense_len = SSD_FULL_SIZE;
11610                         ctl_done((union ctl_io *)ctsio);
11611                         return (retval);
11612                 }
11613         }
11614
11615
11616         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11617                 mtx_unlock(&lun->lun_lock);
11618                 ctl_done((union ctl_io *)ctsio);
11619                 return (retval);
11620         }
11621
11622         /*
11623          * XXX CHD this is where we want to send IO to other side if
11624          * this LUN is secondary on this SC. We will need to make a copy
11625          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11626          * the copy we send as FROM_OTHER.
11627          * We also need to stuff the address of the original IO so we can
11628          * find it easily. Something similar will need be done on the other
11629          * side so when we are done we can find the copy.
11630          */
11631         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11632             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11633             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11634                 union ctl_ha_msg msg_info;
11635                 int isc_retval;
11636
11637                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11638                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11639                 mtx_unlock(&lun->lun_lock);
11640
11641                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11642                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11643                 msg_info.hdr.serializing_sc = NULL;
11644                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11645                 msg_info.scsi.tag_num = ctsio->tag_num;
11646                 msg_info.scsi.tag_type = ctsio->tag_type;
11647                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11648                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11649
11650                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11651                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11652                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11653                         ctl_set_busy(ctsio);
11654                         ctl_done((union ctl_io *)ctsio);
11655                         return (retval);
11656                 }
11657                 return (retval);
11658         }
11659
11660         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11661                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11662                               ctl_ooaq, ooa_links))) {
11663         case CTL_ACTION_BLOCK:
11664                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11665                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11666                                   blocked_links);
11667                 mtx_unlock(&lun->lun_lock);
11668                 return (retval);
11669         case CTL_ACTION_PASS:
11670         case CTL_ACTION_SKIP:
11671                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11672                 mtx_unlock(&lun->lun_lock);
11673                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11674                 break;
11675         case CTL_ACTION_OVERLAP:
11676                 mtx_unlock(&lun->lun_lock);
11677                 ctl_set_overlapped_cmd(ctsio);
11678                 ctl_done((union ctl_io *)ctsio);
11679                 break;
11680         case CTL_ACTION_OVERLAP_TAG:
11681                 mtx_unlock(&lun->lun_lock);
11682                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11683                 ctl_done((union ctl_io *)ctsio);
11684                 break;
11685         case CTL_ACTION_ERROR:
11686         default:
11687                 mtx_unlock(&lun->lun_lock);
11688                 ctl_set_internal_failure(ctsio,
11689                                          /*sks_valid*/ 0,
11690                                          /*retry_count*/ 0);
11691                 ctl_done((union ctl_io *)ctsio);
11692                 break;
11693         }
11694         return (retval);
11695 }
11696
11697 const struct ctl_cmd_entry *
11698 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11699 {
11700         const struct ctl_cmd_entry *entry;
11701         int service_action;
11702
11703         entry = &ctl_cmd_table[ctsio->cdb[0]];
11704         if (sa)
11705                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11706         if (entry->flags & CTL_CMD_FLAG_SA5) {
11707                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11708                 entry = &((const struct ctl_cmd_entry *)
11709                     entry->execute)[service_action];
11710         }
11711         return (entry);
11712 }
11713
11714 const struct ctl_cmd_entry *
11715 ctl_validate_command(struct ctl_scsiio *ctsio)
11716 {
11717         const struct ctl_cmd_entry *entry;
11718         int i, sa;
11719         uint8_t diff;
11720
11721         entry = ctl_get_cmd_entry(ctsio, &sa);
11722         if (entry->execute == NULL) {
11723                 if (sa)
11724                         ctl_set_invalid_field(ctsio,
11725                                               /*sks_valid*/ 1,
11726                                               /*command*/ 1,
11727                                               /*field*/ 1,
11728                                               /*bit_valid*/ 1,
11729                                               /*bit*/ 4);
11730                 else
11731                         ctl_set_invalid_opcode(ctsio);
11732                 ctl_done((union ctl_io *)ctsio);
11733                 return (NULL);
11734         }
11735         KASSERT(entry->length > 0,
11736             ("Not defined length for command 0x%02x/0x%02x",
11737              ctsio->cdb[0], ctsio->cdb[1]));
11738         for (i = 1; i < entry->length; i++) {
11739                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11740                 if (diff == 0)
11741                         continue;
11742                 ctl_set_invalid_field(ctsio,
11743                                       /*sks_valid*/ 1,
11744                                       /*command*/ 1,
11745                                       /*field*/ i,
11746                                       /*bit_valid*/ 1,
11747                                       /*bit*/ fls(diff) - 1);
11748                 ctl_done((union ctl_io *)ctsio);
11749                 return (NULL);
11750         }
11751         return (entry);
11752 }
11753
11754 static int
11755 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11756 {
11757
11758         switch (lun_type) {
11759         case T_DIRECT:
11760                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11761                         return (0);
11762                 break;
11763         case T_PROCESSOR:
11764                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11765                         return (0);
11766                 break;
11767         case T_CDROM:
11768                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11769                         return (0);
11770                 break;
11771         default:
11772                 return (0);
11773         }
11774         return (1);
11775 }
11776
11777 static int
11778 ctl_scsiio(struct ctl_scsiio *ctsio)
11779 {
11780         int retval;
11781         const struct ctl_cmd_entry *entry;
11782
11783         retval = CTL_RETVAL_COMPLETE;
11784
11785         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11786
11787         entry = ctl_get_cmd_entry(ctsio, NULL);
11788
11789         /*
11790          * If this I/O has been aborted, just send it straight to
11791          * ctl_done() without executing it.
11792          */
11793         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11794                 ctl_done((union ctl_io *)ctsio);
11795                 goto bailout;
11796         }
11797
11798         /*
11799          * All the checks should have been handled by ctl_scsiio_precheck().
11800          * We should be clear now to just execute the I/O.
11801          */
11802         retval = entry->execute(ctsio);
11803
11804 bailout:
11805         return (retval);
11806 }
11807
11808 /*
11809  * Since we only implement one target right now, a bus reset simply resets
11810  * our single target.
11811  */
11812 static int
11813 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11814 {
11815         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11816 }
11817
11818 static int
11819 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11820                  ctl_ua_type ua_type)
11821 {
11822         struct ctl_port *port;
11823         struct ctl_lun *lun;
11824         int retval;
11825
11826         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11827                 union ctl_ha_msg msg_info;
11828
11829                 msg_info.hdr.nexus = io->io_hdr.nexus;
11830                 if (ua_type==CTL_UA_TARG_RESET)
11831                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11832                 else
11833                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11834                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11835                 msg_info.hdr.original_sc = NULL;
11836                 msg_info.hdr.serializing_sc = NULL;
11837                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11838                     sizeof(msg_info.task), M_WAITOK);
11839         }
11840         retval = 0;
11841
11842         mtx_lock(&softc->ctl_lock);
11843         port = ctl_io_port(&io->io_hdr);
11844         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11845                 if (port != NULL &&
11846                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11847                         continue;
11848                 retval += ctl_do_lun_reset(lun, io, ua_type);
11849         }
11850         mtx_unlock(&softc->ctl_lock);
11851         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11852         return (retval);
11853 }
11854
11855 /*
11856  * The LUN should always be set.  The I/O is optional, and is used to
11857  * distinguish between I/Os sent by this initiator, and by other
11858  * initiators.  We set unit attention for initiators other than this one.
11859  * SAM-3 is vague on this point.  It does say that a unit attention should
11860  * be established for other initiators when a LUN is reset (see section
11861  * 5.7.3), but it doesn't specifically say that the unit attention should
11862  * be established for this particular initiator when a LUN is reset.  Here
11863  * is the relevant text, from SAM-3 rev 8:
11864  *
11865  * 5.7.2 When a SCSI initiator port aborts its own tasks
11866  *
11867  * When a SCSI initiator port causes its own task(s) to be aborted, no
11868  * notification that the task(s) have been aborted shall be returned to
11869  * the SCSI initiator port other than the completion response for the
11870  * command or task management function action that caused the task(s) to
11871  * be aborted and notification(s) associated with related effects of the
11872  * action (e.g., a reset unit attention condition).
11873  *
11874  * XXX KDM for now, we're setting unit attention for all initiators.
11875  */
11876 static int
11877 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11878 {
11879         union ctl_io *xio;
11880 #if 0
11881         uint32_t initidx;
11882 #endif
11883         int i;
11884
11885         mtx_lock(&lun->lun_lock);
11886         /*
11887          * Run through the OOA queue and abort each I/O.
11888          */
11889         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11890              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11891                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11892         }
11893
11894         /*
11895          * This version sets unit attention for every
11896          */
11897 #if 0
11898         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11899         ctl_est_ua_all(lun, initidx, ua_type);
11900 #else
11901         ctl_est_ua_all(lun, -1, ua_type);
11902 #endif
11903
11904         /*
11905          * A reset (any kind, really) clears reservations established with
11906          * RESERVE/RELEASE.  It does not clear reservations established
11907          * with PERSISTENT RESERVE OUT, but we don't support that at the
11908          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11909          * reservations made with the RESERVE/RELEASE commands, because
11910          * those commands are obsolete in SPC-3.
11911          */
11912         lun->flags &= ~CTL_LUN_RESERVED;
11913
11914 #ifdef CTL_WITH_CA
11915         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11916                 ctl_clear_mask(lun->have_ca, i);
11917 #endif
11918         lun->prevent_count = 0;
11919         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11920                 ctl_clear_mask(lun->prevent, i);
11921         mtx_unlock(&lun->lun_lock);
11922
11923         return (0);
11924 }
11925
11926 static int
11927 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11928 {
11929         struct ctl_lun *lun;
11930         uint32_t targ_lun;
11931         int retval;
11932
11933         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11934         mtx_lock(&softc->ctl_lock);
11935         if ((targ_lun >= CTL_MAX_LUNS) ||
11936             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11937                 mtx_unlock(&softc->ctl_lock);
11938                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11939                 return (1);
11940         }
11941         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11942         mtx_unlock(&softc->ctl_lock);
11943         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11944
11945         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11946                 union ctl_ha_msg msg_info;
11947
11948                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11949                 msg_info.hdr.nexus = io->io_hdr.nexus;
11950                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11951                 msg_info.hdr.original_sc = NULL;
11952                 msg_info.hdr.serializing_sc = NULL;
11953                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11954                     sizeof(msg_info.task), M_WAITOK);
11955         }
11956         return (retval);
11957 }
11958
11959 static void
11960 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11961     int other_sc)
11962 {
11963         union ctl_io *xio;
11964
11965         mtx_assert(&lun->lun_lock, MA_OWNED);
11966
11967         /*
11968          * Run through the OOA queue and attempt to find the given I/O.
11969          * The target port, initiator ID, tag type and tag number have to
11970          * match the values that we got from the initiator.  If we have an
11971          * untagged command to abort, simply abort the first untagged command
11972          * we come to.  We only allow one untagged command at a time of course.
11973          */
11974         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11975              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11976
11977                 if ((targ_port == UINT32_MAX ||
11978                      targ_port == xio->io_hdr.nexus.targ_port) &&
11979                     (init_id == UINT32_MAX ||
11980                      init_id == xio->io_hdr.nexus.initid)) {
11981                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11982                             init_id != xio->io_hdr.nexus.initid)
11983                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11984                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11985                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11986                                 union ctl_ha_msg msg_info;
11987
11988                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11989                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11990                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11991                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11992                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11993                                 msg_info.hdr.original_sc = NULL;
11994                                 msg_info.hdr.serializing_sc = NULL;
11995                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11996                                     sizeof(msg_info.task), M_NOWAIT);
11997                         }
11998                 }
11999         }
12000 }
12001
12002 static int
12003 ctl_abort_task_set(union ctl_io *io)
12004 {
12005         struct ctl_softc *softc = control_softc;
12006         struct ctl_lun *lun;
12007         uint32_t targ_lun;
12008
12009         /*
12010          * Look up the LUN.
12011          */
12012         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12013         mtx_lock(&softc->ctl_lock);
12014         if ((targ_lun >= CTL_MAX_LUNS) ||
12015             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12016                 mtx_unlock(&softc->ctl_lock);
12017                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12018                 return (1);
12019         }
12020
12021         mtx_lock(&lun->lun_lock);
12022         mtx_unlock(&softc->ctl_lock);
12023         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12024                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12025                     io->io_hdr.nexus.initid,
12026                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12027         } else { /* CTL_TASK_CLEAR_TASK_SET */
12028                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12029                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12030         }
12031         mtx_unlock(&lun->lun_lock);
12032         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12033         return (0);
12034 }
12035
12036 static int
12037 ctl_i_t_nexus_reset(union ctl_io *io)
12038 {
12039         struct ctl_softc *softc = control_softc;
12040         struct ctl_lun *lun;
12041         uint32_t initidx;
12042
12043         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12044                 union ctl_ha_msg msg_info;
12045
12046                 msg_info.hdr.nexus = io->io_hdr.nexus;
12047                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12048                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12049                 msg_info.hdr.original_sc = NULL;
12050                 msg_info.hdr.serializing_sc = NULL;
12051                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12052                     sizeof(msg_info.task), M_WAITOK);
12053         }
12054
12055         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12056         mtx_lock(&softc->ctl_lock);
12057         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12058                 mtx_lock(&lun->lun_lock);
12059                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12060                     io->io_hdr.nexus.initid, 1);
12061 #ifdef CTL_WITH_CA
12062                 ctl_clear_mask(lun->have_ca, initidx);
12063 #endif
12064                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12065                         lun->flags &= ~CTL_LUN_RESERVED;
12066                 if (ctl_is_set(lun->prevent, initidx)) {
12067                         ctl_clear_mask(lun->prevent, initidx);
12068                         lun->prevent_count--;
12069                 }
12070                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12071                 mtx_unlock(&lun->lun_lock);
12072         }
12073         mtx_unlock(&softc->ctl_lock);
12074         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12075         return (0);
12076 }
12077
12078 static int
12079 ctl_abort_task(union ctl_io *io)
12080 {
12081         union ctl_io *xio;
12082         struct ctl_lun *lun;
12083         struct ctl_softc *softc;
12084 #if 0
12085         struct sbuf sb;
12086         char printbuf[128];
12087 #endif
12088         int found;
12089         uint32_t targ_lun;
12090
12091         softc = control_softc;
12092         found = 0;
12093
12094         /*
12095          * Look up the LUN.
12096          */
12097         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12098         mtx_lock(&softc->ctl_lock);
12099         if ((targ_lun >= CTL_MAX_LUNS) ||
12100             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12101                 mtx_unlock(&softc->ctl_lock);
12102                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12103                 return (1);
12104         }
12105
12106 #if 0
12107         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12108                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12109 #endif
12110
12111         mtx_lock(&lun->lun_lock);
12112         mtx_unlock(&softc->ctl_lock);
12113         /*
12114          * Run through the OOA queue and attempt to find the given I/O.
12115          * The target port, initiator ID, tag type and tag number have to
12116          * match the values that we got from the initiator.  If we have an
12117          * untagged command to abort, simply abort the first untagged command
12118          * we come to.  We only allow one untagged command at a time of course.
12119          */
12120         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12121              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12122 #if 0
12123                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12124
12125                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12126                             lun->lun, xio->scsiio.tag_num,
12127                             xio->scsiio.tag_type,
12128                             (xio->io_hdr.blocked_links.tqe_prev
12129                             == NULL) ? "" : " BLOCKED",
12130                             (xio->io_hdr.flags &
12131                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12132                             (xio->io_hdr.flags &
12133                             CTL_FLAG_ABORT) ? " ABORT" : "",
12134                             (xio->io_hdr.flags &
12135                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12136                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12137                 sbuf_finish(&sb);
12138                 printf("%s\n", sbuf_data(&sb));
12139 #endif
12140
12141                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12142                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12143                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12144                         continue;
12145
12146                 /*
12147                  * If the abort says that the task is untagged, the
12148                  * task in the queue must be untagged.  Otherwise,
12149                  * we just check to see whether the tag numbers
12150                  * match.  This is because the QLogic firmware
12151                  * doesn't pass back the tag type in an abort
12152                  * request.
12153                  */
12154 #if 0
12155                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12156                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12157                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12158 #endif
12159                 /*
12160                  * XXX KDM we've got problems with FC, because it
12161                  * doesn't send down a tag type with aborts.  So we
12162                  * can only really go by the tag number...
12163                  * This may cause problems with parallel SCSI.
12164                  * Need to figure that out!!
12165                  */
12166                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12167                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12168                         found = 1;
12169                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12170                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12171                                 union ctl_ha_msg msg_info;
12172
12173                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12174                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12175                                 msg_info.task.tag_num = io->taskio.tag_num;
12176                                 msg_info.task.tag_type = io->taskio.tag_type;
12177                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12178                                 msg_info.hdr.original_sc = NULL;
12179                                 msg_info.hdr.serializing_sc = NULL;
12180 #if 0
12181                                 printf("Sent Abort to other side\n");
12182 #endif
12183                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12184                                     sizeof(msg_info.task), M_NOWAIT);
12185                         }
12186 #if 0
12187                         printf("ctl_abort_task: found I/O to abort\n");
12188 #endif
12189                 }
12190         }
12191         mtx_unlock(&lun->lun_lock);
12192
12193         if (found == 0) {
12194                 /*
12195                  * This isn't really an error.  It's entirely possible for
12196                  * the abort and command completion to cross on the wire.
12197                  * This is more of an informative/diagnostic error.
12198                  */
12199 #if 0
12200                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12201                        "%u:%u:%u tag %d type %d\n",
12202                        io->io_hdr.nexus.initid,
12203                        io->io_hdr.nexus.targ_port,
12204                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12205                        io->taskio.tag_type);
12206 #endif
12207         }
12208         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12209         return (0);
12210 }
12211
12212 static int
12213 ctl_query_task(union ctl_io *io, int task_set)
12214 {
12215         union ctl_io *xio;
12216         struct ctl_lun *lun;
12217         struct ctl_softc *softc;
12218         int found = 0;
12219         uint32_t targ_lun;
12220
12221         softc = control_softc;
12222         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12223         mtx_lock(&softc->ctl_lock);
12224         if ((targ_lun >= CTL_MAX_LUNS) ||
12225             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12226                 mtx_unlock(&softc->ctl_lock);
12227                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12228                 return (1);
12229         }
12230         mtx_lock(&lun->lun_lock);
12231         mtx_unlock(&softc->ctl_lock);
12232         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12233              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12234
12235                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12236                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12237                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12238                         continue;
12239
12240                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12241                         found = 1;
12242                         break;
12243                 }
12244         }
12245         mtx_unlock(&lun->lun_lock);
12246         if (found)
12247                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12248         else
12249                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12250         return (0);
12251 }
12252
12253 static int
12254 ctl_query_async_event(union ctl_io *io)
12255 {
12256         struct ctl_lun *lun;
12257         struct ctl_softc *softc;
12258         ctl_ua_type ua;
12259         uint32_t targ_lun, initidx;
12260
12261         softc = control_softc;
12262         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12263         mtx_lock(&softc->ctl_lock);
12264         if ((targ_lun >= CTL_MAX_LUNS) ||
12265             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12266                 mtx_unlock(&softc->ctl_lock);
12267                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12268                 return (1);
12269         }
12270         mtx_lock(&lun->lun_lock);
12271         mtx_unlock(&softc->ctl_lock);
12272         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12273         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12274         mtx_unlock(&lun->lun_lock);
12275         if (ua != CTL_UA_NONE)
12276                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12277         else
12278                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12279         return (0);
12280 }
12281
12282 static void
12283 ctl_run_task(union ctl_io *io)
12284 {
12285         struct ctl_softc *softc = control_softc;
12286         int retval = 1;
12287
12288         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12289         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12290             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12291         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12292         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12293         switch (io->taskio.task_action) {
12294         case CTL_TASK_ABORT_TASK:
12295                 retval = ctl_abort_task(io);
12296                 break;
12297         case CTL_TASK_ABORT_TASK_SET:
12298         case CTL_TASK_CLEAR_TASK_SET:
12299                 retval = ctl_abort_task_set(io);
12300                 break;
12301         case CTL_TASK_CLEAR_ACA:
12302                 break;
12303         case CTL_TASK_I_T_NEXUS_RESET:
12304                 retval = ctl_i_t_nexus_reset(io);
12305                 break;
12306         case CTL_TASK_LUN_RESET:
12307                 retval = ctl_lun_reset(softc, io);
12308                 break;
12309         case CTL_TASK_TARGET_RESET:
12310                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12311                 break;
12312         case CTL_TASK_BUS_RESET:
12313                 retval = ctl_bus_reset(softc, io);
12314                 break;
12315         case CTL_TASK_PORT_LOGIN:
12316                 break;
12317         case CTL_TASK_PORT_LOGOUT:
12318                 break;
12319         case CTL_TASK_QUERY_TASK:
12320                 retval = ctl_query_task(io, 0);
12321                 break;
12322         case CTL_TASK_QUERY_TASK_SET:
12323                 retval = ctl_query_task(io, 1);
12324                 break;
12325         case CTL_TASK_QUERY_ASYNC_EVENT:
12326                 retval = ctl_query_async_event(io);
12327                 break;
12328         default:
12329                 printf("%s: got unknown task management event %d\n",
12330                        __func__, io->taskio.task_action);
12331                 break;
12332         }
12333         if (retval == 0)
12334                 io->io_hdr.status = CTL_SUCCESS;
12335         else
12336                 io->io_hdr.status = CTL_ERROR;
12337         ctl_done(io);
12338 }
12339
12340 /*
12341  * For HA operation.  Handle commands that come in from the other
12342  * controller.
12343  */
12344 static void
12345 ctl_handle_isc(union ctl_io *io)
12346 {
12347         int free_io;
12348         struct ctl_lun *lun;
12349         struct ctl_softc *softc = control_softc;
12350         uint32_t targ_lun;
12351
12352         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12353         lun = softc->ctl_luns[targ_lun];
12354
12355         switch (io->io_hdr.msg_type) {
12356         case CTL_MSG_SERIALIZE:
12357                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12358                 break;
12359         case CTL_MSG_R2R: {
12360                 const struct ctl_cmd_entry *entry;
12361
12362                 /*
12363                  * This is only used in SER_ONLY mode.
12364                  */
12365                 free_io = 0;
12366                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12367                 mtx_lock(&lun->lun_lock);
12368                 if (ctl_scsiio_lun_check(lun,
12369                     entry, (struct ctl_scsiio *)io) != 0) {
12370                         mtx_unlock(&lun->lun_lock);
12371                         ctl_done(io);
12372                         break;
12373                 }
12374                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12375                 mtx_unlock(&lun->lun_lock);
12376                 ctl_enqueue_rtr(io);
12377                 break;
12378         }
12379         case CTL_MSG_FINISH_IO:
12380                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12381                         free_io = 0;
12382                         ctl_done(io);
12383                 } else {
12384                         free_io = 1;
12385                         mtx_lock(&lun->lun_lock);
12386                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12387                                      ooa_links);
12388                         ctl_check_blocked(lun);
12389                         mtx_unlock(&lun->lun_lock);
12390                 }
12391                 break;
12392         case CTL_MSG_PERS_ACTION:
12393                 ctl_hndl_per_res_out_on_other_sc(
12394                         (union ctl_ha_msg *)&io->presio.pr_msg);
12395                 free_io = 1;
12396                 break;
12397         case CTL_MSG_BAD_JUJU:
12398                 free_io = 0;
12399                 ctl_done(io);
12400                 break;
12401         case CTL_MSG_DATAMOVE:
12402                 /* Only used in XFER mode */
12403                 free_io = 0;
12404                 ctl_datamove_remote(io);
12405                 break;
12406         case CTL_MSG_DATAMOVE_DONE:
12407                 /* Only used in XFER mode */
12408                 free_io = 0;
12409                 io->scsiio.be_move_done(io);
12410                 break;
12411         case CTL_MSG_FAILOVER:
12412                 ctl_failover_lun(io);
12413                 free_io = 1;
12414                 break;
12415         default:
12416                 free_io = 1;
12417                 printf("%s: Invalid message type %d\n",
12418                        __func__, io->io_hdr.msg_type);
12419                 break;
12420         }
12421         if (free_io)
12422                 ctl_free_io(io);
12423
12424 }
12425
12426
12427 /*
12428  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12429  * there is no match.
12430  */
12431 static ctl_lun_error_pattern
12432 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12433 {
12434         const struct ctl_cmd_entry *entry;
12435         ctl_lun_error_pattern filtered_pattern, pattern;
12436
12437         pattern = desc->error_pattern;
12438
12439         /*
12440          * XXX KDM we need more data passed into this function to match a
12441          * custom pattern, and we actually need to implement custom pattern
12442          * matching.
12443          */
12444         if (pattern & CTL_LUN_PAT_CMD)
12445                 return (CTL_LUN_PAT_CMD);
12446
12447         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12448                 return (CTL_LUN_PAT_ANY);
12449
12450         entry = ctl_get_cmd_entry(ctsio, NULL);
12451
12452         filtered_pattern = entry->pattern & pattern;
12453
12454         /*
12455          * If the user requested specific flags in the pattern (e.g.
12456          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12457          * flags.
12458          *
12459          * If the user did not specify any flags, it doesn't matter whether
12460          * or not the command supports the flags.
12461          */
12462         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12463              (pattern & ~CTL_LUN_PAT_MASK))
12464                 return (CTL_LUN_PAT_NONE);
12465
12466         /*
12467          * If the user asked for a range check, see if the requested LBA
12468          * range overlaps with this command's LBA range.
12469          */
12470         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12471                 uint64_t lba1;
12472                 uint64_t len1;
12473                 ctl_action action;
12474                 int retval;
12475
12476                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12477                 if (retval != 0)
12478                         return (CTL_LUN_PAT_NONE);
12479
12480                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12481                                               desc->lba_range.len, FALSE);
12482                 /*
12483                  * A "pass" means that the LBA ranges don't overlap, so
12484                  * this doesn't match the user's range criteria.
12485                  */
12486                 if (action == CTL_ACTION_PASS)
12487                         return (CTL_LUN_PAT_NONE);
12488         }
12489
12490         return (filtered_pattern);
12491 }
12492
12493 static void
12494 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12495 {
12496         struct ctl_error_desc *desc, *desc2;
12497
12498         mtx_assert(&lun->lun_lock, MA_OWNED);
12499
12500         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12501                 ctl_lun_error_pattern pattern;
12502                 /*
12503                  * Check to see whether this particular command matches
12504                  * the pattern in the descriptor.
12505                  */
12506                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12507                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12508                         continue;
12509
12510                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12511                 case CTL_LUN_INJ_ABORTED:
12512                         ctl_set_aborted(&io->scsiio);
12513                         break;
12514                 case CTL_LUN_INJ_MEDIUM_ERR:
12515                         ctl_set_medium_error(&io->scsiio,
12516                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12517                              CTL_FLAG_DATA_OUT);
12518                         break;
12519                 case CTL_LUN_INJ_UA:
12520                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12521                          * OCCURRED */
12522                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12523                         break;
12524                 case CTL_LUN_INJ_CUSTOM:
12525                         /*
12526                          * We're assuming the user knows what he is doing.
12527                          * Just copy the sense information without doing
12528                          * checks.
12529                          */
12530                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12531                               MIN(sizeof(desc->custom_sense),
12532                                   sizeof(io->scsiio.sense_data)));
12533                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12534                         io->scsiio.sense_len = SSD_FULL_SIZE;
12535                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12536                         break;
12537                 case CTL_LUN_INJ_NONE:
12538                 default:
12539                         /*
12540                          * If this is an error injection type we don't know
12541                          * about, clear the continuous flag (if it is set)
12542                          * so it will get deleted below.
12543                          */
12544                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12545                         break;
12546                 }
12547                 /*
12548                  * By default, each error injection action is a one-shot
12549                  */
12550                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12551                         continue;
12552
12553                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12554
12555                 free(desc, M_CTL);
12556         }
12557 }
12558
12559 #ifdef CTL_IO_DELAY
12560 static void
12561 ctl_datamove_timer_wakeup(void *arg)
12562 {
12563         union ctl_io *io;
12564
12565         io = (union ctl_io *)arg;
12566
12567         ctl_datamove(io);
12568 }
12569 #endif /* CTL_IO_DELAY */
12570
12571 void
12572 ctl_datamove(union ctl_io *io)
12573 {
12574         struct ctl_lun *lun;
12575         void (*fe_datamove)(union ctl_io *io);
12576
12577         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12578
12579         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12580
12581         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12582 #ifdef CTL_TIME_IO
12583         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12584                 char str[256];
12585                 char path_str[64];
12586                 struct sbuf sb;
12587
12588                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12589                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12590
12591                 sbuf_cat(&sb, path_str);
12592                 switch (io->io_hdr.io_type) {
12593                 case CTL_IO_SCSI:
12594                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12595                         sbuf_printf(&sb, "\n");
12596                         sbuf_cat(&sb, path_str);
12597                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12598                                     io->scsiio.tag_num, io->scsiio.tag_type);
12599                         break;
12600                 case CTL_IO_TASK:
12601                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12602                                     "Tag Type: %d\n", io->taskio.task_action,
12603                                     io->taskio.tag_num, io->taskio.tag_type);
12604                         break;
12605                 default:
12606                         panic("%s: Invalid CTL I/O type %d\n",
12607                             __func__, io->io_hdr.io_type);
12608                 }
12609                 sbuf_cat(&sb, path_str);
12610                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12611                             (intmax_t)time_uptime - io->io_hdr.start_time);
12612                 sbuf_finish(&sb);
12613                 printf("%s", sbuf_data(&sb));
12614         }
12615 #endif /* CTL_TIME_IO */
12616
12617 #ifdef CTL_IO_DELAY
12618         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12619                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12620         } else {
12621                 if ((lun != NULL)
12622                  && (lun->delay_info.datamove_delay > 0)) {
12623
12624                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12625                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12626                         callout_reset(&io->io_hdr.delay_callout,
12627                                       lun->delay_info.datamove_delay * hz,
12628                                       ctl_datamove_timer_wakeup, io);
12629                         if (lun->delay_info.datamove_type ==
12630                             CTL_DELAY_TYPE_ONESHOT)
12631                                 lun->delay_info.datamove_delay = 0;
12632                         return;
12633                 }
12634         }
12635 #endif
12636
12637         /*
12638          * This command has been aborted.  Set the port status, so we fail
12639          * the data move.
12640          */
12641         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12642                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12643                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12644                        io->io_hdr.nexus.targ_port,
12645                        io->io_hdr.nexus.targ_lun);
12646                 io->io_hdr.port_status = 31337;
12647                 /*
12648                  * Note that the backend, in this case, will get the
12649                  * callback in its context.  In other cases it may get
12650                  * called in the frontend's interrupt thread context.
12651                  */
12652                 io->scsiio.be_move_done(io);
12653                 return;
12654         }
12655
12656         /* Don't confuse frontend with zero length data move. */
12657         if (io->scsiio.kern_data_len == 0) {
12658                 io->scsiio.be_move_done(io);
12659                 return;
12660         }
12661
12662         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12663         fe_datamove(io);
12664 }
12665
12666 static void
12667 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12668 {
12669         union ctl_ha_msg msg;
12670 #ifdef CTL_TIME_IO
12671         struct bintime cur_bt;
12672 #endif
12673
12674         memset(&msg, 0, sizeof(msg));
12675         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12676         msg.hdr.original_sc = io;
12677         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12678         msg.hdr.nexus = io->io_hdr.nexus;
12679         msg.hdr.status = io->io_hdr.status;
12680         msg.scsi.tag_num = io->scsiio.tag_num;
12681         msg.scsi.tag_type = io->scsiio.tag_type;
12682         msg.scsi.scsi_status = io->scsiio.scsi_status;
12683         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12684                io->scsiio.sense_len);
12685         msg.scsi.sense_len = io->scsiio.sense_len;
12686         msg.scsi.sense_residual = io->scsiio.sense_residual;
12687         msg.scsi.fetd_status = io->io_hdr.port_status;
12688         msg.scsi.residual = io->scsiio.residual;
12689         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12690         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12691                 ctl_failover_io(io, /*have_lock*/ have_lock);
12692                 return;
12693         }
12694         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12695             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12696             msg.scsi.sense_len, M_WAITOK);
12697
12698 #ifdef CTL_TIME_IO
12699         getbinuptime(&cur_bt);
12700         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12701         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12702 #endif
12703         io->io_hdr.num_dmas++;
12704 }
12705
12706 /*
12707  * The DMA to the remote side is done, now we need to tell the other side
12708  * we're done so it can continue with its data movement.
12709  */
12710 static void
12711 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12712 {
12713         union ctl_io *io;
12714         int i;
12715
12716         io = rq->context;
12717
12718         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12719                 printf("%s: ISC DMA write failed with error %d", __func__,
12720                        rq->ret);
12721                 ctl_set_internal_failure(&io->scsiio,
12722                                          /*sks_valid*/ 1,
12723                                          /*retry_count*/ rq->ret);
12724         }
12725
12726         ctl_dt_req_free(rq);
12727
12728         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12729                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12730         free(io->io_hdr.remote_sglist, M_CTL);
12731         io->io_hdr.remote_sglist = NULL;
12732         io->io_hdr.local_sglist = NULL;
12733
12734         /*
12735          * The data is in local and remote memory, so now we need to send
12736          * status (good or back) back to the other side.
12737          */
12738         ctl_send_datamove_done(io, /*have_lock*/ 0);
12739 }
12740
12741 /*
12742  * We've moved the data from the host/controller into local memory.  Now we
12743  * need to push it over to the remote controller's memory.
12744  */
12745 static int
12746 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12747 {
12748         int retval;
12749
12750         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12751                                           ctl_datamove_remote_write_cb);
12752         return (retval);
12753 }
12754
12755 static void
12756 ctl_datamove_remote_write(union ctl_io *io)
12757 {
12758         int retval;
12759         void (*fe_datamove)(union ctl_io *io);
12760
12761         /*
12762          * - Get the data from the host/HBA into local memory.
12763          * - DMA memory from the local controller to the remote controller.
12764          * - Send status back to the remote controller.
12765          */
12766
12767         retval = ctl_datamove_remote_sgl_setup(io);
12768         if (retval != 0)
12769                 return;
12770
12771         /* Switch the pointer over so the FETD knows what to do */
12772         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12773
12774         /*
12775          * Use a custom move done callback, since we need to send completion
12776          * back to the other controller, not to the backend on this side.
12777          */
12778         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12779
12780         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12781         fe_datamove(io);
12782 }
12783
12784 static int
12785 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12786 {
12787 #if 0
12788         char str[256];
12789         char path_str[64];
12790         struct sbuf sb;
12791 #endif
12792         int i;
12793
12794         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12795                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12796         free(io->io_hdr.remote_sglist, M_CTL);
12797         io->io_hdr.remote_sglist = NULL;
12798         io->io_hdr.local_sglist = NULL;
12799
12800 #if 0
12801         scsi_path_string(io, path_str, sizeof(path_str));
12802         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12803         sbuf_cat(&sb, path_str);
12804         scsi_command_string(&io->scsiio, NULL, &sb);
12805         sbuf_printf(&sb, "\n");
12806         sbuf_cat(&sb, path_str);
12807         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12808                     io->scsiio.tag_num, io->scsiio.tag_type);
12809         sbuf_cat(&sb, path_str);
12810         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12811                     io->io_hdr.flags, io->io_hdr.status);
12812         sbuf_finish(&sb);
12813         printk("%s", sbuf_data(&sb));
12814 #endif
12815
12816
12817         /*
12818          * The read is done, now we need to send status (good or bad) back
12819          * to the other side.
12820          */
12821         ctl_send_datamove_done(io, /*have_lock*/ 0);
12822
12823         return (0);
12824 }
12825
12826 static void
12827 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12828 {
12829         union ctl_io *io;
12830         void (*fe_datamove)(union ctl_io *io);
12831
12832         io = rq->context;
12833
12834         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12835                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12836                        rq->ret);
12837                 ctl_set_internal_failure(&io->scsiio,
12838                                          /*sks_valid*/ 1,
12839                                          /*retry_count*/ rq->ret);
12840         }
12841
12842         ctl_dt_req_free(rq);
12843
12844         /* Switch the pointer over so the FETD knows what to do */
12845         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12846
12847         /*
12848          * Use a custom move done callback, since we need to send completion
12849          * back to the other controller, not to the backend on this side.
12850          */
12851         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12852
12853         /* XXX KDM add checks like the ones in ctl_datamove? */
12854
12855         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12856         fe_datamove(io);
12857 }
12858
12859 static int
12860 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12861 {
12862         struct ctl_sg_entry *local_sglist;
12863         uint32_t len_to_go;
12864         int retval;
12865         int i;
12866
12867         retval = 0;
12868         local_sglist = io->io_hdr.local_sglist;
12869         len_to_go = io->scsiio.kern_data_len;
12870
12871         /*
12872          * The difficult thing here is that the size of the various
12873          * S/G segments may be different than the size from the
12874          * remote controller.  That'll make it harder when DMAing
12875          * the data back to the other side.
12876          */
12877         for (i = 0; len_to_go > 0; i++) {
12878                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12879                 local_sglist[i].addr =
12880                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12881
12882                 len_to_go -= local_sglist[i].len;
12883         }
12884         /*
12885          * Reset the number of S/G entries accordingly.  The original
12886          * number of S/G entries is available in rem_sg_entries.
12887          */
12888         io->scsiio.kern_sg_entries = i;
12889
12890 #if 0
12891         printf("%s: kern_sg_entries = %d\n", __func__,
12892                io->scsiio.kern_sg_entries);
12893         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12894                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12895                        local_sglist[i].addr, local_sglist[i].len);
12896 #endif
12897
12898         return (retval);
12899 }
12900
12901 static int
12902 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12903                          ctl_ha_dt_cb callback)
12904 {
12905         struct ctl_ha_dt_req *rq;
12906         struct ctl_sg_entry *remote_sglist, *local_sglist;
12907         uint32_t local_used, remote_used, total_used;
12908         int i, j, isc_ret;
12909
12910         rq = ctl_dt_req_alloc();
12911
12912         /*
12913          * If we failed to allocate the request, and if the DMA didn't fail
12914          * anyway, set busy status.  This is just a resource allocation
12915          * failure.
12916          */
12917         if ((rq == NULL)
12918          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12919              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12920                 ctl_set_busy(&io->scsiio);
12921
12922         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12923             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12924
12925                 if (rq != NULL)
12926                         ctl_dt_req_free(rq);
12927
12928                 /*
12929                  * The data move failed.  We need to return status back
12930                  * to the other controller.  No point in trying to DMA
12931                  * data to the remote controller.
12932                  */
12933
12934                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12935
12936                 return (1);
12937         }
12938
12939         local_sglist = io->io_hdr.local_sglist;
12940         remote_sglist = io->io_hdr.remote_sglist;
12941         local_used = 0;
12942         remote_used = 0;
12943         total_used = 0;
12944
12945         /*
12946          * Pull/push the data over the wire from/to the other controller.
12947          * This takes into account the possibility that the local and
12948          * remote sglists may not be identical in terms of the size of
12949          * the elements and the number of elements.
12950          *
12951          * One fundamental assumption here is that the length allocated for
12952          * both the local and remote sglists is identical.  Otherwise, we've
12953          * essentially got a coding error of some sort.
12954          */
12955         isc_ret = CTL_HA_STATUS_SUCCESS;
12956         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12957                 uint32_t cur_len;
12958                 uint8_t *tmp_ptr;
12959
12960                 rq->command = command;
12961                 rq->context = io;
12962
12963                 /*
12964                  * Both pointers should be aligned.  But it is possible
12965                  * that the allocation length is not.  They should both
12966                  * also have enough slack left over at the end, though,
12967                  * to round up to the next 8 byte boundary.
12968                  */
12969                 cur_len = MIN(local_sglist[i].len - local_used,
12970                               remote_sglist[j].len - remote_used);
12971                 rq->size = cur_len;
12972
12973                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12974                 tmp_ptr += local_used;
12975
12976 #if 0
12977                 /* Use physical addresses when talking to ISC hardware */
12978                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12979                         /* XXX KDM use busdma */
12980                         rq->local = vtophys(tmp_ptr);
12981                 } else
12982                         rq->local = tmp_ptr;
12983 #else
12984                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12985                     ("HA does not support BUS_ADDR"));
12986                 rq->local = tmp_ptr;
12987 #endif
12988
12989                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12990                 tmp_ptr += remote_used;
12991                 rq->remote = tmp_ptr;
12992
12993                 rq->callback = NULL;
12994
12995                 local_used += cur_len;
12996                 if (local_used >= local_sglist[i].len) {
12997                         i++;
12998                         local_used = 0;
12999                 }
13000
13001                 remote_used += cur_len;
13002                 if (remote_used >= remote_sglist[j].len) {
13003                         j++;
13004                         remote_used = 0;
13005                 }
13006                 total_used += cur_len;
13007
13008                 if (total_used >= io->scsiio.kern_data_len)
13009                         rq->callback = callback;
13010
13011 #if 0
13012                 printf("%s: %s: local %p remote %p size %d\n", __func__,
13013                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13014                        rq->local, rq->remote, rq->size);
13015 #endif
13016
13017                 isc_ret = ctl_dt_single(rq);
13018                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
13019                         break;
13020         }
13021         if (isc_ret != CTL_HA_STATUS_WAIT) {
13022                 rq->ret = isc_ret;
13023                 callback(rq);
13024         }
13025
13026         return (0);
13027 }
13028
13029 static void
13030 ctl_datamove_remote_read(union ctl_io *io)
13031 {
13032         int retval;
13033         int i;
13034
13035         /*
13036          * This will send an error to the other controller in the case of a
13037          * failure.
13038          */
13039         retval = ctl_datamove_remote_sgl_setup(io);
13040         if (retval != 0)
13041                 return;
13042
13043         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13044                                           ctl_datamove_remote_read_cb);
13045         if (retval != 0) {
13046                 /*
13047                  * Make sure we free memory if there was an error..  The
13048                  * ctl_datamove_remote_xfer() function will send the
13049                  * datamove done message, or call the callback with an
13050                  * error if there is a problem.
13051                  */
13052                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13053                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13054                 free(io->io_hdr.remote_sglist, M_CTL);
13055                 io->io_hdr.remote_sglist = NULL;
13056                 io->io_hdr.local_sglist = NULL;
13057         }
13058 }
13059
13060 /*
13061  * Process a datamove request from the other controller.  This is used for
13062  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13063  * first.  Once that is complete, the data gets DMAed into the remote
13064  * controller's memory.  For reads, we DMA from the remote controller's
13065  * memory into our memory first, and then move it out to the FETD.
13066  */
13067 static void
13068 ctl_datamove_remote(union ctl_io *io)
13069 {
13070
13071         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13072
13073         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13074                 ctl_failover_io(io, /*have_lock*/ 0);
13075                 return;
13076         }
13077
13078         /*
13079          * Note that we look for an aborted I/O here, but don't do some of
13080          * the other checks that ctl_datamove() normally does.
13081          * We don't need to run the datamove delay code, since that should
13082          * have been done if need be on the other controller.
13083          */
13084         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13085                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13086                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13087                        io->io_hdr.nexus.targ_port,
13088                        io->io_hdr.nexus.targ_lun);
13089                 io->io_hdr.port_status = 31338;
13090                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13091                 return;
13092         }
13093
13094         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13095                 ctl_datamove_remote_write(io);
13096         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13097                 ctl_datamove_remote_read(io);
13098         else {
13099                 io->io_hdr.port_status = 31339;
13100                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13101         }
13102 }
13103
13104 static void
13105 ctl_process_done(union ctl_io *io)
13106 {
13107         struct ctl_lun *lun;
13108         struct ctl_softc *softc = control_softc;
13109         void (*fe_done)(union ctl_io *io);
13110         union ctl_ha_msg msg;
13111         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13112
13113         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13114         fe_done = softc->ctl_ports[targ_port]->fe_done;
13115
13116 #ifdef CTL_TIME_IO
13117         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13118                 char str[256];
13119                 char path_str[64];
13120                 struct sbuf sb;
13121
13122                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13123                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13124
13125                 sbuf_cat(&sb, path_str);
13126                 switch (io->io_hdr.io_type) {
13127                 case CTL_IO_SCSI:
13128                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13129                         sbuf_printf(&sb, "\n");
13130                         sbuf_cat(&sb, path_str);
13131                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13132                                     io->scsiio.tag_num, io->scsiio.tag_type);
13133                         break;
13134                 case CTL_IO_TASK:
13135                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13136                                     "Tag Type: %d\n", io->taskio.task_action,
13137                                     io->taskio.tag_num, io->taskio.tag_type);
13138                         break;
13139                 default:
13140                         panic("%s: Invalid CTL I/O type %d\n",
13141                             __func__, io->io_hdr.io_type);
13142                 }
13143                 sbuf_cat(&sb, path_str);
13144                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13145                             (intmax_t)time_uptime - io->io_hdr.start_time);
13146                 sbuf_finish(&sb);
13147                 printf("%s", sbuf_data(&sb));
13148         }
13149 #endif /* CTL_TIME_IO */
13150
13151         switch (io->io_hdr.io_type) {
13152         case CTL_IO_SCSI:
13153                 break;
13154         case CTL_IO_TASK:
13155                 if (ctl_debug & CTL_DEBUG_INFO)
13156                         ctl_io_error_print(io, NULL);
13157                 fe_done(io);
13158                 return;
13159         default:
13160                 panic("%s: Invalid CTL I/O type %d\n",
13161                     __func__, io->io_hdr.io_type);
13162         }
13163
13164         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13165         if (lun == NULL) {
13166                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13167                                  io->io_hdr.nexus.targ_mapped_lun));
13168                 goto bailout;
13169         }
13170
13171         mtx_lock(&lun->lun_lock);
13172
13173         /*
13174          * Check to see if we have any errors to inject here.  We only
13175          * inject errors for commands that don't already have errors set.
13176          */
13177         if (!STAILQ_EMPTY(&lun->error_list) &&
13178             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13179             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13180                 ctl_inject_error(lun, io);
13181
13182         /*
13183          * XXX KDM how do we treat commands that aren't completed
13184          * successfully?
13185          *
13186          * XXX KDM should we also track I/O latency?
13187          */
13188         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13189             io->io_hdr.io_type == CTL_IO_SCSI) {
13190 #ifdef CTL_TIME_IO
13191                 struct bintime cur_bt;
13192 #endif
13193                 int type;
13194
13195                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13196                     CTL_FLAG_DATA_IN)
13197                         type = CTL_STATS_READ;
13198                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13199                     CTL_FLAG_DATA_OUT)
13200                         type = CTL_STATS_WRITE;
13201                 else
13202                         type = CTL_STATS_NO_IO;
13203
13204                 lun->stats.ports[targ_port].bytes[type] +=
13205                     io->scsiio.kern_total_len;
13206                 lun->stats.ports[targ_port].operations[type]++;
13207 #ifdef CTL_TIME_IO
13208                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13209                    &io->io_hdr.dma_bt);
13210                 getbinuptime(&cur_bt);
13211                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13212                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13213 #endif
13214                 lun->stats.ports[targ_port].num_dmas[type] +=
13215                     io->io_hdr.num_dmas;
13216         }
13217
13218         /*
13219          * Remove this from the OOA queue.
13220          */
13221         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13222 #ifdef CTL_TIME_IO
13223         if (TAILQ_EMPTY(&lun->ooa_queue))
13224                 lun->last_busy = getsbinuptime();
13225 #endif
13226
13227         /*
13228          * Run through the blocked queue on this LUN and see if anything
13229          * has become unblocked, now that this transaction is done.
13230          */
13231         ctl_check_blocked(lun);
13232
13233         /*
13234          * If the LUN has been invalidated, free it if there is nothing
13235          * left on its OOA queue.
13236          */
13237         if ((lun->flags & CTL_LUN_INVALID)
13238          && TAILQ_EMPTY(&lun->ooa_queue)) {
13239                 mtx_unlock(&lun->lun_lock);
13240                 mtx_lock(&softc->ctl_lock);
13241                 ctl_free_lun(lun);
13242                 mtx_unlock(&softc->ctl_lock);
13243         } else
13244                 mtx_unlock(&lun->lun_lock);
13245
13246 bailout:
13247
13248         /*
13249          * If this command has been aborted, make sure we set the status
13250          * properly.  The FETD is responsible for freeing the I/O and doing
13251          * whatever it needs to do to clean up its state.
13252          */
13253         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13254                 ctl_set_task_aborted(&io->scsiio);
13255
13256         /*
13257          * If enabled, print command error status.
13258          */
13259         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13260             (ctl_debug & CTL_DEBUG_INFO) != 0)
13261                 ctl_io_error_print(io, NULL);
13262
13263         /*
13264          * Tell the FETD or the other shelf controller we're done with this
13265          * command.  Note that only SCSI commands get to this point.  Task
13266          * management commands are completed above.
13267          */
13268         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13269             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13270                 memset(&msg, 0, sizeof(msg));
13271                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13272                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13273                 msg.hdr.nexus = io->io_hdr.nexus;
13274                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13275                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13276                     M_WAITOK);
13277         }
13278
13279         fe_done(io);
13280 }
13281
13282 #ifdef CTL_WITH_CA
13283 /*
13284  * Front end should call this if it doesn't do autosense.  When the request
13285  * sense comes back in from the initiator, we'll dequeue this and send it.
13286  */
13287 int
13288 ctl_queue_sense(union ctl_io *io)
13289 {
13290         struct ctl_lun *lun;
13291         struct ctl_port *port;
13292         struct ctl_softc *softc;
13293         uint32_t initidx, targ_lun;
13294
13295         softc = control_softc;
13296
13297         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13298
13299         /*
13300          * LUN lookup will likely move to the ctl_work_thread() once we
13301          * have our new queueing infrastructure (that doesn't put things on
13302          * a per-LUN queue initially).  That is so that we can handle
13303          * things like an INQUIRY to a LUN that we don't have enabled.  We
13304          * can't deal with that right now.
13305          */
13306         mtx_lock(&softc->ctl_lock);
13307
13308         /*
13309          * If we don't have a LUN for this, just toss the sense
13310          * information.
13311          */
13312         port = ctl_io_port(&ctsio->io_hdr);
13313         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13314         if ((targ_lun < CTL_MAX_LUNS)
13315          && (softc->ctl_luns[targ_lun] != NULL))
13316                 lun = softc->ctl_luns[targ_lun];
13317         else
13318                 goto bailout;
13319
13320         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13321
13322         mtx_lock(&lun->lun_lock);
13323         /*
13324          * Already have CA set for this LUN...toss the sense information.
13325          */
13326         if (ctl_is_set(lun->have_ca, initidx)) {
13327                 mtx_unlock(&lun->lun_lock);
13328                 goto bailout;
13329         }
13330
13331         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13332                MIN(sizeof(lun->pending_sense[initidx]),
13333                sizeof(io->scsiio.sense_data)));
13334         ctl_set_mask(lun->have_ca, initidx);
13335         mtx_unlock(&lun->lun_lock);
13336
13337 bailout:
13338         mtx_unlock(&softc->ctl_lock);
13339
13340         ctl_free_io(io);
13341
13342         return (CTL_RETVAL_COMPLETE);
13343 }
13344 #endif
13345
13346 /*
13347  * Primary command inlet from frontend ports.  All SCSI and task I/O
13348  * requests must go through this function.
13349  */
13350 int
13351 ctl_queue(union ctl_io *io)
13352 {
13353         struct ctl_port *port;
13354
13355         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13356
13357 #ifdef CTL_TIME_IO
13358         io->io_hdr.start_time = time_uptime;
13359         getbinuptime(&io->io_hdr.start_bt);
13360 #endif /* CTL_TIME_IO */
13361
13362         /* Map FE-specific LUN ID into global one. */
13363         port = ctl_io_port(&io->io_hdr);
13364         io->io_hdr.nexus.targ_mapped_lun =
13365             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13366
13367         switch (io->io_hdr.io_type) {
13368         case CTL_IO_SCSI:
13369         case CTL_IO_TASK:
13370                 if (ctl_debug & CTL_DEBUG_CDB)
13371                         ctl_io_print(io);
13372                 ctl_enqueue_incoming(io);
13373                 break;
13374         default:
13375                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13376                 return (EINVAL);
13377         }
13378
13379         return (CTL_RETVAL_COMPLETE);
13380 }
13381
13382 #ifdef CTL_IO_DELAY
13383 static void
13384 ctl_done_timer_wakeup(void *arg)
13385 {
13386         union ctl_io *io;
13387
13388         io = (union ctl_io *)arg;
13389         ctl_done(io);
13390 }
13391 #endif /* CTL_IO_DELAY */
13392
13393 void
13394 ctl_serseq_done(union ctl_io *io)
13395 {
13396         struct ctl_lun *lun;
13397
13398         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13399         if (lun->be_lun == NULL ||
13400             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13401                 return;
13402         mtx_lock(&lun->lun_lock);
13403         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13404         ctl_check_blocked(lun);
13405         mtx_unlock(&lun->lun_lock);
13406 }
13407
13408 void
13409 ctl_done(union ctl_io *io)
13410 {
13411
13412         /*
13413          * Enable this to catch duplicate completion issues.
13414          */
13415 #if 0
13416         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13417                 printf("%s: type %d msg %d cdb %x iptl: "
13418                        "%u:%u:%u tag 0x%04x "
13419                        "flag %#x status %x\n",
13420                         __func__,
13421                         io->io_hdr.io_type,
13422                         io->io_hdr.msg_type,
13423                         io->scsiio.cdb[0],
13424                         io->io_hdr.nexus.initid,
13425                         io->io_hdr.nexus.targ_port,
13426                         io->io_hdr.nexus.targ_lun,
13427                         (io->io_hdr.io_type ==
13428                         CTL_IO_TASK) ?
13429                         io->taskio.tag_num :
13430                         io->scsiio.tag_num,
13431                         io->io_hdr.flags,
13432                         io->io_hdr.status);
13433         } else
13434                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13435 #endif
13436
13437         /*
13438          * This is an internal copy of an I/O, and should not go through
13439          * the normal done processing logic.
13440          */
13441         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13442                 return;
13443
13444 #ifdef CTL_IO_DELAY
13445         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13446                 struct ctl_lun *lun;
13447
13448                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13449
13450                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13451         } else {
13452                 struct ctl_lun *lun;
13453
13454                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13455
13456                 if ((lun != NULL)
13457                  && (lun->delay_info.done_delay > 0)) {
13458
13459                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13460                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13461                         callout_reset(&io->io_hdr.delay_callout,
13462                                       lun->delay_info.done_delay * hz,
13463                                       ctl_done_timer_wakeup, io);
13464                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13465                                 lun->delay_info.done_delay = 0;
13466                         return;
13467                 }
13468         }
13469 #endif /* CTL_IO_DELAY */
13470
13471         ctl_enqueue_done(io);
13472 }
13473
13474 static void
13475 ctl_work_thread(void *arg)
13476 {
13477         struct ctl_thread *thr = (struct ctl_thread *)arg;
13478         struct ctl_softc *softc = thr->ctl_softc;
13479         union ctl_io *io;
13480         int retval;
13481
13482         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13483
13484         for (;;) {
13485                 /*
13486                  * We handle the queues in this order:
13487                  * - ISC
13488                  * - done queue (to free up resources, unblock other commands)
13489                  * - RtR queue
13490                  * - incoming queue
13491                  *
13492                  * If those queues are empty, we break out of the loop and
13493                  * go to sleep.
13494                  */
13495                 mtx_lock(&thr->queue_lock);
13496                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13497                 if (io != NULL) {
13498                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13499                         mtx_unlock(&thr->queue_lock);
13500                         ctl_handle_isc(io);
13501                         continue;
13502                 }
13503                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13504                 if (io != NULL) {
13505                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13506                         /* clear any blocked commands, call fe_done */
13507                         mtx_unlock(&thr->queue_lock);
13508                         ctl_process_done(io);
13509                         continue;
13510                 }
13511                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13512                 if (io != NULL) {
13513                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13514                         mtx_unlock(&thr->queue_lock);
13515                         if (io->io_hdr.io_type == CTL_IO_TASK)
13516                                 ctl_run_task(io);
13517                         else
13518                                 ctl_scsiio_precheck(softc, &io->scsiio);
13519                         continue;
13520                 }
13521                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13522                 if (io != NULL) {
13523                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13524                         mtx_unlock(&thr->queue_lock);
13525                         retval = ctl_scsiio(&io->scsiio);
13526                         if (retval != CTL_RETVAL_COMPLETE)
13527                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13528                         continue;
13529                 }
13530
13531                 /* Sleep until we have something to do. */
13532                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13533         }
13534 }
13535
13536 static void
13537 ctl_lun_thread(void *arg)
13538 {
13539         struct ctl_softc *softc = (struct ctl_softc *)arg;
13540         struct ctl_be_lun *be_lun;
13541
13542         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13543
13544         for (;;) {
13545                 mtx_lock(&softc->ctl_lock);
13546                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13547                 if (be_lun != NULL) {
13548                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13549                         mtx_unlock(&softc->ctl_lock);
13550                         ctl_create_lun(be_lun);
13551                         continue;
13552                 }
13553
13554                 /* Sleep until we have something to do. */
13555                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13556                     PDROP | PRIBIO, "-", 0);
13557         }
13558 }
13559
13560 static void
13561 ctl_thresh_thread(void *arg)
13562 {
13563         struct ctl_softc *softc = (struct ctl_softc *)arg;
13564         struct ctl_lun *lun;
13565         struct scsi_da_rw_recovery_page *rwpage;
13566         struct ctl_logical_block_provisioning_page *page;
13567         const char *attr;
13568         union ctl_ha_msg msg;
13569         uint64_t thres, val;
13570         int i, e, set;
13571
13572         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13573
13574         for (;;) {
13575                 mtx_lock(&softc->ctl_lock);
13576                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13577                         if ((lun->flags & CTL_LUN_DISABLED) ||
13578                             (lun->flags & CTL_LUN_NO_MEDIA) ||
13579                             lun->backend->lun_attr == NULL)
13580                                 continue;
13581                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13582                             softc->ha_mode == CTL_HA_MODE_XFER)
13583                                 continue;
13584                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13585                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13586                                 continue;
13587                         e = 0;
13588                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13589                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13590                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13591                                         continue;
13592                                 thres = scsi_4btoul(page->descr[i].count);
13593                                 thres <<= CTL_LBP_EXPONENT;
13594                                 switch (page->descr[i].resource) {
13595                                 case 0x01:
13596                                         attr = "blocksavail";
13597                                         break;
13598                                 case 0x02:
13599                                         attr = "blocksused";
13600                                         break;
13601                                 case 0xf1:
13602                                         attr = "poolblocksavail";
13603                                         break;
13604                                 case 0xf2:
13605                                         attr = "poolblocksused";
13606                                         break;
13607                                 default:
13608                                         continue;
13609                                 }
13610                                 mtx_unlock(&softc->ctl_lock); // XXX
13611                                 val = lun->backend->lun_attr(
13612                                     lun->be_lun->be_lun, attr);
13613                                 mtx_lock(&softc->ctl_lock);
13614                                 if (val == UINT64_MAX)
13615                                         continue;
13616                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13617                                     == SLBPPD_ARMING_INC)
13618                                         e = (val >= thres);
13619                                 else
13620                                         e = (val <= thres);
13621                                 if (e)
13622                                         break;
13623                         }
13624                         mtx_lock(&lun->lun_lock);
13625                         if (e) {
13626                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13627                                     (uint8_t *)page, lun->ua_tpt_info);
13628                                 if (lun->lasttpt == 0 ||
13629                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13630                                         lun->lasttpt = time_uptime;
13631                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13632                                         set = 1;
13633                                 } else
13634                                         set = 0;
13635                         } else {
13636                                 lun->lasttpt = 0;
13637                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13638                                 set = -1;
13639                         }
13640                         mtx_unlock(&lun->lun_lock);
13641                         if (set != 0 &&
13642                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13643                                 /* Send msg to other side. */
13644                                 bzero(&msg.ua, sizeof(msg.ua));
13645                                 msg.hdr.msg_type = CTL_MSG_UA;
13646                                 msg.hdr.nexus.initid = -1;
13647                                 msg.hdr.nexus.targ_port = -1;
13648                                 msg.hdr.nexus.targ_lun = lun->lun;
13649                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13650                                 msg.ua.ua_all = 1;
13651                                 msg.ua.ua_set = (set > 0);
13652                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13653                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13654                                 mtx_unlock(&softc->ctl_lock); // XXX
13655                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13656                                     sizeof(msg.ua), M_WAITOK);
13657                                 mtx_lock(&softc->ctl_lock);
13658                         }
13659                 }
13660                 mtx_unlock(&softc->ctl_lock);
13661                 pause("-", CTL_LBP_PERIOD * hz);
13662         }
13663 }
13664
13665 static void
13666 ctl_enqueue_incoming(union ctl_io *io)
13667 {
13668         struct ctl_softc *softc = control_softc;
13669         struct ctl_thread *thr;
13670         u_int idx;
13671
13672         idx = (io->io_hdr.nexus.targ_port * 127 +
13673                io->io_hdr.nexus.initid) % worker_threads;
13674         thr = &softc->threads[idx];
13675         mtx_lock(&thr->queue_lock);
13676         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13677         mtx_unlock(&thr->queue_lock);
13678         wakeup(thr);
13679 }
13680
13681 static void
13682 ctl_enqueue_rtr(union ctl_io *io)
13683 {
13684         struct ctl_softc *softc = control_softc;
13685         struct ctl_thread *thr;
13686
13687         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13688         mtx_lock(&thr->queue_lock);
13689         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13690         mtx_unlock(&thr->queue_lock);
13691         wakeup(thr);
13692 }
13693
13694 static void
13695 ctl_enqueue_done(union ctl_io *io)
13696 {
13697         struct ctl_softc *softc = control_softc;
13698         struct ctl_thread *thr;
13699
13700         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13701         mtx_lock(&thr->queue_lock);
13702         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13703         mtx_unlock(&thr->queue_lock);
13704         wakeup(thr);
13705 }
13706
13707 static void
13708 ctl_enqueue_isc(union ctl_io *io)
13709 {
13710         struct ctl_softc *softc = control_softc;
13711         struct ctl_thread *thr;
13712
13713         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13714         mtx_lock(&thr->queue_lock);
13715         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13716         mtx_unlock(&thr->queue_lock);
13717         wakeup(thr);
13718 }
13719
13720 /*
13721  *  vim: ts=8
13722  */