]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r287756:
[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_da.h>
73 #include <cam/ctl/ctl_io.h>
74 #include <cam/ctl/ctl.h>
75 #include <cam/ctl/ctl_frontend.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Template mode pages.
89  */
90
91 /*
92  * Note that these are default values only.  The actual values will be
93  * filled in when the user does a mode sense.
94  */
95 const static struct copan_debugconf_subpage debugconf_page_default = {
96         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
97         DBGCNF_SUBPAGE_CODE,            /* subpage */
98         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
99          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
100         DBGCNF_VERSION,                 /* page_version */
101         {CTL_TIME_IO_DEFAULT_SECS>>8,
102          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
103 };
104
105 const static struct copan_debugconf_subpage debugconf_page_changeable = {
106         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
107         DBGCNF_SUBPAGE_CODE,            /* subpage */
108         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
109          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
110         0,                              /* page_version */
111         {0xff,0xff},                    /* ctl_time_io_secs */
112 };
113
114 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
115         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
118         /*read_retry_count*/0,
119         /*correction_span*/0,
120         /*head_offset_count*/0,
121         /*data_strobe_offset_cnt*/0,
122         /*byte8*/SMS_RWER_LBPERE,
123         /*write_retry_count*/0,
124         /*reserved2*/0,
125         /*recovery_time_limit*/{0, 0},
126 };
127
128 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
129         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
130         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
131         /*byte3*/0,
132         /*read_retry_count*/0,
133         /*correction_span*/0,
134         /*head_offset_count*/0,
135         /*data_strobe_offset_cnt*/0,
136         /*byte8*/0,
137         /*write_retry_count*/0,
138         /*reserved2*/0,
139         /*recovery_time_limit*/{0, 0},
140 };
141
142 const static struct scsi_format_page format_page_default = {
143         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
144         /*page_length*/sizeof(struct scsi_format_page) - 2,
145         /*tracks_per_zone*/ {0, 0},
146         /*alt_sectors_per_zone*/ {0, 0},
147         /*alt_tracks_per_zone*/ {0, 0},
148         /*alt_tracks_per_lun*/ {0, 0},
149         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
150                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
151         /*bytes_per_sector*/ {0, 0},
152         /*interleave*/ {0, 0},
153         /*track_skew*/ {0, 0},
154         /*cylinder_skew*/ {0, 0},
155         /*flags*/ SFP_HSEC,
156         /*reserved*/ {0, 0, 0}
157 };
158
159 const static struct scsi_format_page format_page_changeable = {
160         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
161         /*page_length*/sizeof(struct scsi_format_page) - 2,
162         /*tracks_per_zone*/ {0, 0},
163         /*alt_sectors_per_zone*/ {0, 0},
164         /*alt_tracks_per_zone*/ {0, 0},
165         /*alt_tracks_per_lun*/ {0, 0},
166         /*sectors_per_track*/ {0, 0},
167         /*bytes_per_sector*/ {0, 0},
168         /*interleave*/ {0, 0},
169         /*track_skew*/ {0, 0},
170         /*cylinder_skew*/ {0, 0},
171         /*flags*/ 0,
172         /*reserved*/ {0, 0, 0}
173 };
174
175 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
176         /*page_code*/SMS_RIGID_DISK_PAGE,
177         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
178         /*cylinders*/ {0, 0, 0},
179         /*heads*/ CTL_DEFAULT_HEADS,
180         /*start_write_precomp*/ {0, 0, 0},
181         /*start_reduced_current*/ {0, 0, 0},
182         /*step_rate*/ {0, 0},
183         /*landing_zone_cylinder*/ {0, 0, 0},
184         /*rpl*/ SRDP_RPL_DISABLED,
185         /*rotational_offset*/ 0,
186         /*reserved1*/ 0,
187         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
188                            CTL_DEFAULT_ROTATION_RATE & 0xff},
189         /*reserved2*/ {0, 0}
190 };
191
192 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
193         /*page_code*/SMS_RIGID_DISK_PAGE,
194         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
195         /*cylinders*/ {0, 0, 0},
196         /*heads*/ 0,
197         /*start_write_precomp*/ {0, 0, 0},
198         /*start_reduced_current*/ {0, 0, 0},
199         /*step_rate*/ {0, 0},
200         /*landing_zone_cylinder*/ {0, 0, 0},
201         /*rpl*/ 0,
202         /*rotational_offset*/ 0,
203         /*reserved1*/ 0,
204         /*rotation_rate*/ {0, 0},
205         /*reserved2*/ {0, 0}
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 const static struct scsi_info_exceptions_page ie_page_default = {
265         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
266         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
267         /*info_flags*/SIEP_FLAGS_DEXCPT,
268         /*mrie*/0,
269         /*interval_timer*/{0, 0, 0, 0},
270         /*report_count*/{0, 0, 0, 0}
271 };
272
273 const static struct scsi_info_exceptions_page ie_page_changeable = {
274         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
275         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
276         /*info_flags*/0,
277         /*mrie*/0,
278         /*interval_timer*/{0, 0, 0, 0},
279         /*report_count*/{0, 0, 0, 0}
280 };
281
282 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
283
284 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
286         /*subpage_code*/0x02,
287         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
288         /*flags*/0,
289         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
290         /*descr*/{}},
291         {{/*flags*/0,
292           /*resource*/0x01,
293           /*reserved*/{0, 0},
294           /*count*/{0, 0, 0, 0}},
295          {/*flags*/0,
296           /*resource*/0x02,
297           /*reserved*/{0, 0},
298           /*count*/{0, 0, 0, 0}},
299          {/*flags*/0,
300           /*resource*/0xf1,
301           /*reserved*/{0, 0},
302           /*count*/{0, 0, 0, 0}},
303          {/*flags*/0,
304           /*resource*/0xf2,
305           /*reserved*/{0, 0},
306           /*count*/{0, 0, 0, 0}}
307         }
308 };
309
310 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
311         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
312         /*subpage_code*/0x02,
313         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
314         /*flags*/0,
315         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
316         /*descr*/{}},
317         {{/*flags*/0,
318           /*resource*/0,
319           /*reserved*/{0, 0},
320           /*count*/{0, 0, 0, 0}},
321          {/*flags*/0,
322           /*resource*/0,
323           /*reserved*/{0, 0},
324           /*count*/{0, 0, 0, 0}},
325          {/*flags*/0,
326           /*resource*/0,
327           /*reserved*/{0, 0},
328           /*count*/{0, 0, 0, 0}},
329          {/*flags*/0,
330           /*resource*/0,
331           /*reserved*/{0, 0},
332           /*count*/{0, 0, 0, 0}}
333         }
334 };
335
336 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
337 static int worker_threads = -1;
338 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
339 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
340     &worker_threads, 1, "Number of worker threads");
341 static int ctl_debug = CTL_DEBUG_NONE;
342 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
343 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
344     &ctl_debug, 0, "Enabled debug flags");
345
346 /*
347  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
348  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
349  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
350  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
351  */
352 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
353
354 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
355                                   int param);
356 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
357 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
358 static int ctl_init(void);
359 void ctl_shutdown(void);
360 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
361 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
362 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
363 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
364                               struct ctl_ooa *ooa_hdr,
365                               struct ctl_ooa_entry *kern_entries);
366 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
367                      struct thread *td);
368 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
369                          struct ctl_be_lun *be_lun);
370 static int ctl_free_lun(struct ctl_lun *lun);
371 static void ctl_create_lun(struct ctl_be_lun *be_lun);
372 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
373
374 static int ctl_do_mode_select(union ctl_io *io);
375 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
376                            uint64_t res_key, uint64_t sa_res_key,
377                            uint8_t type, uint32_t residx,
378                            struct ctl_scsiio *ctsio,
379                            struct scsi_per_res_out *cdb,
380                            struct scsi_per_res_out_parms* param);
381 static void ctl_pro_preempt_other(struct ctl_lun *lun,
382                                   union ctl_ha_msg *msg);
383 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
384 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
386 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
387 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
388 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
389 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
390                                          int alloc_len);
391 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
392                                          int alloc_len);
393 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
394 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
395 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
396 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
397 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
398 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
399     bool seq);
400 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
401 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
402     union ctl_io *pending_io, union ctl_io *ooa_io);
403 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
404                                 union ctl_io *starting_io);
405 static int ctl_check_blocked(struct ctl_lun *lun);
406 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
407                                 const struct ctl_cmd_entry *entry,
408                                 struct ctl_scsiio *ctsio);
409 static void ctl_failover_lun(struct ctl_lun *lun);
410 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
411                                struct ctl_scsiio *ctsio);
412 static int ctl_scsiio(struct ctl_scsiio *ctsio);
413
414 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
415 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
416                             ctl_ua_type ua_type);
417 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
418                          ctl_ua_type ua_type);
419 static int ctl_abort_task(union ctl_io *io);
420 static int ctl_abort_task_set(union ctl_io *io);
421 static int ctl_i_t_nexus_reset(union ctl_io *io);
422 static void ctl_run_task(union ctl_io *io);
423 #ifdef CTL_IO_DELAY
424 static void ctl_datamove_timer_wakeup(void *arg);
425 static void ctl_done_timer_wakeup(void *arg);
426 #endif /* CTL_IO_DELAY */
427
428 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
429 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
430 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
431 static void ctl_datamove_remote_write(union ctl_io *io);
432 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
433 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
434 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
435 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
436                                     ctl_ha_dt_cb callback);
437 static void ctl_datamove_remote_read(union ctl_io *io);
438 static void ctl_datamove_remote(union ctl_io *io);
439 static int ctl_process_done(union ctl_io *io);
440 static void ctl_lun_thread(void *arg);
441 static void ctl_thresh_thread(void *arg);
442 static void ctl_work_thread(void *arg);
443 static void ctl_enqueue_incoming(union ctl_io *io);
444 static void ctl_enqueue_rtr(union ctl_io *io);
445 static void ctl_enqueue_done(union ctl_io *io);
446 static void ctl_enqueue_isc(union ctl_io *io);
447 static const struct ctl_cmd_entry *
448     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
449 static const struct ctl_cmd_entry *
450     ctl_validate_command(struct ctl_scsiio *ctsio);
451 static int ctl_cmd_applicable(uint8_t lun_type,
452     const struct ctl_cmd_entry *entry);
453
454 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
455 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
456 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
457 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
458
459 /*
460  * Load the serialization table.  This isn't very pretty, but is probably
461  * the easiest way to do it.
462  */
463 #include "ctl_ser_table.c"
464
465 /*
466  * We only need to define open, close and ioctl routines for this driver.
467  */
468 static struct cdevsw ctl_cdevsw = {
469         .d_version =    D_VERSION,
470         .d_flags =      0,
471         .d_open =       ctl_open,
472         .d_close =      ctl_close,
473         .d_ioctl =      ctl_ioctl,
474         .d_name =       "ctl",
475 };
476
477
478 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
479
480 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
481
482 static moduledata_t ctl_moduledata = {
483         "ctl",
484         ctl_module_event_handler,
485         NULL
486 };
487
488 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
489 MODULE_VERSION(ctl, 1);
490
491 static struct ctl_frontend ha_frontend =
492 {
493         .name = "ha",
494 };
495
496 static void
497 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
498                             union ctl_ha_msg *msg_info)
499 {
500         struct ctl_scsiio *ctsio;
501
502         if (msg_info->hdr.original_sc == NULL) {
503                 printf("%s: original_sc == NULL!\n", __func__);
504                 /* XXX KDM now what? */
505                 return;
506         }
507
508         ctsio = &msg_info->hdr.original_sc->scsiio;
509         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
510         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
511         ctsio->io_hdr.status = msg_info->hdr.status;
512         ctsio->scsi_status = msg_info->scsi.scsi_status;
513         ctsio->sense_len = msg_info->scsi.sense_len;
514         ctsio->sense_residual = msg_info->scsi.sense_residual;
515         ctsio->residual = msg_info->scsi.residual;
516         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
517                msg_info->scsi.sense_len);
518         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
519                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
520         ctl_enqueue_isc((union ctl_io *)ctsio);
521 }
522
523 static void
524 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
525                                 union ctl_ha_msg *msg_info)
526 {
527         struct ctl_scsiio *ctsio;
528
529         if (msg_info->hdr.serializing_sc == NULL) {
530                 printf("%s: serializing_sc == NULL!\n", __func__);
531                 /* XXX KDM now what? */
532                 return;
533         }
534
535         ctsio = &msg_info->hdr.serializing_sc->scsiio;
536         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
537         ctl_enqueue_isc((union ctl_io *)ctsio);
538 }
539
540 void
541 ctl_isc_announce_lun(struct ctl_lun *lun)
542 {
543         struct ctl_softc *softc = lun->ctl_softc;
544         union ctl_ha_msg *msg;
545         struct ctl_ha_msg_lun_pr_key pr_key;
546         int i, k;
547
548         if (softc->ha_link != CTL_HA_LINK_ONLINE)
549                 return;
550         mtx_lock(&lun->lun_lock);
551         i = sizeof(msg->lun);
552         if (lun->lun_devid)
553                 i += lun->lun_devid->len;
554         i += sizeof(pr_key) * lun->pr_key_count;
555 alloc:
556         mtx_unlock(&lun->lun_lock);
557         msg = malloc(i, M_CTL, M_WAITOK);
558         mtx_lock(&lun->lun_lock);
559         k = sizeof(msg->lun);
560         if (lun->lun_devid)
561                 k += lun->lun_devid->len;
562         k += sizeof(pr_key) * lun->pr_key_count;
563         if (i < k) {
564                 free(msg, M_CTL);
565                 i = k;
566                 goto alloc;
567         }
568         bzero(&msg->lun, sizeof(msg->lun));
569         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
570         msg->hdr.nexus.targ_lun = lun->lun;
571         msg->hdr.nexus.targ_mapped_lun = lun->lun;
572         msg->lun.flags = lun->flags;
573         msg->lun.pr_generation = lun->PRGeneration;
574         msg->lun.pr_res_idx = lun->pr_res_idx;
575         msg->lun.pr_res_type = lun->res_type;
576         msg->lun.pr_key_count = lun->pr_key_count;
577         i = 0;
578         if (lun->lun_devid) {
579                 msg->lun.lun_devid_len = lun->lun_devid->len;
580                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
581                     msg->lun.lun_devid_len);
582                 i += msg->lun.lun_devid_len;
583         }
584         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
585                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
586                         continue;
587                 pr_key.pr_iid = k;
588                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
589                 i += sizeof(pr_key);
590         }
591         mtx_unlock(&lun->lun_lock);
592         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
593             M_WAITOK);
594         free(msg, M_CTL);
595 }
596
597 void
598 ctl_isc_announce_port(struct ctl_port *port)
599 {
600         struct ctl_softc *softc = control_softc;
601         union ctl_ha_msg *msg;
602         int i;
603
604         if (port->targ_port < softc->port_min ||
605             port->targ_port >= softc->port_max ||
606             softc->ha_link != CTL_HA_LINK_ONLINE)
607                 return;
608         i = sizeof(msg->port) + strlen(port->port_name) + 1;
609         if (port->lun_map)
610                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
611         if (port->port_devid)
612                 i += port->port_devid->len;
613         if (port->target_devid)
614                 i += port->target_devid->len;
615         msg = malloc(i, M_CTL, M_WAITOK);
616         bzero(&msg->port, sizeof(msg->port));
617         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
618         msg->hdr.nexus.targ_port = port->targ_port;
619         msg->port.port_type = port->port_type;
620         msg->port.physical_port = port->physical_port;
621         msg->port.virtual_port = port->virtual_port;
622         msg->port.status = port->status;
623         i = 0;
624         msg->port.name_len = sprintf(&msg->port.data[i],
625             "%d:%s", softc->ha_id, port->port_name) + 1;
626         i += msg->port.name_len;
627         if (port->lun_map) {
628                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
629                 memcpy(&msg->port.data[i], port->lun_map,
630                     msg->port.lun_map_len);
631                 i += msg->port.lun_map_len;
632         }
633         if (port->port_devid) {
634                 msg->port.port_devid_len = port->port_devid->len;
635                 memcpy(&msg->port.data[i], port->port_devid->data,
636                     msg->port.port_devid_len);
637                 i += msg->port.port_devid_len;
638         }
639         if (port->target_devid) {
640                 msg->port.target_devid_len = port->target_devid->len;
641                 memcpy(&msg->port.data[i], port->target_devid->data,
642                     msg->port.target_devid_len);
643                 i += msg->port.target_devid_len;
644         }
645         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
646             M_WAITOK);
647         free(msg, M_CTL);
648 }
649
650 static void
651 ctl_isc_ha_link_up(struct ctl_softc *softc)
652 {
653         struct ctl_port *port;
654         struct ctl_lun *lun;
655
656         STAILQ_FOREACH(port, &softc->port_list, links)
657                 ctl_isc_announce_port(port);
658         STAILQ_FOREACH(lun, &softc->lun_list, links)
659                 ctl_isc_announce_lun(lun);
660 }
661
662 static void
663 ctl_isc_ha_link_down(struct ctl_softc *softc)
664 {
665         struct ctl_port *port;
666         struct ctl_lun *lun;
667         union ctl_io *io;
668
669         mtx_lock(&softc->ctl_lock);
670         STAILQ_FOREACH(lun, &softc->lun_list, links) {
671                 mtx_lock(&lun->lun_lock);
672                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
673                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
674                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
675                 }
676                 mtx_unlock(&lun->lun_lock);
677
678                 mtx_unlock(&softc->ctl_lock);
679                 io = ctl_alloc_io(softc->othersc_pool);
680                 mtx_lock(&softc->ctl_lock);
681                 ctl_zero_io(io);
682                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
683                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
684                 ctl_enqueue_isc(io);
685         }
686
687         STAILQ_FOREACH(port, &softc->port_list, links) {
688                 if (port->targ_port >= softc->port_min &&
689                     port->targ_port < softc->port_max)
690                         continue;
691                 port->status &= ~CTL_PORT_STATUS_ONLINE;
692         }
693         mtx_unlock(&softc->ctl_lock);
694 }
695
696 static void
697 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
698 {
699         struct ctl_lun *lun;
700         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
701
702         mtx_lock(&softc->ctl_lock);
703         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
704             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
705                 mtx_lock(&lun->lun_lock);
706                 mtx_unlock(&softc->ctl_lock);
707                 if (msg->ua.ua_all) {
708                         if (msg->ua.ua_set)
709                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
710                         else
711                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
712                 } else {
713                         if (msg->ua.ua_set)
714                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
715                         else
716                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
717                 }
718                 mtx_unlock(&lun->lun_lock);
719         } else
720                 mtx_unlock(&softc->ctl_lock);
721 }
722
723 static void
724 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
725 {
726         struct ctl_lun *lun;
727         struct ctl_ha_msg_lun_pr_key pr_key;
728         int i, k;
729         ctl_lun_flags oflags;
730         uint32_t targ_lun;
731
732         targ_lun = msg->hdr.nexus.targ_mapped_lun;
733         mtx_lock(&softc->ctl_lock);
734         if ((targ_lun >= CTL_MAX_LUNS) ||
735             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
736                 mtx_unlock(&softc->ctl_lock);
737                 return;
738         }
739         mtx_lock(&lun->lun_lock);
740         mtx_unlock(&softc->ctl_lock);
741         if (lun->flags & CTL_LUN_DISABLED) {
742                 mtx_unlock(&lun->lun_lock);
743                 return;
744         }
745         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
746         if (msg->lun.lun_devid_len != i || (i > 0 &&
747             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
748                 mtx_unlock(&lun->lun_lock);
749                 printf("%s: Received conflicting HA LUN %d\n",
750                     __func__, msg->hdr.nexus.targ_lun);
751                 return;
752         } else {
753                 /* Record whether peer is primary. */
754                 oflags = lun->flags;
755                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
756                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
757                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
758                 else
759                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
760                 if (oflags != lun->flags)
761                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
762
763                 /* If peer is primary and we are not -- use data */
764                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
765                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
766                         lun->PRGeneration = msg->lun.pr_generation;
767                         lun->pr_res_idx = msg->lun.pr_res_idx;
768                         lun->res_type = msg->lun.pr_res_type;
769                         lun->pr_key_count = msg->lun.pr_key_count;
770                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
771                                 ctl_clr_prkey(lun, k);
772                         for (k = 0; k < msg->lun.pr_key_count; k++) {
773                                 memcpy(&pr_key, &msg->lun.data[i],
774                                     sizeof(pr_key));
775                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
776                                 ctl_set_prkey(lun, pr_key.pr_iid,
777                                     pr_key.pr_key);
778                                 i += sizeof(pr_key);
779                         }
780                 }
781
782                 mtx_unlock(&lun->lun_lock);
783                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
784                     __func__, msg->hdr.nexus.targ_lun,
785                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
786                     "primary" : "secondary"));
787
788                 /* If we are primary but peer doesn't know -- notify */
789                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
790                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
791                         ctl_isc_announce_lun(lun);
792         }
793 }
794
795 static void
796 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
797 {
798         struct ctl_port *port;
799         struct ctl_lun *lun;
800         int i, new;
801
802         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
803         if (port == NULL) {
804                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
805                     msg->hdr.nexus.targ_port));
806                 new = 1;
807                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
808                 port->frontend = &ha_frontend;
809                 port->targ_port = msg->hdr.nexus.targ_port;
810         } else if (port->frontend == &ha_frontend) {
811                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
812                     msg->hdr.nexus.targ_port));
813                 new = 0;
814         } else {
815                 printf("%s: Received conflicting HA port %d\n",
816                     __func__, msg->hdr.nexus.targ_port);
817                 return;
818         }
819         port->port_type = msg->port.port_type;
820         port->physical_port = msg->port.physical_port;
821         port->virtual_port = msg->port.virtual_port;
822         port->status = msg->port.status;
823         i = 0;
824         free(port->port_name, M_CTL);
825         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
826             M_CTL);
827         i += msg->port.name_len;
828         if (msg->port.lun_map_len != 0) {
829                 if (port->lun_map == NULL)
830                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
831                             M_CTL, M_WAITOK);
832                 memcpy(port->lun_map, &msg->port.data[i],
833                     sizeof(uint32_t) * CTL_MAX_LUNS);
834                 i += msg->port.lun_map_len;
835         } else {
836                 free(port->lun_map, M_CTL);
837                 port->lun_map = NULL;
838         }
839         if (msg->port.port_devid_len != 0) {
840                 if (port->port_devid == NULL ||
841                     port->port_devid->len != msg->port.port_devid_len) {
842                         free(port->port_devid, M_CTL);
843                         port->port_devid = malloc(sizeof(struct ctl_devid) +
844                             msg->port.port_devid_len, M_CTL, M_WAITOK);
845                 }
846                 memcpy(port->port_devid->data, &msg->port.data[i],
847                     msg->port.port_devid_len);
848                 port->port_devid->len = msg->port.port_devid_len;
849                 i += msg->port.port_devid_len;
850         } else {
851                 free(port->port_devid, M_CTL);
852                 port->port_devid = NULL;
853         }
854         if (msg->port.target_devid_len != 0) {
855                 if (port->target_devid == NULL ||
856                     port->target_devid->len != msg->port.target_devid_len) {
857                         free(port->target_devid, M_CTL);
858                         port->target_devid = malloc(sizeof(struct ctl_devid) +
859                             msg->port.target_devid_len, M_CTL, M_WAITOK);
860                 }
861                 memcpy(port->target_devid->data, &msg->port.data[i],
862                     msg->port.target_devid_len);
863                 port->target_devid->len = msg->port.target_devid_len;
864                 i += msg->port.target_devid_len;
865         } else {
866                 free(port->port_devid, M_CTL);
867                 port->port_devid = NULL;
868         }
869         if (new) {
870                 if (ctl_port_register(port) != 0) {
871                         printf("%s: ctl_port_register() failed with error\n",
872                             __func__);
873                 }
874         }
875         mtx_lock(&softc->ctl_lock);
876         STAILQ_FOREACH(lun, &softc->lun_list, links) {
877                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
878                         continue;
879                 mtx_lock(&lun->lun_lock);
880                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
881                 mtx_unlock(&lun->lun_lock);
882         }
883         mtx_unlock(&softc->ctl_lock);
884 }
885
886 /*
887  * ISC (Inter Shelf Communication) event handler.  Events from the HA
888  * subsystem come in here.
889  */
890 static void
891 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
892 {
893         struct ctl_softc *softc;
894         union ctl_io *io;
895         struct ctl_prio *presio;
896         ctl_ha_status isc_status;
897
898         softc = control_softc;
899         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
900         if (event == CTL_HA_EVT_MSG_RECV) {
901                 union ctl_ha_msg *msg, msgbuf;
902
903                 if (param > sizeof(msgbuf))
904                         msg = malloc(param, M_CTL, M_WAITOK);
905                 else
906                         msg = &msgbuf;
907                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
908                     M_WAITOK);
909                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
910                         printf("%s: Error receiving message: %d\n",
911                             __func__, isc_status);
912                         if (msg != &msgbuf)
913                                 free(msg, M_CTL);
914                         return;
915                 }
916
917                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
918                 switch (msg->hdr.msg_type) {
919                 case CTL_MSG_SERIALIZE:
920                         io = ctl_alloc_io(softc->othersc_pool);
921                         ctl_zero_io(io);
922                         // populate ctsio from msg
923                         io->io_hdr.io_type = CTL_IO_SCSI;
924                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
925                         io->io_hdr.original_sc = msg->hdr.original_sc;
926                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
927                                             CTL_FLAG_IO_ACTIVE;
928                         /*
929                          * If we're in serialization-only mode, we don't
930                          * want to go through full done processing.  Thus
931                          * the COPY flag.
932                          *
933                          * XXX KDM add another flag that is more specific.
934                          */
935                         if (softc->ha_mode != CTL_HA_MODE_XFER)
936                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
937                         io->io_hdr.nexus = msg->hdr.nexus;
938 #if 0
939                         printf("port %u, iid %u, lun %u\n",
940                                io->io_hdr.nexus.targ_port,
941                                io->io_hdr.nexus.initid,
942                                io->io_hdr.nexus.targ_lun);
943 #endif
944                         io->scsiio.tag_num = msg->scsi.tag_num;
945                         io->scsiio.tag_type = msg->scsi.tag_type;
946 #ifdef CTL_TIME_IO
947                         io->io_hdr.start_time = time_uptime;
948                         getbintime(&io->io_hdr.start_bt);
949 #endif /* CTL_TIME_IO */
950                         io->scsiio.cdb_len = msg->scsi.cdb_len;
951                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
952                                CTL_MAX_CDBLEN);
953                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
954                                 const struct ctl_cmd_entry *entry;
955
956                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
957                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
958                                 io->io_hdr.flags |=
959                                         entry->flags & CTL_FLAG_DATA_MASK;
960                         }
961                         ctl_enqueue_isc(io);
962                         break;
963
964                 /* Performed on the Originating SC, XFER mode only */
965                 case CTL_MSG_DATAMOVE: {
966                         struct ctl_sg_entry *sgl;
967                         int i, j;
968
969                         io = msg->hdr.original_sc;
970                         if (io == NULL) {
971                                 printf("%s: original_sc == NULL!\n", __func__);
972                                 /* XXX KDM do something here */
973                                 break;
974                         }
975                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
976                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
977                         /*
978                          * Keep track of this, we need to send it back over
979                          * when the datamove is complete.
980                          */
981                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
982
983                         if (msg->dt.sg_sequence == 0) {
984                                 i = msg->dt.kern_sg_entries +
985                                     io->scsiio.kern_data_len /
986                                     CTL_HA_DATAMOVE_SEGMENT + 1;
987                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
988                                     M_WAITOK | M_ZERO);
989                                 io->io_hdr.remote_sglist = sgl;
990                                 io->io_hdr.local_sglist =
991                                     &sgl[msg->dt.kern_sg_entries];
992
993                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
994
995                                 io->scsiio.kern_sg_entries =
996                                         msg->dt.kern_sg_entries;
997                                 io->scsiio.rem_sg_entries =
998                                         msg->dt.kern_sg_entries;
999                                 io->scsiio.kern_data_len =
1000                                         msg->dt.kern_data_len;
1001                                 io->scsiio.kern_total_len =
1002                                         msg->dt.kern_total_len;
1003                                 io->scsiio.kern_data_resid =
1004                                         msg->dt.kern_data_resid;
1005                                 io->scsiio.kern_rel_offset =
1006                                         msg->dt.kern_rel_offset;
1007                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1008                                 io->io_hdr.flags |= msg->dt.flags &
1009                                     CTL_FLAG_BUS_ADDR;
1010                         } else
1011                                 sgl = (struct ctl_sg_entry *)
1012                                         io->scsiio.kern_data_ptr;
1013
1014                         for (i = msg->dt.sent_sg_entries, j = 0;
1015                              i < (msg->dt.sent_sg_entries +
1016                              msg->dt.cur_sg_entries); i++, j++) {
1017                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1018                                 sgl[i].len = msg->dt.sg_list[j].len;
1019
1020 #if 0
1021                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
1022                                        __func__,
1023                                        msg->dt.sg_list[j].addr,
1024                                        msg->dt.sg_list[j].len,
1025                                        sgl[i].addr, sgl[i].len, j, i);
1026 #endif
1027                         }
1028
1029                         /*
1030                          * If this is the last piece of the I/O, we've got
1031                          * the full S/G list.  Queue processing in the thread.
1032                          * Otherwise wait for the next piece.
1033                          */
1034                         if (msg->dt.sg_last != 0)
1035                                 ctl_enqueue_isc(io);
1036                         break;
1037                 }
1038                 /* Performed on the Serializing (primary) SC, XFER mode only */
1039                 case CTL_MSG_DATAMOVE_DONE: {
1040                         if (msg->hdr.serializing_sc == NULL) {
1041                                 printf("%s: serializing_sc == NULL!\n",
1042                                        __func__);
1043                                 /* XXX KDM now what? */
1044                                 break;
1045                         }
1046                         /*
1047                          * We grab the sense information here in case
1048                          * there was a failure, so we can return status
1049                          * back to the initiator.
1050                          */
1051                         io = msg->hdr.serializing_sc;
1052                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1053                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1054                         io->io_hdr.port_status = msg->scsi.fetd_status;
1055                         io->scsiio.residual = msg->scsi.residual;
1056                         if (msg->hdr.status != CTL_STATUS_NONE) {
1057                                 io->io_hdr.status = msg->hdr.status;
1058                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1059                                 io->scsiio.sense_len = msg->scsi.sense_len;
1060                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1061                                 memcpy(&io->scsiio.sense_data,
1062                                     &msg->scsi.sense_data,
1063                                     msg->scsi.sense_len);
1064                         }
1065                         ctl_enqueue_isc(io);
1066                         break;
1067                 }
1068
1069                 /* Preformed on Originating SC, SER_ONLY mode */
1070                 case CTL_MSG_R2R:
1071                         io = msg->hdr.original_sc;
1072                         if (io == NULL) {
1073                                 printf("%s: original_sc == NULL!\n",
1074                                     __func__);
1075                                 break;
1076                         }
1077                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1078                         io->io_hdr.msg_type = CTL_MSG_R2R;
1079                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1080                         ctl_enqueue_isc(io);
1081                         break;
1082
1083                 /*
1084                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1085                  * mode.
1086                  * Performed on the Originating (i.e. secondary) SC in XFER
1087                  * mode
1088                  */
1089                 case CTL_MSG_FINISH_IO:
1090                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1091                                 ctl_isc_handler_finish_xfer(softc, msg);
1092                         else
1093                                 ctl_isc_handler_finish_ser_only(softc, msg);
1094                         break;
1095
1096                 /* Preformed on Originating SC */
1097                 case CTL_MSG_BAD_JUJU:
1098                         io = msg->hdr.original_sc;
1099                         if (io == NULL) {
1100                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1101                                        __func__);
1102                                 break;
1103                         }
1104                         ctl_copy_sense_data(msg, io);
1105                         /*
1106                          * IO should have already been cleaned up on other
1107                          * SC so clear this flag so we won't send a message
1108                          * back to finish the IO there.
1109                          */
1110                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1111                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1112
1113                         /* io = msg->hdr.serializing_sc; */
1114                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1115                         ctl_enqueue_isc(io);
1116                         break;
1117
1118                 /* Handle resets sent from the other side */
1119                 case CTL_MSG_MANAGE_TASKS: {
1120                         struct ctl_taskio *taskio;
1121                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1122                             softc->othersc_pool);
1123                         ctl_zero_io((union ctl_io *)taskio);
1124                         taskio->io_hdr.io_type = CTL_IO_TASK;
1125                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1126                         taskio->io_hdr.nexus = msg->hdr.nexus;
1127                         taskio->task_action = msg->task.task_action;
1128                         taskio->tag_num = msg->task.tag_num;
1129                         taskio->tag_type = msg->task.tag_type;
1130 #ifdef CTL_TIME_IO
1131                         taskio->io_hdr.start_time = time_uptime;
1132                         getbintime(&taskio->io_hdr.start_bt);
1133 #endif /* CTL_TIME_IO */
1134                         ctl_run_task((union ctl_io *)taskio);
1135                         break;
1136                 }
1137                 /* Persistent Reserve action which needs attention */
1138                 case CTL_MSG_PERS_ACTION:
1139                         presio = (struct ctl_prio *)ctl_alloc_io(
1140                             softc->othersc_pool);
1141                         ctl_zero_io((union ctl_io *)presio);
1142                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1143                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1144                         presio->io_hdr.nexus = msg->hdr.nexus;
1145                         presio->pr_msg = msg->pr;
1146                         ctl_enqueue_isc((union ctl_io *)presio);
1147                         break;
1148                 case CTL_MSG_UA:
1149                         ctl_isc_ua(softc, msg, param);
1150                         break;
1151                 case CTL_MSG_PORT_SYNC:
1152                         ctl_isc_port_sync(softc, msg, param);
1153                         break;
1154                 case CTL_MSG_LUN_SYNC:
1155                         ctl_isc_lun_sync(softc, msg, param);
1156                         break;
1157                 default:
1158                         printf("Received HA message of unknown type %d\n",
1159                             msg->hdr.msg_type);
1160                         break;
1161                 }
1162                 if (msg != &msgbuf)
1163                         free(msg, M_CTL);
1164         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1165                 printf("CTL: HA link status changed from %d to %d\n",
1166                     softc->ha_link, param);
1167                 if (param == softc->ha_link)
1168                         return;
1169                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1170                         softc->ha_link = param;
1171                         ctl_isc_ha_link_down(softc);
1172                 } else {
1173                         softc->ha_link = param;
1174                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1175                                 ctl_isc_ha_link_up(softc);
1176                 }
1177                 return;
1178         } else {
1179                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1180                 return;
1181         }
1182 }
1183
1184 static void
1185 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1186 {
1187
1188         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1189             src->scsi.sense_len);
1190         dest->scsiio.scsi_status = src->scsi.scsi_status;
1191         dest->scsiio.sense_len = src->scsi.sense_len;
1192         dest->io_hdr.status = src->hdr.status;
1193 }
1194
1195 static void
1196 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1197 {
1198
1199         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1200             src->scsiio.sense_len);
1201         dest->scsi.scsi_status = src->scsiio.scsi_status;
1202         dest->scsi.sense_len = src->scsiio.sense_len;
1203         dest->hdr.status = src->io_hdr.status;
1204 }
1205
1206 void
1207 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1208 {
1209         struct ctl_softc *softc = lun->ctl_softc;
1210         ctl_ua_type *pu;
1211
1212         if (initidx < softc->init_min || initidx >= softc->init_max)
1213                 return;
1214         mtx_assert(&lun->lun_lock, MA_OWNED);
1215         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1216         if (pu == NULL)
1217                 return;
1218         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1219 }
1220
1221 void
1222 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1223 {
1224         int i;
1225
1226         mtx_assert(&lun->lun_lock, MA_OWNED);
1227         if (lun->pending_ua[port] == NULL)
1228                 return;
1229         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1230                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1231                         continue;
1232                 lun->pending_ua[port][i] |= ua;
1233         }
1234 }
1235
1236 void
1237 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1238 {
1239         struct ctl_softc *softc = lun->ctl_softc;
1240         int i;
1241
1242         mtx_assert(&lun->lun_lock, MA_OWNED);
1243         for (i = softc->port_min; i < softc->port_max; i++)
1244                 ctl_est_ua_port(lun, i, except, ua);
1245 }
1246
1247 void
1248 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1249 {
1250         struct ctl_softc *softc = lun->ctl_softc;
1251         ctl_ua_type *pu;
1252
1253         if (initidx < softc->init_min || initidx >= softc->init_max)
1254                 return;
1255         mtx_assert(&lun->lun_lock, MA_OWNED);
1256         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1257         if (pu == NULL)
1258                 return;
1259         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1260 }
1261
1262 void
1263 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1264 {
1265         struct ctl_softc *softc = lun->ctl_softc;
1266         int i, j;
1267
1268         mtx_assert(&lun->lun_lock, MA_OWNED);
1269         for (i = softc->port_min; i < softc->port_max; i++) {
1270                 if (lun->pending_ua[i] == NULL)
1271                         continue;
1272                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1273                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1274                                 continue;
1275                         lun->pending_ua[i][j] &= ~ua;
1276                 }
1277         }
1278 }
1279
1280 void
1281 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1282     ctl_ua_type ua_type)
1283 {
1284         struct ctl_lun *lun;
1285
1286         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1287         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1288                 mtx_lock(&lun->lun_lock);
1289                 ctl_clr_ua(lun, initidx, ua_type);
1290                 mtx_unlock(&lun->lun_lock);
1291         }
1292 }
1293
1294 static int
1295 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1296 {
1297         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1298         struct ctl_lun *lun;
1299         struct ctl_lun_req ireq;
1300         int error, value;
1301
1302         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1303         error = sysctl_handle_int(oidp, &value, 0, req);
1304         if ((error != 0) || (req->newptr == NULL))
1305                 return (error);
1306
1307         mtx_lock(&softc->ctl_lock);
1308         if (value == 0)
1309                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1310         else
1311                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1312         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1313                 mtx_unlock(&softc->ctl_lock);
1314                 bzero(&ireq, sizeof(ireq));
1315                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1316                 ireq.reqdata.modify.lun_id = lun->lun;
1317                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1318                     curthread);
1319                 if (ireq.status != CTL_LUN_OK) {
1320                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1321                             __func__, ireq.status, ireq.error_str);
1322                 }
1323                 mtx_lock(&softc->ctl_lock);
1324         }
1325         mtx_unlock(&softc->ctl_lock);
1326         return (0);
1327 }
1328
1329 static int
1330 ctl_init(void)
1331 {
1332         struct ctl_softc *softc;
1333         void *other_pool;
1334         int i, error, retval;
1335
1336         retval = 0;
1337         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1338                                M_WAITOK | M_ZERO);
1339         softc = control_softc;
1340
1341         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1342                               "cam/ctl");
1343
1344         softc->dev->si_drv1 = softc;
1345
1346         sysctl_ctx_init(&softc->sysctl_ctx);
1347         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1348                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1349                 CTLFLAG_RD, 0, "CAM Target Layer");
1350
1351         if (softc->sysctl_tree == NULL) {
1352                 printf("%s: unable to allocate sysctl tree\n", __func__);
1353                 destroy_dev(softc->dev);
1354                 free(control_softc, M_DEVBUF);
1355                 control_softc = NULL;
1356                 return (ENOMEM);
1357         }
1358
1359         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1360         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1361             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1362         softc->open_count = 0;
1363
1364         /*
1365          * Default to actually sending a SYNCHRONIZE CACHE command down to
1366          * the drive.
1367          */
1368         softc->flags = CTL_FLAG_REAL_SYNC;
1369
1370         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1371             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1372             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1373
1374         /*
1375          * In Copan's HA scheme, the "master" and "slave" roles are
1376          * figured out through the slot the controller is in.  Although it
1377          * is an active/active system, someone has to be in charge.
1378          */
1379         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1380             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1381             "HA head ID (0 - no HA)");
1382         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1383                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1384                 softc->is_single = 1;
1385                 softc->port_cnt = CTL_MAX_PORTS;
1386                 softc->port_min = 0;
1387         } else {
1388                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1389                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1390         }
1391         softc->port_max = softc->port_min + softc->port_cnt;
1392         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1393         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1394
1395         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1396             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1397             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1398
1399         STAILQ_INIT(&softc->lun_list);
1400         STAILQ_INIT(&softc->pending_lun_queue);
1401         STAILQ_INIT(&softc->fe_list);
1402         STAILQ_INIT(&softc->port_list);
1403         STAILQ_INIT(&softc->be_list);
1404         ctl_tpc_init(softc);
1405
1406         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1407                             &other_pool) != 0)
1408         {
1409                 printf("ctl: can't allocate %d entry other SC pool, "
1410                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1411                 return (ENOMEM);
1412         }
1413         softc->othersc_pool = other_pool;
1414
1415         if (worker_threads <= 0)
1416                 worker_threads = max(1, mp_ncpus / 4);
1417         if (worker_threads > CTL_MAX_THREADS)
1418                 worker_threads = CTL_MAX_THREADS;
1419
1420         for (i = 0; i < worker_threads; i++) {
1421                 struct ctl_thread *thr = &softc->threads[i];
1422
1423                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1424                 thr->ctl_softc = softc;
1425                 STAILQ_INIT(&thr->incoming_queue);
1426                 STAILQ_INIT(&thr->rtr_queue);
1427                 STAILQ_INIT(&thr->done_queue);
1428                 STAILQ_INIT(&thr->isc_queue);
1429
1430                 error = kproc_kthread_add(ctl_work_thread, thr,
1431                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1432                 if (error != 0) {
1433                         printf("error creating CTL work thread!\n");
1434                         ctl_pool_free(other_pool);
1435                         return (error);
1436                 }
1437         }
1438         error = kproc_kthread_add(ctl_lun_thread, softc,
1439             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1440         if (error != 0) {
1441                 printf("error creating CTL lun thread!\n");
1442                 ctl_pool_free(other_pool);
1443                 return (error);
1444         }
1445         error = kproc_kthread_add(ctl_thresh_thread, softc,
1446             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1447         if (error != 0) {
1448                 printf("error creating CTL threshold thread!\n");
1449                 ctl_pool_free(other_pool);
1450                 return (error);
1451         }
1452
1453         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1454             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1455             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1456
1457         if (softc->is_single == 0) {
1458                 ctl_frontend_register(&ha_frontend);
1459                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1460                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1461                         softc->is_single = 1;
1462                 } else
1463                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1464                     != CTL_HA_STATUS_SUCCESS) {
1465                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1466                         softc->is_single = 1;
1467                 }
1468         }
1469         return (0);
1470 }
1471
1472 void
1473 ctl_shutdown(void)
1474 {
1475         struct ctl_softc *softc;
1476         struct ctl_lun *lun, *next_lun;
1477
1478         softc = (struct ctl_softc *)control_softc;
1479
1480         if (softc->is_single == 0) {
1481                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1482                     != CTL_HA_STATUS_SUCCESS) {
1483                         printf("ctl_shutdown: ctl_ha_msg_deregister failed.\n");
1484                 }
1485                 if (ctl_ha_msg_shutdown(softc) != CTL_HA_STATUS_SUCCESS) {
1486                         printf("ctl_shutdown: ctl_ha_msg_shutdown failed.\n");
1487                 }
1488                 ctl_frontend_deregister(&ha_frontend);
1489         }
1490
1491         mtx_lock(&softc->ctl_lock);
1492
1493         /*
1494          * Free up each LUN.
1495          */
1496         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1497                 next_lun = STAILQ_NEXT(lun, links);
1498                 ctl_free_lun(lun);
1499         }
1500
1501         mtx_unlock(&softc->ctl_lock);
1502
1503 #if 0
1504         ctl_shutdown_thread(softc->work_thread);
1505         mtx_destroy(&softc->queue_lock);
1506 #endif
1507
1508         ctl_tpc_shutdown(softc);
1509         uma_zdestroy(softc->io_zone);
1510         mtx_destroy(&softc->ctl_lock);
1511
1512         destroy_dev(softc->dev);
1513
1514         sysctl_ctx_free(&softc->sysctl_ctx);
1515
1516         free(control_softc, M_DEVBUF);
1517         control_softc = NULL;
1518 }
1519
1520 static int
1521 ctl_module_event_handler(module_t mod, int what, void *arg)
1522 {
1523
1524         switch (what) {
1525         case MOD_LOAD:
1526                 return (ctl_init());
1527         case MOD_UNLOAD:
1528                 return (EBUSY);
1529         default:
1530                 return (EOPNOTSUPP);
1531         }
1532 }
1533
1534 /*
1535  * XXX KDM should we do some access checks here?  Bump a reference count to
1536  * prevent a CTL module from being unloaded while someone has it open?
1537  */
1538 static int
1539 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1540 {
1541         return (0);
1542 }
1543
1544 static int
1545 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1546 {
1547         return (0);
1548 }
1549
1550 /*
1551  * Remove an initiator by port number and initiator ID.
1552  * Returns 0 for success, -1 for failure.
1553  */
1554 int
1555 ctl_remove_initiator(struct ctl_port *port, int iid)
1556 {
1557         struct ctl_softc *softc = control_softc;
1558
1559         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1560
1561         if (iid > CTL_MAX_INIT_PER_PORT) {
1562                 printf("%s: initiator ID %u > maximun %u!\n",
1563                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1564                 return (-1);
1565         }
1566
1567         mtx_lock(&softc->ctl_lock);
1568         port->wwpn_iid[iid].in_use--;
1569         port->wwpn_iid[iid].last_use = time_uptime;
1570         mtx_unlock(&softc->ctl_lock);
1571
1572         return (0);
1573 }
1574
1575 /*
1576  * Add an initiator to the initiator map.
1577  * Returns iid for success, < 0 for failure.
1578  */
1579 int
1580 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1581 {
1582         struct ctl_softc *softc = control_softc;
1583         time_t best_time;
1584         int i, best;
1585
1586         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1587
1588         if (iid >= CTL_MAX_INIT_PER_PORT) {
1589                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1590                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1591                 free(name, M_CTL);
1592                 return (-1);
1593         }
1594
1595         mtx_lock(&softc->ctl_lock);
1596
1597         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1598                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1599                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1600                                 iid = i;
1601                                 break;
1602                         }
1603                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1604                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1605                                 iid = i;
1606                                 break;
1607                         }
1608                 }
1609         }
1610
1611         if (iid < 0) {
1612                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1613                         if (port->wwpn_iid[i].in_use == 0 &&
1614                             port->wwpn_iid[i].wwpn == 0 &&
1615                             port->wwpn_iid[i].name == NULL) {
1616                                 iid = i;
1617                                 break;
1618                         }
1619                 }
1620         }
1621
1622         if (iid < 0) {
1623                 best = -1;
1624                 best_time = INT32_MAX;
1625                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1626                         if (port->wwpn_iid[i].in_use == 0) {
1627                                 if (port->wwpn_iid[i].last_use < best_time) {
1628                                         best = i;
1629                                         best_time = port->wwpn_iid[i].last_use;
1630                                 }
1631                         }
1632                 }
1633                 iid = best;
1634         }
1635
1636         if (iid < 0) {
1637                 mtx_unlock(&softc->ctl_lock);
1638                 free(name, M_CTL);
1639                 return (-2);
1640         }
1641
1642         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1643                 /*
1644                  * This is not an error yet.
1645                  */
1646                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1647 #if 0
1648                         printf("%s: port %d iid %u WWPN %#jx arrived"
1649                             " again\n", __func__, port->targ_port,
1650                             iid, (uintmax_t)wwpn);
1651 #endif
1652                         goto take;
1653                 }
1654                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1655                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1656 #if 0
1657                         printf("%s: port %d iid %u name '%s' arrived"
1658                             " again\n", __func__, port->targ_port,
1659                             iid, name);
1660 #endif
1661                         goto take;
1662                 }
1663
1664                 /*
1665                  * This is an error, but what do we do about it?  The
1666                  * driver is telling us we have a new WWPN for this
1667                  * initiator ID, so we pretty much need to use it.
1668                  */
1669                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1670                     " but WWPN %#jx '%s' is still at that address\n",
1671                     __func__, port->targ_port, iid, wwpn, name,
1672                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1673                     port->wwpn_iid[iid].name);
1674
1675                 /*
1676                  * XXX KDM clear have_ca and ua_pending on each LUN for
1677                  * this initiator.
1678                  */
1679         }
1680 take:
1681         free(port->wwpn_iid[iid].name, M_CTL);
1682         port->wwpn_iid[iid].name = name;
1683         port->wwpn_iid[iid].wwpn = wwpn;
1684         port->wwpn_iid[iid].in_use++;
1685         mtx_unlock(&softc->ctl_lock);
1686
1687         return (iid);
1688 }
1689
1690 static int
1691 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1692 {
1693         int len;
1694
1695         switch (port->port_type) {
1696         case CTL_PORT_FC:
1697         {
1698                 struct scsi_transportid_fcp *id =
1699                     (struct scsi_transportid_fcp *)buf;
1700                 if (port->wwpn_iid[iid].wwpn == 0)
1701                         return (0);
1702                 memset(id, 0, sizeof(*id));
1703                 id->format_protocol = SCSI_PROTO_FC;
1704                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1705                 return (sizeof(*id));
1706         }
1707         case CTL_PORT_ISCSI:
1708         {
1709                 struct scsi_transportid_iscsi_port *id =
1710                     (struct scsi_transportid_iscsi_port *)buf;
1711                 if (port->wwpn_iid[iid].name == NULL)
1712                         return (0);
1713                 memset(id, 0, 256);
1714                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1715                     SCSI_PROTO_ISCSI;
1716                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1717                 len = roundup2(min(len, 252), 4);
1718                 scsi_ulto2b(len, id->additional_length);
1719                 return (sizeof(*id) + len);
1720         }
1721         case CTL_PORT_SAS:
1722         {
1723                 struct scsi_transportid_sas *id =
1724                     (struct scsi_transportid_sas *)buf;
1725                 if (port->wwpn_iid[iid].wwpn == 0)
1726                         return (0);
1727                 memset(id, 0, sizeof(*id));
1728                 id->format_protocol = SCSI_PROTO_SAS;
1729                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1730                 return (sizeof(*id));
1731         }
1732         default:
1733         {
1734                 struct scsi_transportid_spi *id =
1735                     (struct scsi_transportid_spi *)buf;
1736                 memset(id, 0, sizeof(*id));
1737                 id->format_protocol = SCSI_PROTO_SPI;
1738                 scsi_ulto2b(iid, id->scsi_addr);
1739                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1740                 return (sizeof(*id));
1741         }
1742         }
1743 }
1744
1745 /*
1746  * Serialize a command that went down the "wrong" side, and so was sent to
1747  * this controller for execution.  The logic is a little different than the
1748  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1749  * sent back to the other side, but in the success case, we execute the
1750  * command on this side (XFER mode) or tell the other side to execute it
1751  * (SER_ONLY mode).
1752  */
1753 static int
1754 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1755 {
1756         struct ctl_softc *softc;
1757         union ctl_ha_msg msg_info;
1758         struct ctl_lun *lun;
1759         const struct ctl_cmd_entry *entry;
1760         int retval = 0;
1761         uint32_t targ_lun;
1762
1763         softc = control_softc;
1764
1765         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1766         mtx_lock(&softc->ctl_lock);
1767         if ((targ_lun < CTL_MAX_LUNS) &&
1768             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
1769                 mtx_lock(&lun->lun_lock);
1770                 mtx_unlock(&softc->ctl_lock);
1771                 /*
1772                  * If the LUN is invalid, pretend that it doesn't exist.
1773                  * It will go away as soon as all pending I/O has been
1774                  * completed.
1775                  */
1776                 if (lun->flags & CTL_LUN_DISABLED) {
1777                         mtx_unlock(&lun->lun_lock);
1778                         lun = NULL;
1779                 }
1780         } else {
1781                 mtx_unlock(&softc->ctl_lock);
1782                 lun = NULL;
1783         }
1784         if (lun == NULL) {
1785                 /*
1786                  * The other node would not send this request to us unless
1787                  * received announce that we are primary node for this LUN.
1788                  * If this LUN does not exist now, it is probably result of
1789                  * a race, so respond to initiator in the most opaque way.
1790                  */
1791                 ctl_set_busy(ctsio);
1792                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1793                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1794                 msg_info.hdr.serializing_sc = NULL;
1795                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1796                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1797                     sizeof(msg_info.scsi), M_WAITOK);
1798                 return(1);
1799         }
1800
1801         entry = ctl_get_cmd_entry(ctsio, NULL);
1802         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
1803                 mtx_unlock(&lun->lun_lock);
1804                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1805                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1806                 msg_info.hdr.serializing_sc = NULL;
1807                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1808                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1809                     sizeof(msg_info.scsi), M_WAITOK);
1810                 return(1);
1811         }
1812
1813         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
1814         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
1815
1816         /*
1817          * Every I/O goes into the OOA queue for a
1818          * particular LUN, and stays there until completion.
1819          */
1820 #ifdef CTL_TIME_IO
1821         if (TAILQ_EMPTY(&lun->ooa_queue))
1822                 lun->idle_time += getsbinuptime() - lun->last_busy;
1823 #endif
1824         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1825
1826         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1827                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1828                  ooa_links))) {
1829         case CTL_ACTION_BLOCK:
1830                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1831                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1832                                   blocked_links);
1833                 mtx_unlock(&lun->lun_lock);
1834                 break;
1835         case CTL_ACTION_PASS:
1836         case CTL_ACTION_SKIP:
1837                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1838                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1839                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1840                         mtx_unlock(&lun->lun_lock);
1841                 } else {
1842                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
1843                         mtx_unlock(&lun->lun_lock);
1844
1845                         /* send msg back to other side */
1846                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1847                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1848                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1849                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1850                             sizeof(msg_info.hdr), M_WAITOK);
1851                 }
1852                 break;
1853         case CTL_ACTION_OVERLAP:
1854                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1855                 mtx_unlock(&lun->lun_lock);
1856                 retval = 1;
1857
1858                 ctl_set_overlapped_cmd(ctsio);
1859                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1860                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1861                 msg_info.hdr.serializing_sc = NULL;
1862                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1863                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1864                     sizeof(msg_info.scsi), M_WAITOK);
1865                 break;
1866         case CTL_ACTION_OVERLAP_TAG:
1867                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868                 mtx_unlock(&lun->lun_lock);
1869                 retval = 1;
1870                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
1871                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1872                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1873                 msg_info.hdr.serializing_sc = NULL;
1874                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1875                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1876                     sizeof(msg_info.scsi), M_WAITOK);
1877                 break;
1878         case CTL_ACTION_ERROR:
1879         default:
1880                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1881                 mtx_unlock(&lun->lun_lock);
1882                 retval = 1;
1883
1884                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
1885                                          /*retry_count*/ 0);
1886                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1887                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1888                 msg_info.hdr.serializing_sc = NULL;
1889                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1890                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1891                     sizeof(msg_info.scsi), M_WAITOK);
1892                 break;
1893         }
1894         return (retval);
1895 }
1896
1897 /*
1898  * Returns 0 for success, errno for failure.
1899  */
1900 static int
1901 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1902                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1903 {
1904         union ctl_io *io;
1905         int retval;
1906
1907         retval = 0;
1908
1909         mtx_lock(&lun->lun_lock);
1910         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1911              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1912              ooa_links)) {
1913                 struct ctl_ooa_entry *entry;
1914
1915                 /*
1916                  * If we've got more than we can fit, just count the
1917                  * remaining entries.
1918                  */
1919                 if (*cur_fill_num >= ooa_hdr->alloc_num)
1920                         continue;
1921
1922                 entry = &kern_entries[*cur_fill_num];
1923
1924                 entry->tag_num = io->scsiio.tag_num;
1925                 entry->lun_num = lun->lun;
1926 #ifdef CTL_TIME_IO
1927                 entry->start_bt = io->io_hdr.start_bt;
1928 #endif
1929                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1930                 entry->cdb_len = io->scsiio.cdb_len;
1931                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1932                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1933
1934                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1935                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1936
1937                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
1938                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1939
1940                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1941                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1942
1943                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1944                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1945         }
1946         mtx_unlock(&lun->lun_lock);
1947
1948         return (retval);
1949 }
1950
1951 static void *
1952 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
1953                  size_t error_str_len)
1954 {
1955         void *kptr;
1956
1957         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
1958
1959         if (copyin(user_addr, kptr, len) != 0) {
1960                 snprintf(error_str, error_str_len, "Error copying %d bytes "
1961                          "from user address %p to kernel address %p", len,
1962                          user_addr, kptr);
1963                 free(kptr, M_CTL);
1964                 return (NULL);
1965         }
1966
1967         return (kptr);
1968 }
1969
1970 static void
1971 ctl_free_args(int num_args, struct ctl_be_arg *args)
1972 {
1973         int i;
1974
1975         if (args == NULL)
1976                 return;
1977
1978         for (i = 0; i < num_args; i++) {
1979                 free(args[i].kname, M_CTL);
1980                 free(args[i].kvalue, M_CTL);
1981         }
1982
1983         free(args, M_CTL);
1984 }
1985
1986 static struct ctl_be_arg *
1987 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
1988                 char *error_str, size_t error_str_len)
1989 {
1990         struct ctl_be_arg *args;
1991         int i;
1992
1993         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
1994                                 error_str, error_str_len);
1995
1996         if (args == NULL)
1997                 goto bailout;
1998
1999         for (i = 0; i < num_args; i++) {
2000                 args[i].kname = NULL;
2001                 args[i].kvalue = NULL;
2002         }
2003
2004         for (i = 0; i < num_args; i++) {
2005                 uint8_t *tmpptr;
2006
2007                 args[i].kname = ctl_copyin_alloc(args[i].name,
2008                         args[i].namelen, error_str, error_str_len);
2009                 if (args[i].kname == NULL)
2010                         goto bailout;
2011
2012                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2013                         snprintf(error_str, error_str_len, "Argument %d "
2014                                  "name is not NUL-terminated", i);
2015                         goto bailout;
2016                 }
2017
2018                 if (args[i].flags & CTL_BEARG_RD) {
2019                         tmpptr = ctl_copyin_alloc(args[i].value,
2020                                 args[i].vallen, error_str, error_str_len);
2021                         if (tmpptr == NULL)
2022                                 goto bailout;
2023                         if ((args[i].flags & CTL_BEARG_ASCII)
2024                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2025                                 snprintf(error_str, error_str_len, "Argument "
2026                                     "%d value is not NUL-terminated", i);
2027                                 goto bailout;
2028                         }
2029                         args[i].kvalue = tmpptr;
2030                 } else {
2031                         args[i].kvalue = malloc(args[i].vallen,
2032                             M_CTL, M_WAITOK | M_ZERO);
2033                 }
2034         }
2035
2036         return (args);
2037 bailout:
2038
2039         ctl_free_args(num_args, args);
2040
2041         return (NULL);
2042 }
2043
2044 static void
2045 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2046 {
2047         int i;
2048
2049         for (i = 0; i < num_args; i++) {
2050                 if (args[i].flags & CTL_BEARG_WR)
2051                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2052         }
2053 }
2054
2055 /*
2056  * Escape characters that are illegal or not recommended in XML.
2057  */
2058 int
2059 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2060 {
2061         char *end = str + size;
2062         int retval;
2063
2064         retval = 0;
2065
2066         for (; *str && str < end; str++) {
2067                 switch (*str) {
2068                 case '&':
2069                         retval = sbuf_printf(sb, "&amp;");
2070                         break;
2071                 case '>':
2072                         retval = sbuf_printf(sb, "&gt;");
2073                         break;
2074                 case '<':
2075                         retval = sbuf_printf(sb, "&lt;");
2076                         break;
2077                 default:
2078                         retval = sbuf_putc(sb, *str);
2079                         break;
2080                 }
2081
2082                 if (retval != 0)
2083                         break;
2084
2085         }
2086
2087         return (retval);
2088 }
2089
2090 static void
2091 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2092 {
2093         struct scsi_vpd_id_descriptor *desc;
2094         int i;
2095
2096         if (id == NULL || id->len < 4)
2097                 return;
2098         desc = (struct scsi_vpd_id_descriptor *)id->data;
2099         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2100         case SVPD_ID_TYPE_T10:
2101                 sbuf_printf(sb, "t10.");
2102                 break;
2103         case SVPD_ID_TYPE_EUI64:
2104                 sbuf_printf(sb, "eui.");
2105                 break;
2106         case SVPD_ID_TYPE_NAA:
2107                 sbuf_printf(sb, "naa.");
2108                 break;
2109         case SVPD_ID_TYPE_SCSI_NAME:
2110                 break;
2111         }
2112         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2113         case SVPD_ID_CODESET_BINARY:
2114                 for (i = 0; i < desc->length; i++)
2115                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2116                 break;
2117         case SVPD_ID_CODESET_ASCII:
2118                 sbuf_printf(sb, "%.*s", (int)desc->length,
2119                     (char *)desc->identifier);
2120                 break;
2121         case SVPD_ID_CODESET_UTF8:
2122                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2123                 break;
2124         }
2125 }
2126
2127 static int
2128 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2129           struct thread *td)
2130 {
2131         struct ctl_softc *softc;
2132         struct ctl_lun *lun;
2133         int retval;
2134
2135         softc = control_softc;
2136
2137         retval = 0;
2138
2139         switch (cmd) {
2140         case CTL_IO:
2141                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2142                 break;
2143         case CTL_ENABLE_PORT:
2144         case CTL_DISABLE_PORT:
2145         case CTL_SET_PORT_WWNS: {
2146                 struct ctl_port *port;
2147                 struct ctl_port_entry *entry;
2148
2149                 entry = (struct ctl_port_entry *)addr;
2150                 
2151                 mtx_lock(&softc->ctl_lock);
2152                 STAILQ_FOREACH(port, &softc->port_list, links) {
2153                         int action, done;
2154
2155                         if (port->targ_port < softc->port_min ||
2156                             port->targ_port >= softc->port_max)
2157                                 continue;
2158
2159                         action = 0;
2160                         done = 0;
2161                         if ((entry->port_type == CTL_PORT_NONE)
2162                          && (entry->targ_port == port->targ_port)) {
2163                                 /*
2164                                  * If the user only wants to enable or
2165                                  * disable or set WWNs on a specific port,
2166                                  * do the operation and we're done.
2167                                  */
2168                                 action = 1;
2169                                 done = 1;
2170                         } else if (entry->port_type & port->port_type) {
2171                                 /*
2172                                  * Compare the user's type mask with the
2173                                  * particular frontend type to see if we
2174                                  * have a match.
2175                                  */
2176                                 action = 1;
2177                                 done = 0;
2178
2179                                 /*
2180                                  * Make sure the user isn't trying to set
2181                                  * WWNs on multiple ports at the same time.
2182                                  */
2183                                 if (cmd == CTL_SET_PORT_WWNS) {
2184                                         printf("%s: Can't set WWNs on "
2185                                                "multiple ports\n", __func__);
2186                                         retval = EINVAL;
2187                                         break;
2188                                 }
2189                         }
2190                         if (action == 0)
2191                                 continue;
2192
2193                         /*
2194                          * XXX KDM we have to drop the lock here, because
2195                          * the online/offline operations can potentially
2196                          * block.  We need to reference count the frontends
2197                          * so they can't go away,
2198                          */
2199                         if (cmd == CTL_ENABLE_PORT) {
2200                                 mtx_unlock(&softc->ctl_lock);
2201                                 ctl_port_online(port);
2202                                 mtx_lock(&softc->ctl_lock);
2203                         } else if (cmd == CTL_DISABLE_PORT) {
2204                                 mtx_unlock(&softc->ctl_lock);
2205                                 ctl_port_offline(port);
2206                                 mtx_lock(&softc->ctl_lock);
2207                         } else if (cmd == CTL_SET_PORT_WWNS) {
2208                                 ctl_port_set_wwns(port,
2209                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2210                                     1 : 0, entry->wwnn,
2211                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2212                                     1 : 0, entry->wwpn);
2213                         }
2214                         if (done != 0)
2215                                 break;
2216                 }
2217                 mtx_unlock(&softc->ctl_lock);
2218                 break;
2219         }
2220         case CTL_GET_PORT_LIST: {
2221                 struct ctl_port *port;
2222                 struct ctl_port_list *list;
2223                 int i;
2224
2225                 list = (struct ctl_port_list *)addr;
2226
2227                 if (list->alloc_len != (list->alloc_num *
2228                     sizeof(struct ctl_port_entry))) {
2229                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2230                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2231                                "%zu\n", __func__, list->alloc_len,
2232                                list->alloc_num, sizeof(struct ctl_port_entry));
2233                         retval = EINVAL;
2234                         break;
2235                 }
2236                 list->fill_len = 0;
2237                 list->fill_num = 0;
2238                 list->dropped_num = 0;
2239                 i = 0;
2240                 mtx_lock(&softc->ctl_lock);
2241                 STAILQ_FOREACH(port, &softc->port_list, links) {
2242                         struct ctl_port_entry entry, *list_entry;
2243
2244                         if (list->fill_num >= list->alloc_num) {
2245                                 list->dropped_num++;
2246                                 continue;
2247                         }
2248
2249                         entry.port_type = port->port_type;
2250                         strlcpy(entry.port_name, port->port_name,
2251                                 sizeof(entry.port_name));
2252                         entry.targ_port = port->targ_port;
2253                         entry.physical_port = port->physical_port;
2254                         entry.virtual_port = port->virtual_port;
2255                         entry.wwnn = port->wwnn;
2256                         entry.wwpn = port->wwpn;
2257                         if (port->status & CTL_PORT_STATUS_ONLINE)
2258                                 entry.online = 1;
2259                         else
2260                                 entry.online = 0;
2261
2262                         list_entry = &list->entries[i];
2263
2264                         retval = copyout(&entry, list_entry, sizeof(entry));
2265                         if (retval != 0) {
2266                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2267                                        "returned %d\n", __func__, retval);
2268                                 break;
2269                         }
2270                         i++;
2271                         list->fill_num++;
2272                         list->fill_len += sizeof(entry);
2273                 }
2274                 mtx_unlock(&softc->ctl_lock);
2275
2276                 /*
2277                  * If this is non-zero, we had a copyout fault, so there's
2278                  * probably no point in attempting to set the status inside
2279                  * the structure.
2280                  */
2281                 if (retval != 0)
2282                         break;
2283
2284                 if (list->dropped_num > 0)
2285                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2286                 else
2287                         list->status = CTL_PORT_LIST_OK;
2288                 break;
2289         }
2290         case CTL_DUMP_OOA: {
2291                 union ctl_io *io;
2292                 char printbuf[128];
2293                 struct sbuf sb;
2294
2295                 mtx_lock(&softc->ctl_lock);
2296                 printf("Dumping OOA queues:\n");
2297                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2298                         mtx_lock(&lun->lun_lock);
2299                         for (io = (union ctl_io *)TAILQ_FIRST(
2300                              &lun->ooa_queue); io != NULL;
2301                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2302                              ooa_links)) {
2303                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2304                                          SBUF_FIXEDLEN);
2305                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2306                                             (intmax_t)lun->lun,
2307                                             io->scsiio.tag_num,
2308                                             (io->io_hdr.flags &
2309                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2310                                             (io->io_hdr.flags &
2311                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2312                                             (io->io_hdr.flags &
2313                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2314                                             (io->io_hdr.flags &
2315                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2316                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2317                                 sbuf_finish(&sb);
2318                                 printf("%s\n", sbuf_data(&sb));
2319                         }
2320                         mtx_unlock(&lun->lun_lock);
2321                 }
2322                 printf("OOA queues dump done\n");
2323                 mtx_unlock(&softc->ctl_lock);
2324                 break;
2325         }
2326         case CTL_GET_OOA: {
2327                 struct ctl_ooa *ooa_hdr;
2328                 struct ctl_ooa_entry *entries;
2329                 uint32_t cur_fill_num;
2330
2331                 ooa_hdr = (struct ctl_ooa *)addr;
2332
2333                 if ((ooa_hdr->alloc_len == 0)
2334                  || (ooa_hdr->alloc_num == 0)) {
2335                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2336                                "must be non-zero\n", __func__,
2337                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2338                         retval = EINVAL;
2339                         break;
2340                 }
2341
2342                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2343                     sizeof(struct ctl_ooa_entry))) {
2344                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2345                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2346                                __func__, ooa_hdr->alloc_len,
2347                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2348                         retval = EINVAL;
2349                         break;
2350                 }
2351
2352                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2353                 if (entries == NULL) {
2354                         printf("%s: could not allocate %d bytes for OOA "
2355                                "dump\n", __func__, ooa_hdr->alloc_len);
2356                         retval = ENOMEM;
2357                         break;
2358                 }
2359
2360                 mtx_lock(&softc->ctl_lock);
2361                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2362                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2363                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2364                         mtx_unlock(&softc->ctl_lock);
2365                         free(entries, M_CTL);
2366                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2367                                __func__, (uintmax_t)ooa_hdr->lun_num);
2368                         retval = EINVAL;
2369                         break;
2370                 }
2371
2372                 cur_fill_num = 0;
2373
2374                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2375                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2376                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2377                                         ooa_hdr, entries);
2378                                 if (retval != 0)
2379                                         break;
2380                         }
2381                         if (retval != 0) {
2382                                 mtx_unlock(&softc->ctl_lock);
2383                                 free(entries, M_CTL);
2384                                 break;
2385                         }
2386                 } else {
2387                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2388
2389                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2390                                                     entries);
2391                 }
2392                 mtx_unlock(&softc->ctl_lock);
2393
2394                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2395                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2396                         sizeof(struct ctl_ooa_entry);
2397                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2398                 if (retval != 0) {
2399                         printf("%s: error copying out %d bytes for OOA dump\n", 
2400                                __func__, ooa_hdr->fill_len);
2401                 }
2402
2403                 getbintime(&ooa_hdr->cur_bt);
2404
2405                 if (cur_fill_num > ooa_hdr->alloc_num) {
2406                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2407                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2408                 } else {
2409                         ooa_hdr->dropped_num = 0;
2410                         ooa_hdr->status = CTL_OOA_OK;
2411                 }
2412
2413                 free(entries, M_CTL);
2414                 break;
2415         }
2416         case CTL_CHECK_OOA: {
2417                 union ctl_io *io;
2418                 struct ctl_ooa_info *ooa_info;
2419
2420
2421                 ooa_info = (struct ctl_ooa_info *)addr;
2422
2423                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2424                         ooa_info->status = CTL_OOA_INVALID_LUN;
2425                         break;
2426                 }
2427                 mtx_lock(&softc->ctl_lock);
2428                 lun = softc->ctl_luns[ooa_info->lun_id];
2429                 if (lun == NULL) {
2430                         mtx_unlock(&softc->ctl_lock);
2431                         ooa_info->status = CTL_OOA_INVALID_LUN;
2432                         break;
2433                 }
2434                 mtx_lock(&lun->lun_lock);
2435                 mtx_unlock(&softc->ctl_lock);
2436                 ooa_info->num_entries = 0;
2437                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2438                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2439                      &io->io_hdr, ooa_links)) {
2440                         ooa_info->num_entries++;
2441                 }
2442                 mtx_unlock(&lun->lun_lock);
2443
2444                 ooa_info->status = CTL_OOA_SUCCESS;
2445
2446                 break;
2447         }
2448         case CTL_DELAY_IO: {
2449                 struct ctl_io_delay_info *delay_info;
2450
2451                 delay_info = (struct ctl_io_delay_info *)addr;
2452
2453 #ifdef CTL_IO_DELAY
2454                 mtx_lock(&softc->ctl_lock);
2455
2456                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2457                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2458                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2459                 } else {
2460                         lun = softc->ctl_luns[delay_info->lun_id];
2461                         mtx_lock(&lun->lun_lock);
2462
2463                         delay_info->status = CTL_DELAY_STATUS_OK;
2464
2465                         switch (delay_info->delay_type) {
2466                         case CTL_DELAY_TYPE_CONT:
2467                                 break;
2468                         case CTL_DELAY_TYPE_ONESHOT:
2469                                 break;
2470                         default:
2471                                 delay_info->status =
2472                                         CTL_DELAY_STATUS_INVALID_TYPE;
2473                                 break;
2474                         }
2475
2476                         switch (delay_info->delay_loc) {
2477                         case CTL_DELAY_LOC_DATAMOVE:
2478                                 lun->delay_info.datamove_type =
2479                                         delay_info->delay_type;
2480                                 lun->delay_info.datamove_delay =
2481                                         delay_info->delay_secs;
2482                                 break;
2483                         case CTL_DELAY_LOC_DONE:
2484                                 lun->delay_info.done_type =
2485                                         delay_info->delay_type;
2486                                 lun->delay_info.done_delay =
2487                                         delay_info->delay_secs;
2488                                 break;
2489                         default:
2490                                 delay_info->status =
2491                                         CTL_DELAY_STATUS_INVALID_LOC;
2492                                 break;
2493                         }
2494                         mtx_unlock(&lun->lun_lock);
2495                 }
2496
2497                 mtx_unlock(&softc->ctl_lock);
2498 #else
2499                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2500 #endif /* CTL_IO_DELAY */
2501                 break;
2502         }
2503         case CTL_REALSYNC_SET: {
2504                 int *syncstate;
2505
2506                 syncstate = (int *)addr;
2507
2508                 mtx_lock(&softc->ctl_lock);
2509                 switch (*syncstate) {
2510                 case 0:
2511                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2512                         break;
2513                 case 1:
2514                         softc->flags |= CTL_FLAG_REAL_SYNC;
2515                         break;
2516                 default:
2517                         retval = EINVAL;
2518                         break;
2519                 }
2520                 mtx_unlock(&softc->ctl_lock);
2521                 break;
2522         }
2523         case CTL_REALSYNC_GET: {
2524                 int *syncstate;
2525
2526                 syncstate = (int*)addr;
2527
2528                 mtx_lock(&softc->ctl_lock);
2529                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2530                         *syncstate = 1;
2531                 else
2532                         *syncstate = 0;
2533                 mtx_unlock(&softc->ctl_lock);
2534
2535                 break;
2536         }
2537         case CTL_SETSYNC:
2538         case CTL_GETSYNC: {
2539                 struct ctl_sync_info *sync_info;
2540
2541                 sync_info = (struct ctl_sync_info *)addr;
2542
2543                 mtx_lock(&softc->ctl_lock);
2544                 lun = softc->ctl_luns[sync_info->lun_id];
2545                 if (lun == NULL) {
2546                         mtx_unlock(&softc->ctl_lock);
2547                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2548                         break;
2549                 }
2550                 /*
2551                  * Get or set the sync interval.  We're not bounds checking
2552                  * in the set case, hopefully the user won't do something
2553                  * silly.
2554                  */
2555                 mtx_lock(&lun->lun_lock);
2556                 mtx_unlock(&softc->ctl_lock);
2557                 if (cmd == CTL_GETSYNC)
2558                         sync_info->sync_interval = lun->sync_interval;
2559                 else
2560                         lun->sync_interval = sync_info->sync_interval;
2561                 mtx_unlock(&lun->lun_lock);
2562
2563                 sync_info->status = CTL_GS_SYNC_OK;
2564
2565                 break;
2566         }
2567         case CTL_GETSTATS: {
2568                 struct ctl_stats *stats;
2569                 int i;
2570
2571                 stats = (struct ctl_stats *)addr;
2572
2573                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2574                      stats->alloc_len) {
2575                         stats->status = CTL_SS_NEED_MORE_SPACE;
2576                         stats->num_luns = softc->num_luns;
2577                         break;
2578                 }
2579                 /*
2580                  * XXX KDM no locking here.  If the LUN list changes,
2581                  * things can blow up.
2582                  */
2583                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2584                      i++, lun = STAILQ_NEXT(lun, links)) {
2585                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2586                                          sizeof(lun->stats));
2587                         if (retval != 0)
2588                                 break;
2589                 }
2590                 stats->num_luns = softc->num_luns;
2591                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2592                                  softc->num_luns;
2593                 stats->status = CTL_SS_OK;
2594 #ifdef CTL_TIME_IO
2595                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2596 #else
2597                 stats->flags = CTL_STATS_FLAG_NONE;
2598 #endif
2599                 getnanouptime(&stats->timestamp);
2600                 break;
2601         }
2602         case CTL_ERROR_INJECT: {
2603                 struct ctl_error_desc *err_desc, *new_err_desc;
2604
2605                 err_desc = (struct ctl_error_desc *)addr;
2606
2607                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2608                                       M_WAITOK | M_ZERO);
2609                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2610
2611                 mtx_lock(&softc->ctl_lock);
2612                 lun = softc->ctl_luns[err_desc->lun_id];
2613                 if (lun == NULL) {
2614                         mtx_unlock(&softc->ctl_lock);
2615                         free(new_err_desc, M_CTL);
2616                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2617                                __func__, (uintmax_t)err_desc->lun_id);
2618                         retval = EINVAL;
2619                         break;
2620                 }
2621                 mtx_lock(&lun->lun_lock);
2622                 mtx_unlock(&softc->ctl_lock);
2623
2624                 /*
2625                  * We could do some checking here to verify the validity
2626                  * of the request, but given the complexity of error
2627                  * injection requests, the checking logic would be fairly
2628                  * complex.
2629                  *
2630                  * For now, if the request is invalid, it just won't get
2631                  * executed and might get deleted.
2632                  */
2633                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2634
2635                 /*
2636                  * XXX KDM check to make sure the serial number is unique,
2637                  * in case we somehow manage to wrap.  That shouldn't
2638                  * happen for a very long time, but it's the right thing to
2639                  * do.
2640                  */
2641                 new_err_desc->serial = lun->error_serial;
2642                 err_desc->serial = lun->error_serial;
2643                 lun->error_serial++;
2644
2645                 mtx_unlock(&lun->lun_lock);
2646                 break;
2647         }
2648         case CTL_ERROR_INJECT_DELETE: {
2649                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2650                 int delete_done;
2651
2652                 delete_desc = (struct ctl_error_desc *)addr;
2653                 delete_done = 0;
2654
2655                 mtx_lock(&softc->ctl_lock);
2656                 lun = softc->ctl_luns[delete_desc->lun_id];
2657                 if (lun == NULL) {
2658                         mtx_unlock(&softc->ctl_lock);
2659                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2660                                __func__, (uintmax_t)delete_desc->lun_id);
2661                         retval = EINVAL;
2662                         break;
2663                 }
2664                 mtx_lock(&lun->lun_lock);
2665                 mtx_unlock(&softc->ctl_lock);
2666                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2667                         if (desc->serial != delete_desc->serial)
2668                                 continue;
2669
2670                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2671                                       links);
2672                         free(desc, M_CTL);
2673                         delete_done = 1;
2674                 }
2675                 mtx_unlock(&lun->lun_lock);
2676                 if (delete_done == 0) {
2677                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2678                                "error serial %ju on LUN %u\n", __func__, 
2679                                delete_desc->serial, delete_desc->lun_id);
2680                         retval = EINVAL;
2681                         break;
2682                 }
2683                 break;
2684         }
2685         case CTL_DUMP_STRUCTS: {
2686                 int i, j, k;
2687                 struct ctl_port *port;
2688                 struct ctl_frontend *fe;
2689
2690                 mtx_lock(&softc->ctl_lock);
2691                 printf("CTL Persistent Reservation information start:\n");
2692                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2693                         lun = softc->ctl_luns[i];
2694
2695                         if ((lun == NULL)
2696                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2697                                 continue;
2698
2699                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2700                                 if (lun->pr_keys[j] == NULL)
2701                                         continue;
2702                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2703                                         if (lun->pr_keys[j][k] == 0)
2704                                                 continue;
2705                                         printf("  LUN %d port %d iid %d key "
2706                                                "%#jx\n", i, j, k,
2707                                                (uintmax_t)lun->pr_keys[j][k]);
2708                                 }
2709                         }
2710                 }
2711                 printf("CTL Persistent Reservation information end\n");
2712                 printf("CTL Ports:\n");
2713                 STAILQ_FOREACH(port, &softc->port_list, links) {
2714                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2715                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2716                                port->frontend->name, port->port_type,
2717                                port->physical_port, port->virtual_port,
2718                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2719                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2720                                 if (port->wwpn_iid[j].in_use == 0 &&
2721                                     port->wwpn_iid[j].wwpn == 0 &&
2722                                     port->wwpn_iid[j].name == NULL)
2723                                         continue;
2724
2725                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2726                                     j, port->wwpn_iid[j].in_use,
2727                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2728                                     port->wwpn_iid[j].name);
2729                         }
2730                 }
2731                 printf("CTL Port information end\n");
2732                 mtx_unlock(&softc->ctl_lock);
2733                 /*
2734                  * XXX KDM calling this without a lock.  We'd likely want
2735                  * to drop the lock before calling the frontend's dump
2736                  * routine anyway.
2737                  */
2738                 printf("CTL Frontends:\n");
2739                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2740                         printf("  Frontend '%s'\n", fe->name);
2741                         if (fe->fe_dump != NULL)
2742                                 fe->fe_dump();
2743                 }
2744                 printf("CTL Frontend information end\n");
2745                 break;
2746         }
2747         case CTL_LUN_REQ: {
2748                 struct ctl_lun_req *lun_req;
2749                 struct ctl_backend_driver *backend;
2750
2751                 lun_req = (struct ctl_lun_req *)addr;
2752
2753                 backend = ctl_backend_find(lun_req->backend);
2754                 if (backend == NULL) {
2755                         lun_req->status = CTL_LUN_ERROR;
2756                         snprintf(lun_req->error_str,
2757                                  sizeof(lun_req->error_str),
2758                                  "Backend \"%s\" not found.",
2759                                  lun_req->backend);
2760                         break;
2761                 }
2762                 if (lun_req->num_be_args > 0) {
2763                         lun_req->kern_be_args = ctl_copyin_args(
2764                                 lun_req->num_be_args,
2765                                 lun_req->be_args,
2766                                 lun_req->error_str,
2767                                 sizeof(lun_req->error_str));
2768                         if (lun_req->kern_be_args == NULL) {
2769                                 lun_req->status = CTL_LUN_ERROR;
2770                                 break;
2771                         }
2772                 }
2773
2774                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2775
2776                 if (lun_req->num_be_args > 0) {
2777                         ctl_copyout_args(lun_req->num_be_args,
2778                                       lun_req->kern_be_args);
2779                         ctl_free_args(lun_req->num_be_args,
2780                                       lun_req->kern_be_args);
2781                 }
2782                 break;
2783         }
2784         case CTL_LUN_LIST: {
2785                 struct sbuf *sb;
2786                 struct ctl_lun_list *list;
2787                 struct ctl_option *opt;
2788
2789                 list = (struct ctl_lun_list *)addr;
2790
2791                 /*
2792                  * Allocate a fixed length sbuf here, based on the length
2793                  * of the user's buffer.  We could allocate an auto-extending
2794                  * buffer, and then tell the user how much larger our
2795                  * amount of data is than his buffer, but that presents
2796                  * some problems:
2797                  *
2798                  * 1.  The sbuf(9) routines use a blocking malloc, and so
2799                  *     we can't hold a lock while calling them with an
2800                  *     auto-extending buffer.
2801                  *
2802                  * 2.  There is not currently a LUN reference counting
2803                  *     mechanism, outside of outstanding transactions on
2804                  *     the LUN's OOA queue.  So a LUN could go away on us
2805                  *     while we're getting the LUN number, backend-specific
2806                  *     information, etc.  Thus, given the way things
2807                  *     currently work, we need to hold the CTL lock while
2808                  *     grabbing LUN information.
2809                  *
2810                  * So, from the user's standpoint, the best thing to do is
2811                  * allocate what he thinks is a reasonable buffer length,
2812                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2813                  * double the buffer length and try again.  (And repeat
2814                  * that until he succeeds.)
2815                  */
2816                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2817                 if (sb == NULL) {
2818                         list->status = CTL_LUN_LIST_ERROR;
2819                         snprintf(list->error_str, sizeof(list->error_str),
2820                                  "Unable to allocate %d bytes for LUN list",
2821                                  list->alloc_len);
2822                         break;
2823                 }
2824
2825                 sbuf_printf(sb, "<ctllunlist>\n");
2826
2827                 mtx_lock(&softc->ctl_lock);
2828                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2829                         mtx_lock(&lun->lun_lock);
2830                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2831                                              (uintmax_t)lun->lun);
2832
2833                         /*
2834                          * Bail out as soon as we see that we've overfilled
2835                          * the buffer.
2836                          */
2837                         if (retval != 0)
2838                                 break;
2839
2840                         retval = sbuf_printf(sb, "\t<backend_type>%s"
2841                                              "</backend_type>\n",
2842                                              (lun->backend == NULL) ?  "none" :
2843                                              lun->backend->name);
2844
2845                         if (retval != 0)
2846                                 break;
2847
2848                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2849                                              lun->be_lun->lun_type);
2850
2851                         if (retval != 0)
2852                                 break;
2853
2854                         if (lun->backend == NULL) {
2855                                 retval = sbuf_printf(sb, "</lun>\n");
2856                                 if (retval != 0)
2857                                         break;
2858                                 continue;
2859                         }
2860
2861                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2862                                              (lun->be_lun->maxlba > 0) ?
2863                                              lun->be_lun->maxlba + 1 : 0);
2864
2865                         if (retval != 0)
2866                                 break;
2867
2868                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2869                                              lun->be_lun->blocksize);
2870
2871                         if (retval != 0)
2872                                 break;
2873
2874                         retval = sbuf_printf(sb, "\t<serial_number>");
2875
2876                         if (retval != 0)
2877                                 break;
2878
2879                         retval = ctl_sbuf_printf_esc(sb,
2880                             lun->be_lun->serial_num,
2881                             sizeof(lun->be_lun->serial_num));
2882
2883                         if (retval != 0)
2884                                 break;
2885
2886                         retval = sbuf_printf(sb, "</serial_number>\n");
2887                 
2888                         if (retval != 0)
2889                                 break;
2890
2891                         retval = sbuf_printf(sb, "\t<device_id>");
2892
2893                         if (retval != 0)
2894                                 break;
2895
2896                         retval = ctl_sbuf_printf_esc(sb,
2897                             lun->be_lun->device_id,
2898                             sizeof(lun->be_lun->device_id));
2899
2900                         if (retval != 0)
2901                                 break;
2902
2903                         retval = sbuf_printf(sb, "</device_id>\n");
2904
2905                         if (retval != 0)
2906                                 break;
2907
2908                         if (lun->backend->lun_info != NULL) {
2909                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
2910                                 if (retval != 0)
2911                                         break;
2912                         }
2913                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
2914                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2915                                     opt->name, opt->value, opt->name);
2916                                 if (retval != 0)
2917                                         break;
2918                         }
2919
2920                         retval = sbuf_printf(sb, "</lun>\n");
2921
2922                         if (retval != 0)
2923                                 break;
2924                         mtx_unlock(&lun->lun_lock);
2925                 }
2926                 if (lun != NULL)
2927                         mtx_unlock(&lun->lun_lock);
2928                 mtx_unlock(&softc->ctl_lock);
2929
2930                 if ((retval != 0)
2931                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
2932                         retval = 0;
2933                         sbuf_delete(sb);
2934                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2935                         snprintf(list->error_str, sizeof(list->error_str),
2936                                  "Out of space, %d bytes is too small",
2937                                  list->alloc_len);
2938                         break;
2939                 }
2940
2941                 sbuf_finish(sb);
2942
2943                 retval = copyout(sbuf_data(sb), list->lun_xml,
2944                                  sbuf_len(sb) + 1);
2945
2946                 list->fill_len = sbuf_len(sb) + 1;
2947                 list->status = CTL_LUN_LIST_OK;
2948                 sbuf_delete(sb);
2949                 break;
2950         }
2951         case CTL_ISCSI: {
2952                 struct ctl_iscsi *ci;
2953                 struct ctl_frontend *fe;
2954
2955                 ci = (struct ctl_iscsi *)addr;
2956
2957                 fe = ctl_frontend_find("iscsi");
2958                 if (fe == NULL) {
2959                         ci->status = CTL_ISCSI_ERROR;
2960                         snprintf(ci->error_str, sizeof(ci->error_str),
2961                             "Frontend \"iscsi\" not found.");
2962                         break;
2963                 }
2964
2965                 retval = fe->ioctl(dev, cmd, addr, flag, td);
2966                 break;
2967         }
2968         case CTL_PORT_REQ: {
2969                 struct ctl_req *req;
2970                 struct ctl_frontend *fe;
2971
2972                 req = (struct ctl_req *)addr;
2973
2974                 fe = ctl_frontend_find(req->driver);
2975                 if (fe == NULL) {
2976                         req->status = CTL_LUN_ERROR;
2977                         snprintf(req->error_str, sizeof(req->error_str),
2978                             "Frontend \"%s\" not found.", req->driver);
2979                         break;
2980                 }
2981                 if (req->num_args > 0) {
2982                         req->kern_args = ctl_copyin_args(req->num_args,
2983                             req->args, req->error_str, sizeof(req->error_str));
2984                         if (req->kern_args == NULL) {
2985                                 req->status = CTL_LUN_ERROR;
2986                                 break;
2987                         }
2988                 }
2989
2990                 if (fe->ioctl)
2991                         retval = fe->ioctl(dev, cmd, addr, flag, td);
2992                 else
2993                         retval = ENODEV;
2994
2995                 if (req->num_args > 0) {
2996                         ctl_copyout_args(req->num_args, req->kern_args);
2997                         ctl_free_args(req->num_args, req->kern_args);
2998                 }
2999                 break;
3000         }
3001         case CTL_PORT_LIST: {
3002                 struct sbuf *sb;
3003                 struct ctl_port *port;
3004                 struct ctl_lun_list *list;
3005                 struct ctl_option *opt;
3006                 int j;
3007                 uint32_t plun;
3008
3009                 list = (struct ctl_lun_list *)addr;
3010
3011                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3012                 if (sb == NULL) {
3013                         list->status = CTL_LUN_LIST_ERROR;
3014                         snprintf(list->error_str, sizeof(list->error_str),
3015                                  "Unable to allocate %d bytes for LUN list",
3016                                  list->alloc_len);
3017                         break;
3018                 }
3019
3020                 sbuf_printf(sb, "<ctlportlist>\n");
3021
3022                 mtx_lock(&softc->ctl_lock);
3023                 STAILQ_FOREACH(port, &softc->port_list, links) {
3024                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3025                                              (uintmax_t)port->targ_port);
3026
3027                         /*
3028                          * Bail out as soon as we see that we've overfilled
3029                          * the buffer.
3030                          */
3031                         if (retval != 0)
3032                                 break;
3033
3034                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3035                             "</frontend_type>\n", port->frontend->name);
3036                         if (retval != 0)
3037                                 break;
3038
3039                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3040                                              port->port_type);
3041                         if (retval != 0)
3042                                 break;
3043
3044                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3045                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3046                         if (retval != 0)
3047                                 break;
3048
3049                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3050                             port->port_name);
3051                         if (retval != 0)
3052                                 break;
3053
3054                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3055                             port->physical_port);
3056                         if (retval != 0)
3057                                 break;
3058
3059                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3060                             port->virtual_port);
3061                         if (retval != 0)
3062                                 break;
3063
3064                         if (port->target_devid != NULL) {
3065                                 sbuf_printf(sb, "\t<target>");
3066                                 ctl_id_sbuf(port->target_devid, sb);
3067                                 sbuf_printf(sb, "</target>\n");
3068                         }
3069
3070                         if (port->port_devid != NULL) {
3071                                 sbuf_printf(sb, "\t<port>");
3072                                 ctl_id_sbuf(port->port_devid, sb);
3073                                 sbuf_printf(sb, "</port>\n");
3074                         }
3075
3076                         if (port->port_info != NULL) {
3077                                 retval = port->port_info(port->onoff_arg, sb);
3078                                 if (retval != 0)
3079                                         break;
3080                         }
3081                         STAILQ_FOREACH(opt, &port->options, links) {
3082                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3083                                     opt->name, opt->value, opt->name);
3084                                 if (retval != 0)
3085                                         break;
3086                         }
3087
3088                         if (port->lun_map != NULL) {
3089                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3090                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3091                                         plun = ctl_lun_map_from_port(port, j);
3092                                         if (plun >= CTL_MAX_LUNS)
3093                                                 continue;
3094                                         sbuf_printf(sb,
3095                                             "\t<lun id=\"%u\">%u</lun>\n",
3096                                             j, plun);
3097                                 }
3098                         }
3099
3100                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3101                                 if (port->wwpn_iid[j].in_use == 0 ||
3102                                     (port->wwpn_iid[j].wwpn == 0 &&
3103                                      port->wwpn_iid[j].name == NULL))
3104                                         continue;
3105
3106                                 if (port->wwpn_iid[j].name != NULL)
3107                                         retval = sbuf_printf(sb,
3108                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3109                                             j, port->wwpn_iid[j].name);
3110                                 else
3111                                         retval = sbuf_printf(sb,
3112                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3113                                             j, port->wwpn_iid[j].wwpn);
3114                                 if (retval != 0)
3115                                         break;
3116                         }
3117                         if (retval != 0)
3118                                 break;
3119
3120                         retval = sbuf_printf(sb, "</targ_port>\n");
3121                         if (retval != 0)
3122                                 break;
3123                 }
3124                 mtx_unlock(&softc->ctl_lock);
3125
3126                 if ((retval != 0)
3127                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3128                         retval = 0;
3129                         sbuf_delete(sb);
3130                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3131                         snprintf(list->error_str, sizeof(list->error_str),
3132                                  "Out of space, %d bytes is too small",
3133                                  list->alloc_len);
3134                         break;
3135                 }
3136
3137                 sbuf_finish(sb);
3138
3139                 retval = copyout(sbuf_data(sb), list->lun_xml,
3140                                  sbuf_len(sb) + 1);
3141
3142                 list->fill_len = sbuf_len(sb) + 1;
3143                 list->status = CTL_LUN_LIST_OK;
3144                 sbuf_delete(sb);
3145                 break;
3146         }
3147         case CTL_LUN_MAP: {
3148                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3149                 struct ctl_port *port;
3150
3151                 mtx_lock(&softc->ctl_lock);
3152                 if (lm->port < softc->port_min ||
3153                     lm->port >= softc->port_max ||
3154                     (port = softc->ctl_ports[lm->port]) == NULL) {
3155                         mtx_unlock(&softc->ctl_lock);
3156                         return (ENXIO);
3157                 }
3158                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3159                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
3160                                 continue;
3161                         mtx_lock(&lun->lun_lock);
3162                         ctl_est_ua_port(lun, lm->port, -1, CTL_UA_LUN_CHANGE);
3163                         mtx_unlock(&lun->lun_lock);
3164                 }
3165                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3166                 if (lm->plun < CTL_MAX_LUNS) {
3167                         if (lm->lun == UINT32_MAX)
3168                                 retval = ctl_lun_map_unset(port, lm->plun);
3169                         else if (lm->lun < CTL_MAX_LUNS &&
3170                             softc->ctl_luns[lm->lun] != NULL)
3171                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3172                         else
3173                                 return (ENXIO);
3174                 } else if (lm->plun == UINT32_MAX) {
3175                         if (lm->lun == UINT32_MAX)
3176                                 retval = ctl_lun_map_deinit(port);
3177                         else
3178                                 retval = ctl_lun_map_init(port);
3179                 } else
3180                         return (ENXIO);
3181                 break;
3182         }
3183         default: {
3184                 /* XXX KDM should we fix this? */
3185 #if 0
3186                 struct ctl_backend_driver *backend;
3187                 unsigned int type;
3188                 int found;
3189
3190                 found = 0;
3191
3192                 /*
3193                  * We encode the backend type as the ioctl type for backend
3194                  * ioctls.  So parse it out here, and then search for a
3195                  * backend of this type.
3196                  */
3197                 type = _IOC_TYPE(cmd);
3198
3199                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3200                         if (backend->type == type) {
3201                                 found = 1;
3202                                 break;
3203                         }
3204                 }
3205                 if (found == 0) {
3206                         printf("ctl: unknown ioctl command %#lx or backend "
3207                                "%d\n", cmd, type);
3208                         retval = EINVAL;
3209                         break;
3210                 }
3211                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3212 #endif
3213                 retval = ENOTTY;
3214                 break;
3215         }
3216         }
3217         return (retval);
3218 }
3219
3220 uint32_t
3221 ctl_get_initindex(struct ctl_nexus *nexus)
3222 {
3223         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3224 }
3225
3226 int
3227 ctl_lun_map_init(struct ctl_port *port)
3228 {
3229         struct ctl_softc *softc = control_softc;
3230         struct ctl_lun *lun;
3231         uint32_t i;
3232
3233         if (port->lun_map == NULL)
3234                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3235                     M_CTL, M_NOWAIT);
3236         if (port->lun_map == NULL)
3237                 return (ENOMEM);
3238         for (i = 0; i < CTL_MAX_LUNS; i++)
3239                 port->lun_map[i] = UINT32_MAX;
3240         if (port->status & CTL_PORT_STATUS_ONLINE) {
3241                 if (port->lun_disable != NULL) {
3242                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3243                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3244                 }
3245                 ctl_isc_announce_port(port);
3246         }
3247         return (0);
3248 }
3249
3250 int
3251 ctl_lun_map_deinit(struct ctl_port *port)
3252 {
3253         struct ctl_softc *softc = control_softc;
3254         struct ctl_lun *lun;
3255
3256         if (port->lun_map == NULL)
3257                 return (0);
3258         free(port->lun_map, M_CTL);
3259         port->lun_map = NULL;
3260         if (port->status & CTL_PORT_STATUS_ONLINE) {
3261                 if (port->lun_enable != NULL) {
3262                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3263                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3264                 }
3265                 ctl_isc_announce_port(port);
3266         }
3267         return (0);
3268 }
3269
3270 int
3271 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3272 {
3273         int status;
3274         uint32_t old;
3275
3276         if (port->lun_map == NULL) {
3277                 status = ctl_lun_map_init(port);
3278                 if (status != 0)
3279                         return (status);
3280         }
3281         old = port->lun_map[plun];
3282         port->lun_map[plun] = glun;
3283         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3284                 if (port->lun_enable != NULL)
3285                         port->lun_enable(port->targ_lun_arg, plun);
3286                 ctl_isc_announce_port(port);
3287         }
3288         return (0);
3289 }
3290
3291 int
3292 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3293 {
3294         uint32_t old;
3295
3296         if (port->lun_map == NULL)
3297                 return (0);
3298         old = port->lun_map[plun];
3299         port->lun_map[plun] = UINT32_MAX;
3300         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3301                 if (port->lun_disable != NULL)
3302                         port->lun_disable(port->targ_lun_arg, plun);
3303                 ctl_isc_announce_port(port);
3304         }
3305         return (0);
3306 }
3307
3308 uint32_t
3309 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3310 {
3311
3312         if (port == NULL)
3313                 return (UINT32_MAX);
3314         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3315                 return (lun_id);
3316         return (port->lun_map[lun_id]);
3317 }
3318
3319 uint32_t
3320 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3321 {
3322         uint32_t i;
3323
3324         if (port == NULL)
3325                 return (UINT32_MAX);
3326         if (port->lun_map == NULL)
3327                 return (lun_id);
3328         for (i = 0; i < CTL_MAX_LUNS; i++) {
3329                 if (port->lun_map[i] == lun_id)
3330                         return (i);
3331         }
3332         return (UINT32_MAX);
3333 }
3334
3335 static struct ctl_port *
3336 ctl_io_port(struct ctl_io_hdr *io_hdr)
3337 {
3338
3339         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3340 }
3341
3342 int
3343 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3344 {
3345         int i;
3346
3347         for (i = first; i < last; i++) {
3348                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3349                         return (i);
3350         }
3351         return (-1);
3352 }
3353
3354 int
3355 ctl_set_mask(uint32_t *mask, uint32_t bit)
3356 {
3357         uint32_t chunk, piece;
3358
3359         chunk = bit >> 5;
3360         piece = bit % (sizeof(uint32_t) * 8);
3361
3362         if ((mask[chunk] & (1 << piece)) != 0)
3363                 return (-1);
3364         else
3365                 mask[chunk] |= (1 << piece);
3366
3367         return (0);
3368 }
3369
3370 int
3371 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3372 {
3373         uint32_t chunk, piece;
3374
3375         chunk = bit >> 5;
3376         piece = bit % (sizeof(uint32_t) * 8);
3377
3378         if ((mask[chunk] & (1 << piece)) == 0)
3379                 return (-1);
3380         else
3381                 mask[chunk] &= ~(1 << piece);
3382
3383         return (0);
3384 }
3385
3386 int
3387 ctl_is_set(uint32_t *mask, uint32_t bit)
3388 {
3389         uint32_t chunk, piece;
3390
3391         chunk = bit >> 5;
3392         piece = bit % (sizeof(uint32_t) * 8);
3393
3394         if ((mask[chunk] & (1 << piece)) == 0)
3395                 return (0);
3396         else
3397                 return (1);
3398 }
3399
3400 static uint64_t
3401 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3402 {
3403         uint64_t *t;
3404
3405         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3406         if (t == NULL)
3407                 return (0);
3408         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3409 }
3410
3411 static void
3412 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3413 {
3414         uint64_t *t;
3415
3416         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3417         if (t == NULL)
3418                 return;
3419         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3420 }
3421
3422 static void
3423 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3424 {
3425         uint64_t *p;
3426         u_int i;
3427
3428         i = residx/CTL_MAX_INIT_PER_PORT;
3429         if (lun->pr_keys[i] != NULL)
3430                 return;
3431         mtx_unlock(&lun->lun_lock);
3432         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3433             M_WAITOK | M_ZERO);
3434         mtx_lock(&lun->lun_lock);
3435         if (lun->pr_keys[i] == NULL)
3436                 lun->pr_keys[i] = p;
3437         else
3438                 free(p, M_CTL);
3439 }
3440
3441 static void
3442 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3443 {
3444         uint64_t *t;
3445
3446         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3447         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3448         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3449 }
3450
3451 /*
3452  * ctl_softc, pool_name, total_ctl_io are passed in.
3453  * npool is passed out.
3454  */
3455 int
3456 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3457                 uint32_t total_ctl_io, void **npool)
3458 {
3459 #ifdef IO_POOLS
3460         struct ctl_io_pool *pool;
3461
3462         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3463                                             M_NOWAIT | M_ZERO);
3464         if (pool == NULL)
3465                 return (ENOMEM);
3466
3467         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3468         pool->ctl_softc = ctl_softc;
3469         pool->zone = uma_zsecond_create(pool->name, NULL,
3470             NULL, NULL, NULL, ctl_softc->io_zone);
3471         /* uma_prealloc(pool->zone, total_ctl_io); */
3472
3473         *npool = pool;
3474 #else
3475         *npool = ctl_softc->io_zone;
3476 #endif
3477         return (0);
3478 }
3479
3480 void
3481 ctl_pool_free(struct ctl_io_pool *pool)
3482 {
3483
3484         if (pool == NULL)
3485                 return;
3486
3487 #ifdef IO_POOLS
3488         uma_zdestroy(pool->zone);
3489         free(pool, M_CTL);
3490 #endif
3491 }
3492
3493 union ctl_io *
3494 ctl_alloc_io(void *pool_ref)
3495 {
3496         union ctl_io *io;
3497 #ifdef IO_POOLS
3498         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3499
3500         io = uma_zalloc(pool->zone, M_WAITOK);
3501 #else
3502         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3503 #endif
3504         if (io != NULL)
3505                 io->io_hdr.pool = pool_ref;
3506         return (io);
3507 }
3508
3509 union ctl_io *
3510 ctl_alloc_io_nowait(void *pool_ref)
3511 {
3512         union ctl_io *io;
3513 #ifdef IO_POOLS
3514         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3515
3516         io = uma_zalloc(pool->zone, M_NOWAIT);
3517 #else
3518         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3519 #endif
3520         if (io != NULL)
3521                 io->io_hdr.pool = pool_ref;
3522         return (io);
3523 }
3524
3525 void
3526 ctl_free_io(union ctl_io *io)
3527 {
3528 #ifdef IO_POOLS
3529         struct ctl_io_pool *pool;
3530 #endif
3531
3532         if (io == NULL)
3533                 return;
3534
3535 #ifdef IO_POOLS
3536         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3537         uma_zfree(pool->zone, io);
3538 #else
3539         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3540 #endif
3541 }
3542
3543 void
3544 ctl_zero_io(union ctl_io *io)
3545 {
3546         void *pool_ref;
3547
3548         if (io == NULL)
3549                 return;
3550
3551         /*
3552          * May need to preserve linked list pointers at some point too.
3553          */
3554         pool_ref = io->io_hdr.pool;
3555         memset(io, 0, sizeof(*io));
3556         io->io_hdr.pool = pool_ref;
3557 }
3558
3559 /*
3560  * This routine is currently used for internal copies of ctl_ios that need
3561  * to persist for some reason after we've already returned status to the
3562  * FETD.  (Thus the flag set.)
3563  *
3564  * XXX XXX
3565  * Note that this makes a blind copy of all fields in the ctl_io, except
3566  * for the pool reference.  This includes any memory that has been
3567  * allocated!  That memory will no longer be valid after done has been
3568  * called, so this would be VERY DANGEROUS for command that actually does
3569  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3570  * start and stop commands, which don't transfer any data, so this is not a
3571  * problem.  If it is used for anything else, the caller would also need to
3572  * allocate data buffer space and this routine would need to be modified to
3573  * copy the data buffer(s) as well.
3574  */
3575 void
3576 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3577 {
3578         void *pool_ref;
3579
3580         if ((src == NULL)
3581          || (dest == NULL))
3582                 return;
3583
3584         /*
3585          * May need to preserve linked list pointers at some point too.
3586          */
3587         pool_ref = dest->io_hdr.pool;
3588
3589         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3590
3591         dest->io_hdr.pool = pool_ref;
3592         /*
3593          * We need to know that this is an internal copy, and doesn't need
3594          * to get passed back to the FETD that allocated it.
3595          */
3596         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3597 }
3598
3599 int
3600 ctl_expand_number(const char *buf, uint64_t *num)
3601 {
3602         char *endptr;
3603         uint64_t number;
3604         unsigned shift;
3605
3606         number = strtoq(buf, &endptr, 0);
3607
3608         switch (tolower((unsigned char)*endptr)) {
3609         case 'e':
3610                 shift = 60;
3611                 break;
3612         case 'p':
3613                 shift = 50;
3614                 break;
3615         case 't':
3616                 shift = 40;
3617                 break;
3618         case 'g':
3619                 shift = 30;
3620                 break;
3621         case 'm':
3622                 shift = 20;
3623                 break;
3624         case 'k':
3625                 shift = 10;
3626                 break;
3627         case 'b':
3628         case '\0': /* No unit. */
3629                 *num = number;
3630                 return (0);
3631         default:
3632                 /* Unrecognized unit. */
3633                 return (-1);
3634         }
3635
3636         if ((number << shift) >> shift != number) {
3637                 /* Overflow */
3638                 return (-1);
3639         }
3640         *num = number << shift;
3641         return (0);
3642 }
3643
3644
3645 /*
3646  * This routine could be used in the future to load default and/or saved
3647  * mode page parameters for a particuar lun.
3648  */
3649 static int
3650 ctl_init_page_index(struct ctl_lun *lun)
3651 {
3652         int i;
3653         struct ctl_page_index *page_index;
3654         const char *value;
3655         uint64_t ival;
3656
3657         memcpy(&lun->mode_pages.index, page_index_template,
3658                sizeof(page_index_template));
3659
3660         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3661
3662                 page_index = &lun->mode_pages.index[i];
3663                 /*
3664                  * If this is a disk-only mode page, there's no point in
3665                  * setting it up.  For some pages, we have to have some
3666                  * basic information about the disk in order to calculate the
3667                  * mode page data.
3668                  */
3669                 if ((lun->be_lun->lun_type != T_DIRECT)
3670                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3671                         continue;
3672
3673                 switch (page_index->page_code & SMPH_PC_MASK) {
3674                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3675                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3676                                 panic("subpage is incorrect!");
3677                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3678                                &rw_er_page_default,
3679                                sizeof(rw_er_page_default));
3680                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3681                                &rw_er_page_changeable,
3682                                sizeof(rw_er_page_changeable));
3683                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3684                                &rw_er_page_default,
3685                                sizeof(rw_er_page_default));
3686                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3687                                &rw_er_page_default,
3688                                sizeof(rw_er_page_default));
3689                         page_index->page_data =
3690                                 (uint8_t *)lun->mode_pages.rw_er_page;
3691                         break;
3692                 }
3693                 case SMS_FORMAT_DEVICE_PAGE: {
3694                         struct scsi_format_page *format_page;
3695
3696                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3697                                 panic("subpage is incorrect!");
3698
3699                         /*
3700                          * Sectors per track are set above.  Bytes per
3701                          * sector need to be set here on a per-LUN basis.
3702                          */
3703                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3704                                &format_page_default,
3705                                sizeof(format_page_default));
3706                         memcpy(&lun->mode_pages.format_page[
3707                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3708                                sizeof(format_page_changeable));
3709                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3710                                &format_page_default,
3711                                sizeof(format_page_default));
3712                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3713                                &format_page_default,
3714                                sizeof(format_page_default));
3715
3716                         format_page = &lun->mode_pages.format_page[
3717                                 CTL_PAGE_CURRENT];
3718                         scsi_ulto2b(lun->be_lun->blocksize,
3719                                     format_page->bytes_per_sector);
3720
3721                         format_page = &lun->mode_pages.format_page[
3722                                 CTL_PAGE_DEFAULT];
3723                         scsi_ulto2b(lun->be_lun->blocksize,
3724                                     format_page->bytes_per_sector);
3725
3726                         format_page = &lun->mode_pages.format_page[
3727                                 CTL_PAGE_SAVED];
3728                         scsi_ulto2b(lun->be_lun->blocksize,
3729                                     format_page->bytes_per_sector);
3730
3731                         page_index->page_data =
3732                                 (uint8_t *)lun->mode_pages.format_page;
3733                         break;
3734                 }
3735                 case SMS_RIGID_DISK_PAGE: {
3736                         struct scsi_rigid_disk_page *rigid_disk_page;
3737                         uint32_t sectors_per_cylinder;
3738                         uint64_t cylinders;
3739 #ifndef __XSCALE__
3740                         int shift;
3741 #endif /* !__XSCALE__ */
3742
3743                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3744                                 panic("invalid subpage value %d",
3745                                       page_index->subpage);
3746
3747                         /*
3748                          * Rotation rate and sectors per track are set
3749                          * above.  We calculate the cylinders here based on
3750                          * capacity.  Due to the number of heads and
3751                          * sectors per track we're using, smaller arrays
3752                          * may turn out to have 0 cylinders.  Linux and
3753                          * FreeBSD don't pay attention to these mode pages
3754                          * to figure out capacity, but Solaris does.  It
3755                          * seems to deal with 0 cylinders just fine, and
3756                          * works out a fake geometry based on the capacity.
3757                          */
3758                         memcpy(&lun->mode_pages.rigid_disk_page[
3759                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3760                                sizeof(rigid_disk_page_default));
3761                         memcpy(&lun->mode_pages.rigid_disk_page[
3762                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3763                                sizeof(rigid_disk_page_changeable));
3764
3765                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3766                                 CTL_DEFAULT_HEADS;
3767
3768                         /*
3769                          * The divide method here will be more accurate,
3770                          * probably, but results in floating point being
3771                          * used in the kernel on i386 (__udivdi3()).  On the
3772                          * XScale, though, __udivdi3() is implemented in
3773                          * software.
3774                          *
3775                          * The shift method for cylinder calculation is
3776                          * accurate if sectors_per_cylinder is a power of
3777                          * 2.  Otherwise it might be slightly off -- you
3778                          * might have a bit of a truncation problem.
3779                          */
3780 #ifdef  __XSCALE__
3781                         cylinders = (lun->be_lun->maxlba + 1) /
3782                                 sectors_per_cylinder;
3783 #else
3784                         for (shift = 31; shift > 0; shift--) {
3785                                 if (sectors_per_cylinder & (1 << shift))
3786                                         break;
3787                         }
3788                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
3789 #endif
3790
3791                         /*
3792                          * We've basically got 3 bytes, or 24 bits for the
3793                          * cylinder size in the mode page.  If we're over,
3794                          * just round down to 2^24.
3795                          */
3796                         if (cylinders > 0xffffff)
3797                                 cylinders = 0xffffff;
3798
3799                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3800                                 CTL_PAGE_DEFAULT];
3801                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3802
3803                         if ((value = ctl_get_opt(&lun->be_lun->options,
3804                             "rpm")) != NULL) {
3805                                 scsi_ulto2b(strtol(value, NULL, 0),
3806                                      rigid_disk_page->rotation_rate);
3807                         }
3808
3809                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3810                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3811                                sizeof(rigid_disk_page_default));
3812                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3813                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3814                                sizeof(rigid_disk_page_default));
3815
3816                         page_index->page_data =
3817                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
3818                         break;
3819                 }
3820                 case SMS_CACHING_PAGE: {
3821                         struct scsi_caching_page *caching_page;
3822
3823                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3824                                 panic("invalid subpage value %d",
3825                                       page_index->subpage);
3826                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3827                                &caching_page_default,
3828                                sizeof(caching_page_default));
3829                         memcpy(&lun->mode_pages.caching_page[
3830                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3831                                sizeof(caching_page_changeable));
3832                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3833                                &caching_page_default,
3834                                sizeof(caching_page_default));
3835                         caching_page = &lun->mode_pages.caching_page[
3836                             CTL_PAGE_SAVED];
3837                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
3838                         if (value != NULL && strcmp(value, "off") == 0)
3839                                 caching_page->flags1 &= ~SCP_WCE;
3840                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
3841                         if (value != NULL && strcmp(value, "off") == 0)
3842                                 caching_page->flags1 |= SCP_RCD;
3843                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3844                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3845                                sizeof(caching_page_default));
3846                         page_index->page_data =
3847                                 (uint8_t *)lun->mode_pages.caching_page;
3848                         break;
3849                 }
3850                 case SMS_CONTROL_MODE_PAGE: {
3851                         struct scsi_control_page *control_page;
3852
3853                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3854                                 panic("invalid subpage value %d",
3855                                       page_index->subpage);
3856
3857                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
3858                                &control_page_default,
3859                                sizeof(control_page_default));
3860                         memcpy(&lun->mode_pages.control_page[
3861                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
3862                                sizeof(control_page_changeable));
3863                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
3864                                &control_page_default,
3865                                sizeof(control_page_default));
3866                         control_page = &lun->mode_pages.control_page[
3867                             CTL_PAGE_SAVED];
3868                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
3869                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
3870                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
3871                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
3872                         }
3873                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
3874                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
3875                                sizeof(control_page_default));
3876                         page_index->page_data =
3877                                 (uint8_t *)lun->mode_pages.control_page;
3878                         break;
3879
3880                 }
3881                 case SMS_INFO_EXCEPTIONS_PAGE: {
3882                         switch (page_index->subpage) {
3883                         case SMS_SUBPAGE_PAGE_0:
3884                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
3885                                        &ie_page_default,
3886                                        sizeof(ie_page_default));
3887                                 memcpy(&lun->mode_pages.ie_page[
3888                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
3889                                        sizeof(ie_page_changeable));
3890                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
3891                                        &ie_page_default,
3892                                        sizeof(ie_page_default));
3893                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
3894                                        &ie_page_default,
3895                                        sizeof(ie_page_default));
3896                                 page_index->page_data =
3897                                         (uint8_t *)lun->mode_pages.ie_page;
3898                                 break;
3899                         case 0x02: {
3900                                 struct ctl_logical_block_provisioning_page *page;
3901
3902                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
3903                                        &lbp_page_default,
3904                                        sizeof(lbp_page_default));
3905                                 memcpy(&lun->mode_pages.lbp_page[
3906                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
3907                                        sizeof(lbp_page_changeable));
3908                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3909                                        &lbp_page_default,
3910                                        sizeof(lbp_page_default));
3911                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
3912                                 value = ctl_get_opt(&lun->be_lun->options,
3913                                     "avail-threshold");
3914                                 if (value != NULL &&
3915                                     ctl_expand_number(value, &ival) == 0) {
3916                                         page->descr[0].flags |= SLBPPD_ENABLED |
3917                                             SLBPPD_ARMING_DEC;
3918                                         if (lun->be_lun->blocksize)
3919                                                 ival /= lun->be_lun->blocksize;
3920                                         else
3921                                                 ival /= 512;
3922                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3923                                             page->descr[0].count);
3924                                 }
3925                                 value = ctl_get_opt(&lun->be_lun->options,
3926                                     "used-threshold");
3927                                 if (value != NULL &&
3928                                     ctl_expand_number(value, &ival) == 0) {
3929                                         page->descr[1].flags |= SLBPPD_ENABLED |
3930                                             SLBPPD_ARMING_INC;
3931                                         if (lun->be_lun->blocksize)
3932                                                 ival /= lun->be_lun->blocksize;
3933                                         else
3934                                                 ival /= 512;
3935                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3936                                             page->descr[1].count);
3937                                 }
3938                                 value = ctl_get_opt(&lun->be_lun->options,
3939                                     "pool-avail-threshold");
3940                                 if (value != NULL &&
3941                                     ctl_expand_number(value, &ival) == 0) {
3942                                         page->descr[2].flags |= SLBPPD_ENABLED |
3943                                             SLBPPD_ARMING_DEC;
3944                                         if (lun->be_lun->blocksize)
3945                                                 ival /= lun->be_lun->blocksize;
3946                                         else
3947                                                 ival /= 512;
3948                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3949                                             page->descr[2].count);
3950                                 }
3951                                 value = ctl_get_opt(&lun->be_lun->options,
3952                                     "pool-used-threshold");
3953                                 if (value != NULL &&
3954                                     ctl_expand_number(value, &ival) == 0) {
3955                                         page->descr[3].flags |= SLBPPD_ENABLED |
3956                                             SLBPPD_ARMING_INC;
3957                                         if (lun->be_lun->blocksize)
3958                                                 ival /= lun->be_lun->blocksize;
3959                                         else
3960                                                 ival /= 512;
3961                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3962                                             page->descr[3].count);
3963                                 }
3964                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
3965                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3966                                        sizeof(lbp_page_default));
3967                                 page_index->page_data =
3968                                         (uint8_t *)lun->mode_pages.lbp_page;
3969                         }}
3970                         break;
3971                 }
3972                 case SMS_VENDOR_SPECIFIC_PAGE:{
3973                         switch (page_index->subpage) {
3974                         case DBGCNF_SUBPAGE_CODE: {
3975                                 struct copan_debugconf_subpage *current_page,
3976                                                                *saved_page;
3977
3978                                 memcpy(&lun->mode_pages.debugconf_subpage[
3979                                        CTL_PAGE_CURRENT],
3980                                        &debugconf_page_default,
3981                                        sizeof(debugconf_page_default));
3982                                 memcpy(&lun->mode_pages.debugconf_subpage[
3983                                        CTL_PAGE_CHANGEABLE],
3984                                        &debugconf_page_changeable,
3985                                        sizeof(debugconf_page_changeable));
3986                                 memcpy(&lun->mode_pages.debugconf_subpage[
3987                                        CTL_PAGE_DEFAULT],
3988                                        &debugconf_page_default,
3989                                        sizeof(debugconf_page_default));
3990                                 memcpy(&lun->mode_pages.debugconf_subpage[
3991                                        CTL_PAGE_SAVED],
3992                                        &debugconf_page_default,
3993                                        sizeof(debugconf_page_default));
3994                                 page_index->page_data =
3995                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
3996
3997                                 current_page = (struct copan_debugconf_subpage *)
3998                                         (page_index->page_data +
3999                                          (page_index->page_len *
4000                                           CTL_PAGE_CURRENT));
4001                                 saved_page = (struct copan_debugconf_subpage *)
4002                                         (page_index->page_data +
4003                                          (page_index->page_len *
4004                                           CTL_PAGE_SAVED));
4005                                 break;
4006                         }
4007                         default:
4008                                 panic("invalid subpage value %d",
4009                                       page_index->subpage);
4010                                 break;
4011                         }
4012                         break;
4013                 }
4014                 default:
4015                         panic("invalid page value %d",
4016                               page_index->page_code & SMPH_PC_MASK);
4017                         break;
4018         }
4019         }
4020
4021         return (CTL_RETVAL_COMPLETE);
4022 }
4023
4024 static int
4025 ctl_init_log_page_index(struct ctl_lun *lun)
4026 {
4027         struct ctl_page_index *page_index;
4028         int i, j, k, prev;
4029
4030         memcpy(&lun->log_pages.index, log_page_index_template,
4031                sizeof(log_page_index_template));
4032
4033         prev = -1;
4034         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4035
4036                 page_index = &lun->log_pages.index[i];
4037                 /*
4038                  * If this is a disk-only mode page, there's no point in
4039                  * setting it up.  For some pages, we have to have some
4040                  * basic information about the disk in order to calculate the
4041                  * mode page data.
4042                  */
4043                 if ((lun->be_lun->lun_type != T_DIRECT)
4044                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4045                         continue;
4046
4047                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4048                      lun->backend->lun_attr == NULL)
4049                         continue;
4050
4051                 if (page_index->page_code != prev) {
4052                         lun->log_pages.pages_page[j] = page_index->page_code;
4053                         prev = page_index->page_code;
4054                         j++;
4055                 }
4056                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4057                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4058                 k++;
4059         }
4060         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4061         lun->log_pages.index[0].page_len = j;
4062         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4063         lun->log_pages.index[1].page_len = k * 2;
4064         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4065         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4066         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4067         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4068
4069         return (CTL_RETVAL_COMPLETE);
4070 }
4071
4072 static int
4073 hex2bin(const char *str, uint8_t *buf, int buf_size)
4074 {
4075         int i;
4076         u_char c;
4077
4078         memset(buf, 0, buf_size);
4079         while (isspace(str[0]))
4080                 str++;
4081         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4082                 str += 2;
4083         buf_size *= 2;
4084         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4085                 c = str[i];
4086                 if (isdigit(c))
4087                         c -= '0';
4088                 else if (isalpha(c))
4089                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4090                 else
4091                         break;
4092                 if (c >= 16)
4093                         break;
4094                 if ((i & 1) == 0)
4095                         buf[i / 2] |= (c << 4);
4096                 else
4097                         buf[i / 2] |= c;
4098         }
4099         return ((i + 1) / 2);
4100 }
4101
4102 /*
4103  * LUN allocation.
4104  *
4105  * Requirements:
4106  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4107  *   wants us to allocate the LUN and he can block.
4108  * - ctl_softc is always set
4109  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4110  *
4111  * Returns 0 for success, non-zero (errno) for failure.
4112  */
4113 static int
4114 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4115               struct ctl_be_lun *const be_lun)
4116 {
4117         struct ctl_lun *nlun, *lun;
4118         struct scsi_vpd_id_descriptor *desc;
4119         struct scsi_vpd_id_t10 *t10id;
4120         const char *eui, *naa, *scsiname, *vendor;
4121         int lun_number, i, lun_malloced;
4122         int devidlen, idlen1, idlen2 = 0, len;
4123
4124         if (be_lun == NULL)
4125                 return (EINVAL);
4126
4127         /*
4128          * We currently only support Direct Access or Processor LUN types.
4129          */
4130         switch (be_lun->lun_type) {
4131         case T_DIRECT:
4132                 break;
4133         case T_PROCESSOR:
4134                 break;
4135         case T_SEQUENTIAL:
4136         case T_CHANGER:
4137         default:
4138                 be_lun->lun_config_status(be_lun->be_lun,
4139                                           CTL_LUN_CONFIG_FAILURE);
4140                 break;
4141         }
4142         if (ctl_lun == NULL) {
4143                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4144                 lun_malloced = 1;
4145         } else {
4146                 lun_malloced = 0;
4147                 lun = ctl_lun;
4148         }
4149
4150         memset(lun, 0, sizeof(*lun));
4151         if (lun_malloced)
4152                 lun->flags = CTL_LUN_MALLOCED;
4153
4154         /* Generate LUN ID. */
4155         devidlen = max(CTL_DEVID_MIN_LEN,
4156             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4157         idlen1 = sizeof(*t10id) + devidlen;
4158         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4159         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4160         if (scsiname != NULL) {
4161                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4162                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4163         }
4164         eui = ctl_get_opt(&be_lun->options, "eui");
4165         if (eui != NULL) {
4166                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4167         }
4168         naa = ctl_get_opt(&be_lun->options, "naa");
4169         if (naa != NULL) {
4170                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4171         }
4172         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4173             M_CTL, M_WAITOK | M_ZERO);
4174         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4175         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4176         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4177         desc->length = idlen1;
4178         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4179         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4180         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4181                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4182         } else {
4183                 strncpy(t10id->vendor, vendor,
4184                     min(sizeof(t10id->vendor), strlen(vendor)));
4185         }
4186         strncpy((char *)t10id->vendor_spec_id,
4187             (char *)be_lun->device_id, devidlen);
4188         if (scsiname != NULL) {
4189                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4190                     desc->length);
4191                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4192                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4193                     SVPD_ID_TYPE_SCSI_NAME;
4194                 desc->length = idlen2;
4195                 strlcpy(desc->identifier, scsiname, idlen2);
4196         }
4197         if (eui != NULL) {
4198                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4199                     desc->length);
4200                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4201                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4202                     SVPD_ID_TYPE_EUI64;
4203                 desc->length = hex2bin(eui, desc->identifier, 16);
4204                 desc->length = desc->length > 12 ? 16 :
4205                     (desc->length > 8 ? 12 : 8);
4206                 len -= 16 - desc->length;
4207         }
4208         if (naa != NULL) {
4209                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4210                     desc->length);
4211                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4212                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4213                     SVPD_ID_TYPE_NAA;
4214                 desc->length = hex2bin(naa, desc->identifier, 16);
4215                 desc->length = desc->length > 8 ? 16 : 8;
4216                 len -= 16 - desc->length;
4217         }
4218         lun->lun_devid->len = len;
4219
4220         mtx_lock(&ctl_softc->ctl_lock);
4221         /*
4222          * See if the caller requested a particular LUN number.  If so, see
4223          * if it is available.  Otherwise, allocate the first available LUN.
4224          */
4225         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4226                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4227                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4228                         mtx_unlock(&ctl_softc->ctl_lock);
4229                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4230                                 printf("ctl: requested LUN ID %d is higher "
4231                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4232                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4233                         } else {
4234                                 /*
4235                                  * XXX KDM return an error, or just assign
4236                                  * another LUN ID in this case??
4237                                  */
4238                                 printf("ctl: requested LUN ID %d is already "
4239                                        "in use\n", be_lun->req_lun_id);
4240                         }
4241                         if (lun->flags & CTL_LUN_MALLOCED)
4242                                 free(lun, M_CTL);
4243                         be_lun->lun_config_status(be_lun->be_lun,
4244                                                   CTL_LUN_CONFIG_FAILURE);
4245                         return (ENOSPC);
4246                 }
4247                 lun_number = be_lun->req_lun_id;
4248         } else {
4249                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4250                 if (lun_number == -1) {
4251                         mtx_unlock(&ctl_softc->ctl_lock);
4252                         printf("ctl: can't allocate LUN, out of LUNs\n");
4253                         if (lun->flags & CTL_LUN_MALLOCED)
4254                                 free(lun, M_CTL);
4255                         be_lun->lun_config_status(be_lun->be_lun,
4256                                                   CTL_LUN_CONFIG_FAILURE);
4257                         return (ENOSPC);
4258                 }
4259         }
4260         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4261
4262         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4263         lun->lun = lun_number;
4264         lun->be_lun = be_lun;
4265         /*
4266          * The processor LUN is always enabled.  Disk LUNs come on line
4267          * disabled, and must be enabled by the backend.
4268          */
4269         lun->flags |= CTL_LUN_DISABLED;
4270         lun->backend = be_lun->be;
4271         be_lun->ctl_lun = lun;
4272         be_lun->lun_id = lun_number;
4273         atomic_add_int(&be_lun->be->num_luns, 1);
4274         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4275                 lun->flags |= CTL_LUN_OFFLINE;
4276
4277         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4278                 lun->flags |= CTL_LUN_STOPPED;
4279
4280         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4281                 lun->flags |= CTL_LUN_INOPERABLE;
4282
4283         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4284                 lun->flags |= CTL_LUN_PRIMARY_SC;
4285
4286         lun->ctl_softc = ctl_softc;
4287 #ifdef CTL_TIME_IO
4288         lun->last_busy = getsbinuptime();
4289 #endif
4290         TAILQ_INIT(&lun->ooa_queue);
4291         TAILQ_INIT(&lun->blocked_queue);
4292         STAILQ_INIT(&lun->error_list);
4293         ctl_tpc_lun_init(lun);
4294
4295         /*
4296          * Initialize the mode and log page index.
4297          */
4298         ctl_init_page_index(lun);
4299         ctl_init_log_page_index(lun);
4300
4301         /*
4302          * Now, before we insert this lun on the lun list, set the lun
4303          * inventory changed UA for all other luns.
4304          */
4305         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4306                 mtx_lock(&nlun->lun_lock);
4307                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4308                 mtx_unlock(&nlun->lun_lock);
4309         }
4310
4311         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4312
4313         ctl_softc->ctl_luns[lun_number] = lun;
4314
4315         ctl_softc->num_luns++;
4316
4317         /* Setup statistics gathering */
4318         lun->stats.device_type = be_lun->lun_type;
4319         lun->stats.lun_number = lun_number;
4320         if (lun->stats.device_type == T_DIRECT)
4321                 lun->stats.blocksize = be_lun->blocksize;
4322         else
4323                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4324         for (i = 0;i < CTL_MAX_PORTS;i++)
4325                 lun->stats.ports[i].targ_port = i;
4326
4327         mtx_unlock(&ctl_softc->ctl_lock);
4328
4329         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4330         return (0);
4331 }
4332
4333 /*
4334  * Delete a LUN.
4335  * Assumptions:
4336  * - LUN has already been marked invalid and any pending I/O has been taken
4337  *   care of.
4338  */
4339 static int
4340 ctl_free_lun(struct ctl_lun *lun)
4341 {
4342         struct ctl_softc *softc;
4343         struct ctl_lun *nlun;
4344         int i;
4345
4346         softc = lun->ctl_softc;
4347
4348         mtx_assert(&softc->ctl_lock, MA_OWNED);
4349
4350         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4351
4352         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4353
4354         softc->ctl_luns[lun->lun] = NULL;
4355
4356         if (!TAILQ_EMPTY(&lun->ooa_queue))
4357                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4358
4359         softc->num_luns--;
4360
4361         /*
4362          * Tell the backend to free resources, if this LUN has a backend.
4363          */
4364         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4365         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4366
4367         ctl_tpc_lun_shutdown(lun);
4368         mtx_destroy(&lun->lun_lock);
4369         free(lun->lun_devid, M_CTL);
4370         for (i = 0; i < CTL_MAX_PORTS; i++)
4371                 free(lun->pending_ua[i], M_CTL);
4372         for (i = 0; i < CTL_MAX_PORTS; i++)
4373                 free(lun->pr_keys[i], M_CTL);
4374         free(lun->write_buffer, M_CTL);
4375         if (lun->flags & CTL_LUN_MALLOCED)
4376                 free(lun, M_CTL);
4377
4378         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4379                 mtx_lock(&nlun->lun_lock);
4380                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4381                 mtx_unlock(&nlun->lun_lock);
4382         }
4383
4384         return (0);
4385 }
4386
4387 static void
4388 ctl_create_lun(struct ctl_be_lun *be_lun)
4389 {
4390         struct ctl_softc *softc;
4391
4392         softc = control_softc;
4393
4394         /*
4395          * ctl_alloc_lun() should handle all potential failure cases.
4396          */
4397         ctl_alloc_lun(softc, NULL, be_lun);
4398 }
4399
4400 int
4401 ctl_add_lun(struct ctl_be_lun *be_lun)
4402 {
4403         struct ctl_softc *softc = control_softc;
4404
4405         mtx_lock(&softc->ctl_lock);
4406         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4407         mtx_unlock(&softc->ctl_lock);
4408         wakeup(&softc->pending_lun_queue);
4409
4410         return (0);
4411 }
4412
4413 int
4414 ctl_enable_lun(struct ctl_be_lun *be_lun)
4415 {
4416         struct ctl_softc *softc;
4417         struct ctl_port *port, *nport;
4418         struct ctl_lun *lun;
4419         int retval;
4420
4421         lun = (struct ctl_lun *)be_lun->ctl_lun;
4422         softc = lun->ctl_softc;
4423
4424         mtx_lock(&softc->ctl_lock);
4425         mtx_lock(&lun->lun_lock);
4426         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4427                 /*
4428                  * eh?  Why did we get called if the LUN is already
4429                  * enabled?
4430                  */
4431                 mtx_unlock(&lun->lun_lock);
4432                 mtx_unlock(&softc->ctl_lock);
4433                 return (0);
4434         }
4435         lun->flags &= ~CTL_LUN_DISABLED;
4436         mtx_unlock(&lun->lun_lock);
4437
4438         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4439                 nport = STAILQ_NEXT(port, links);
4440                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4441                     port->lun_map != NULL || port->lun_enable == NULL)
4442                         continue;
4443
4444                 /*
4445                  * Drop the lock while we call the FETD's enable routine.
4446                  * This can lead to a callback into CTL (at least in the
4447                  * case of the internal initiator frontend.
4448                  */
4449                 mtx_unlock(&softc->ctl_lock);
4450                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4451                 mtx_lock(&softc->ctl_lock);
4452                 if (retval != 0) {
4453                         printf("%s: FETD %s port %d returned error "
4454                                "%d for lun_enable on lun %jd\n",
4455                                __func__, port->port_name, port->targ_port,
4456                                retval, (intmax_t)lun->lun);
4457                 }
4458         }
4459
4460         mtx_unlock(&softc->ctl_lock);
4461         ctl_isc_announce_lun(lun);
4462
4463         return (0);
4464 }
4465
4466 int
4467 ctl_disable_lun(struct ctl_be_lun *be_lun)
4468 {
4469         struct ctl_softc *softc;
4470         struct ctl_port *port;
4471         struct ctl_lun *lun;
4472         int retval;
4473
4474         lun = (struct ctl_lun *)be_lun->ctl_lun;
4475         softc = lun->ctl_softc;
4476
4477         mtx_lock(&softc->ctl_lock);
4478         mtx_lock(&lun->lun_lock);
4479         if (lun->flags & CTL_LUN_DISABLED) {
4480                 mtx_unlock(&lun->lun_lock);
4481                 mtx_unlock(&softc->ctl_lock);
4482                 return (0);
4483         }
4484         lun->flags |= CTL_LUN_DISABLED;
4485         mtx_unlock(&lun->lun_lock);
4486
4487         STAILQ_FOREACH(port, &softc->port_list, links) {
4488                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4489                     port->lun_map != NULL || port->lun_disable == NULL)
4490                         continue;
4491
4492                 /*
4493                  * Drop the lock before we call the frontend's disable
4494                  * routine, to avoid lock order reversals.
4495                  *
4496                  * XXX KDM what happens if the frontend list changes while
4497                  * we're traversing it?  It's unlikely, but should be handled.
4498                  */
4499                 mtx_unlock(&softc->ctl_lock);
4500                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4501                 mtx_lock(&softc->ctl_lock);
4502                 if (retval != 0) {
4503                         printf("%s: FETD %s port %d returned error "
4504                                "%d for lun_disable on lun %jd\n",
4505                                __func__, port->port_name, port->targ_port,
4506                                retval, (intmax_t)lun->lun);
4507                 }
4508         }
4509
4510         mtx_unlock(&softc->ctl_lock);
4511         ctl_isc_announce_lun(lun);
4512
4513         return (0);
4514 }
4515
4516 int
4517 ctl_start_lun(struct ctl_be_lun *be_lun)
4518 {
4519         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4520
4521         mtx_lock(&lun->lun_lock);
4522         lun->flags &= ~CTL_LUN_STOPPED;
4523         mtx_unlock(&lun->lun_lock);
4524         return (0);
4525 }
4526
4527 int
4528 ctl_stop_lun(struct ctl_be_lun *be_lun)
4529 {
4530         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4531
4532         mtx_lock(&lun->lun_lock);
4533         lun->flags |= CTL_LUN_STOPPED;
4534         mtx_unlock(&lun->lun_lock);
4535         return (0);
4536 }
4537
4538 int
4539 ctl_lun_offline(struct ctl_be_lun *be_lun)
4540 {
4541         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4542
4543         mtx_lock(&lun->lun_lock);
4544         lun->flags |= CTL_LUN_OFFLINE;
4545         mtx_unlock(&lun->lun_lock);
4546         return (0);
4547 }
4548
4549 int
4550 ctl_lun_online(struct ctl_be_lun *be_lun)
4551 {
4552         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4553
4554         mtx_lock(&lun->lun_lock);
4555         lun->flags &= ~CTL_LUN_OFFLINE;
4556         mtx_unlock(&lun->lun_lock);
4557         return (0);
4558 }
4559
4560 int
4561 ctl_lun_primary(struct ctl_be_lun *be_lun)
4562 {
4563         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4564
4565         mtx_lock(&lun->lun_lock);
4566         lun->flags |= CTL_LUN_PRIMARY_SC;
4567         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4568         mtx_unlock(&lun->lun_lock);
4569         ctl_isc_announce_lun(lun);
4570         return (0);
4571 }
4572
4573 int
4574 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4575 {
4576         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4577
4578         mtx_lock(&lun->lun_lock);
4579         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4580         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4581         mtx_unlock(&lun->lun_lock);
4582         ctl_isc_announce_lun(lun);
4583         return (0);
4584 }
4585
4586 int
4587 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4588 {
4589         struct ctl_softc *softc;
4590         struct ctl_lun *lun;
4591
4592         lun = (struct ctl_lun *)be_lun->ctl_lun;
4593         softc = lun->ctl_softc;
4594
4595         mtx_lock(&lun->lun_lock);
4596
4597         /*
4598          * The LUN needs to be disabled before it can be marked invalid.
4599          */
4600         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4601                 mtx_unlock(&lun->lun_lock);
4602                 return (-1);
4603         }
4604         /*
4605          * Mark the LUN invalid.
4606          */
4607         lun->flags |= CTL_LUN_INVALID;
4608
4609         /*
4610          * If there is nothing in the OOA queue, go ahead and free the LUN.
4611          * If we have something in the OOA queue, we'll free it when the
4612          * last I/O completes.
4613          */
4614         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4615                 mtx_unlock(&lun->lun_lock);
4616                 mtx_lock(&softc->ctl_lock);
4617                 ctl_free_lun(lun);
4618                 mtx_unlock(&softc->ctl_lock);
4619         } else
4620                 mtx_unlock(&lun->lun_lock);
4621
4622         return (0);
4623 }
4624
4625 int
4626 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4627 {
4628         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4629
4630         mtx_lock(&lun->lun_lock);
4631         lun->flags |= CTL_LUN_INOPERABLE;
4632         mtx_unlock(&lun->lun_lock);
4633         return (0);
4634 }
4635
4636 int
4637 ctl_lun_operable(struct ctl_be_lun *be_lun)
4638 {
4639         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4640
4641         mtx_lock(&lun->lun_lock);
4642         lun->flags &= ~CTL_LUN_INOPERABLE;
4643         mtx_unlock(&lun->lun_lock);
4644         return (0);
4645 }
4646
4647 void
4648 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4649 {
4650         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4651         union ctl_ha_msg msg;
4652
4653         mtx_lock(&lun->lun_lock);
4654         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4655         mtx_unlock(&lun->lun_lock);
4656         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4657                 /* Send msg to other side. */
4658                 bzero(&msg.ua, sizeof(msg.ua));
4659                 msg.hdr.msg_type = CTL_MSG_UA;
4660                 msg.hdr.nexus.initid = -1;
4661                 msg.hdr.nexus.targ_port = -1;
4662                 msg.hdr.nexus.targ_lun = lun->lun;
4663                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4664                 msg.ua.ua_all = 1;
4665                 msg.ua.ua_set = 1;
4666                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4667                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4668                     M_WAITOK);
4669         }
4670 }
4671
4672 /*
4673  * Backend "memory move is complete" callback for requests that never
4674  * make it down to say RAIDCore's configuration code.
4675  */
4676 int
4677 ctl_config_move_done(union ctl_io *io)
4678 {
4679         int retval;
4680
4681         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4682         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4683             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4684
4685         if ((io->io_hdr.port_status != 0) &&
4686             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4687              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4688                 /*
4689                  * For hardware error sense keys, the sense key
4690                  * specific value is defined to be a retry count,
4691                  * but we use it to pass back an internal FETD
4692                  * error code.  XXX KDM  Hopefully the FETD is only
4693                  * using 16 bits for an error code, since that's
4694                  * all the space we have in the sks field.
4695                  */
4696                 ctl_set_internal_failure(&io->scsiio,
4697                                          /*sks_valid*/ 1,
4698                                          /*retry_count*/
4699                                          io->io_hdr.port_status);
4700         }
4701
4702         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4703                 ctl_data_print(io);
4704         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4705             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4706              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4707             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4708                 /*
4709                  * XXX KDM just assuming a single pointer here, and not a
4710                  * S/G list.  If we start using S/G lists for config data,
4711                  * we'll need to know how to clean them up here as well.
4712                  */
4713                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4714                         free(io->scsiio.kern_data_ptr, M_CTL);
4715                 ctl_done(io);
4716                 retval = CTL_RETVAL_COMPLETE;
4717         } else {
4718                 /*
4719                  * XXX KDM now we need to continue data movement.  Some
4720                  * options:
4721                  * - call ctl_scsiio() again?  We don't do this for data
4722                  *   writes, because for those at least we know ahead of
4723                  *   time where the write will go and how long it is.  For
4724                  *   config writes, though, that information is largely
4725                  *   contained within the write itself, thus we need to
4726                  *   parse out the data again.
4727                  *
4728                  * - Call some other function once the data is in?
4729                  */
4730
4731                 /*
4732                  * XXX KDM call ctl_scsiio() again for now, and check flag
4733                  * bits to see whether we're allocated or not.
4734                  */
4735                 retval = ctl_scsiio(&io->scsiio);
4736         }
4737         return (retval);
4738 }
4739
4740 /*
4741  * This gets called by a backend driver when it is done with a
4742  * data_submit method.
4743  */
4744 void
4745 ctl_data_submit_done(union ctl_io *io)
4746 {
4747         /*
4748          * If the IO_CONT flag is set, we need to call the supplied
4749          * function to continue processing the I/O, instead of completing
4750          * the I/O just yet.
4751          *
4752          * If there is an error, though, we don't want to keep processing.
4753          * Instead, just send status back to the initiator.
4754          */
4755         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4756             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4757             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4758              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4759                 io->scsiio.io_cont(io);
4760                 return;
4761         }
4762         ctl_done(io);
4763 }
4764
4765 /*
4766  * This gets called by a backend driver when it is done with a
4767  * configuration write.
4768  */
4769 void
4770 ctl_config_write_done(union ctl_io *io)
4771 {
4772         uint8_t *buf;
4773
4774         /*
4775          * If the IO_CONT flag is set, we need to call the supplied
4776          * function to continue processing the I/O, instead of completing
4777          * the I/O just yet.
4778          *
4779          * If there is an error, though, we don't want to keep processing.
4780          * Instead, just send status back to the initiator.
4781          */
4782         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4783             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4784             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4785              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4786                 io->scsiio.io_cont(io);
4787                 return;
4788         }
4789         /*
4790          * Since a configuration write can be done for commands that actually
4791          * have data allocated, like write buffer, and commands that have
4792          * no data, like start/stop unit, we need to check here.
4793          */
4794         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4795                 buf = io->scsiio.kern_data_ptr;
4796         else
4797                 buf = NULL;
4798         ctl_done(io);
4799         if (buf)
4800                 free(buf, M_CTL);
4801 }
4802
4803 void
4804 ctl_config_read_done(union ctl_io *io)
4805 {
4806         uint8_t *buf;
4807
4808         /*
4809          * If there is some error -- we are done, skip data transfer.
4810          */
4811         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4812             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4813              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4814                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4815                         buf = io->scsiio.kern_data_ptr;
4816                 else
4817                         buf = NULL;
4818                 ctl_done(io);
4819                 if (buf)
4820                         free(buf, M_CTL);
4821                 return;
4822         }
4823
4824         /*
4825          * If the IO_CONT flag is set, we need to call the supplied
4826          * function to continue processing the I/O, instead of completing
4827          * the I/O just yet.
4828          */
4829         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4830                 io->scsiio.io_cont(io);
4831                 return;
4832         }
4833
4834         ctl_datamove(io);
4835 }
4836
4837 /*
4838  * SCSI release command.
4839  */
4840 int
4841 ctl_scsi_release(struct ctl_scsiio *ctsio)
4842 {
4843         int length, longid, thirdparty_id, resv_id;
4844         struct ctl_lun *lun;
4845         uint32_t residx;
4846
4847         length = 0;
4848         resv_id = 0;
4849
4850         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4851
4852         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4853         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4854
4855         switch (ctsio->cdb[0]) {
4856         case RELEASE_10: {
4857                 struct scsi_release_10 *cdb;
4858
4859                 cdb = (struct scsi_release_10 *)ctsio->cdb;
4860
4861                 if (cdb->byte2 & SR10_LONGID)
4862                         longid = 1;
4863                 else
4864                         thirdparty_id = cdb->thirdparty_id;
4865
4866                 resv_id = cdb->resv_id;
4867                 length = scsi_2btoul(cdb->length);
4868                 break;
4869         }
4870         }
4871
4872
4873         /*
4874          * XXX KDM right now, we only support LUN reservation.  We don't
4875          * support 3rd party reservations, or extent reservations, which
4876          * might actually need the parameter list.  If we've gotten this
4877          * far, we've got a LUN reservation.  Anything else got kicked out
4878          * above.  So, according to SPC, ignore the length.
4879          */
4880         length = 0;
4881
4882         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4883          && (length > 0)) {
4884                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4885                 ctsio->kern_data_len = length;
4886                 ctsio->kern_total_len = length;
4887                 ctsio->kern_data_resid = 0;
4888                 ctsio->kern_rel_offset = 0;
4889                 ctsio->kern_sg_entries = 0;
4890                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4891                 ctsio->be_move_done = ctl_config_move_done;
4892                 ctl_datamove((union ctl_io *)ctsio);
4893
4894                 return (CTL_RETVAL_COMPLETE);
4895         }
4896
4897         if (length > 0)
4898                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4899
4900         mtx_lock(&lun->lun_lock);
4901
4902         /*
4903          * According to SPC, it is not an error for an intiator to attempt
4904          * to release a reservation on a LUN that isn't reserved, or that
4905          * is reserved by another initiator.  The reservation can only be
4906          * released, though, by the initiator who made it or by one of
4907          * several reset type events.
4908          */
4909         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
4910                         lun->flags &= ~CTL_LUN_RESERVED;
4911
4912         mtx_unlock(&lun->lun_lock);
4913
4914         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4915                 free(ctsio->kern_data_ptr, M_CTL);
4916                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4917         }
4918
4919         ctl_set_success(ctsio);
4920         ctl_done((union ctl_io *)ctsio);
4921         return (CTL_RETVAL_COMPLETE);
4922 }
4923
4924 int
4925 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
4926 {
4927         int extent, thirdparty, longid;
4928         int resv_id, length;
4929         uint64_t thirdparty_id;
4930         struct ctl_lun *lun;
4931         uint32_t residx;
4932
4933         extent = 0;
4934         thirdparty = 0;
4935         longid = 0;
4936         resv_id = 0;
4937         length = 0;
4938         thirdparty_id = 0;
4939
4940         CTL_DEBUG_PRINT(("ctl_reserve\n"));
4941
4942         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4943         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4944
4945         switch (ctsio->cdb[0]) {
4946         case RESERVE_10: {
4947                 struct scsi_reserve_10 *cdb;
4948
4949                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
4950
4951                 if (cdb->byte2 & SR10_LONGID)
4952                         longid = 1;
4953                 else
4954                         thirdparty_id = cdb->thirdparty_id;
4955
4956                 resv_id = cdb->resv_id;
4957                 length = scsi_2btoul(cdb->length);
4958                 break;
4959         }
4960         }
4961
4962         /*
4963          * XXX KDM right now, we only support LUN reservation.  We don't
4964          * support 3rd party reservations, or extent reservations, which
4965          * might actually need the parameter list.  If we've gotten this
4966          * far, we've got a LUN reservation.  Anything else got kicked out
4967          * above.  So, according to SPC, ignore the length.
4968          */
4969         length = 0;
4970
4971         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4972          && (length > 0)) {
4973                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4974                 ctsio->kern_data_len = length;
4975                 ctsio->kern_total_len = length;
4976                 ctsio->kern_data_resid = 0;
4977                 ctsio->kern_rel_offset = 0;
4978                 ctsio->kern_sg_entries = 0;
4979                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4980                 ctsio->be_move_done = ctl_config_move_done;
4981                 ctl_datamove((union ctl_io *)ctsio);
4982
4983                 return (CTL_RETVAL_COMPLETE);
4984         }
4985
4986         if (length > 0)
4987                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4988
4989         mtx_lock(&lun->lun_lock);
4990         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
4991                 ctl_set_reservation_conflict(ctsio);
4992                 goto bailout;
4993         }
4994
4995         lun->flags |= CTL_LUN_RESERVED;
4996         lun->res_idx = residx;
4997
4998         ctl_set_success(ctsio);
4999
5000 bailout:
5001         mtx_unlock(&lun->lun_lock);
5002
5003         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5004                 free(ctsio->kern_data_ptr, M_CTL);
5005                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5006         }
5007
5008         ctl_done((union ctl_io *)ctsio);
5009         return (CTL_RETVAL_COMPLETE);
5010 }
5011
5012 int
5013 ctl_start_stop(struct ctl_scsiio *ctsio)
5014 {
5015         struct scsi_start_stop_unit *cdb;
5016         struct ctl_lun *lun;
5017         int retval;
5018
5019         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5020
5021         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5022         retval = 0;
5023
5024         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5025
5026         /*
5027          * XXX KDM
5028          * We don't support the immediate bit on a stop unit.  In order to
5029          * do that, we would need to code up a way to know that a stop is
5030          * pending, and hold off any new commands until it completes, one
5031          * way or another.  Then we could accept or reject those commands
5032          * depending on its status.  We would almost need to do the reverse
5033          * of what we do below for an immediate start -- return the copy of
5034          * the ctl_io to the FETD with status to send to the host (and to
5035          * free the copy!) and then free the original I/O once the stop
5036          * actually completes.  That way, the OOA queue mechanism can work
5037          * to block commands that shouldn't proceed.  Another alternative
5038          * would be to put the copy in the queue in place of the original,
5039          * and return the original back to the caller.  That could be
5040          * slightly safer..
5041          */
5042         if ((cdb->byte2 & SSS_IMMED)
5043          && ((cdb->how & SSS_START) == 0)) {
5044                 ctl_set_invalid_field(ctsio,
5045                                       /*sks_valid*/ 1,
5046                                       /*command*/ 1,
5047                                       /*field*/ 1,
5048                                       /*bit_valid*/ 1,
5049                                       /*bit*/ 0);
5050                 ctl_done((union ctl_io *)ctsio);
5051                 return (CTL_RETVAL_COMPLETE);
5052         }
5053
5054         if ((lun->flags & CTL_LUN_PR_RESERVED)
5055          && ((cdb->how & SSS_START)==0)) {
5056                 uint32_t residx;
5057
5058                 residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5059                 if (ctl_get_prkey(lun, residx) == 0
5060                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5061
5062                         ctl_set_reservation_conflict(ctsio);
5063                         ctl_done((union ctl_io *)ctsio);
5064                         return (CTL_RETVAL_COMPLETE);
5065                 }
5066         }
5067
5068         /*
5069          * If there is no backend on this device, we can't start or stop
5070          * it.  In theory we shouldn't get any start/stop commands in the
5071          * first place at this level if the LUN doesn't have a backend.
5072          * That should get stopped by the command decode code.
5073          */
5074         if (lun->backend == NULL) {
5075                 ctl_set_invalid_opcode(ctsio);
5076                 ctl_done((union ctl_io *)ctsio);
5077                 return (CTL_RETVAL_COMPLETE);
5078         }
5079
5080         /*
5081          * XXX KDM Copan-specific offline behavior.
5082          * Figure out a reasonable way to port this?
5083          */
5084 #ifdef NEEDTOPORT
5085         mtx_lock(&lun->lun_lock);
5086
5087         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5088          && (lun->flags & CTL_LUN_OFFLINE)) {
5089                 /*
5090                  * If the LUN is offline, and the on/offline bit isn't set,
5091                  * reject the start or stop.  Otherwise, let it through.
5092                  */
5093                 mtx_unlock(&lun->lun_lock);
5094                 ctl_set_lun_not_ready(ctsio);
5095                 ctl_done((union ctl_io *)ctsio);
5096         } else {
5097                 mtx_unlock(&lun->lun_lock);
5098 #endif /* NEEDTOPORT */
5099                 /*
5100                  * This could be a start or a stop when we're online,
5101                  * or a stop/offline or start/online.  A start or stop when
5102                  * we're offline is covered in the case above.
5103                  */
5104                 /*
5105                  * In the non-immediate case, we send the request to
5106                  * the backend and return status to the user when
5107                  * it is done.
5108                  *
5109                  * In the immediate case, we allocate a new ctl_io
5110                  * to hold a copy of the request, and send that to
5111                  * the backend.  We then set good status on the
5112                  * user's request and return it immediately.
5113                  */
5114                 if (cdb->byte2 & SSS_IMMED) {
5115                         union ctl_io *new_io;
5116
5117                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5118                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5119                         retval = lun->backend->config_write(new_io);
5120                         ctl_set_success(ctsio);
5121                         ctl_done((union ctl_io *)ctsio);
5122                 } else {
5123                         retval = lun->backend->config_write(
5124                                 (union ctl_io *)ctsio);
5125                 }
5126 #ifdef NEEDTOPORT
5127         }
5128 #endif
5129         return (retval);
5130 }
5131
5132 /*
5133  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5134  * we don't really do anything with the LBA and length fields if the user
5135  * passes them in.  Instead we'll just flush out the cache for the entire
5136  * LUN.
5137  */
5138 int
5139 ctl_sync_cache(struct ctl_scsiio *ctsio)
5140 {
5141         struct ctl_lun *lun;
5142         struct ctl_softc *softc;
5143         struct ctl_lba_len_flags *lbalen;
5144         uint64_t starting_lba;
5145         uint32_t block_count;
5146         int retval;
5147         uint8_t byte2;
5148
5149         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5150
5151         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5152         softc = lun->ctl_softc;
5153         retval = 0;
5154
5155         switch (ctsio->cdb[0]) {
5156         case SYNCHRONIZE_CACHE: {
5157                 struct scsi_sync_cache *cdb;
5158                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5159
5160                 starting_lba = scsi_4btoul(cdb->begin_lba);
5161                 block_count = scsi_2btoul(cdb->lb_count);
5162                 byte2 = cdb->byte2;
5163                 break;
5164         }
5165         case SYNCHRONIZE_CACHE_16: {
5166                 struct scsi_sync_cache_16 *cdb;
5167                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5168
5169                 starting_lba = scsi_8btou64(cdb->begin_lba);
5170                 block_count = scsi_4btoul(cdb->lb_count);
5171                 byte2 = cdb->byte2;
5172                 break;
5173         }
5174         default:
5175                 ctl_set_invalid_opcode(ctsio);
5176                 ctl_done((union ctl_io *)ctsio);
5177                 goto bailout;
5178                 break; /* NOTREACHED */
5179         }
5180
5181         /*
5182          * We check the LBA and length, but don't do anything with them.
5183          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5184          * get flushed.  This check will just help satisfy anyone who wants
5185          * to see an error for an out of range LBA.
5186          */
5187         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5188                 ctl_set_lba_out_of_range(ctsio);
5189                 ctl_done((union ctl_io *)ctsio);
5190                 goto bailout;
5191         }
5192
5193         /*
5194          * If this LUN has no backend, we can't flush the cache anyway.
5195          */
5196         if (lun->backend == NULL) {
5197                 ctl_set_invalid_opcode(ctsio);
5198                 ctl_done((union ctl_io *)ctsio);
5199                 goto bailout;
5200         }
5201
5202         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5203         lbalen->lba = starting_lba;
5204         lbalen->len = block_count;
5205         lbalen->flags = byte2;
5206
5207         /*
5208          * Check to see whether we're configured to send the SYNCHRONIZE
5209          * CACHE command directly to the back end.
5210          */
5211         mtx_lock(&lun->lun_lock);
5212         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5213          && (++(lun->sync_count) >= lun->sync_interval)) {
5214                 lun->sync_count = 0;
5215                 mtx_unlock(&lun->lun_lock);
5216                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5217         } else {
5218                 mtx_unlock(&lun->lun_lock);
5219                 ctl_set_success(ctsio);
5220                 ctl_done((union ctl_io *)ctsio);
5221         }
5222
5223 bailout:
5224
5225         return (retval);
5226 }
5227
5228 int
5229 ctl_format(struct ctl_scsiio *ctsio)
5230 {
5231         struct scsi_format *cdb;
5232         struct ctl_lun *lun;
5233         int length, defect_list_len;
5234
5235         CTL_DEBUG_PRINT(("ctl_format\n"));
5236
5237         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5238
5239         cdb = (struct scsi_format *)ctsio->cdb;
5240
5241         length = 0;
5242         if (cdb->byte2 & SF_FMTDATA) {
5243                 if (cdb->byte2 & SF_LONGLIST)
5244                         length = sizeof(struct scsi_format_header_long);
5245                 else
5246                         length = sizeof(struct scsi_format_header_short);
5247         }
5248
5249         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5250          && (length > 0)) {
5251                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5252                 ctsio->kern_data_len = length;
5253                 ctsio->kern_total_len = length;
5254                 ctsio->kern_data_resid = 0;
5255                 ctsio->kern_rel_offset = 0;
5256                 ctsio->kern_sg_entries = 0;
5257                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5258                 ctsio->be_move_done = ctl_config_move_done;
5259                 ctl_datamove((union ctl_io *)ctsio);
5260
5261                 return (CTL_RETVAL_COMPLETE);
5262         }
5263
5264         defect_list_len = 0;
5265
5266         if (cdb->byte2 & SF_FMTDATA) {
5267                 if (cdb->byte2 & SF_LONGLIST) {
5268                         struct scsi_format_header_long *header;
5269
5270                         header = (struct scsi_format_header_long *)
5271                                 ctsio->kern_data_ptr;
5272
5273                         defect_list_len = scsi_4btoul(header->defect_list_len);
5274                         if (defect_list_len != 0) {
5275                                 ctl_set_invalid_field(ctsio,
5276                                                       /*sks_valid*/ 1,
5277                                                       /*command*/ 0,
5278                                                       /*field*/ 2,
5279                                                       /*bit_valid*/ 0,
5280                                                       /*bit*/ 0);
5281                                 goto bailout;
5282                         }
5283                 } else {
5284                         struct scsi_format_header_short *header;
5285
5286                         header = (struct scsi_format_header_short *)
5287                                 ctsio->kern_data_ptr;
5288
5289                         defect_list_len = scsi_2btoul(header->defect_list_len);
5290                         if (defect_list_len != 0) {
5291                                 ctl_set_invalid_field(ctsio,
5292                                                       /*sks_valid*/ 1,
5293                                                       /*command*/ 0,
5294                                                       /*field*/ 2,
5295                                                       /*bit_valid*/ 0,
5296                                                       /*bit*/ 0);
5297                                 goto bailout;
5298                         }
5299                 }
5300         }
5301
5302         /*
5303          * The format command will clear out the "Medium format corrupted"
5304          * status if set by the configuration code.  That status is really
5305          * just a way to notify the host that we have lost the media, and
5306          * get them to issue a command that will basically make them think
5307          * they're blowing away the media.
5308          */
5309         mtx_lock(&lun->lun_lock);
5310         lun->flags &= ~CTL_LUN_INOPERABLE;
5311         mtx_unlock(&lun->lun_lock);
5312
5313         ctl_set_success(ctsio);
5314 bailout:
5315
5316         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5317                 free(ctsio->kern_data_ptr, M_CTL);
5318                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5319         }
5320
5321         ctl_done((union ctl_io *)ctsio);
5322         return (CTL_RETVAL_COMPLETE);
5323 }
5324
5325 int
5326 ctl_read_buffer(struct ctl_scsiio *ctsio)
5327 {
5328         struct scsi_read_buffer *cdb;
5329         struct ctl_lun *lun;
5330         int buffer_offset, len;
5331         static uint8_t descr[4];
5332         static uint8_t echo_descr[4] = { 0 };
5333
5334         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5335
5336         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5337         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5338
5339         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5340             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5341             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5342                 ctl_set_invalid_field(ctsio,
5343                                       /*sks_valid*/ 1,
5344                                       /*command*/ 1,
5345                                       /*field*/ 1,
5346                                       /*bit_valid*/ 1,
5347                                       /*bit*/ 4);
5348                 ctl_done((union ctl_io *)ctsio);
5349                 return (CTL_RETVAL_COMPLETE);
5350         }
5351
5352         len = scsi_3btoul(cdb->length);
5353         buffer_offset = scsi_3btoul(cdb->offset);
5354
5355         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5356                 ctl_set_invalid_field(ctsio,
5357                                       /*sks_valid*/ 1,
5358                                       /*command*/ 1,
5359                                       /*field*/ 6,
5360                                       /*bit_valid*/ 0,
5361                                       /*bit*/ 0);
5362                 ctl_done((union ctl_io *)ctsio);
5363                 return (CTL_RETVAL_COMPLETE);
5364         }
5365
5366         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5367                 descr[0] = 0;
5368                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5369                 ctsio->kern_data_ptr = descr;
5370                 len = min(len, sizeof(descr));
5371         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5372                 ctsio->kern_data_ptr = echo_descr;
5373                 len = min(len, sizeof(echo_descr));
5374         } else {
5375                 if (lun->write_buffer == NULL) {
5376                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5377                             M_CTL, M_WAITOK);
5378                 }
5379                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5380         }
5381         ctsio->kern_data_len = len;
5382         ctsio->kern_total_len = len;
5383         ctsio->kern_data_resid = 0;
5384         ctsio->kern_rel_offset = 0;
5385         ctsio->kern_sg_entries = 0;
5386         ctl_set_success(ctsio);
5387         ctsio->be_move_done = ctl_config_move_done;
5388         ctl_datamove((union ctl_io *)ctsio);
5389         return (CTL_RETVAL_COMPLETE);
5390 }
5391
5392 int
5393 ctl_write_buffer(struct ctl_scsiio *ctsio)
5394 {
5395         struct scsi_write_buffer *cdb;
5396         struct ctl_lun *lun;
5397         int buffer_offset, len;
5398
5399         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5400
5401         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5402         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5403
5404         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5405                 ctl_set_invalid_field(ctsio,
5406                                       /*sks_valid*/ 1,
5407                                       /*command*/ 1,
5408                                       /*field*/ 1,
5409                                       /*bit_valid*/ 1,
5410                                       /*bit*/ 4);
5411                 ctl_done((union ctl_io *)ctsio);
5412                 return (CTL_RETVAL_COMPLETE);
5413         }
5414
5415         len = scsi_3btoul(cdb->length);
5416         buffer_offset = scsi_3btoul(cdb->offset);
5417
5418         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5419                 ctl_set_invalid_field(ctsio,
5420                                       /*sks_valid*/ 1,
5421                                       /*command*/ 1,
5422                                       /*field*/ 6,
5423                                       /*bit_valid*/ 0,
5424                                       /*bit*/ 0);
5425                 ctl_done((union ctl_io *)ctsio);
5426                 return (CTL_RETVAL_COMPLETE);
5427         }
5428
5429         /*
5430          * If we've got a kernel request that hasn't been malloced yet,
5431          * malloc it and tell the caller the data buffer is here.
5432          */
5433         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5434                 if (lun->write_buffer == NULL) {
5435                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5436                             M_CTL, M_WAITOK);
5437                 }
5438                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5439                 ctsio->kern_data_len = len;
5440                 ctsio->kern_total_len = len;
5441                 ctsio->kern_data_resid = 0;
5442                 ctsio->kern_rel_offset = 0;
5443                 ctsio->kern_sg_entries = 0;
5444                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5445                 ctsio->be_move_done = ctl_config_move_done;
5446                 ctl_datamove((union ctl_io *)ctsio);
5447
5448                 return (CTL_RETVAL_COMPLETE);
5449         }
5450
5451         ctl_set_success(ctsio);
5452         ctl_done((union ctl_io *)ctsio);
5453         return (CTL_RETVAL_COMPLETE);
5454 }
5455
5456 int
5457 ctl_write_same(struct ctl_scsiio *ctsio)
5458 {
5459         struct ctl_lun *lun;
5460         struct ctl_lba_len_flags *lbalen;
5461         uint64_t lba;
5462         uint32_t num_blocks;
5463         int len, retval;
5464         uint8_t byte2;
5465
5466         retval = CTL_RETVAL_COMPLETE;
5467
5468         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5469
5470         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5471
5472         switch (ctsio->cdb[0]) {
5473         case WRITE_SAME_10: {
5474                 struct scsi_write_same_10 *cdb;
5475
5476                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5477
5478                 lba = scsi_4btoul(cdb->addr);
5479                 num_blocks = scsi_2btoul(cdb->length);
5480                 byte2 = cdb->byte2;
5481                 break;
5482         }
5483         case WRITE_SAME_16: {
5484                 struct scsi_write_same_16 *cdb;
5485
5486                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5487
5488                 lba = scsi_8btou64(cdb->addr);
5489                 num_blocks = scsi_4btoul(cdb->length);
5490                 byte2 = cdb->byte2;
5491                 break;
5492         }
5493         default:
5494                 /*
5495                  * We got a command we don't support.  This shouldn't
5496                  * happen, commands should be filtered out above us.
5497                  */
5498                 ctl_set_invalid_opcode(ctsio);
5499                 ctl_done((union ctl_io *)ctsio);
5500
5501                 return (CTL_RETVAL_COMPLETE);
5502                 break; /* NOTREACHED */
5503         }
5504
5505         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5506         if ((byte2 & SWS_UNMAP) == 0 &&
5507             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5508                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5509                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5510                 ctl_done((union ctl_io *)ctsio);
5511                 return (CTL_RETVAL_COMPLETE);
5512         }
5513
5514         /*
5515          * The first check is to make sure we're in bounds, the second
5516          * check is to catch wrap-around problems.  If the lba + num blocks
5517          * is less than the lba, then we've wrapped around and the block
5518          * range is invalid anyway.
5519          */
5520         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5521          || ((lba + num_blocks) < lba)) {
5522                 ctl_set_lba_out_of_range(ctsio);
5523                 ctl_done((union ctl_io *)ctsio);
5524                 return (CTL_RETVAL_COMPLETE);
5525         }
5526
5527         /* Zero number of blocks means "to the last logical block" */
5528         if (num_blocks == 0) {
5529                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5530                         ctl_set_invalid_field(ctsio,
5531                                               /*sks_valid*/ 0,
5532                                               /*command*/ 1,
5533                                               /*field*/ 0,
5534                                               /*bit_valid*/ 0,
5535                                               /*bit*/ 0);
5536                         ctl_done((union ctl_io *)ctsio);
5537                         return (CTL_RETVAL_COMPLETE);
5538                 }
5539                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5540         }
5541
5542         len = lun->be_lun->blocksize;
5543
5544         /*
5545          * If we've got a kernel request that hasn't been malloced yet,
5546          * malloc it and tell the caller the data buffer is here.
5547          */
5548         if ((byte2 & SWS_NDOB) == 0 &&
5549             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5550                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5551                 ctsio->kern_data_len = len;
5552                 ctsio->kern_total_len = len;
5553                 ctsio->kern_data_resid = 0;
5554                 ctsio->kern_rel_offset = 0;
5555                 ctsio->kern_sg_entries = 0;
5556                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5557                 ctsio->be_move_done = ctl_config_move_done;
5558                 ctl_datamove((union ctl_io *)ctsio);
5559
5560                 return (CTL_RETVAL_COMPLETE);
5561         }
5562
5563         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5564         lbalen->lba = lba;
5565         lbalen->len = num_blocks;
5566         lbalen->flags = byte2;
5567         retval = lun->backend->config_write((union ctl_io *)ctsio);
5568
5569         return (retval);
5570 }
5571
5572 int
5573 ctl_unmap(struct ctl_scsiio *ctsio)
5574 {
5575         struct ctl_lun *lun;
5576         struct scsi_unmap *cdb;
5577         struct ctl_ptr_len_flags *ptrlen;
5578         struct scsi_unmap_header *hdr;
5579         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5580         uint64_t lba;
5581         uint32_t num_blocks;
5582         int len, retval;
5583         uint8_t byte2;
5584
5585         retval = CTL_RETVAL_COMPLETE;
5586
5587         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5588
5589         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5590         cdb = (struct scsi_unmap *)ctsio->cdb;
5591
5592         len = scsi_2btoul(cdb->length);
5593         byte2 = cdb->byte2;
5594
5595         /*
5596          * If we've got a kernel request that hasn't been malloced yet,
5597          * malloc it and tell the caller the data buffer is here.
5598          */
5599         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5600                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5601                 ctsio->kern_data_len = len;
5602                 ctsio->kern_total_len = len;
5603                 ctsio->kern_data_resid = 0;
5604                 ctsio->kern_rel_offset = 0;
5605                 ctsio->kern_sg_entries = 0;
5606                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5607                 ctsio->be_move_done = ctl_config_move_done;
5608                 ctl_datamove((union ctl_io *)ctsio);
5609
5610                 return (CTL_RETVAL_COMPLETE);
5611         }
5612
5613         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5614         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5615         if (len < sizeof (*hdr) ||
5616             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5617             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5618             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5619                 ctl_set_invalid_field(ctsio,
5620                                       /*sks_valid*/ 0,
5621                                       /*command*/ 0,
5622                                       /*field*/ 0,
5623                                       /*bit_valid*/ 0,
5624                                       /*bit*/ 0);
5625                 goto done;
5626         }
5627         len = scsi_2btoul(hdr->desc_length);
5628         buf = (struct scsi_unmap_desc *)(hdr + 1);
5629         end = buf + len / sizeof(*buf);
5630
5631         endnz = buf;
5632         for (range = buf; range < end; range++) {
5633                 lba = scsi_8btou64(range->lba);
5634                 num_blocks = scsi_4btoul(range->length);
5635                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5636                  || ((lba + num_blocks) < lba)) {
5637                         ctl_set_lba_out_of_range(ctsio);
5638                         ctl_done((union ctl_io *)ctsio);
5639                         return (CTL_RETVAL_COMPLETE);
5640                 }
5641                 if (num_blocks != 0)
5642                         endnz = range + 1;
5643         }
5644
5645         /*
5646          * Block backend can not handle zero last range.
5647          * Filter it out and return if there is nothing left.
5648          */
5649         len = (uint8_t *)endnz - (uint8_t *)buf;
5650         if (len == 0) {
5651                 ctl_set_success(ctsio);
5652                 goto done;
5653         }
5654
5655         mtx_lock(&lun->lun_lock);
5656         ptrlen = (struct ctl_ptr_len_flags *)
5657             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5658         ptrlen->ptr = (void *)buf;
5659         ptrlen->len = len;
5660         ptrlen->flags = byte2;
5661         ctl_check_blocked(lun);
5662         mtx_unlock(&lun->lun_lock);
5663
5664         retval = lun->backend->config_write((union ctl_io *)ctsio);
5665         return (retval);
5666
5667 done:
5668         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5669                 free(ctsio->kern_data_ptr, M_CTL);
5670                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5671         }
5672         ctl_done((union ctl_io *)ctsio);
5673         return (CTL_RETVAL_COMPLETE);
5674 }
5675
5676 /*
5677  * Note that this function currently doesn't actually do anything inside
5678  * CTL to enforce things if the DQue bit is turned on.
5679  *
5680  * Also note that this function can't be used in the default case, because
5681  * the DQue bit isn't set in the changeable mask for the control mode page
5682  * anyway.  This is just here as an example for how to implement a page
5683  * handler, and a placeholder in case we want to allow the user to turn
5684  * tagged queueing on and off.
5685  *
5686  * The D_SENSE bit handling is functional, however, and will turn
5687  * descriptor sense on and off for a given LUN.
5688  */
5689 int
5690 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5691                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5692 {
5693         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5694         struct ctl_lun *lun;
5695         int set_ua;
5696         uint32_t initidx;
5697
5698         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5699         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5700         set_ua = 0;
5701
5702         user_cp = (struct scsi_control_page *)page_ptr;
5703         current_cp = (struct scsi_control_page *)
5704                 (page_index->page_data + (page_index->page_len *
5705                 CTL_PAGE_CURRENT));
5706         saved_cp = (struct scsi_control_page *)
5707                 (page_index->page_data + (page_index->page_len *
5708                 CTL_PAGE_SAVED));
5709
5710         mtx_lock(&lun->lun_lock);
5711         if (((current_cp->rlec & SCP_DSENSE) == 0)
5712          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5713                 /*
5714                  * Descriptor sense is currently turned off and the user
5715                  * wants to turn it on.
5716                  */
5717                 current_cp->rlec |= SCP_DSENSE;
5718                 saved_cp->rlec |= SCP_DSENSE;
5719                 lun->flags |= CTL_LUN_SENSE_DESC;
5720                 set_ua = 1;
5721         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5722                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5723                 /*
5724                  * Descriptor sense is currently turned on, and the user
5725                  * wants to turn it off.
5726                  */
5727                 current_cp->rlec &= ~SCP_DSENSE;
5728                 saved_cp->rlec &= ~SCP_DSENSE;
5729                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5730                 set_ua = 1;
5731         }
5732         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5733             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5734                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5735                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5736                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5737                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5738                 set_ua = 1;
5739         }
5740         if ((current_cp->eca_and_aen & SCP_SWP) !=
5741             (user_cp->eca_and_aen & SCP_SWP)) {
5742                 current_cp->eca_and_aen &= ~SCP_SWP;
5743                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5744                 saved_cp->eca_and_aen &= ~SCP_SWP;
5745                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5746                 set_ua = 1;
5747         }
5748         if (set_ua != 0)
5749                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5750         mtx_unlock(&lun->lun_lock);
5751
5752         return (0);
5753 }
5754
5755 int
5756 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5757                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5758 {
5759         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5760         struct ctl_lun *lun;
5761         int set_ua;
5762         uint32_t initidx;
5763
5764         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5765         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5766         set_ua = 0;
5767
5768         user_cp = (struct scsi_caching_page *)page_ptr;
5769         current_cp = (struct scsi_caching_page *)
5770                 (page_index->page_data + (page_index->page_len *
5771                 CTL_PAGE_CURRENT));
5772         saved_cp = (struct scsi_caching_page *)
5773                 (page_index->page_data + (page_index->page_len *
5774                 CTL_PAGE_SAVED));
5775
5776         mtx_lock(&lun->lun_lock);
5777         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5778             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5779                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5780                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5781                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5782                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5783                 set_ua = 1;
5784         }
5785         if (set_ua != 0)
5786                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5787         mtx_unlock(&lun->lun_lock);
5788
5789         return (0);
5790 }
5791
5792 int
5793 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5794                                 struct ctl_page_index *page_index,
5795                                 uint8_t *page_ptr)
5796 {
5797         uint8_t *c;
5798         int i;
5799
5800         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5801         ctl_time_io_secs =
5802                 (c[0] << 8) |
5803                 (c[1] << 0) |
5804                 0;
5805         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5806         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5807         printf("page data:");
5808         for (i=0; i<8; i++)
5809                 printf(" %.2x",page_ptr[i]);
5810         printf("\n");
5811         return (0);
5812 }
5813
5814 int
5815 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5816                                struct ctl_page_index *page_index,
5817                                int pc)
5818 {
5819         struct copan_debugconf_subpage *page;
5820
5821         page = (struct copan_debugconf_subpage *)page_index->page_data +
5822                 (page_index->page_len * pc);
5823
5824         switch (pc) {
5825         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5826         case SMS_PAGE_CTRL_DEFAULT >> 6:
5827         case SMS_PAGE_CTRL_SAVED >> 6:
5828                 /*
5829                  * We don't update the changable or default bits for this page.
5830                  */
5831                 break;
5832         case SMS_PAGE_CTRL_CURRENT >> 6:
5833                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5834                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5835                 break;
5836         default:
5837 #ifdef NEEDTOPORT
5838                 EPRINT(0, "Invalid PC %d!!", pc);
5839 #endif /* NEEDTOPORT */
5840                 break;
5841         }
5842         return (0);
5843 }
5844
5845
5846 static int
5847 ctl_do_mode_select(union ctl_io *io)
5848 {
5849         struct scsi_mode_page_header *page_header;
5850         struct ctl_page_index *page_index;
5851         struct ctl_scsiio *ctsio;
5852         int control_dev, page_len;
5853         int page_len_offset, page_len_size;
5854         union ctl_modepage_info *modepage_info;
5855         struct ctl_lun *lun;
5856         int *len_left, *len_used;
5857         int retval, i;
5858
5859         ctsio = &io->scsiio;
5860         page_index = NULL;
5861         page_len = 0;
5862         retval = CTL_RETVAL_COMPLETE;
5863
5864         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5865
5866         if (lun->be_lun->lun_type != T_DIRECT)
5867                 control_dev = 1;
5868         else
5869                 control_dev = 0;
5870
5871         modepage_info = (union ctl_modepage_info *)
5872                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5873         len_left = &modepage_info->header.len_left;
5874         len_used = &modepage_info->header.len_used;
5875
5876 do_next_page:
5877
5878         page_header = (struct scsi_mode_page_header *)
5879                 (ctsio->kern_data_ptr + *len_used);
5880
5881         if (*len_left == 0) {
5882                 free(ctsio->kern_data_ptr, M_CTL);
5883                 ctl_set_success(ctsio);
5884                 ctl_done((union ctl_io *)ctsio);
5885                 return (CTL_RETVAL_COMPLETE);
5886         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5887
5888                 free(ctsio->kern_data_ptr, M_CTL);
5889                 ctl_set_param_len_error(ctsio);
5890                 ctl_done((union ctl_io *)ctsio);
5891                 return (CTL_RETVAL_COMPLETE);
5892
5893         } else if ((page_header->page_code & SMPH_SPF)
5894                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5895
5896                 free(ctsio->kern_data_ptr, M_CTL);
5897                 ctl_set_param_len_error(ctsio);
5898                 ctl_done((union ctl_io *)ctsio);
5899                 return (CTL_RETVAL_COMPLETE);
5900         }
5901
5902
5903         /*
5904          * XXX KDM should we do something with the block descriptor?
5905          */
5906         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5907
5908                 if ((control_dev != 0)
5909                  && (lun->mode_pages.index[i].page_flags &
5910                      CTL_PAGE_FLAG_DISK_ONLY))
5911                         continue;
5912
5913                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5914                     (page_header->page_code & SMPH_PC_MASK))
5915                         continue;
5916
5917                 /*
5918                  * If neither page has a subpage code, then we've got a
5919                  * match.
5920                  */
5921                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
5922                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5923                         page_index = &lun->mode_pages.index[i];
5924                         page_len = page_header->page_length;
5925                         break;
5926                 }
5927
5928                 /*
5929                  * If both pages have subpages, then the subpage numbers
5930                  * have to match.
5931                  */
5932                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
5933                   && (page_header->page_code & SMPH_SPF)) {
5934                         struct scsi_mode_page_header_sp *sph;
5935
5936                         sph = (struct scsi_mode_page_header_sp *)page_header;
5937
5938                         if (lun->mode_pages.index[i].subpage ==
5939                             sph->subpage) {
5940                                 page_index = &lun->mode_pages.index[i];
5941                                 page_len = scsi_2btoul(sph->page_length);
5942                                 break;
5943                         }
5944                 }
5945         }
5946
5947         /*
5948          * If we couldn't find the page, or if we don't have a mode select
5949          * handler for it, send back an error to the user.
5950          */
5951         if ((page_index == NULL)
5952          || (page_index->select_handler == NULL)) {
5953                 ctl_set_invalid_field(ctsio,
5954                                       /*sks_valid*/ 1,
5955                                       /*command*/ 0,
5956                                       /*field*/ *len_used,
5957                                       /*bit_valid*/ 0,
5958                                       /*bit*/ 0);
5959                 free(ctsio->kern_data_ptr, M_CTL);
5960                 ctl_done((union ctl_io *)ctsio);
5961                 return (CTL_RETVAL_COMPLETE);
5962         }
5963
5964         if (page_index->page_code & SMPH_SPF) {
5965                 page_len_offset = 2;
5966                 page_len_size = 2;
5967         } else {
5968                 page_len_size = 1;
5969                 page_len_offset = 1;
5970         }
5971
5972         /*
5973          * If the length the initiator gives us isn't the one we specify in
5974          * the mode page header, or if they didn't specify enough data in
5975          * the CDB to avoid truncating this page, kick out the request.
5976          */
5977         if ((page_len != (page_index->page_len - page_len_offset -
5978                           page_len_size))
5979          || (*len_left < page_index->page_len)) {
5980
5981
5982                 ctl_set_invalid_field(ctsio,
5983                                       /*sks_valid*/ 1,
5984                                       /*command*/ 0,
5985                                       /*field*/ *len_used + page_len_offset,
5986                                       /*bit_valid*/ 0,
5987                                       /*bit*/ 0);
5988                 free(ctsio->kern_data_ptr, M_CTL);
5989                 ctl_done((union ctl_io *)ctsio);
5990                 return (CTL_RETVAL_COMPLETE);
5991         }
5992
5993         /*
5994          * Run through the mode page, checking to make sure that the bits
5995          * the user changed are actually legal for him to change.
5996          */
5997         for (i = 0; i < page_index->page_len; i++) {
5998                 uint8_t *user_byte, *change_mask, *current_byte;
5999                 int bad_bit;
6000                 int j;
6001
6002                 user_byte = (uint8_t *)page_header + i;
6003                 change_mask = page_index->page_data +
6004                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6005                 current_byte = page_index->page_data +
6006                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6007
6008                 /*
6009                  * Check to see whether the user set any bits in this byte
6010                  * that he is not allowed to set.
6011                  */
6012                 if ((*user_byte & ~(*change_mask)) ==
6013                     (*current_byte & ~(*change_mask)))
6014                         continue;
6015
6016                 /*
6017                  * Go through bit by bit to determine which one is illegal.
6018                  */
6019                 bad_bit = 0;
6020                 for (j = 7; j >= 0; j--) {
6021                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6022                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6023                                 bad_bit = i;
6024                                 break;
6025                         }
6026                 }
6027                 ctl_set_invalid_field(ctsio,
6028                                       /*sks_valid*/ 1,
6029                                       /*command*/ 0,
6030                                       /*field*/ *len_used + i,
6031                                       /*bit_valid*/ 1,
6032                                       /*bit*/ bad_bit);
6033                 free(ctsio->kern_data_ptr, M_CTL);
6034                 ctl_done((union ctl_io *)ctsio);
6035                 return (CTL_RETVAL_COMPLETE);
6036         }
6037
6038         /*
6039          * Decrement these before we call the page handler, since we may
6040          * end up getting called back one way or another before the handler
6041          * returns to this context.
6042          */
6043         *len_left -= page_index->page_len;
6044         *len_used += page_index->page_len;
6045
6046         retval = page_index->select_handler(ctsio, page_index,
6047                                             (uint8_t *)page_header);
6048
6049         /*
6050          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6051          * wait until this queued command completes to finish processing
6052          * the mode page.  If it returns anything other than
6053          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6054          * already set the sense information, freed the data pointer, and
6055          * completed the io for us.
6056          */
6057         if (retval != CTL_RETVAL_COMPLETE)
6058                 goto bailout_no_done;
6059
6060         /*
6061          * If the initiator sent us more than one page, parse the next one.
6062          */
6063         if (*len_left > 0)
6064                 goto do_next_page;
6065
6066         ctl_set_success(ctsio);
6067         free(ctsio->kern_data_ptr, M_CTL);
6068         ctl_done((union ctl_io *)ctsio);
6069
6070 bailout_no_done:
6071
6072         return (CTL_RETVAL_COMPLETE);
6073
6074 }
6075
6076 int
6077 ctl_mode_select(struct ctl_scsiio *ctsio)
6078 {
6079         int param_len, pf, sp;
6080         int header_size, bd_len;
6081         int len_left, len_used;
6082         struct ctl_page_index *page_index;
6083         struct ctl_lun *lun;
6084         int control_dev, page_len;
6085         union ctl_modepage_info *modepage_info;
6086         int retval;
6087
6088         pf = 0;
6089         sp = 0;
6090         page_len = 0;
6091         len_used = 0;
6092         len_left = 0;
6093         retval = 0;
6094         bd_len = 0;
6095         page_index = NULL;
6096
6097         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6098
6099         if (lun->be_lun->lun_type != T_DIRECT)
6100                 control_dev = 1;
6101         else
6102                 control_dev = 0;
6103
6104         switch (ctsio->cdb[0]) {
6105         case MODE_SELECT_6: {
6106                 struct scsi_mode_select_6 *cdb;
6107
6108                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6109
6110                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6111                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6112
6113                 param_len = cdb->length;
6114                 header_size = sizeof(struct scsi_mode_header_6);
6115                 break;
6116         }
6117         case MODE_SELECT_10: {
6118                 struct scsi_mode_select_10 *cdb;
6119
6120                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6121
6122                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6123                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6124
6125                 param_len = scsi_2btoul(cdb->length);
6126                 header_size = sizeof(struct scsi_mode_header_10);
6127                 break;
6128         }
6129         default:
6130                 ctl_set_invalid_opcode(ctsio);
6131                 ctl_done((union ctl_io *)ctsio);
6132                 return (CTL_RETVAL_COMPLETE);
6133                 break; /* NOTREACHED */
6134         }
6135
6136         /*
6137          * From SPC-3:
6138          * "A parameter list length of zero indicates that the Data-Out Buffer
6139          * shall be empty. This condition shall not be considered as an error."
6140          */
6141         if (param_len == 0) {
6142                 ctl_set_success(ctsio);
6143                 ctl_done((union ctl_io *)ctsio);
6144                 return (CTL_RETVAL_COMPLETE);
6145         }
6146
6147         /*
6148          * Since we'll hit this the first time through, prior to
6149          * allocation, we don't need to free a data buffer here.
6150          */
6151         if (param_len < header_size) {
6152                 ctl_set_param_len_error(ctsio);
6153                 ctl_done((union ctl_io *)ctsio);
6154                 return (CTL_RETVAL_COMPLETE);
6155         }
6156
6157         /*
6158          * Allocate the data buffer and grab the user's data.  In theory,
6159          * we shouldn't have to sanity check the parameter list length here
6160          * because the maximum size is 64K.  We should be able to malloc
6161          * that much without too many problems.
6162          */
6163         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6164                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6165                 ctsio->kern_data_len = param_len;
6166                 ctsio->kern_total_len = param_len;
6167                 ctsio->kern_data_resid = 0;
6168                 ctsio->kern_rel_offset = 0;
6169                 ctsio->kern_sg_entries = 0;
6170                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6171                 ctsio->be_move_done = ctl_config_move_done;
6172                 ctl_datamove((union ctl_io *)ctsio);
6173
6174                 return (CTL_RETVAL_COMPLETE);
6175         }
6176
6177         switch (ctsio->cdb[0]) {
6178         case MODE_SELECT_6: {
6179                 struct scsi_mode_header_6 *mh6;
6180
6181                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6182                 bd_len = mh6->blk_desc_len;
6183                 break;
6184         }
6185         case MODE_SELECT_10: {
6186                 struct scsi_mode_header_10 *mh10;
6187
6188                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6189                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6190                 break;
6191         }
6192         default:
6193                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6194                 break;
6195         }
6196
6197         if (param_len < (header_size + bd_len)) {
6198                 free(ctsio->kern_data_ptr, M_CTL);
6199                 ctl_set_param_len_error(ctsio);
6200                 ctl_done((union ctl_io *)ctsio);
6201                 return (CTL_RETVAL_COMPLETE);
6202         }
6203
6204         /*
6205          * Set the IO_CONT flag, so that if this I/O gets passed to
6206          * ctl_config_write_done(), it'll get passed back to
6207          * ctl_do_mode_select() for further processing, or completion if
6208          * we're all done.
6209          */
6210         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6211         ctsio->io_cont = ctl_do_mode_select;
6212
6213         modepage_info = (union ctl_modepage_info *)
6214                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6215
6216         memset(modepage_info, 0, sizeof(*modepage_info));
6217
6218         len_left = param_len - header_size - bd_len;
6219         len_used = header_size + bd_len;
6220
6221         modepage_info->header.len_left = len_left;
6222         modepage_info->header.len_used = len_used;
6223
6224         return (ctl_do_mode_select((union ctl_io *)ctsio));
6225 }
6226
6227 int
6228 ctl_mode_sense(struct ctl_scsiio *ctsio)
6229 {
6230         struct ctl_lun *lun;
6231         int pc, page_code, dbd, llba, subpage;
6232         int alloc_len, page_len, header_len, total_len;
6233         struct scsi_mode_block_descr *block_desc;
6234         struct ctl_page_index *page_index;
6235         int control_dev;
6236
6237         dbd = 0;
6238         llba = 0;
6239         block_desc = NULL;
6240         page_index = NULL;
6241
6242         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6243
6244         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6245
6246         if (lun->be_lun->lun_type != T_DIRECT)
6247                 control_dev = 1;
6248         else
6249                 control_dev = 0;
6250
6251         switch (ctsio->cdb[0]) {
6252         case MODE_SENSE_6: {
6253                 struct scsi_mode_sense_6 *cdb;
6254
6255                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6256
6257                 header_len = sizeof(struct scsi_mode_hdr_6);
6258                 if (cdb->byte2 & SMS_DBD)
6259                         dbd = 1;
6260                 else
6261                         header_len += sizeof(struct scsi_mode_block_descr);
6262
6263                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6264                 page_code = cdb->page & SMS_PAGE_CODE;
6265                 subpage = cdb->subpage;
6266                 alloc_len = cdb->length;
6267                 break;
6268         }
6269         case MODE_SENSE_10: {
6270                 struct scsi_mode_sense_10 *cdb;
6271
6272                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6273
6274                 header_len = sizeof(struct scsi_mode_hdr_10);
6275
6276                 if (cdb->byte2 & SMS_DBD)
6277                         dbd = 1;
6278                 else
6279                         header_len += sizeof(struct scsi_mode_block_descr);
6280                 if (cdb->byte2 & SMS10_LLBAA)
6281                         llba = 1;
6282                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6283                 page_code = cdb->page & SMS_PAGE_CODE;
6284                 subpage = cdb->subpage;
6285                 alloc_len = scsi_2btoul(cdb->length);
6286                 break;
6287         }
6288         default:
6289                 ctl_set_invalid_opcode(ctsio);
6290                 ctl_done((union ctl_io *)ctsio);
6291                 return (CTL_RETVAL_COMPLETE);
6292                 break; /* NOTREACHED */
6293         }
6294
6295         /*
6296          * We have to make a first pass through to calculate the size of
6297          * the pages that match the user's query.  Then we allocate enough
6298          * memory to hold it, and actually copy the data into the buffer.
6299          */
6300         switch (page_code) {
6301         case SMS_ALL_PAGES_PAGE: {
6302                 int i;
6303
6304                 page_len = 0;
6305
6306                 /*
6307                  * At the moment, values other than 0 and 0xff here are
6308                  * reserved according to SPC-3.
6309                  */
6310                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6311                  && (subpage != SMS_SUBPAGE_ALL)) {
6312                         ctl_set_invalid_field(ctsio,
6313                                               /*sks_valid*/ 1,
6314                                               /*command*/ 1,
6315                                               /*field*/ 3,
6316                                               /*bit_valid*/ 0,
6317                                               /*bit*/ 0);
6318                         ctl_done((union ctl_io *)ctsio);
6319                         return (CTL_RETVAL_COMPLETE);
6320                 }
6321
6322                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6323                         if ((control_dev != 0)
6324                          && (lun->mode_pages.index[i].page_flags &
6325                              CTL_PAGE_FLAG_DISK_ONLY))
6326                                 continue;
6327
6328                         /*
6329                          * We don't use this subpage if the user didn't
6330                          * request all subpages.
6331                          */
6332                         if ((lun->mode_pages.index[i].subpage != 0)
6333                          && (subpage == SMS_SUBPAGE_PAGE_0))
6334                                 continue;
6335
6336 #if 0
6337                         printf("found page %#x len %d\n",
6338                                lun->mode_pages.index[i].page_code &
6339                                SMPH_PC_MASK,
6340                                lun->mode_pages.index[i].page_len);
6341 #endif
6342                         page_len += lun->mode_pages.index[i].page_len;
6343                 }
6344                 break;
6345         }
6346         default: {
6347                 int i;
6348
6349                 page_len = 0;
6350
6351                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6352                         /* Look for the right page code */
6353                         if ((lun->mode_pages.index[i].page_code &
6354                              SMPH_PC_MASK) != page_code)
6355                                 continue;
6356
6357                         /* Look for the right subpage or the subpage wildcard*/
6358                         if ((lun->mode_pages.index[i].subpage != subpage)
6359                          && (subpage != SMS_SUBPAGE_ALL))
6360                                 continue;
6361
6362                         /* Make sure the page is supported for this dev type */
6363                         if ((control_dev != 0)
6364                          && (lun->mode_pages.index[i].page_flags &
6365                              CTL_PAGE_FLAG_DISK_ONLY))
6366                                 continue;
6367
6368 #if 0
6369                         printf("found page %#x len %d\n",
6370                                lun->mode_pages.index[i].page_code &
6371                                SMPH_PC_MASK,
6372                                lun->mode_pages.index[i].page_len);
6373 #endif
6374
6375                         page_len += lun->mode_pages.index[i].page_len;
6376                 }
6377
6378                 if (page_len == 0) {
6379                         ctl_set_invalid_field(ctsio,
6380                                               /*sks_valid*/ 1,
6381                                               /*command*/ 1,
6382                                               /*field*/ 2,
6383                                               /*bit_valid*/ 1,
6384                                               /*bit*/ 5);
6385                         ctl_done((union ctl_io *)ctsio);
6386                         return (CTL_RETVAL_COMPLETE);
6387                 }
6388                 break;
6389         }
6390         }
6391
6392         total_len = header_len + page_len;
6393 #if 0
6394         printf("header_len = %d, page_len = %d, total_len = %d\n",
6395                header_len, page_len, total_len);
6396 #endif
6397
6398         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6399         ctsio->kern_sg_entries = 0;
6400         ctsio->kern_data_resid = 0;
6401         ctsio->kern_rel_offset = 0;
6402         if (total_len < alloc_len) {
6403                 ctsio->residual = alloc_len - total_len;
6404                 ctsio->kern_data_len = total_len;
6405                 ctsio->kern_total_len = total_len;
6406         } else {
6407                 ctsio->residual = 0;
6408                 ctsio->kern_data_len = alloc_len;
6409                 ctsio->kern_total_len = alloc_len;
6410         }
6411
6412         switch (ctsio->cdb[0]) {
6413         case MODE_SENSE_6: {
6414                 struct scsi_mode_hdr_6 *header;
6415
6416                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6417
6418                 header->datalen = MIN(total_len - 1, 254);
6419                 if (control_dev == 0) {
6420                         header->dev_specific = 0x10; /* DPOFUA */
6421                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6422                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6423                             .eca_and_aen & SCP_SWP) != 0)
6424                                     header->dev_specific |= 0x80; /* WP */
6425                 }
6426                 if (dbd)
6427                         header->block_descr_len = 0;
6428                 else
6429                         header->block_descr_len =
6430                                 sizeof(struct scsi_mode_block_descr);
6431                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6432                 break;
6433         }
6434         case MODE_SENSE_10: {
6435                 struct scsi_mode_hdr_10 *header;
6436                 int datalen;
6437
6438                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6439
6440                 datalen = MIN(total_len - 2, 65533);
6441                 scsi_ulto2b(datalen, header->datalen);
6442                 if (control_dev == 0) {
6443                         header->dev_specific = 0x10; /* DPOFUA */
6444                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6445                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6446                             .eca_and_aen & SCP_SWP) != 0)
6447                                     header->dev_specific |= 0x80; /* WP */
6448                 }
6449                 if (dbd)
6450                         scsi_ulto2b(0, header->block_descr_len);
6451                 else
6452                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6453                                     header->block_descr_len);
6454                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6455                 break;
6456         }
6457         default:
6458                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6459                 break; /* NOTREACHED */
6460         }
6461
6462         /*
6463          * If we've got a disk, use its blocksize in the block
6464          * descriptor.  Otherwise, just set it to 0.
6465          */
6466         if (dbd == 0) {
6467                 if (control_dev == 0)
6468                         scsi_ulto3b(lun->be_lun->blocksize,
6469                                     block_desc->block_len);
6470                 else
6471                         scsi_ulto3b(0, block_desc->block_len);
6472         }
6473
6474         switch (page_code) {
6475         case SMS_ALL_PAGES_PAGE: {
6476                 int i, data_used;
6477
6478                 data_used = header_len;
6479                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6480                         struct ctl_page_index *page_index;
6481
6482                         page_index = &lun->mode_pages.index[i];
6483
6484                         if ((control_dev != 0)
6485                          && (page_index->page_flags &
6486                             CTL_PAGE_FLAG_DISK_ONLY))
6487                                 continue;
6488
6489                         /*
6490                          * We don't use this subpage if the user didn't
6491                          * request all subpages.  We already checked (above)
6492                          * to make sure the user only specified a subpage
6493                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6494                          */
6495                         if ((page_index->subpage != 0)
6496                          && (subpage == SMS_SUBPAGE_PAGE_0))
6497                                 continue;
6498
6499                         /*
6500                          * Call the handler, if it exists, to update the
6501                          * page to the latest values.
6502                          */
6503                         if (page_index->sense_handler != NULL)
6504                                 page_index->sense_handler(ctsio, page_index,pc);
6505
6506                         memcpy(ctsio->kern_data_ptr + data_used,
6507                                page_index->page_data +
6508                                (page_index->page_len * pc),
6509                                page_index->page_len);
6510                         data_used += page_index->page_len;
6511                 }
6512                 break;
6513         }
6514         default: {
6515                 int i, data_used;
6516
6517                 data_used = header_len;
6518
6519                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6520                         struct ctl_page_index *page_index;
6521
6522                         page_index = &lun->mode_pages.index[i];
6523
6524                         /* Look for the right page code */
6525                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6526                                 continue;
6527
6528                         /* Look for the right subpage or the subpage wildcard*/
6529                         if ((page_index->subpage != subpage)
6530                          && (subpage != SMS_SUBPAGE_ALL))
6531                                 continue;
6532
6533                         /* Make sure the page is supported for this dev type */
6534                         if ((control_dev != 0)
6535                          && (page_index->page_flags &
6536                              CTL_PAGE_FLAG_DISK_ONLY))
6537                                 continue;
6538
6539                         /*
6540                          * Call the handler, if it exists, to update the
6541                          * page to the latest values.
6542                          */
6543                         if (page_index->sense_handler != NULL)
6544                                 page_index->sense_handler(ctsio, page_index,pc);
6545
6546                         memcpy(ctsio->kern_data_ptr + data_used,
6547                                page_index->page_data +
6548                                (page_index->page_len * pc),
6549                                page_index->page_len);
6550                         data_used += page_index->page_len;
6551                 }
6552                 break;
6553         }
6554         }
6555
6556         ctl_set_success(ctsio);
6557         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6558         ctsio->be_move_done = ctl_config_move_done;
6559         ctl_datamove((union ctl_io *)ctsio);
6560         return (CTL_RETVAL_COMPLETE);
6561 }
6562
6563 int
6564 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6565                                struct ctl_page_index *page_index,
6566                                int pc)
6567 {
6568         struct ctl_lun *lun;
6569         struct scsi_log_param_header *phdr;
6570         uint8_t *data;
6571         uint64_t val;
6572
6573         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6574         data = page_index->page_data;
6575
6576         if (lun->backend->lun_attr != NULL &&
6577             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6578              != UINT64_MAX) {
6579                 phdr = (struct scsi_log_param_header *)data;
6580                 scsi_ulto2b(0x0001, phdr->param_code);
6581                 phdr->param_control = SLP_LBIN | SLP_LP;
6582                 phdr->param_len = 8;
6583                 data = (uint8_t *)(phdr + 1);
6584                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6585                 data[4] = 0x02; /* per-pool */
6586                 data += phdr->param_len;
6587         }
6588
6589         if (lun->backend->lun_attr != NULL &&
6590             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6591              != UINT64_MAX) {
6592                 phdr = (struct scsi_log_param_header *)data;
6593                 scsi_ulto2b(0x0002, phdr->param_code);
6594                 phdr->param_control = SLP_LBIN | SLP_LP;
6595                 phdr->param_len = 8;
6596                 data = (uint8_t *)(phdr + 1);
6597                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6598                 data[4] = 0x01; /* per-LUN */
6599                 data += phdr->param_len;
6600         }
6601
6602         if (lun->backend->lun_attr != NULL &&
6603             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6604              != UINT64_MAX) {
6605                 phdr = (struct scsi_log_param_header *)data;
6606                 scsi_ulto2b(0x00f1, phdr->param_code);
6607                 phdr->param_control = SLP_LBIN | SLP_LP;
6608                 phdr->param_len = 8;
6609                 data = (uint8_t *)(phdr + 1);
6610                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6611                 data[4] = 0x02; /* per-pool */
6612                 data += phdr->param_len;
6613         }
6614
6615         if (lun->backend->lun_attr != NULL &&
6616             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6617              != UINT64_MAX) {
6618                 phdr = (struct scsi_log_param_header *)data;
6619                 scsi_ulto2b(0x00f2, phdr->param_code);
6620                 phdr->param_control = SLP_LBIN | SLP_LP;
6621                 phdr->param_len = 8;
6622                 data = (uint8_t *)(phdr + 1);
6623                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6624                 data[4] = 0x02; /* per-pool */
6625                 data += phdr->param_len;
6626         }
6627
6628         page_index->page_len = data - page_index->page_data;
6629         return (0);
6630 }
6631
6632 int
6633 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6634                                struct ctl_page_index *page_index,
6635                                int pc)
6636 {
6637         struct ctl_lun *lun;
6638         struct stat_page *data;
6639         uint64_t rn, wn, rb, wb;
6640         struct bintime rt, wt;
6641         int i;
6642
6643         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6644         data = (struct stat_page *)page_index->page_data;
6645
6646         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6647         data->sap.hdr.param_control = SLP_LBIN;
6648         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6649             sizeof(struct scsi_log_param_header);
6650         rn = wn = rb = wb = 0;
6651         bintime_clear(&rt);
6652         bintime_clear(&wt);
6653         for (i = 0; i < CTL_MAX_PORTS; i++) {
6654                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6655                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6656                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6657                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6658                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6659                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6660         }
6661         scsi_u64to8b(rn, data->sap.read_num);
6662         scsi_u64to8b(wn, data->sap.write_num);
6663         if (lun->stats.blocksize > 0) {
6664                 scsi_u64to8b(wb / lun->stats.blocksize,
6665                     data->sap.recvieved_lba);
6666                 scsi_u64to8b(rb / lun->stats.blocksize,
6667                     data->sap.transmitted_lba);
6668         }
6669         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6670             data->sap.read_int);
6671         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6672             data->sap.write_int);
6673         scsi_u64to8b(0, data->sap.weighted_num);
6674         scsi_u64to8b(0, data->sap.weighted_int);
6675         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6676         data->it.hdr.param_control = SLP_LBIN;
6677         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6678             sizeof(struct scsi_log_param_header);
6679 #ifdef CTL_TIME_IO
6680         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6681 #endif
6682         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6683         data->it.hdr.param_control = SLP_LBIN;
6684         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6685             sizeof(struct scsi_log_param_header);
6686         scsi_ulto4b(3, data->ti.exponent);
6687         scsi_ulto4b(1, data->ti.integer);
6688
6689         page_index->page_len = sizeof(*data);
6690         return (0);
6691 }
6692
6693 int
6694 ctl_log_sense(struct ctl_scsiio *ctsio)
6695 {
6696         struct ctl_lun *lun;
6697         int i, pc, page_code, subpage;
6698         int alloc_len, total_len;
6699         struct ctl_page_index *page_index;
6700         struct scsi_log_sense *cdb;
6701         struct scsi_log_header *header;
6702
6703         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6704
6705         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6706         cdb = (struct scsi_log_sense *)ctsio->cdb;
6707         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6708         page_code = cdb->page & SLS_PAGE_CODE;
6709         subpage = cdb->subpage;
6710         alloc_len = scsi_2btoul(cdb->length);
6711
6712         page_index = NULL;
6713         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6714                 page_index = &lun->log_pages.index[i];
6715
6716                 /* Look for the right page code */
6717                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6718                         continue;
6719
6720                 /* Look for the right subpage or the subpage wildcard*/
6721                 if (page_index->subpage != subpage)
6722                         continue;
6723
6724                 break;
6725         }
6726         if (i >= CTL_NUM_LOG_PAGES) {
6727                 ctl_set_invalid_field(ctsio,
6728                                       /*sks_valid*/ 1,
6729                                       /*command*/ 1,
6730                                       /*field*/ 2,
6731                                       /*bit_valid*/ 0,
6732                                       /*bit*/ 0);
6733                 ctl_done((union ctl_io *)ctsio);
6734                 return (CTL_RETVAL_COMPLETE);
6735         }
6736
6737         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6738
6739         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6740         ctsio->kern_sg_entries = 0;
6741         ctsio->kern_data_resid = 0;
6742         ctsio->kern_rel_offset = 0;
6743         if (total_len < alloc_len) {
6744                 ctsio->residual = alloc_len - total_len;
6745                 ctsio->kern_data_len = total_len;
6746                 ctsio->kern_total_len = total_len;
6747         } else {
6748                 ctsio->residual = 0;
6749                 ctsio->kern_data_len = alloc_len;
6750                 ctsio->kern_total_len = alloc_len;
6751         }
6752
6753         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6754         header->page = page_index->page_code;
6755         if (page_index->subpage) {
6756                 header->page |= SL_SPF;
6757                 header->subpage = page_index->subpage;
6758         }
6759         scsi_ulto2b(page_index->page_len, header->datalen);
6760
6761         /*
6762          * Call the handler, if it exists, to update the
6763          * page to the latest values.
6764          */
6765         if (page_index->sense_handler != NULL)
6766                 page_index->sense_handler(ctsio, page_index, pc);
6767
6768         memcpy(header + 1, page_index->page_data, page_index->page_len);
6769
6770         ctl_set_success(ctsio);
6771         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6772         ctsio->be_move_done = ctl_config_move_done;
6773         ctl_datamove((union ctl_io *)ctsio);
6774         return (CTL_RETVAL_COMPLETE);
6775 }
6776
6777 int
6778 ctl_read_capacity(struct ctl_scsiio *ctsio)
6779 {
6780         struct scsi_read_capacity *cdb;
6781         struct scsi_read_capacity_data *data;
6782         struct ctl_lun *lun;
6783         uint32_t lba;
6784
6785         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6786
6787         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6788
6789         lba = scsi_4btoul(cdb->addr);
6790         if (((cdb->pmi & SRC_PMI) == 0)
6791          && (lba != 0)) {
6792                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6793                                       /*sks_valid*/ 1,
6794                                       /*command*/ 1,
6795                                       /*field*/ 2,
6796                                       /*bit_valid*/ 0,
6797                                       /*bit*/ 0);
6798                 ctl_done((union ctl_io *)ctsio);
6799                 return (CTL_RETVAL_COMPLETE);
6800         }
6801
6802         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6803
6804         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6805         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6806         ctsio->residual = 0;
6807         ctsio->kern_data_len = sizeof(*data);
6808         ctsio->kern_total_len = sizeof(*data);
6809         ctsio->kern_data_resid = 0;
6810         ctsio->kern_rel_offset = 0;
6811         ctsio->kern_sg_entries = 0;
6812
6813         /*
6814          * If the maximum LBA is greater than 0xfffffffe, the user must
6815          * issue a SERVICE ACTION IN (16) command, with the read capacity
6816          * serivce action set.
6817          */
6818         if (lun->be_lun->maxlba > 0xfffffffe)
6819                 scsi_ulto4b(0xffffffff, data->addr);
6820         else
6821                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6822
6823         /*
6824          * XXX KDM this may not be 512 bytes...
6825          */
6826         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6827
6828         ctl_set_success(ctsio);
6829         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6830         ctsio->be_move_done = ctl_config_move_done;
6831         ctl_datamove((union ctl_io *)ctsio);
6832         return (CTL_RETVAL_COMPLETE);
6833 }
6834
6835 int
6836 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6837 {
6838         struct scsi_read_capacity_16 *cdb;
6839         struct scsi_read_capacity_data_long *data;
6840         struct ctl_lun *lun;
6841         uint64_t lba;
6842         uint32_t alloc_len;
6843
6844         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6845
6846         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6847
6848         alloc_len = scsi_4btoul(cdb->alloc_len);
6849         lba = scsi_8btou64(cdb->addr);
6850
6851         if ((cdb->reladr & SRC16_PMI)
6852          && (lba != 0)) {
6853                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6854                                       /*sks_valid*/ 1,
6855                                       /*command*/ 1,
6856                                       /*field*/ 2,
6857                                       /*bit_valid*/ 0,
6858                                       /*bit*/ 0);
6859                 ctl_done((union ctl_io *)ctsio);
6860                 return (CTL_RETVAL_COMPLETE);
6861         }
6862
6863         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6864
6865         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6866         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6867
6868         if (sizeof(*data) < alloc_len) {
6869                 ctsio->residual = alloc_len - sizeof(*data);
6870                 ctsio->kern_data_len = sizeof(*data);
6871                 ctsio->kern_total_len = sizeof(*data);
6872         } else {
6873                 ctsio->residual = 0;
6874                 ctsio->kern_data_len = alloc_len;
6875                 ctsio->kern_total_len = alloc_len;
6876         }
6877         ctsio->kern_data_resid = 0;
6878         ctsio->kern_rel_offset = 0;
6879         ctsio->kern_sg_entries = 0;
6880
6881         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6882         /* XXX KDM this may not be 512 bytes... */
6883         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6884         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6885         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6886         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6887                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6888
6889         ctl_set_success(ctsio);
6890         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6891         ctsio->be_move_done = ctl_config_move_done;
6892         ctl_datamove((union ctl_io *)ctsio);
6893         return (CTL_RETVAL_COMPLETE);
6894 }
6895
6896 int
6897 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6898 {
6899         struct scsi_get_lba_status *cdb;
6900         struct scsi_get_lba_status_data *data;
6901         struct ctl_lun *lun;
6902         struct ctl_lba_len_flags *lbalen;
6903         uint64_t lba;
6904         uint32_t alloc_len, total_len;
6905         int retval;
6906
6907         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6908
6909         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6910         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6911         lba = scsi_8btou64(cdb->addr);
6912         alloc_len = scsi_4btoul(cdb->alloc_len);
6913
6914         if (lba > lun->be_lun->maxlba) {
6915                 ctl_set_lba_out_of_range(ctsio);
6916                 ctl_done((union ctl_io *)ctsio);
6917                 return (CTL_RETVAL_COMPLETE);
6918         }
6919
6920         total_len = sizeof(*data) + sizeof(data->descr[0]);
6921         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6922         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6923
6924         if (total_len < alloc_len) {
6925                 ctsio->residual = alloc_len - total_len;
6926                 ctsio->kern_data_len = total_len;
6927                 ctsio->kern_total_len = total_len;
6928         } else {
6929                 ctsio->residual = 0;
6930                 ctsio->kern_data_len = alloc_len;
6931                 ctsio->kern_total_len = alloc_len;
6932         }
6933         ctsio->kern_data_resid = 0;
6934         ctsio->kern_rel_offset = 0;
6935         ctsio->kern_sg_entries = 0;
6936
6937         /* Fill dummy data in case backend can't tell anything. */
6938         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6939         scsi_u64to8b(lba, data->descr[0].addr);
6940         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6941             data->descr[0].length);
6942         data->descr[0].status = 0; /* Mapped or unknown. */
6943
6944         ctl_set_success(ctsio);
6945         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6946         ctsio->be_move_done = ctl_config_move_done;
6947
6948         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6949         lbalen->lba = lba;
6950         lbalen->len = total_len;
6951         lbalen->flags = 0;
6952         retval = lun->backend->config_read((union ctl_io *)ctsio);
6953         return (CTL_RETVAL_COMPLETE);
6954 }
6955
6956 int
6957 ctl_read_defect(struct ctl_scsiio *ctsio)
6958 {
6959         struct scsi_read_defect_data_10 *ccb10;
6960         struct scsi_read_defect_data_12 *ccb12;
6961         struct scsi_read_defect_data_hdr_10 *data10;
6962         struct scsi_read_defect_data_hdr_12 *data12;
6963         uint32_t alloc_len, data_len;
6964         uint8_t format;
6965
6966         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6967
6968         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6969                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6970                 format = ccb10->format;
6971                 alloc_len = scsi_2btoul(ccb10->alloc_length);
6972                 data_len = sizeof(*data10);
6973         } else {
6974                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6975                 format = ccb12->format;
6976                 alloc_len = scsi_4btoul(ccb12->alloc_length);
6977                 data_len = sizeof(*data12);
6978         }
6979         if (alloc_len == 0) {
6980                 ctl_set_success(ctsio);
6981                 ctl_done((union ctl_io *)ctsio);
6982                 return (CTL_RETVAL_COMPLETE);
6983         }
6984
6985         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
6986         if (data_len < alloc_len) {
6987                 ctsio->residual = alloc_len - data_len;
6988                 ctsio->kern_data_len = data_len;
6989                 ctsio->kern_total_len = data_len;
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         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7000                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7001                     ctsio->kern_data_ptr;
7002                 data10->format = format;
7003                 scsi_ulto2b(0, data10->length);
7004         } else {
7005                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7006                     ctsio->kern_data_ptr;
7007                 data12->format = format;
7008                 scsi_ulto2b(0, data12->generation);
7009                 scsi_ulto4b(0, data12->length);
7010         }
7011
7012         ctl_set_success(ctsio);
7013         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7014         ctsio->be_move_done = ctl_config_move_done;
7015         ctl_datamove((union ctl_io *)ctsio);
7016         return (CTL_RETVAL_COMPLETE);
7017 }
7018
7019 int
7020 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7021 {
7022         struct scsi_maintenance_in *cdb;
7023         int retval;
7024         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7025         int num_target_port_groups, num_target_ports;
7026         struct ctl_lun *lun;
7027         struct ctl_softc *softc;
7028         struct ctl_port *port;
7029         struct scsi_target_group_data *rtg_ptr;
7030         struct scsi_target_group_data_extended *rtg_ext_ptr;
7031         struct scsi_target_port_group_descriptor *tpg_desc;
7032
7033         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7034
7035         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7036         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7037         softc = lun->ctl_softc;
7038
7039         retval = CTL_RETVAL_COMPLETE;
7040
7041         switch (cdb->byte2 & STG_PDF_MASK) {
7042         case STG_PDF_LENGTH:
7043                 ext = 0;
7044                 break;
7045         case STG_PDF_EXTENDED:
7046                 ext = 1;
7047                 break;
7048         default:
7049                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7050                                       /*sks_valid*/ 1,
7051                                       /*command*/ 1,
7052                                       /*field*/ 2,
7053                                       /*bit_valid*/ 1,
7054                                       /*bit*/ 5);
7055                 ctl_done((union ctl_io *)ctsio);
7056                 return(retval);
7057         }
7058
7059         if (softc->is_single)
7060                 num_target_port_groups = 1;
7061         else
7062                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7063         num_target_ports = 0;
7064         mtx_lock(&softc->ctl_lock);
7065         STAILQ_FOREACH(port, &softc->port_list, links) {
7066                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7067                         continue;
7068                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7069                         continue;
7070                 num_target_ports++;
7071         }
7072         mtx_unlock(&softc->ctl_lock);
7073
7074         if (ext)
7075                 total_len = sizeof(struct scsi_target_group_data_extended);
7076         else
7077                 total_len = sizeof(struct scsi_target_group_data);
7078         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7079                 num_target_port_groups +
7080             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7081
7082         alloc_len = scsi_4btoul(cdb->length);
7083
7084         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7085
7086         ctsio->kern_sg_entries = 0;
7087
7088         if (total_len < alloc_len) {
7089                 ctsio->residual = alloc_len - total_len;
7090                 ctsio->kern_data_len = total_len;
7091                 ctsio->kern_total_len = total_len;
7092         } else {
7093                 ctsio->residual = 0;
7094                 ctsio->kern_data_len = alloc_len;
7095                 ctsio->kern_total_len = alloc_len;
7096         }
7097         ctsio->kern_data_resid = 0;
7098         ctsio->kern_rel_offset = 0;
7099
7100         if (ext) {
7101                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7102                     ctsio->kern_data_ptr;
7103                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7104                 rtg_ext_ptr->format_type = 0x10;
7105                 rtg_ext_ptr->implicit_transition_time = 0;
7106                 tpg_desc = &rtg_ext_ptr->groups[0];
7107         } else {
7108                 rtg_ptr = (struct scsi_target_group_data *)
7109                     ctsio->kern_data_ptr;
7110                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7111                 tpg_desc = &rtg_ptr->groups[0];
7112         }
7113
7114         mtx_lock(&softc->ctl_lock);
7115         pg = softc->port_min / softc->port_cnt;
7116         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7117                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7118         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7119                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7120         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7121                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7122         else
7123                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7124         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7125                 os = gs;
7126                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7127         } else
7128                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7129         for (g = 0; g < num_target_port_groups; g++) {
7130                 tpg_desc->pref_state = (g == pg) ? gs : os;
7131                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7132                     TPG_U_SUP | TPG_T_SUP;
7133                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7134                 tpg_desc->status = TPG_IMPLICIT;
7135                 pc = 0;
7136                 STAILQ_FOREACH(port, &softc->port_list, links) {
7137                         if (port->targ_port < g * softc->port_cnt ||
7138                             port->targ_port >= (g + 1) * softc->port_cnt)
7139                                 continue;
7140                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7141                                 continue;
7142                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7143                                 continue;
7144                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7145                             relative_target_port_identifier);
7146                         pc++;
7147                 }
7148                 tpg_desc->target_port_count = pc;
7149                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7150                     &tpg_desc->descriptors[pc];
7151         }
7152         mtx_unlock(&softc->ctl_lock);
7153
7154         ctl_set_success(ctsio);
7155         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7156         ctsio->be_move_done = ctl_config_move_done;
7157         ctl_datamove((union ctl_io *)ctsio);
7158         return(retval);
7159 }
7160
7161 int
7162 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7163 {
7164         struct ctl_lun *lun;
7165         struct scsi_report_supported_opcodes *cdb;
7166         const struct ctl_cmd_entry *entry, *sentry;
7167         struct scsi_report_supported_opcodes_all *all;
7168         struct scsi_report_supported_opcodes_descr *descr;
7169         struct scsi_report_supported_opcodes_one *one;
7170         int retval;
7171         int alloc_len, total_len;
7172         int opcode, service_action, i, j, num;
7173
7174         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7175
7176         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7177         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7178
7179         retval = CTL_RETVAL_COMPLETE;
7180
7181         opcode = cdb->requested_opcode;
7182         service_action = scsi_2btoul(cdb->requested_service_action);
7183         switch (cdb->options & RSO_OPTIONS_MASK) {
7184         case RSO_OPTIONS_ALL:
7185                 num = 0;
7186                 for (i = 0; i < 256; i++) {
7187                         entry = &ctl_cmd_table[i];
7188                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7189                                 for (j = 0; j < 32; j++) {
7190                                         sentry = &((const struct ctl_cmd_entry *)
7191                                             entry->execute)[j];
7192                                         if (ctl_cmd_applicable(
7193                                             lun->be_lun->lun_type, sentry))
7194                                                 num++;
7195                                 }
7196                         } else {
7197                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7198                                     entry))
7199                                         num++;
7200                         }
7201                 }
7202                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7203                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7204                 break;
7205         case RSO_OPTIONS_OC:
7206                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7207                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7208                                               /*sks_valid*/ 1,
7209                                               /*command*/ 1,
7210                                               /*field*/ 2,
7211                                               /*bit_valid*/ 1,
7212                                               /*bit*/ 2);
7213                         ctl_done((union ctl_io *)ctsio);
7214                         return (CTL_RETVAL_COMPLETE);
7215                 }
7216                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7217                 break;
7218         case RSO_OPTIONS_OC_SA:
7219                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7220                     service_action >= 32) {
7221                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7222                                               /*sks_valid*/ 1,
7223                                               /*command*/ 1,
7224                                               /*field*/ 2,
7225                                               /*bit_valid*/ 1,
7226                                               /*bit*/ 2);
7227                         ctl_done((union ctl_io *)ctsio);
7228                         return (CTL_RETVAL_COMPLETE);
7229                 }
7230                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7231                 break;
7232         default:
7233                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7234                                       /*sks_valid*/ 1,
7235                                       /*command*/ 1,
7236                                       /*field*/ 2,
7237                                       /*bit_valid*/ 1,
7238                                       /*bit*/ 2);
7239                 ctl_done((union ctl_io *)ctsio);
7240                 return (CTL_RETVAL_COMPLETE);
7241         }
7242
7243         alloc_len = scsi_4btoul(cdb->length);
7244
7245         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7246
7247         ctsio->kern_sg_entries = 0;
7248
7249         if (total_len < alloc_len) {
7250                 ctsio->residual = alloc_len - total_len;
7251                 ctsio->kern_data_len = total_len;
7252                 ctsio->kern_total_len = total_len;
7253         } else {
7254                 ctsio->residual = 0;
7255                 ctsio->kern_data_len = alloc_len;
7256                 ctsio->kern_total_len = alloc_len;
7257         }
7258         ctsio->kern_data_resid = 0;
7259         ctsio->kern_rel_offset = 0;
7260
7261         switch (cdb->options & RSO_OPTIONS_MASK) {
7262         case RSO_OPTIONS_ALL:
7263                 all = (struct scsi_report_supported_opcodes_all *)
7264                     ctsio->kern_data_ptr;
7265                 num = 0;
7266                 for (i = 0; i < 256; i++) {
7267                         entry = &ctl_cmd_table[i];
7268                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7269                                 for (j = 0; j < 32; j++) {
7270                                         sentry = &((const struct ctl_cmd_entry *)
7271                                             entry->execute)[j];
7272                                         if (!ctl_cmd_applicable(
7273                                             lun->be_lun->lun_type, sentry))
7274                                                 continue;
7275                                         descr = &all->descr[num++];
7276                                         descr->opcode = i;
7277                                         scsi_ulto2b(j, descr->service_action);
7278                                         descr->flags = RSO_SERVACTV;
7279                                         scsi_ulto2b(sentry->length,
7280                                             descr->cdb_length);
7281                                 }
7282                         } else {
7283                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7284                                     entry))
7285                                         continue;
7286                                 descr = &all->descr[num++];
7287                                 descr->opcode = i;
7288                                 scsi_ulto2b(0, descr->service_action);
7289                                 descr->flags = 0;
7290                                 scsi_ulto2b(entry->length, descr->cdb_length);
7291                         }
7292                 }
7293                 scsi_ulto4b(
7294                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7295                     all->length);
7296                 break;
7297         case RSO_OPTIONS_OC:
7298                 one = (struct scsi_report_supported_opcodes_one *)
7299                     ctsio->kern_data_ptr;
7300                 entry = &ctl_cmd_table[opcode];
7301                 goto fill_one;
7302         case RSO_OPTIONS_OC_SA:
7303                 one = (struct scsi_report_supported_opcodes_one *)
7304                     ctsio->kern_data_ptr;
7305                 entry = &ctl_cmd_table[opcode];
7306                 entry = &((const struct ctl_cmd_entry *)
7307                     entry->execute)[service_action];
7308 fill_one:
7309                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7310                         one->support = 3;
7311                         scsi_ulto2b(entry->length, one->cdb_length);
7312                         one->cdb_usage[0] = opcode;
7313                         memcpy(&one->cdb_usage[1], entry->usage,
7314                             entry->length - 1);
7315                 } else
7316                         one->support = 1;
7317                 break;
7318         }
7319
7320         ctl_set_success(ctsio);
7321         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7322         ctsio->be_move_done = ctl_config_move_done;
7323         ctl_datamove((union ctl_io *)ctsio);
7324         return(retval);
7325 }
7326
7327 int
7328 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7329 {
7330         struct scsi_report_supported_tmf *cdb;
7331         struct scsi_report_supported_tmf_data *data;
7332         int retval;
7333         int alloc_len, total_len;
7334
7335         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7336
7337         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7338
7339         retval = CTL_RETVAL_COMPLETE;
7340
7341         total_len = sizeof(struct scsi_report_supported_tmf_data);
7342         alloc_len = scsi_4btoul(cdb->length);
7343
7344         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7345
7346         ctsio->kern_sg_entries = 0;
7347
7348         if (total_len < alloc_len) {
7349                 ctsio->residual = alloc_len - total_len;
7350                 ctsio->kern_data_len = total_len;
7351                 ctsio->kern_total_len = total_len;
7352         } else {
7353                 ctsio->residual = 0;
7354                 ctsio->kern_data_len = alloc_len;
7355                 ctsio->kern_total_len = alloc_len;
7356         }
7357         ctsio->kern_data_resid = 0;
7358         ctsio->kern_rel_offset = 0;
7359
7360         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7361         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7362         data->byte2 |= RST_ITNRS;
7363
7364         ctl_set_success(ctsio);
7365         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7366         ctsio->be_move_done = ctl_config_move_done;
7367         ctl_datamove((union ctl_io *)ctsio);
7368         return (retval);
7369 }
7370
7371 int
7372 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7373 {
7374         struct scsi_report_timestamp *cdb;
7375         struct scsi_report_timestamp_data *data;
7376         struct timeval tv;
7377         int64_t timestamp;
7378         int retval;
7379         int alloc_len, total_len;
7380
7381         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7382
7383         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7384
7385         retval = CTL_RETVAL_COMPLETE;
7386
7387         total_len = sizeof(struct scsi_report_timestamp_data);
7388         alloc_len = scsi_4btoul(cdb->length);
7389
7390         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7391
7392         ctsio->kern_sg_entries = 0;
7393
7394         if (total_len < alloc_len) {
7395                 ctsio->residual = alloc_len - total_len;
7396                 ctsio->kern_data_len = total_len;
7397                 ctsio->kern_total_len = total_len;
7398         } else {
7399                 ctsio->residual = 0;
7400                 ctsio->kern_data_len = alloc_len;
7401                 ctsio->kern_total_len = alloc_len;
7402         }
7403         ctsio->kern_data_resid = 0;
7404         ctsio->kern_rel_offset = 0;
7405
7406         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7407         scsi_ulto2b(sizeof(*data) - 2, data->length);
7408         data->origin = RTS_ORIG_OUTSIDE;
7409         getmicrotime(&tv);
7410         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7411         scsi_ulto4b(timestamp >> 16, data->timestamp);
7412         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7413
7414         ctl_set_success(ctsio);
7415         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7416         ctsio->be_move_done = ctl_config_move_done;
7417         ctl_datamove((union ctl_io *)ctsio);
7418         return (retval);
7419 }
7420
7421 int
7422 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7423 {
7424         struct scsi_per_res_in *cdb;
7425         int alloc_len, total_len = 0;
7426         /* struct scsi_per_res_in_rsrv in_data; */
7427         struct ctl_lun *lun;
7428         struct ctl_softc *softc;
7429         uint64_t key;
7430
7431         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7432
7433         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7434
7435         alloc_len = scsi_2btoul(cdb->length);
7436
7437         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7438         softc = lun->ctl_softc;
7439
7440 retry:
7441         mtx_lock(&lun->lun_lock);
7442         switch (cdb->action) {
7443         case SPRI_RK: /* read keys */
7444                 total_len = sizeof(struct scsi_per_res_in_keys) +
7445                         lun->pr_key_count *
7446                         sizeof(struct scsi_per_res_key);
7447                 break;
7448         case SPRI_RR: /* read reservation */
7449                 if (lun->flags & CTL_LUN_PR_RESERVED)
7450                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7451                 else
7452                         total_len = sizeof(struct scsi_per_res_in_header);
7453                 break;
7454         case SPRI_RC: /* report capabilities */
7455                 total_len = sizeof(struct scsi_per_res_cap);
7456                 break;
7457         case SPRI_RS: /* read full status */
7458                 total_len = sizeof(struct scsi_per_res_in_header) +
7459                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7460                     lun->pr_key_count;
7461                 break;
7462         default:
7463                 panic("Invalid PR type %x", cdb->action);
7464         }
7465         mtx_unlock(&lun->lun_lock);
7466
7467         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7468
7469         if (total_len < alloc_len) {
7470                 ctsio->residual = alloc_len - total_len;
7471                 ctsio->kern_data_len = total_len;
7472                 ctsio->kern_total_len = total_len;
7473         } else {
7474                 ctsio->residual = 0;
7475                 ctsio->kern_data_len = alloc_len;
7476                 ctsio->kern_total_len = alloc_len;
7477         }
7478
7479         ctsio->kern_data_resid = 0;
7480         ctsio->kern_rel_offset = 0;
7481         ctsio->kern_sg_entries = 0;
7482
7483         mtx_lock(&lun->lun_lock);
7484         switch (cdb->action) {
7485         case SPRI_RK: { // read keys
7486         struct scsi_per_res_in_keys *res_keys;
7487                 int i, key_count;
7488
7489                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7490
7491                 /*
7492                  * We had to drop the lock to allocate our buffer, which
7493                  * leaves time for someone to come in with another
7494                  * persistent reservation.  (That is unlikely, though,
7495                  * since this should be the only persistent reservation
7496                  * command active right now.)
7497                  */
7498                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7499                     (lun->pr_key_count *
7500                      sizeof(struct scsi_per_res_key)))){
7501                         mtx_unlock(&lun->lun_lock);
7502                         free(ctsio->kern_data_ptr, M_CTL);
7503                         printf("%s: reservation length changed, retrying\n",
7504                                __func__);
7505                         goto retry;
7506                 }
7507
7508                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7509
7510                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7511                              lun->pr_key_count, res_keys->header.length);
7512
7513                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7514                         if ((key = ctl_get_prkey(lun, i)) == 0)
7515                                 continue;
7516
7517                         /*
7518                          * We used lun->pr_key_count to calculate the
7519                          * size to allocate.  If it turns out the number of
7520                          * initiators with the registered flag set is
7521                          * larger than that (i.e. they haven't been kept in
7522                          * sync), we've got a problem.
7523                          */
7524                         if (key_count >= lun->pr_key_count) {
7525 #ifdef NEEDTOPORT
7526                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7527                                             CTL_PR_ERROR,
7528                                             csevent_LogType_Fault,
7529                                             csevent_AlertLevel_Yellow,
7530                                             csevent_FRU_ShelfController,
7531                                             csevent_FRU_Firmware,
7532                                         csevent_FRU_Unknown,
7533                                             "registered keys %d >= key "
7534                                             "count %d", key_count,
7535                                             lun->pr_key_count);
7536 #endif
7537                                 key_count++;
7538                                 continue;
7539                         }
7540                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7541                         key_count++;
7542                 }
7543                 break;
7544         }
7545         case SPRI_RR: { // read reservation
7546                 struct scsi_per_res_in_rsrv *res;
7547                 int tmp_len, header_only;
7548
7549                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7550
7551                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7552
7553                 if (lun->flags & CTL_LUN_PR_RESERVED)
7554                 {
7555                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7556                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7557                                     res->header.length);
7558                         header_only = 0;
7559                 } else {
7560                         tmp_len = sizeof(struct scsi_per_res_in_header);
7561                         scsi_ulto4b(0, res->header.length);
7562                         header_only = 1;
7563                 }
7564
7565                 /*
7566                  * We had to drop the lock to allocate our buffer, which
7567                  * leaves time for someone to come in with another
7568                  * persistent reservation.  (That is unlikely, though,
7569                  * since this should be the only persistent reservation
7570                  * command active right now.)
7571                  */
7572                 if (tmp_len != total_len) {
7573                         mtx_unlock(&lun->lun_lock);
7574                         free(ctsio->kern_data_ptr, M_CTL);
7575                         printf("%s: reservation status changed, retrying\n",
7576                                __func__);
7577                         goto retry;
7578                 }
7579
7580                 /*
7581                  * No reservation held, so we're done.
7582                  */
7583                 if (header_only != 0)
7584                         break;
7585
7586                 /*
7587                  * If the registration is an All Registrants type, the key
7588                  * is 0, since it doesn't really matter.
7589                  */
7590                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7591                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7592                             res->data.reservation);
7593                 }
7594                 res->data.scopetype = lun->res_type;
7595                 break;
7596         }
7597         case SPRI_RC:     //report capabilities
7598         {
7599                 struct scsi_per_res_cap *res_cap;
7600                 uint16_t type_mask;
7601
7602                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7603                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7604                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7605                 type_mask = SPRI_TM_WR_EX_AR |
7606                             SPRI_TM_EX_AC_RO |
7607                             SPRI_TM_WR_EX_RO |
7608                             SPRI_TM_EX_AC |
7609                             SPRI_TM_WR_EX |
7610                             SPRI_TM_EX_AC_AR;
7611                 scsi_ulto2b(type_mask, res_cap->type_mask);
7612                 break;
7613         }
7614         case SPRI_RS: { // read full status
7615                 struct scsi_per_res_in_full *res_status;
7616                 struct scsi_per_res_in_full_desc *res_desc;
7617                 struct ctl_port *port;
7618                 int i, len;
7619
7620                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7621
7622                 /*
7623                  * We had to drop the lock to allocate our buffer, which
7624                  * leaves time for someone to come in with another
7625                  * persistent reservation.  (That is unlikely, though,
7626                  * since this should be the only persistent reservation
7627                  * command active right now.)
7628                  */
7629                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7630                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7631                      lun->pr_key_count)){
7632                         mtx_unlock(&lun->lun_lock);
7633                         free(ctsio->kern_data_ptr, M_CTL);
7634                         printf("%s: reservation length changed, retrying\n",
7635                                __func__);
7636                         goto retry;
7637                 }
7638
7639                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7640
7641                 res_desc = &res_status->desc[0];
7642                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7643                         if ((key = ctl_get_prkey(lun, i)) == 0)
7644                                 continue;
7645
7646                         scsi_u64to8b(key, res_desc->res_key.key);
7647                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7648                             (lun->pr_res_idx == i ||
7649                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7650                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7651                                 res_desc->scopetype = lun->res_type;
7652                         }
7653                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7654                             res_desc->rel_trgt_port_id);
7655                         len = 0;
7656                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7657                         if (port != NULL)
7658                                 len = ctl_create_iid(port,
7659                                     i % CTL_MAX_INIT_PER_PORT,
7660                                     res_desc->transport_id);
7661                         scsi_ulto4b(len, res_desc->additional_length);
7662                         res_desc = (struct scsi_per_res_in_full_desc *)
7663                             &res_desc->transport_id[len];
7664                 }
7665                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7666                     res_status->header.length);
7667                 break;
7668         }
7669         default:
7670                 /*
7671                  * This is a bug, because we just checked for this above,
7672                  * and should have returned an error.
7673                  */
7674                 panic("Invalid PR type %x", cdb->action);
7675                 break; /* NOTREACHED */
7676         }
7677         mtx_unlock(&lun->lun_lock);
7678
7679         ctl_set_success(ctsio);
7680         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7681         ctsio->be_move_done = ctl_config_move_done;
7682         ctl_datamove((union ctl_io *)ctsio);
7683         return (CTL_RETVAL_COMPLETE);
7684 }
7685
7686 /*
7687  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7688  * it should return.
7689  */
7690 static int
7691 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7692                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7693                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7694                 struct scsi_per_res_out_parms* param)
7695 {
7696         union ctl_ha_msg persis_io;
7697         int i;
7698
7699         mtx_lock(&lun->lun_lock);
7700         if (sa_res_key == 0) {
7701                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7702                         /* validate scope and type */
7703                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7704                              SPR_LU_SCOPE) {
7705                                 mtx_unlock(&lun->lun_lock);
7706                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7707                                                       /*sks_valid*/ 1,
7708                                                       /*command*/ 1,
7709                                                       /*field*/ 2,
7710                                                       /*bit_valid*/ 1,
7711                                                       /*bit*/ 4);
7712                                 ctl_done((union ctl_io *)ctsio);
7713                                 return (1);
7714                         }
7715
7716                         if (type>8 || type==2 || type==4 || type==0) {
7717                                 mtx_unlock(&lun->lun_lock);
7718                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7719                                                       /*sks_valid*/ 1,
7720                                                       /*command*/ 1,
7721                                                       /*field*/ 2,
7722                                                       /*bit_valid*/ 1,
7723                                                       /*bit*/ 0);
7724                                 ctl_done((union ctl_io *)ctsio);
7725                                 return (1);
7726                         }
7727
7728                         /*
7729                          * Unregister everybody else and build UA for
7730                          * them
7731                          */
7732                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7733                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7734                                         continue;
7735
7736                                 ctl_clr_prkey(lun, i);
7737                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7738                         }
7739                         lun->pr_key_count = 1;
7740                         lun->res_type = type;
7741                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7742                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7743                                 lun->pr_res_idx = residx;
7744                         lun->PRGeneration++;
7745                         mtx_unlock(&lun->lun_lock);
7746
7747                         /* send msg to other side */
7748                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7749                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7750                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7751                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7752                         persis_io.pr.pr_info.res_type = type;
7753                         memcpy(persis_io.pr.pr_info.sa_res_key,
7754                                param->serv_act_res_key,
7755                                sizeof(param->serv_act_res_key));
7756                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7757                             sizeof(persis_io.pr), M_WAITOK);
7758                 } else {
7759                         /* not all registrants */
7760                         mtx_unlock(&lun->lun_lock);
7761                         free(ctsio->kern_data_ptr, M_CTL);
7762                         ctl_set_invalid_field(ctsio,
7763                                               /*sks_valid*/ 1,
7764                                               /*command*/ 0,
7765                                               /*field*/ 8,
7766                                               /*bit_valid*/ 0,
7767                                               /*bit*/ 0);
7768                         ctl_done((union ctl_io *)ctsio);
7769                         return (1);
7770                 }
7771         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7772                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7773                 int found = 0;
7774
7775                 if (res_key == sa_res_key) {
7776                         /* special case */
7777                         /*
7778                          * The spec implies this is not good but doesn't
7779                          * say what to do. There are two choices either
7780                          * generate a res conflict or check condition
7781                          * with illegal field in parameter data. Since
7782                          * that is what is done when the sa_res_key is
7783                          * zero I'll take that approach since this has
7784                          * to do with the sa_res_key.
7785                          */
7786                         mtx_unlock(&lun->lun_lock);
7787                         free(ctsio->kern_data_ptr, M_CTL);
7788                         ctl_set_invalid_field(ctsio,
7789                                               /*sks_valid*/ 1,
7790                                               /*command*/ 0,
7791                                               /*field*/ 8,
7792                                               /*bit_valid*/ 0,
7793                                               /*bit*/ 0);
7794                         ctl_done((union ctl_io *)ctsio);
7795                         return (1);
7796                 }
7797
7798                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7799                         if (ctl_get_prkey(lun, i) != sa_res_key)
7800                                 continue;
7801
7802                         found = 1;
7803                         ctl_clr_prkey(lun, i);
7804                         lun->pr_key_count--;
7805                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7806                 }
7807                 if (!found) {
7808                         mtx_unlock(&lun->lun_lock);
7809                         free(ctsio->kern_data_ptr, M_CTL);
7810                         ctl_set_reservation_conflict(ctsio);
7811                         ctl_done((union ctl_io *)ctsio);
7812                         return (CTL_RETVAL_COMPLETE);
7813                 }
7814                 lun->PRGeneration++;
7815                 mtx_unlock(&lun->lun_lock);
7816
7817                 /* send msg to other side */
7818                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7819                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7820                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7821                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7822                 persis_io.pr.pr_info.res_type = type;
7823                 memcpy(persis_io.pr.pr_info.sa_res_key,
7824                        param->serv_act_res_key,
7825                        sizeof(param->serv_act_res_key));
7826                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7827                     sizeof(persis_io.pr), M_WAITOK);
7828         } else {
7829                 /* Reserved but not all registrants */
7830                 /* sa_res_key is res holder */
7831                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7832                         /* validate scope and type */
7833                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7834                              SPR_LU_SCOPE) {
7835                                 mtx_unlock(&lun->lun_lock);
7836                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7837                                                       /*sks_valid*/ 1,
7838                                                       /*command*/ 1,
7839                                                       /*field*/ 2,
7840                                                       /*bit_valid*/ 1,
7841                                                       /*bit*/ 4);
7842                                 ctl_done((union ctl_io *)ctsio);
7843                                 return (1);
7844                         }
7845
7846                         if (type>8 || type==2 || type==4 || type==0) {
7847                                 mtx_unlock(&lun->lun_lock);
7848                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7849                                                       /*sks_valid*/ 1,
7850                                                       /*command*/ 1,
7851                                                       /*field*/ 2,
7852                                                       /*bit_valid*/ 1,
7853                                                       /*bit*/ 0);
7854                                 ctl_done((union ctl_io *)ctsio);
7855                                 return (1);
7856                         }
7857
7858                         /*
7859                          * Do the following:
7860                          * if sa_res_key != res_key remove all
7861                          * registrants w/sa_res_key and generate UA
7862                          * for these registrants(Registrations
7863                          * Preempted) if it wasn't an exclusive
7864                          * reservation generate UA(Reservations
7865                          * Preempted) for all other registered nexuses
7866                          * if the type has changed. Establish the new
7867                          * reservation and holder. If res_key and
7868                          * sa_res_key are the same do the above
7869                          * except don't unregister the res holder.
7870                          */
7871
7872                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7873                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7874                                         continue;
7875
7876                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7877                                         ctl_clr_prkey(lun, i);
7878                                         lun->pr_key_count--;
7879                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7880                                 } else if (type != lun->res_type
7881                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
7882                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7883                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7884                                 }
7885                         }
7886                         lun->res_type = type;
7887                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7888                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7889                                 lun->pr_res_idx = residx;
7890                         else
7891                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7892                         lun->PRGeneration++;
7893                         mtx_unlock(&lun->lun_lock);
7894
7895                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7896                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7897                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7898                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7899                         persis_io.pr.pr_info.res_type = type;
7900                         memcpy(persis_io.pr.pr_info.sa_res_key,
7901                                param->serv_act_res_key,
7902                                sizeof(param->serv_act_res_key));
7903                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7904                             sizeof(persis_io.pr), M_WAITOK);
7905                 } else {
7906                         /*
7907                          * sa_res_key is not the res holder just
7908                          * remove registrants
7909                          */
7910                         int found=0;
7911
7912                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7913                                 if (sa_res_key != ctl_get_prkey(lun, i))
7914                                         continue;
7915
7916                                 found = 1;
7917                                 ctl_clr_prkey(lun, i);
7918                                 lun->pr_key_count--;
7919                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7920                         }
7921
7922                         if (!found) {
7923                                 mtx_unlock(&lun->lun_lock);
7924                                 free(ctsio->kern_data_ptr, M_CTL);
7925                                 ctl_set_reservation_conflict(ctsio);
7926                                 ctl_done((union ctl_io *)ctsio);
7927                                 return (1);
7928                         }
7929                         lun->PRGeneration++;
7930                         mtx_unlock(&lun->lun_lock);
7931
7932                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7933                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7934                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7935                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7936                         persis_io.pr.pr_info.res_type = type;
7937                         memcpy(persis_io.pr.pr_info.sa_res_key,
7938                                param->serv_act_res_key,
7939                                sizeof(param->serv_act_res_key));
7940                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7941                             sizeof(persis_io.pr), M_WAITOK);
7942                 }
7943         }
7944         return (0);
7945 }
7946
7947 static void
7948 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7949 {
7950         uint64_t sa_res_key;
7951         int i;
7952
7953         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7954
7955         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7956          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7957          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7958                 if (sa_res_key == 0) {
7959                         /*
7960                          * Unregister everybody else and build UA for
7961                          * them
7962                          */
7963                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7964                                 if (i == msg->pr.pr_info.residx ||
7965                                     ctl_get_prkey(lun, i) == 0)
7966                                         continue;
7967
7968                                 ctl_clr_prkey(lun, i);
7969                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7970                         }
7971
7972                         lun->pr_key_count = 1;
7973                         lun->res_type = msg->pr.pr_info.res_type;
7974                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7975                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7976                                 lun->pr_res_idx = msg->pr.pr_info.residx;
7977                 } else {
7978                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7979                                 if (sa_res_key == ctl_get_prkey(lun, i))
7980                                         continue;
7981
7982                                 ctl_clr_prkey(lun, i);
7983                                 lun->pr_key_count--;
7984                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7985                         }
7986                 }
7987         } else {
7988                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7989                         if (i == msg->pr.pr_info.residx ||
7990                             ctl_get_prkey(lun, i) == 0)
7991                                 continue;
7992
7993                         if (sa_res_key == ctl_get_prkey(lun, i)) {
7994                                 ctl_clr_prkey(lun, i);
7995                                 lun->pr_key_count--;
7996                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7997                         } else if (msg->pr.pr_info.res_type != lun->res_type
7998                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
7999                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8000                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8001                         }
8002                 }
8003                 lun->res_type = msg->pr.pr_info.res_type;
8004                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8005                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8006                         lun->pr_res_idx = msg->pr.pr_info.residx;
8007                 else
8008                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8009         }
8010         lun->PRGeneration++;
8011
8012 }
8013
8014
8015 int
8016 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8017 {
8018         int retval;
8019         u_int32_t param_len;
8020         struct scsi_per_res_out *cdb;
8021         struct ctl_lun *lun;
8022         struct scsi_per_res_out_parms* param;
8023         struct ctl_softc *softc;
8024         uint32_t residx;
8025         uint64_t res_key, sa_res_key, key;
8026         uint8_t type;
8027         union ctl_ha_msg persis_io;
8028         int    i;
8029
8030         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8031
8032         retval = CTL_RETVAL_COMPLETE;
8033
8034         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8035         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8036         softc = lun->ctl_softc;
8037
8038         /*
8039          * We only support whole-LUN scope.  The scope & type are ignored for
8040          * register, register and ignore existing key and clear.
8041          * We sometimes ignore scope and type on preempts too!!
8042          * Verify reservation type here as well.
8043          */
8044         type = cdb->scope_type & SPR_TYPE_MASK;
8045         if ((cdb->action == SPRO_RESERVE)
8046          || (cdb->action == SPRO_RELEASE)) {
8047                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8048                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8049                                               /*sks_valid*/ 1,
8050                                               /*command*/ 1,
8051                                               /*field*/ 2,
8052                                               /*bit_valid*/ 1,
8053                                               /*bit*/ 4);
8054                         ctl_done((union ctl_io *)ctsio);
8055                         return (CTL_RETVAL_COMPLETE);
8056                 }
8057
8058                 if (type>8 || type==2 || type==4 || type==0) {
8059                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8060                                               /*sks_valid*/ 1,
8061                                               /*command*/ 1,
8062                                               /*field*/ 2,
8063                                               /*bit_valid*/ 1,
8064                                               /*bit*/ 0);
8065                         ctl_done((union ctl_io *)ctsio);
8066                         return (CTL_RETVAL_COMPLETE);
8067                 }
8068         }
8069
8070         param_len = scsi_4btoul(cdb->length);
8071
8072         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8073                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8074                 ctsio->kern_data_len = param_len;
8075                 ctsio->kern_total_len = param_len;
8076                 ctsio->kern_data_resid = 0;
8077                 ctsio->kern_rel_offset = 0;
8078                 ctsio->kern_sg_entries = 0;
8079                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8080                 ctsio->be_move_done = ctl_config_move_done;
8081                 ctl_datamove((union ctl_io *)ctsio);
8082
8083                 return (CTL_RETVAL_COMPLETE);
8084         }
8085
8086         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8087
8088         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8089         res_key = scsi_8btou64(param->res_key.key);
8090         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8091
8092         /*
8093          * Validate the reservation key here except for SPRO_REG_IGNO
8094          * This must be done for all other service actions
8095          */
8096         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8097                 mtx_lock(&lun->lun_lock);
8098                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8099                         if (res_key != key) {
8100                                 /*
8101                                  * The current key passed in doesn't match
8102                                  * the one the initiator previously
8103                                  * registered.
8104                                  */
8105                                 mtx_unlock(&lun->lun_lock);
8106                                 free(ctsio->kern_data_ptr, M_CTL);
8107                                 ctl_set_reservation_conflict(ctsio);
8108                                 ctl_done((union ctl_io *)ctsio);
8109                                 return (CTL_RETVAL_COMPLETE);
8110                         }
8111                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8112                         /*
8113                          * We are not registered
8114                          */
8115                         mtx_unlock(&lun->lun_lock);
8116                         free(ctsio->kern_data_ptr, M_CTL);
8117                         ctl_set_reservation_conflict(ctsio);
8118                         ctl_done((union ctl_io *)ctsio);
8119                         return (CTL_RETVAL_COMPLETE);
8120                 } else if (res_key != 0) {
8121                         /*
8122                          * We are not registered and trying to register but
8123                          * the register key isn't zero.
8124                          */
8125                         mtx_unlock(&lun->lun_lock);
8126                         free(ctsio->kern_data_ptr, M_CTL);
8127                         ctl_set_reservation_conflict(ctsio);
8128                         ctl_done((union ctl_io *)ctsio);
8129                         return (CTL_RETVAL_COMPLETE);
8130                 }
8131                 mtx_unlock(&lun->lun_lock);
8132         }
8133
8134         switch (cdb->action & SPRO_ACTION_MASK) {
8135         case SPRO_REGISTER:
8136         case SPRO_REG_IGNO: {
8137
8138 #if 0
8139                 printf("Registration received\n");
8140 #endif
8141
8142                 /*
8143                  * We don't support any of these options, as we report in
8144                  * the read capabilities request (see
8145                  * ctl_persistent_reserve_in(), above).
8146                  */
8147                 if ((param->flags & SPR_SPEC_I_PT)
8148                  || (param->flags & SPR_ALL_TG_PT)
8149                  || (param->flags & SPR_APTPL)) {
8150                         int bit_ptr;
8151
8152                         if (param->flags & SPR_APTPL)
8153                                 bit_ptr = 0;
8154                         else if (param->flags & SPR_ALL_TG_PT)
8155                                 bit_ptr = 2;
8156                         else /* SPR_SPEC_I_PT */
8157                                 bit_ptr = 3;
8158
8159                         free(ctsio->kern_data_ptr, M_CTL);
8160                         ctl_set_invalid_field(ctsio,
8161                                               /*sks_valid*/ 1,
8162                                               /*command*/ 0,
8163                                               /*field*/ 20,
8164                                               /*bit_valid*/ 1,
8165                                               /*bit*/ bit_ptr);
8166                         ctl_done((union ctl_io *)ctsio);
8167                         return (CTL_RETVAL_COMPLETE);
8168                 }
8169
8170                 mtx_lock(&lun->lun_lock);
8171
8172                 /*
8173                  * The initiator wants to clear the
8174                  * key/unregister.
8175                  */
8176                 if (sa_res_key == 0) {
8177                         if ((res_key == 0
8178                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8179                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8180                           && ctl_get_prkey(lun, residx) == 0)) {
8181                                 mtx_unlock(&lun->lun_lock);
8182                                 goto done;
8183                         }
8184
8185                         ctl_clr_prkey(lun, residx);
8186                         lun->pr_key_count--;
8187
8188                         if (residx == lun->pr_res_idx) {
8189                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8190                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8191
8192                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8193                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8194                                  && lun->pr_key_count) {
8195                                         /*
8196                                          * If the reservation is a registrants
8197                                          * only type we need to generate a UA
8198                                          * for other registered inits.  The
8199                                          * sense code should be RESERVATIONS
8200                                          * RELEASED
8201                                          */
8202
8203                                         for (i = softc->init_min; i < softc->init_max; i++){
8204                                                 if (ctl_get_prkey(lun, i) == 0)
8205                                                         continue;
8206                                                 ctl_est_ua(lun, i,
8207                                                     CTL_UA_RES_RELEASE);
8208                                         }
8209                                 }
8210                                 lun->res_type = 0;
8211                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8212                                 if (lun->pr_key_count==0) {
8213                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8214                                         lun->res_type = 0;
8215                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8216                                 }
8217                         }
8218                         lun->PRGeneration++;
8219                         mtx_unlock(&lun->lun_lock);
8220
8221                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8222                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8223                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8224                         persis_io.pr.pr_info.residx = residx;
8225                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8226                             sizeof(persis_io.pr), M_WAITOK);
8227                 } else /* sa_res_key != 0 */ {
8228
8229                         /*
8230                          * If we aren't registered currently then increment
8231                          * the key count and set the registered flag.
8232                          */
8233                         ctl_alloc_prkey(lun, residx);
8234                         if (ctl_get_prkey(lun, residx) == 0)
8235                                 lun->pr_key_count++;
8236                         ctl_set_prkey(lun, residx, sa_res_key);
8237                         lun->PRGeneration++;
8238                         mtx_unlock(&lun->lun_lock);
8239
8240                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8241                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8242                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8243                         persis_io.pr.pr_info.residx = residx;
8244                         memcpy(persis_io.pr.pr_info.sa_res_key,
8245                                param->serv_act_res_key,
8246                                sizeof(param->serv_act_res_key));
8247                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8248                             sizeof(persis_io.pr), M_WAITOK);
8249                 }
8250
8251                 break;
8252         }
8253         case SPRO_RESERVE:
8254 #if 0
8255                 printf("Reserve executed type %d\n", type);
8256 #endif
8257                 mtx_lock(&lun->lun_lock);
8258                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8259                         /*
8260                          * if this isn't the reservation holder and it's
8261                          * not a "all registrants" type or if the type is
8262                          * different then we have a conflict
8263                          */
8264                         if ((lun->pr_res_idx != residx
8265                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8266                          || lun->res_type != type) {
8267                                 mtx_unlock(&lun->lun_lock);
8268                                 free(ctsio->kern_data_ptr, M_CTL);
8269                                 ctl_set_reservation_conflict(ctsio);
8270                                 ctl_done((union ctl_io *)ctsio);
8271                                 return (CTL_RETVAL_COMPLETE);
8272                         }
8273                         mtx_unlock(&lun->lun_lock);
8274                 } else /* create a reservation */ {
8275                         /*
8276                          * If it's not an "all registrants" type record
8277                          * reservation holder
8278                          */
8279                         if (type != SPR_TYPE_WR_EX_AR
8280                          && type != SPR_TYPE_EX_AC_AR)
8281                                 lun->pr_res_idx = residx; /* Res holder */
8282                         else
8283                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8284
8285                         lun->flags |= CTL_LUN_PR_RESERVED;
8286                         lun->res_type = type;
8287
8288                         mtx_unlock(&lun->lun_lock);
8289
8290                         /* send msg to other side */
8291                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8292                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8293                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8294                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8295                         persis_io.pr.pr_info.res_type = type;
8296                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8297                             sizeof(persis_io.pr), M_WAITOK);
8298                 }
8299                 break;
8300
8301         case SPRO_RELEASE:
8302                 mtx_lock(&lun->lun_lock);
8303                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8304                         /* No reservation exists return good status */
8305                         mtx_unlock(&lun->lun_lock);
8306                         goto done;
8307                 }
8308                 /*
8309                  * Is this nexus a reservation holder?
8310                  */
8311                 if (lun->pr_res_idx != residx
8312                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8313                         /*
8314                          * not a res holder return good status but
8315                          * do nothing
8316                          */
8317                         mtx_unlock(&lun->lun_lock);
8318                         goto done;
8319                 }
8320
8321                 if (lun->res_type != type) {
8322                         mtx_unlock(&lun->lun_lock);
8323                         free(ctsio->kern_data_ptr, M_CTL);
8324                         ctl_set_illegal_pr_release(ctsio);
8325                         ctl_done((union ctl_io *)ctsio);
8326                         return (CTL_RETVAL_COMPLETE);
8327                 }
8328
8329                 /* okay to release */
8330                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8331                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8332                 lun->res_type = 0;
8333
8334                 /*
8335                  * if this isn't an exclusive access
8336                  * res generate UA for all other
8337                  * registrants.
8338                  */
8339                 if (type != SPR_TYPE_EX_AC
8340                  && type != SPR_TYPE_WR_EX) {
8341                         for (i = softc->init_min; i < softc->init_max; i++) {
8342                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8343                                         continue;
8344                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8345                         }
8346                 }
8347                 mtx_unlock(&lun->lun_lock);
8348
8349                 /* Send msg to other side */
8350                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8351                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8352                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8353                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8354                      sizeof(persis_io.pr), M_WAITOK);
8355                 break;
8356
8357         case SPRO_CLEAR:
8358                 /* send msg to other side */
8359
8360                 mtx_lock(&lun->lun_lock);
8361                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8362                 lun->res_type = 0;
8363                 lun->pr_key_count = 0;
8364                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8365
8366                 ctl_clr_prkey(lun, residx);
8367                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8368                         if (ctl_get_prkey(lun, i) != 0) {
8369                                 ctl_clr_prkey(lun, i);
8370                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8371                         }
8372                 lun->PRGeneration++;
8373                 mtx_unlock(&lun->lun_lock);
8374
8375                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8376                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8377                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8378                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8379                      sizeof(persis_io.pr), M_WAITOK);
8380                 break;
8381
8382         case SPRO_PREEMPT:
8383         case SPRO_PRE_ABO: {
8384                 int nretval;
8385
8386                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8387                                           residx, ctsio, cdb, param);
8388                 if (nretval != 0)
8389                         return (CTL_RETVAL_COMPLETE);
8390                 break;
8391         }
8392         default:
8393                 panic("Invalid PR type %x", cdb->action);
8394         }
8395
8396 done:
8397         free(ctsio->kern_data_ptr, M_CTL);
8398         ctl_set_success(ctsio);
8399         ctl_done((union ctl_io *)ctsio);
8400
8401         return (retval);
8402 }
8403
8404 /*
8405  * This routine is for handling a message from the other SC pertaining to
8406  * persistent reserve out. All the error checking will have been done
8407  * so only perorming the action need be done here to keep the two
8408  * in sync.
8409  */
8410 static void
8411 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8412 {
8413         struct ctl_lun *lun;
8414         struct ctl_softc *softc;
8415         int i;
8416         uint32_t residx, targ_lun;
8417
8418         softc = control_softc;
8419         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8420         mtx_lock(&softc->ctl_lock);
8421         if ((targ_lun >= CTL_MAX_LUNS) ||
8422             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8423                 mtx_unlock(&softc->ctl_lock);
8424                 return;
8425         }
8426         mtx_lock(&lun->lun_lock);
8427         mtx_unlock(&softc->ctl_lock);
8428         if (lun->flags & CTL_LUN_DISABLED) {
8429                 mtx_unlock(&lun->lun_lock);
8430                 return;
8431         }
8432         residx = ctl_get_initindex(&msg->hdr.nexus);
8433         switch(msg->pr.pr_info.action) {
8434         case CTL_PR_REG_KEY:
8435                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8436                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8437                         lun->pr_key_count++;
8438                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8439                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8440                 lun->PRGeneration++;
8441                 break;
8442
8443         case CTL_PR_UNREG_KEY:
8444                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8445                 lun->pr_key_count--;
8446
8447                 /* XXX Need to see if the reservation has been released */
8448                 /* if so do we need to generate UA? */
8449                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8450                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8451                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8452
8453                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8454                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8455                          && lun->pr_key_count) {
8456                                 /*
8457                                  * If the reservation is a registrants
8458                                  * only type we need to generate a UA
8459                                  * for other registered inits.  The
8460                                  * sense code should be RESERVATIONS
8461                                  * RELEASED
8462                                  */
8463
8464                                 for (i = softc->init_min; i < softc->init_max; i++) {
8465                                         if (ctl_get_prkey(lun, i) == 0)
8466                                                 continue;
8467
8468                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8469                                 }
8470                         }
8471                         lun->res_type = 0;
8472                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8473                         if (lun->pr_key_count==0) {
8474                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8475                                 lun->res_type = 0;
8476                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8477                         }
8478                 }
8479                 lun->PRGeneration++;
8480                 break;
8481
8482         case CTL_PR_RESERVE:
8483                 lun->flags |= CTL_LUN_PR_RESERVED;
8484                 lun->res_type = msg->pr.pr_info.res_type;
8485                 lun->pr_res_idx = msg->pr.pr_info.residx;
8486
8487                 break;
8488
8489         case CTL_PR_RELEASE:
8490                 /*
8491                  * if this isn't an exclusive access res generate UA for all
8492                  * other registrants.
8493                  */
8494                 if (lun->res_type != SPR_TYPE_EX_AC
8495                  && lun->res_type != SPR_TYPE_WR_EX) {
8496                         for (i = softc->init_min; i < softc->init_max; i++)
8497                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8498                                         continue;
8499                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8500                 }
8501
8502                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8503                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8504                 lun->res_type = 0;
8505                 break;
8506
8507         case CTL_PR_PREEMPT:
8508                 ctl_pro_preempt_other(lun, msg);
8509                 break;
8510         case CTL_PR_CLEAR:
8511                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8512                 lun->res_type = 0;
8513                 lun->pr_key_count = 0;
8514                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8515
8516                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8517                         if (ctl_get_prkey(lun, i) == 0)
8518                                 continue;
8519                         ctl_clr_prkey(lun, i);
8520                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8521                 }
8522                 lun->PRGeneration++;
8523                 break;
8524         }
8525
8526         mtx_unlock(&lun->lun_lock);
8527 }
8528
8529 int
8530 ctl_read_write(struct ctl_scsiio *ctsio)
8531 {
8532         struct ctl_lun *lun;
8533         struct ctl_lba_len_flags *lbalen;
8534         uint64_t lba;
8535         uint32_t num_blocks;
8536         int flags, retval;
8537         int isread;
8538
8539         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8540
8541         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8542
8543         flags = 0;
8544         retval = CTL_RETVAL_COMPLETE;
8545
8546         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8547               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8548         switch (ctsio->cdb[0]) {
8549         case READ_6:
8550         case WRITE_6: {
8551                 struct scsi_rw_6 *cdb;
8552
8553                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8554
8555                 lba = scsi_3btoul(cdb->addr);
8556                 /* only 5 bits are valid in the most significant address byte */
8557                 lba &= 0x1fffff;
8558                 num_blocks = cdb->length;
8559                 /*
8560                  * This is correct according to SBC-2.
8561                  */
8562                 if (num_blocks == 0)
8563                         num_blocks = 256;
8564                 break;
8565         }
8566         case READ_10:
8567         case WRITE_10: {
8568                 struct scsi_rw_10 *cdb;
8569
8570                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8571                 if (cdb->byte2 & SRW10_FUA)
8572                         flags |= CTL_LLF_FUA;
8573                 if (cdb->byte2 & SRW10_DPO)
8574                         flags |= CTL_LLF_DPO;
8575                 lba = scsi_4btoul(cdb->addr);
8576                 num_blocks = scsi_2btoul(cdb->length);
8577                 break;
8578         }
8579         case WRITE_VERIFY_10: {
8580                 struct scsi_write_verify_10 *cdb;
8581
8582                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8583                 flags |= CTL_LLF_FUA;
8584                 if (cdb->byte2 & SWV_DPO)
8585                         flags |= CTL_LLF_DPO;
8586                 lba = scsi_4btoul(cdb->addr);
8587                 num_blocks = scsi_2btoul(cdb->length);
8588                 break;
8589         }
8590         case READ_12:
8591         case WRITE_12: {
8592                 struct scsi_rw_12 *cdb;
8593
8594                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8595                 if (cdb->byte2 & SRW12_FUA)
8596                         flags |= CTL_LLF_FUA;
8597                 if (cdb->byte2 & SRW12_DPO)
8598                         flags |= CTL_LLF_DPO;
8599                 lba = scsi_4btoul(cdb->addr);
8600                 num_blocks = scsi_4btoul(cdb->length);
8601                 break;
8602         }
8603         case WRITE_VERIFY_12: {
8604                 struct scsi_write_verify_12 *cdb;
8605
8606                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8607                 flags |= CTL_LLF_FUA;
8608                 if (cdb->byte2 & SWV_DPO)
8609                         flags |= CTL_LLF_DPO;
8610                 lba = scsi_4btoul(cdb->addr);
8611                 num_blocks = scsi_4btoul(cdb->length);
8612                 break;
8613         }
8614         case READ_16:
8615         case WRITE_16: {
8616                 struct scsi_rw_16 *cdb;
8617
8618                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8619                 if (cdb->byte2 & SRW12_FUA)
8620                         flags |= CTL_LLF_FUA;
8621                 if (cdb->byte2 & SRW12_DPO)
8622                         flags |= CTL_LLF_DPO;
8623                 lba = scsi_8btou64(cdb->addr);
8624                 num_blocks = scsi_4btoul(cdb->length);
8625                 break;
8626         }
8627         case WRITE_ATOMIC_16: {
8628                 struct scsi_rw_16 *cdb;
8629
8630                 if (lun->be_lun->atomicblock == 0) {
8631                         ctl_set_invalid_opcode(ctsio);
8632                         ctl_done((union ctl_io *)ctsio);
8633                         return (CTL_RETVAL_COMPLETE);
8634                 }
8635
8636                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8637                 if (cdb->byte2 & SRW12_FUA)
8638                         flags |= CTL_LLF_FUA;
8639                 if (cdb->byte2 & SRW12_DPO)
8640                         flags |= CTL_LLF_DPO;
8641                 lba = scsi_8btou64(cdb->addr);
8642                 num_blocks = scsi_4btoul(cdb->length);
8643                 if (num_blocks > lun->be_lun->atomicblock) {
8644                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8645                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8646                             /*bit*/ 0);
8647                         ctl_done((union ctl_io *)ctsio);
8648                         return (CTL_RETVAL_COMPLETE);
8649                 }
8650                 break;
8651         }
8652         case WRITE_VERIFY_16: {
8653                 struct scsi_write_verify_16 *cdb;
8654
8655                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8656                 flags |= CTL_LLF_FUA;
8657                 if (cdb->byte2 & SWV_DPO)
8658                         flags |= CTL_LLF_DPO;
8659                 lba = scsi_8btou64(cdb->addr);
8660                 num_blocks = scsi_4btoul(cdb->length);
8661                 break;
8662         }
8663         default:
8664                 /*
8665                  * We got a command we don't support.  This shouldn't
8666                  * happen, commands should be filtered out above us.
8667                  */
8668                 ctl_set_invalid_opcode(ctsio);
8669                 ctl_done((union ctl_io *)ctsio);
8670
8671                 return (CTL_RETVAL_COMPLETE);
8672                 break; /* NOTREACHED */
8673         }
8674
8675         /*
8676          * The first check is to make sure we're in bounds, the second
8677          * check is to catch wrap-around problems.  If the lba + num blocks
8678          * is less than the lba, then we've wrapped around and the block
8679          * range is invalid anyway.
8680          */
8681         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8682          || ((lba + num_blocks) < lba)) {
8683                 ctl_set_lba_out_of_range(ctsio);
8684                 ctl_done((union ctl_io *)ctsio);
8685                 return (CTL_RETVAL_COMPLETE);
8686         }
8687
8688         /*
8689          * According to SBC-3, a transfer length of 0 is not an error.
8690          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8691          * translates to 256 blocks for those commands.
8692          */
8693         if (num_blocks == 0) {
8694                 ctl_set_success(ctsio);
8695                 ctl_done((union ctl_io *)ctsio);
8696                 return (CTL_RETVAL_COMPLETE);
8697         }
8698
8699         /* Set FUA and/or DPO if caches are disabled. */
8700         if (isread) {
8701                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8702                     SCP_RCD) != 0)
8703                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8704         } else {
8705                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8706                     SCP_WCE) == 0)
8707                         flags |= CTL_LLF_FUA;
8708         }
8709
8710         lbalen = (struct ctl_lba_len_flags *)
8711             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8712         lbalen->lba = lba;
8713         lbalen->len = num_blocks;
8714         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8715
8716         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8717         ctsio->kern_rel_offset = 0;
8718
8719         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8720
8721         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8722
8723         return (retval);
8724 }
8725
8726 static int
8727 ctl_cnw_cont(union ctl_io *io)
8728 {
8729         struct ctl_scsiio *ctsio;
8730         struct ctl_lun *lun;
8731         struct ctl_lba_len_flags *lbalen;
8732         int retval;
8733
8734         ctsio = &io->scsiio;
8735         ctsio->io_hdr.status = CTL_STATUS_NONE;
8736         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8737         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8738         lbalen = (struct ctl_lba_len_flags *)
8739             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8740         lbalen->flags &= ~CTL_LLF_COMPARE;
8741         lbalen->flags |= CTL_LLF_WRITE;
8742
8743         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8744         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8745         return (retval);
8746 }
8747
8748 int
8749 ctl_cnw(struct ctl_scsiio *ctsio)
8750 {
8751         struct ctl_lun *lun;
8752         struct ctl_lba_len_flags *lbalen;
8753         uint64_t lba;
8754         uint32_t num_blocks;
8755         int flags, retval;
8756
8757         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8758
8759         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8760
8761         flags = 0;
8762         retval = CTL_RETVAL_COMPLETE;
8763
8764         switch (ctsio->cdb[0]) {
8765         case COMPARE_AND_WRITE: {
8766                 struct scsi_compare_and_write *cdb;
8767
8768                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8769                 if (cdb->byte2 & SRW10_FUA)
8770                         flags |= CTL_LLF_FUA;
8771                 if (cdb->byte2 & SRW10_DPO)
8772                         flags |= CTL_LLF_DPO;
8773                 lba = scsi_8btou64(cdb->addr);
8774                 num_blocks = cdb->length;
8775                 break;
8776         }
8777         default:
8778                 /*
8779                  * We got a command we don't support.  This shouldn't
8780                  * happen, commands should be filtered out above us.
8781                  */
8782                 ctl_set_invalid_opcode(ctsio);
8783                 ctl_done((union ctl_io *)ctsio);
8784
8785                 return (CTL_RETVAL_COMPLETE);
8786                 break; /* NOTREACHED */
8787         }
8788
8789         /*
8790          * The first check is to make sure we're in bounds, the second
8791          * check is to catch wrap-around problems.  If the lba + num blocks
8792          * is less than the lba, then we've wrapped around and the block
8793          * range is invalid anyway.
8794          */
8795         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8796          || ((lba + num_blocks) < lba)) {
8797                 ctl_set_lba_out_of_range(ctsio);
8798                 ctl_done((union ctl_io *)ctsio);
8799                 return (CTL_RETVAL_COMPLETE);
8800         }
8801
8802         /*
8803          * According to SBC-3, a transfer length of 0 is not an error.
8804          */
8805         if (num_blocks == 0) {
8806                 ctl_set_success(ctsio);
8807                 ctl_done((union ctl_io *)ctsio);
8808                 return (CTL_RETVAL_COMPLETE);
8809         }
8810
8811         /* Set FUA if write cache is disabled. */
8812         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8813             SCP_WCE) == 0)
8814                 flags |= CTL_LLF_FUA;
8815
8816         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8817         ctsio->kern_rel_offset = 0;
8818
8819         /*
8820          * Set the IO_CONT flag, so that if this I/O gets passed to
8821          * ctl_data_submit_done(), it'll get passed back to
8822          * ctl_ctl_cnw_cont() for further processing.
8823          */
8824         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8825         ctsio->io_cont = ctl_cnw_cont;
8826
8827         lbalen = (struct ctl_lba_len_flags *)
8828             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8829         lbalen->lba = lba;
8830         lbalen->len = num_blocks;
8831         lbalen->flags = CTL_LLF_COMPARE | flags;
8832
8833         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8834         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8835         return (retval);
8836 }
8837
8838 int
8839 ctl_verify(struct ctl_scsiio *ctsio)
8840 {
8841         struct ctl_lun *lun;
8842         struct ctl_lba_len_flags *lbalen;
8843         uint64_t lba;
8844         uint32_t num_blocks;
8845         int bytchk, flags;
8846         int retval;
8847
8848         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8849
8850         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8851
8852         bytchk = 0;
8853         flags = CTL_LLF_FUA;
8854         retval = CTL_RETVAL_COMPLETE;
8855
8856         switch (ctsio->cdb[0]) {
8857         case VERIFY_10: {
8858                 struct scsi_verify_10 *cdb;
8859
8860                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8861                 if (cdb->byte2 & SVFY_BYTCHK)
8862                         bytchk = 1;
8863                 if (cdb->byte2 & SVFY_DPO)
8864                         flags |= CTL_LLF_DPO;
8865                 lba = scsi_4btoul(cdb->addr);
8866                 num_blocks = scsi_2btoul(cdb->length);
8867                 break;
8868         }
8869         case VERIFY_12: {
8870                 struct scsi_verify_12 *cdb;
8871
8872                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8873                 if (cdb->byte2 & SVFY_BYTCHK)
8874                         bytchk = 1;
8875                 if (cdb->byte2 & SVFY_DPO)
8876                         flags |= CTL_LLF_DPO;
8877                 lba = scsi_4btoul(cdb->addr);
8878                 num_blocks = scsi_4btoul(cdb->length);
8879                 break;
8880         }
8881         case VERIFY_16: {
8882                 struct scsi_rw_16 *cdb;
8883
8884                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8885                 if (cdb->byte2 & SVFY_BYTCHK)
8886                         bytchk = 1;
8887                 if (cdb->byte2 & SVFY_DPO)
8888                         flags |= CTL_LLF_DPO;
8889                 lba = scsi_8btou64(cdb->addr);
8890                 num_blocks = scsi_4btoul(cdb->length);
8891                 break;
8892         }
8893         default:
8894                 /*
8895                  * We got a command we don't support.  This shouldn't
8896                  * happen, commands should be filtered out above us.
8897                  */
8898                 ctl_set_invalid_opcode(ctsio);
8899                 ctl_done((union ctl_io *)ctsio);
8900                 return (CTL_RETVAL_COMPLETE);
8901         }
8902
8903         /*
8904          * The first check is to make sure we're in bounds, the second
8905          * check is to catch wrap-around problems.  If the lba + num blocks
8906          * is less than the lba, then we've wrapped around and the block
8907          * range is invalid anyway.
8908          */
8909         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8910          || ((lba + num_blocks) < lba)) {
8911                 ctl_set_lba_out_of_range(ctsio);
8912                 ctl_done((union ctl_io *)ctsio);
8913                 return (CTL_RETVAL_COMPLETE);
8914         }
8915
8916         /*
8917          * According to SBC-3, a transfer length of 0 is not an error.
8918          */
8919         if (num_blocks == 0) {
8920                 ctl_set_success(ctsio);
8921                 ctl_done((union ctl_io *)ctsio);
8922                 return (CTL_RETVAL_COMPLETE);
8923         }
8924
8925         lbalen = (struct ctl_lba_len_flags *)
8926             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8927         lbalen->lba = lba;
8928         lbalen->len = num_blocks;
8929         if (bytchk) {
8930                 lbalen->flags = CTL_LLF_COMPARE | flags;
8931                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8932         } else {
8933                 lbalen->flags = CTL_LLF_VERIFY | flags;
8934                 ctsio->kern_total_len = 0;
8935         }
8936         ctsio->kern_rel_offset = 0;
8937
8938         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8939         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8940         return (retval);
8941 }
8942
8943 int
8944 ctl_report_luns(struct ctl_scsiio *ctsio)
8945 {
8946         struct ctl_softc *softc = control_softc;
8947         struct scsi_report_luns *cdb;
8948         struct scsi_report_luns_data *lun_data;
8949         struct ctl_lun *lun, *request_lun;
8950         struct ctl_port *port;
8951         int num_luns, retval;
8952         uint32_t alloc_len, lun_datalen;
8953         int num_filled, well_known;
8954         uint32_t initidx, targ_lun_id, lun_id;
8955
8956         retval = CTL_RETVAL_COMPLETE;
8957         well_known = 0;
8958
8959         cdb = (struct scsi_report_luns *)ctsio->cdb;
8960         port = ctl_io_port(&ctsio->io_hdr);
8961
8962         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8963
8964         mtx_lock(&softc->ctl_lock);
8965         num_luns = 0;
8966         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8967                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8968                         num_luns++;
8969         }
8970         mtx_unlock(&softc->ctl_lock);
8971
8972         switch (cdb->select_report) {
8973         case RPL_REPORT_DEFAULT:
8974         case RPL_REPORT_ALL:
8975                 break;
8976         case RPL_REPORT_WELLKNOWN:
8977                 well_known = 1;
8978                 num_luns = 0;
8979                 break;
8980         default:
8981                 ctl_set_invalid_field(ctsio,
8982                                       /*sks_valid*/ 1,
8983                                       /*command*/ 1,
8984                                       /*field*/ 2,
8985                                       /*bit_valid*/ 0,
8986                                       /*bit*/ 0);
8987                 ctl_done((union ctl_io *)ctsio);
8988                 return (retval);
8989                 break; /* NOTREACHED */
8990         }
8991
8992         alloc_len = scsi_4btoul(cdb->length);
8993         /*
8994          * The initiator has to allocate at least 16 bytes for this request,
8995          * so he can at least get the header and the first LUN.  Otherwise
8996          * we reject the request (per SPC-3 rev 14, section 6.21).
8997          */
8998         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
8999             sizeof(struct scsi_report_luns_lundata))) {
9000                 ctl_set_invalid_field(ctsio,
9001                                       /*sks_valid*/ 1,
9002                                       /*command*/ 1,
9003                                       /*field*/ 6,
9004                                       /*bit_valid*/ 0,
9005                                       /*bit*/ 0);
9006                 ctl_done((union ctl_io *)ctsio);
9007                 return (retval);
9008         }
9009
9010         request_lun = (struct ctl_lun *)
9011                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9012
9013         lun_datalen = sizeof(*lun_data) +
9014                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9015
9016         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9017         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9018         ctsio->kern_sg_entries = 0;
9019
9020         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9021
9022         mtx_lock(&softc->ctl_lock);
9023         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9024                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9025                 if (lun_id >= CTL_MAX_LUNS)
9026                         continue;
9027                 lun = softc->ctl_luns[lun_id];
9028                 if (lun == NULL)
9029                         continue;
9030
9031                 if (targ_lun_id <= 0xff) {
9032                         /*
9033                          * Peripheral addressing method, bus number 0.
9034                          */
9035                         lun_data->luns[num_filled].lundata[0] =
9036                                 RPL_LUNDATA_ATYP_PERIPH;
9037                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9038                         num_filled++;
9039                 } else if (targ_lun_id <= 0x3fff) {
9040                         /*
9041                          * Flat addressing method.
9042                          */
9043                         lun_data->luns[num_filled].lundata[0] =
9044                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9045                         lun_data->luns[num_filled].lundata[1] =
9046                                 (targ_lun_id & 0xff);
9047                         num_filled++;
9048                 } else if (targ_lun_id <= 0xffffff) {
9049                         /*
9050                          * Extended flat addressing method.
9051                          */
9052                         lun_data->luns[num_filled].lundata[0] =
9053                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9054                         scsi_ulto3b(targ_lun_id,
9055                             &lun_data->luns[num_filled].lundata[1]);
9056                         num_filled++;
9057                 } else {
9058                         printf("ctl_report_luns: bogus LUN number %jd, "
9059                                "skipping\n", (intmax_t)targ_lun_id);
9060                 }
9061                 /*
9062                  * According to SPC-3, rev 14 section 6.21:
9063                  *
9064                  * "The execution of a REPORT LUNS command to any valid and
9065                  * installed logical unit shall clear the REPORTED LUNS DATA
9066                  * HAS CHANGED unit attention condition for all logical
9067                  * units of that target with respect to the requesting
9068                  * initiator. A valid and installed logical unit is one
9069                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9070                  * INQUIRY data (see 6.4.2)."
9071                  *
9072                  * If request_lun is NULL, the LUN this report luns command
9073                  * was issued to is either disabled or doesn't exist. In that
9074                  * case, we shouldn't clear any pending lun change unit
9075                  * attention.
9076                  */
9077                 if (request_lun != NULL) {
9078                         mtx_lock(&lun->lun_lock);
9079                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9080                         mtx_unlock(&lun->lun_lock);
9081                 }
9082         }
9083         mtx_unlock(&softc->ctl_lock);
9084
9085         /*
9086          * It's quite possible that we've returned fewer LUNs than we allocated
9087          * space for.  Trim it.
9088          */
9089         lun_datalen = sizeof(*lun_data) +
9090                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9091
9092         if (lun_datalen < alloc_len) {
9093                 ctsio->residual = alloc_len - lun_datalen;
9094                 ctsio->kern_data_len = lun_datalen;
9095                 ctsio->kern_total_len = lun_datalen;
9096         } else {
9097                 ctsio->residual = 0;
9098                 ctsio->kern_data_len = alloc_len;
9099                 ctsio->kern_total_len = alloc_len;
9100         }
9101         ctsio->kern_data_resid = 0;
9102         ctsio->kern_rel_offset = 0;
9103         ctsio->kern_sg_entries = 0;
9104
9105         /*
9106          * We set this to the actual data length, regardless of how much
9107          * space we actually have to return results.  If the user looks at
9108          * this value, he'll know whether or not he allocated enough space
9109          * and reissue the command if necessary.  We don't support well
9110          * known logical units, so if the user asks for that, return none.
9111          */
9112         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9113
9114         /*
9115          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9116          * this request.
9117          */
9118         ctl_set_success(ctsio);
9119         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9120         ctsio->be_move_done = ctl_config_move_done;
9121         ctl_datamove((union ctl_io *)ctsio);
9122         return (retval);
9123 }
9124
9125 int
9126 ctl_request_sense(struct ctl_scsiio *ctsio)
9127 {
9128         struct scsi_request_sense *cdb;
9129         struct scsi_sense_data *sense_ptr;
9130         struct ctl_softc *ctl_softc;
9131         struct ctl_lun *lun;
9132         uint32_t initidx;
9133         int have_error;
9134         scsi_sense_data_type sense_format;
9135         ctl_ua_type ua_type;
9136
9137         cdb = (struct scsi_request_sense *)ctsio->cdb;
9138
9139         ctl_softc = control_softc;
9140         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9141
9142         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9143
9144         /*
9145          * Determine which sense format the user wants.
9146          */
9147         if (cdb->byte2 & SRS_DESC)
9148                 sense_format = SSD_TYPE_DESC;
9149         else
9150                 sense_format = SSD_TYPE_FIXED;
9151
9152         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9153         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9154         ctsio->kern_sg_entries = 0;
9155
9156         /*
9157          * struct scsi_sense_data, which is currently set to 256 bytes, is
9158          * larger than the largest allowed value for the length field in the
9159          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9160          */
9161         ctsio->residual = 0;
9162         ctsio->kern_data_len = cdb->length;
9163         ctsio->kern_total_len = cdb->length;
9164
9165         ctsio->kern_data_resid = 0;
9166         ctsio->kern_rel_offset = 0;
9167         ctsio->kern_sg_entries = 0;
9168
9169         /*
9170          * If we don't have a LUN, we don't have any pending sense.
9171          */
9172         if (lun == NULL)
9173                 goto no_sense;
9174
9175         have_error = 0;
9176         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9177         /*
9178          * Check for pending sense, and then for pending unit attentions.
9179          * Pending sense gets returned first, then pending unit attentions.
9180          */
9181         mtx_lock(&lun->lun_lock);
9182 #ifdef CTL_WITH_CA
9183         if (ctl_is_set(lun->have_ca, initidx)) {
9184                 scsi_sense_data_type stored_format;
9185
9186                 /*
9187                  * Check to see which sense format was used for the stored
9188                  * sense data.
9189                  */
9190                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9191
9192                 /*
9193                  * If the user requested a different sense format than the
9194                  * one we stored, then we need to convert it to the other
9195                  * format.  If we're going from descriptor to fixed format
9196                  * sense data, we may lose things in translation, depending
9197                  * on what options were used.
9198                  *
9199                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9200                  * for some reason we'll just copy it out as-is.
9201                  */
9202                 if ((stored_format == SSD_TYPE_FIXED)
9203                  && (sense_format == SSD_TYPE_DESC))
9204                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9205                             &lun->pending_sense[initidx],
9206                             (struct scsi_sense_data_desc *)sense_ptr);
9207                 else if ((stored_format == SSD_TYPE_DESC)
9208                       && (sense_format == SSD_TYPE_FIXED))
9209                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9210                             &lun->pending_sense[initidx],
9211                             (struct scsi_sense_data_fixed *)sense_ptr);
9212                 else
9213                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9214                                MIN(sizeof(*sense_ptr),
9215                                sizeof(lun->pending_sense[initidx])));
9216
9217                 ctl_clear_mask(lun->have_ca, initidx);
9218                 have_error = 1;
9219         } else
9220 #endif
9221         {
9222                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9223                 if (ua_type != CTL_UA_NONE)
9224                         have_error = 1;
9225                 if (ua_type == CTL_UA_LUN_CHANGE) {
9226                         mtx_unlock(&lun->lun_lock);
9227                         mtx_lock(&ctl_softc->ctl_lock);
9228                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9229                         mtx_unlock(&ctl_softc->ctl_lock);
9230                         mtx_lock(&lun->lun_lock);
9231                 }
9232
9233         }
9234         mtx_unlock(&lun->lun_lock);
9235
9236         /*
9237          * We already have a pending error, return it.
9238          */
9239         if (have_error != 0) {
9240                 /*
9241                  * We report the SCSI status as OK, since the status of the
9242                  * request sense command itself is OK.
9243                  * We report 0 for the sense length, because we aren't doing
9244                  * autosense in this case.  We're reporting sense as
9245                  * parameter data.
9246                  */
9247                 ctl_set_success(ctsio);
9248                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9249                 ctsio->be_move_done = ctl_config_move_done;
9250                 ctl_datamove((union ctl_io *)ctsio);
9251                 return (CTL_RETVAL_COMPLETE);
9252         }
9253
9254 no_sense:
9255
9256         /*
9257          * No sense information to report, so we report that everything is
9258          * okay.
9259          */
9260         ctl_set_sense_data(sense_ptr,
9261                            lun,
9262                            sense_format,
9263                            /*current_error*/ 1,
9264                            /*sense_key*/ SSD_KEY_NO_SENSE,
9265                            /*asc*/ 0x00,
9266                            /*ascq*/ 0x00,
9267                            SSD_ELEM_NONE);
9268
9269         /*
9270          * We report 0 for the sense length, because we aren't doing
9271          * autosense in this case.  We're reporting sense as parameter data.
9272          */
9273         ctl_set_success(ctsio);
9274         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9275         ctsio->be_move_done = ctl_config_move_done;
9276         ctl_datamove((union ctl_io *)ctsio);
9277         return (CTL_RETVAL_COMPLETE);
9278 }
9279
9280 int
9281 ctl_tur(struct ctl_scsiio *ctsio)
9282 {
9283
9284         CTL_DEBUG_PRINT(("ctl_tur\n"));
9285
9286         ctl_set_success(ctsio);
9287         ctl_done((union ctl_io *)ctsio);
9288
9289         return (CTL_RETVAL_COMPLETE);
9290 }
9291
9292 /*
9293  * SCSI VPD page 0x00, the Supported VPD Pages page.
9294  */
9295 static int
9296 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9297 {
9298         struct scsi_vpd_supported_pages *pages;
9299         int sup_page_size;
9300         struct ctl_lun *lun;
9301         int p;
9302
9303         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9304
9305         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9306             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9307         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9308         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9309         ctsio->kern_sg_entries = 0;
9310
9311         if (sup_page_size < alloc_len) {
9312                 ctsio->residual = alloc_len - sup_page_size;
9313                 ctsio->kern_data_len = sup_page_size;
9314                 ctsio->kern_total_len = sup_page_size;
9315         } else {
9316                 ctsio->residual = 0;
9317                 ctsio->kern_data_len = alloc_len;
9318                 ctsio->kern_total_len = alloc_len;
9319         }
9320         ctsio->kern_data_resid = 0;
9321         ctsio->kern_rel_offset = 0;
9322         ctsio->kern_sg_entries = 0;
9323
9324         /*
9325          * The control device is always connected.  The disk device, on the
9326          * other hand, may not be online all the time.  Need to change this
9327          * to figure out whether the disk device is actually online or not.
9328          */
9329         if (lun != NULL)
9330                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9331                                 lun->be_lun->lun_type;
9332         else
9333                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9334
9335         p = 0;
9336         /* Supported VPD pages */
9337         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9338         /* Serial Number */
9339         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9340         /* Device Identification */
9341         pages->page_list[p++] = SVPD_DEVICE_ID;
9342         /* Extended INQUIRY Data */
9343         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9344         /* Mode Page Policy */
9345         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9346         /* SCSI Ports */
9347         pages->page_list[p++] = SVPD_SCSI_PORTS;
9348         /* Third-party Copy */
9349         pages->page_list[p++] = SVPD_SCSI_TPC;
9350         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9351                 /* Block limits */
9352                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9353                 /* Block Device Characteristics */
9354                 pages->page_list[p++] = SVPD_BDC;
9355                 /* Logical Block Provisioning */
9356                 pages->page_list[p++] = SVPD_LBP;
9357         }
9358         pages->length = p;
9359
9360         ctl_set_success(ctsio);
9361         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9362         ctsio->be_move_done = ctl_config_move_done;
9363         ctl_datamove((union ctl_io *)ctsio);
9364         return (CTL_RETVAL_COMPLETE);
9365 }
9366
9367 /*
9368  * SCSI VPD page 0x80, the Unit Serial Number page.
9369  */
9370 static int
9371 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9372 {
9373         struct scsi_vpd_unit_serial_number *sn_ptr;
9374         struct ctl_lun *lun;
9375         int data_len;
9376
9377         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9378
9379         data_len = 4 + CTL_SN_LEN;
9380         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9381         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9382         if (data_len < alloc_len) {
9383                 ctsio->residual = alloc_len - data_len;
9384                 ctsio->kern_data_len = data_len;
9385                 ctsio->kern_total_len = data_len;
9386         } else {
9387                 ctsio->residual = 0;
9388                 ctsio->kern_data_len = alloc_len;
9389                 ctsio->kern_total_len = alloc_len;
9390         }
9391         ctsio->kern_data_resid = 0;
9392         ctsio->kern_rel_offset = 0;
9393         ctsio->kern_sg_entries = 0;
9394
9395         /*
9396          * The control device is always connected.  The disk device, on the
9397          * other hand, may not be online all the time.  Need to change this
9398          * to figure out whether the disk device is actually online or not.
9399          */
9400         if (lun != NULL)
9401                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9402                                   lun->be_lun->lun_type;
9403         else
9404                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9405
9406         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9407         sn_ptr->length = CTL_SN_LEN;
9408         /*
9409          * If we don't have a LUN, we just leave the serial number as
9410          * all spaces.
9411          */
9412         if (lun != NULL) {
9413                 strncpy((char *)sn_ptr->serial_num,
9414                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9415         } else
9416                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9417
9418         ctl_set_success(ctsio);
9419         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9420         ctsio->be_move_done = ctl_config_move_done;
9421         ctl_datamove((union ctl_io *)ctsio);
9422         return (CTL_RETVAL_COMPLETE);
9423 }
9424
9425
9426 /*
9427  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9428  */
9429 static int
9430 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9431 {
9432         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9433         struct ctl_lun *lun;
9434         int data_len;
9435
9436         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9437
9438         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9439         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9440         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9441         ctsio->kern_sg_entries = 0;
9442
9443         if (data_len < alloc_len) {
9444                 ctsio->residual = alloc_len - data_len;
9445                 ctsio->kern_data_len = data_len;
9446                 ctsio->kern_total_len = data_len;
9447         } else {
9448                 ctsio->residual = 0;
9449                 ctsio->kern_data_len = alloc_len;
9450                 ctsio->kern_total_len = alloc_len;
9451         }
9452         ctsio->kern_data_resid = 0;
9453         ctsio->kern_rel_offset = 0;
9454         ctsio->kern_sg_entries = 0;
9455
9456         /*
9457          * The control device is always connected.  The disk device, on the
9458          * other hand, may not be online all the time.
9459          */
9460         if (lun != NULL)
9461                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9462                                      lun->be_lun->lun_type;
9463         else
9464                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9465         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9466         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9467         /*
9468          * We support head of queue, ordered and simple tags.
9469          */
9470         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9471         /*
9472          * Volatile cache supported.
9473          */
9474         eid_ptr->flags3 = SVPD_EID_V_SUP;
9475
9476         /*
9477          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9478          * attention for a particular IT nexus on all LUNs once we report
9479          * it to that nexus once.  This bit is required as of SPC-4.
9480          */
9481         eid_ptr->flags4 = SVPD_EID_LUICLT;
9482
9483         /*
9484          * XXX KDM in order to correctly answer this, we would need
9485          * information from the SIM to determine how much sense data it
9486          * can send.  So this would really be a path inquiry field, most
9487          * likely.  This can be set to a maximum of 252 according to SPC-4,
9488          * but the hardware may or may not be able to support that much.
9489          * 0 just means that the maximum sense data length is not reported.
9490          */
9491         eid_ptr->max_sense_length = 0;
9492
9493         ctl_set_success(ctsio);
9494         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9495         ctsio->be_move_done = ctl_config_move_done;
9496         ctl_datamove((union ctl_io *)ctsio);
9497         return (CTL_RETVAL_COMPLETE);
9498 }
9499
9500 static int
9501 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9502 {
9503         struct scsi_vpd_mode_page_policy *mpp_ptr;
9504         struct ctl_lun *lun;
9505         int data_len;
9506
9507         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9508
9509         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9510             sizeof(struct scsi_vpd_mode_page_policy_descr);
9511
9512         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9513         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9514         ctsio->kern_sg_entries = 0;
9515
9516         if (data_len < alloc_len) {
9517                 ctsio->residual = alloc_len - data_len;
9518                 ctsio->kern_data_len = data_len;
9519                 ctsio->kern_total_len = data_len;
9520         } else {
9521                 ctsio->residual = 0;
9522                 ctsio->kern_data_len = alloc_len;
9523                 ctsio->kern_total_len = alloc_len;
9524         }
9525         ctsio->kern_data_resid = 0;
9526         ctsio->kern_rel_offset = 0;
9527         ctsio->kern_sg_entries = 0;
9528
9529         /*
9530          * The control device is always connected.  The disk device, on the
9531          * other hand, may not be online all the time.
9532          */
9533         if (lun != NULL)
9534                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9535                                      lun->be_lun->lun_type;
9536         else
9537                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9538         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9539         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9540         mpp_ptr->descr[0].page_code = 0x3f;
9541         mpp_ptr->descr[0].subpage_code = 0xff;
9542         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9543
9544         ctl_set_success(ctsio);
9545         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9546         ctsio->be_move_done = ctl_config_move_done;
9547         ctl_datamove((union ctl_io *)ctsio);
9548         return (CTL_RETVAL_COMPLETE);
9549 }
9550
9551 /*
9552  * SCSI VPD page 0x83, the Device Identification page.
9553  */
9554 static int
9555 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9556 {
9557         struct scsi_vpd_device_id *devid_ptr;
9558         struct scsi_vpd_id_descriptor *desc;
9559         struct ctl_softc *softc;
9560         struct ctl_lun *lun;
9561         struct ctl_port *port;
9562         int data_len;
9563         uint8_t proto;
9564
9565         softc = control_softc;
9566
9567         port = ctl_io_port(&ctsio->io_hdr);
9568         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9569
9570         data_len = sizeof(struct scsi_vpd_device_id) +
9571             sizeof(struct scsi_vpd_id_descriptor) +
9572                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9573             sizeof(struct scsi_vpd_id_descriptor) +
9574                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9575         if (lun && lun->lun_devid)
9576                 data_len += lun->lun_devid->len;
9577         if (port && port->port_devid)
9578                 data_len += port->port_devid->len;
9579         if (port && port->target_devid)
9580                 data_len += port->target_devid->len;
9581
9582         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9583         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9584         ctsio->kern_sg_entries = 0;
9585
9586         if (data_len < alloc_len) {
9587                 ctsio->residual = alloc_len - data_len;
9588                 ctsio->kern_data_len = data_len;
9589                 ctsio->kern_total_len = data_len;
9590         } else {
9591                 ctsio->residual = 0;
9592                 ctsio->kern_data_len = alloc_len;
9593                 ctsio->kern_total_len = alloc_len;
9594         }
9595         ctsio->kern_data_resid = 0;
9596         ctsio->kern_rel_offset = 0;
9597         ctsio->kern_sg_entries = 0;
9598
9599         /*
9600          * The control device is always connected.  The disk device, on the
9601          * other hand, may not be online all the time.
9602          */
9603         if (lun != NULL)
9604                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9605                                      lun->be_lun->lun_type;
9606         else
9607                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9608         devid_ptr->page_code = SVPD_DEVICE_ID;
9609         scsi_ulto2b(data_len - 4, devid_ptr->length);
9610
9611         if (port && port->port_type == CTL_PORT_FC)
9612                 proto = SCSI_PROTO_FC << 4;
9613         else if (port && port->port_type == CTL_PORT_ISCSI)
9614                 proto = SCSI_PROTO_ISCSI << 4;
9615         else
9616                 proto = SCSI_PROTO_SPI << 4;
9617         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9618
9619         /*
9620          * We're using a LUN association here.  i.e., this device ID is a
9621          * per-LUN identifier.
9622          */
9623         if (lun && lun->lun_devid) {
9624                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9625                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9626                     lun->lun_devid->len);
9627         }
9628
9629         /*
9630          * This is for the WWPN which is a port association.
9631          */
9632         if (port && port->port_devid) {
9633                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9634                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9635                     port->port_devid->len);
9636         }
9637
9638         /*
9639          * This is for the Relative Target Port(type 4h) identifier
9640          */
9641         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9642         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9643             SVPD_ID_TYPE_RELTARG;
9644         desc->length = 4;
9645         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9646         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9647             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9648
9649         /*
9650          * This is for the Target Port Group(type 5h) identifier
9651          */
9652         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9653         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9654             SVPD_ID_TYPE_TPORTGRP;
9655         desc->length = 4;
9656         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9657             &desc->identifier[2]);
9658         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9659             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9660
9661         /*
9662          * This is for the Target identifier
9663          */
9664         if (port && port->target_devid) {
9665                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9666         }
9667
9668         ctl_set_success(ctsio);
9669         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9670         ctsio->be_move_done = ctl_config_move_done;
9671         ctl_datamove((union ctl_io *)ctsio);
9672         return (CTL_RETVAL_COMPLETE);
9673 }
9674
9675 static int
9676 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9677 {
9678         struct ctl_softc *softc = control_softc;
9679         struct scsi_vpd_scsi_ports *sp;
9680         struct scsi_vpd_port_designation *pd;
9681         struct scsi_vpd_port_designation_cont *pdc;
9682         struct ctl_lun *lun;
9683         struct ctl_port *port;
9684         int data_len, num_target_ports, iid_len, id_len;
9685
9686         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9687
9688         num_target_ports = 0;
9689         iid_len = 0;
9690         id_len = 0;
9691         mtx_lock(&softc->ctl_lock);
9692         STAILQ_FOREACH(port, &softc->port_list, links) {
9693                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9694                         continue;
9695                 if (lun != NULL &&
9696                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9697                         continue;
9698                 num_target_ports++;
9699                 if (port->init_devid)
9700                         iid_len += port->init_devid->len;
9701                 if (port->port_devid)
9702                         id_len += port->port_devid->len;
9703         }
9704         mtx_unlock(&softc->ctl_lock);
9705
9706         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9707             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9708              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9709         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9710         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9711         ctsio->kern_sg_entries = 0;
9712
9713         if (data_len < alloc_len) {
9714                 ctsio->residual = alloc_len - data_len;
9715                 ctsio->kern_data_len = data_len;
9716                 ctsio->kern_total_len = data_len;
9717         } else {
9718                 ctsio->residual = 0;
9719                 ctsio->kern_data_len = alloc_len;
9720                 ctsio->kern_total_len = alloc_len;
9721         }
9722         ctsio->kern_data_resid = 0;
9723         ctsio->kern_rel_offset = 0;
9724         ctsio->kern_sg_entries = 0;
9725
9726         /*
9727          * The control device is always connected.  The disk device, on the
9728          * other hand, may not be online all the time.  Need to change this
9729          * to figure out whether the disk device is actually online or not.
9730          */
9731         if (lun != NULL)
9732                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9733                                   lun->be_lun->lun_type;
9734         else
9735                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9736
9737         sp->page_code = SVPD_SCSI_PORTS;
9738         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9739             sp->page_length);
9740         pd = &sp->design[0];
9741
9742         mtx_lock(&softc->ctl_lock);
9743         STAILQ_FOREACH(port, &softc->port_list, links) {
9744                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9745                         continue;
9746                 if (lun != NULL &&
9747                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9748                         continue;
9749                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9750                 if (port->init_devid) {
9751                         iid_len = port->init_devid->len;
9752                         memcpy(pd->initiator_transportid,
9753                             port->init_devid->data, port->init_devid->len);
9754                 } else
9755                         iid_len = 0;
9756                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9757                 pdc = (struct scsi_vpd_port_designation_cont *)
9758                     (&pd->initiator_transportid[iid_len]);
9759                 if (port->port_devid) {
9760                         id_len = port->port_devid->len;
9761                         memcpy(pdc->target_port_descriptors,
9762                             port->port_devid->data, port->port_devid->len);
9763                 } else
9764                         id_len = 0;
9765                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9766                 pd = (struct scsi_vpd_port_designation *)
9767                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9768         }
9769         mtx_unlock(&softc->ctl_lock);
9770
9771         ctl_set_success(ctsio);
9772         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9773         ctsio->be_move_done = ctl_config_move_done;
9774         ctl_datamove((union ctl_io *)ctsio);
9775         return (CTL_RETVAL_COMPLETE);
9776 }
9777
9778 static int
9779 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9780 {
9781         struct scsi_vpd_block_limits *bl_ptr;
9782         struct ctl_lun *lun;
9783         int bs;
9784
9785         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9786
9787         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9788         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9789         ctsio->kern_sg_entries = 0;
9790
9791         if (sizeof(*bl_ptr) < alloc_len) {
9792                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9793                 ctsio->kern_data_len = sizeof(*bl_ptr);
9794                 ctsio->kern_total_len = sizeof(*bl_ptr);
9795         } else {
9796                 ctsio->residual = 0;
9797                 ctsio->kern_data_len = alloc_len;
9798                 ctsio->kern_total_len = alloc_len;
9799         }
9800         ctsio->kern_data_resid = 0;
9801         ctsio->kern_rel_offset = 0;
9802         ctsio->kern_sg_entries = 0;
9803
9804         /*
9805          * The control device is always connected.  The disk device, on the
9806          * other hand, may not be online all the time.  Need to change this
9807          * to figure out whether the disk device is actually online or not.
9808          */
9809         if (lun != NULL)
9810                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9811                                   lun->be_lun->lun_type;
9812         else
9813                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9814
9815         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9816         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9817         bl_ptr->max_cmp_write_len = 0xff;
9818         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9819         if (lun != NULL) {
9820                 bs = lun->be_lun->blocksize;
9821                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9822                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9823                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9824                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9825                         if (lun->be_lun->ublockexp != 0) {
9826                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9827                                     bl_ptr->opt_unmap_grain);
9828                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9829                                     bl_ptr->unmap_grain_align);
9830                         }
9831                 }
9832                 scsi_ulto4b(lun->be_lun->atomicblock,
9833                     bl_ptr->max_atomic_transfer_length);
9834                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9835                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9836         }
9837         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9838
9839         ctl_set_success(ctsio);
9840         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9841         ctsio->be_move_done = ctl_config_move_done;
9842         ctl_datamove((union ctl_io *)ctsio);
9843         return (CTL_RETVAL_COMPLETE);
9844 }
9845
9846 static int
9847 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9848 {
9849         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9850         struct ctl_lun *lun;
9851         const char *value;
9852         u_int i;
9853
9854         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9855
9856         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9857         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9858         ctsio->kern_sg_entries = 0;
9859
9860         if (sizeof(*bdc_ptr) < alloc_len) {
9861                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9862                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9863                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9864         } else {
9865                 ctsio->residual = 0;
9866                 ctsio->kern_data_len = alloc_len;
9867                 ctsio->kern_total_len = alloc_len;
9868         }
9869         ctsio->kern_data_resid = 0;
9870         ctsio->kern_rel_offset = 0;
9871         ctsio->kern_sg_entries = 0;
9872
9873         /*
9874          * The control device is always connected.  The disk device, on the
9875          * other hand, may not be online all the time.  Need to change this
9876          * to figure out whether the disk device is actually online or not.
9877          */
9878         if (lun != NULL)
9879                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9880                                   lun->be_lun->lun_type;
9881         else
9882                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9883         bdc_ptr->page_code = SVPD_BDC;
9884         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9885         if (lun != NULL &&
9886             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9887                 i = strtol(value, NULL, 0);
9888         else
9889                 i = CTL_DEFAULT_ROTATION_RATE;
9890         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9891         if (lun != NULL &&
9892             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9893                 i = strtol(value, NULL, 0);
9894         else
9895                 i = 0;
9896         bdc_ptr->wab_wac_ff = (i & 0x0f);
9897         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9898
9899         ctl_set_success(ctsio);
9900         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9901         ctsio->be_move_done = ctl_config_move_done;
9902         ctl_datamove((union ctl_io *)ctsio);
9903         return (CTL_RETVAL_COMPLETE);
9904 }
9905
9906 static int
9907 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9908 {
9909         struct scsi_vpd_logical_block_prov *lbp_ptr;
9910         struct ctl_lun *lun;
9911
9912         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9913
9914         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9915         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9916         ctsio->kern_sg_entries = 0;
9917
9918         if (sizeof(*lbp_ptr) < alloc_len) {
9919                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9920                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9921                 ctsio->kern_total_len = sizeof(*lbp_ptr);
9922         } else {
9923                 ctsio->residual = 0;
9924                 ctsio->kern_data_len = alloc_len;
9925                 ctsio->kern_total_len = alloc_len;
9926         }
9927         ctsio->kern_data_resid = 0;
9928         ctsio->kern_rel_offset = 0;
9929         ctsio->kern_sg_entries = 0;
9930
9931         /*
9932          * The control device is always connected.  The disk device, on the
9933          * other hand, may not be online all the time.  Need to change this
9934          * to figure out whether the disk device is actually online or not.
9935          */
9936         if (lun != NULL)
9937                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9938                                   lun->be_lun->lun_type;
9939         else
9940                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9941
9942         lbp_ptr->page_code = SVPD_LBP;
9943         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9944         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9945         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9946                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9947                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9948                 lbp_ptr->prov_type = SVPD_LBP_THIN;
9949         }
9950
9951         ctl_set_success(ctsio);
9952         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9953         ctsio->be_move_done = ctl_config_move_done;
9954         ctl_datamove((union ctl_io *)ctsio);
9955         return (CTL_RETVAL_COMPLETE);
9956 }
9957
9958 /*
9959  * INQUIRY with the EVPD bit set.
9960  */
9961 static int
9962 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9963 {
9964         struct ctl_lun *lun;
9965         struct scsi_inquiry *cdb;
9966         int alloc_len, retval;
9967
9968         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9969         cdb = (struct scsi_inquiry *)ctsio->cdb;
9970         alloc_len = scsi_2btoul(cdb->length);
9971
9972         switch (cdb->page_code) {
9973         case SVPD_SUPPORTED_PAGES:
9974                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9975                 break;
9976         case SVPD_UNIT_SERIAL_NUMBER:
9977                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9978                 break;
9979         case SVPD_DEVICE_ID:
9980                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9981                 break;
9982         case SVPD_EXTENDED_INQUIRY_DATA:
9983                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9984                 break;
9985         case SVPD_MODE_PAGE_POLICY:
9986                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9987                 break;
9988         case SVPD_SCSI_PORTS:
9989                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9990                 break;
9991         case SVPD_SCSI_TPC:
9992                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9993                 break;
9994         case SVPD_BLOCK_LIMITS:
9995                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9996                         goto err;
9997                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9998                 break;
9999         case SVPD_BDC:
10000                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10001                         goto err;
10002                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10003                 break;
10004         case SVPD_LBP:
10005                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10006                         goto err;
10007                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10008                 break;
10009         default:
10010 err:
10011                 ctl_set_invalid_field(ctsio,
10012                                       /*sks_valid*/ 1,
10013                                       /*command*/ 1,
10014                                       /*field*/ 2,
10015                                       /*bit_valid*/ 0,
10016                                       /*bit*/ 0);
10017                 ctl_done((union ctl_io *)ctsio);
10018                 retval = CTL_RETVAL_COMPLETE;
10019                 break;
10020         }
10021
10022         return (retval);
10023 }
10024
10025 /*
10026  * Standard INQUIRY data.
10027  */
10028 static int
10029 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10030 {
10031         struct scsi_inquiry_data *inq_ptr;
10032         struct scsi_inquiry *cdb;
10033         struct ctl_softc *softc;
10034         struct ctl_port *port;
10035         struct ctl_lun *lun;
10036         char *val;
10037         uint32_t alloc_len, data_len;
10038         ctl_port_type port_type;
10039
10040         softc = control_softc;
10041
10042         /*
10043          * Figure out whether we're talking to a Fibre Channel port or not.
10044          * We treat the ioctl front end, and any SCSI adapters, as packetized
10045          * SCSI front ends.
10046          */
10047         port = ctl_io_port(&ctsio->io_hdr);
10048         if (port != NULL)
10049                 port_type = port->port_type;
10050         else
10051                 port_type = CTL_PORT_SCSI;
10052         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10053                 port_type = CTL_PORT_SCSI;
10054
10055         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10056         cdb = (struct scsi_inquiry *)ctsio->cdb;
10057         alloc_len = scsi_2btoul(cdb->length);
10058
10059         /*
10060          * We malloc the full inquiry data size here and fill it
10061          * in.  If the user only asks for less, we'll give him
10062          * that much.
10063          */
10064         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10065         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10066         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10067         ctsio->kern_sg_entries = 0;
10068         ctsio->kern_data_resid = 0;
10069         ctsio->kern_rel_offset = 0;
10070
10071         if (data_len < alloc_len) {
10072                 ctsio->residual = alloc_len - data_len;
10073                 ctsio->kern_data_len = data_len;
10074                 ctsio->kern_total_len = data_len;
10075         } else {
10076                 ctsio->residual = 0;
10077                 ctsio->kern_data_len = alloc_len;
10078                 ctsio->kern_total_len = alloc_len;
10079         }
10080
10081         if (lun != NULL) {
10082                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10083                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10084                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10085                             lun->be_lun->lun_type;
10086                 } else {
10087                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10088                             lun->be_lun->lun_type;
10089                 }
10090         } else
10091                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10092
10093         /* RMB in byte 2 is 0 */
10094         inq_ptr->version = SCSI_REV_SPC4;
10095
10096         /*
10097          * According to SAM-3, even if a device only supports a single
10098          * level of LUN addressing, it should still set the HISUP bit:
10099          *
10100          * 4.9.1 Logical unit numbers overview
10101          *
10102          * All logical unit number formats described in this standard are
10103          * hierarchical in structure even when only a single level in that
10104          * hierarchy is used. The HISUP bit shall be set to one in the
10105          * standard INQUIRY data (see SPC-2) when any logical unit number
10106          * format described in this standard is used.  Non-hierarchical
10107          * formats are outside the scope of this standard.
10108          *
10109          * Therefore we set the HiSup bit here.
10110          *
10111          * The reponse format is 2, per SPC-3.
10112          */
10113         inq_ptr->response_format = SID_HiSup | 2;
10114
10115         inq_ptr->additional_length = data_len -
10116             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10117         CTL_DEBUG_PRINT(("additional_length = %d\n",
10118                          inq_ptr->additional_length));
10119
10120         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10121         /* 16 bit addressing */
10122         if (port_type == CTL_PORT_SCSI)
10123                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10124         /* XXX set the SID_MultiP bit here if we're actually going to
10125            respond on multiple ports */
10126         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10127
10128         /* 16 bit data bus, synchronous transfers */
10129         if (port_type == CTL_PORT_SCSI)
10130                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10131         /*
10132          * XXX KDM do we want to support tagged queueing on the control
10133          * device at all?
10134          */
10135         if ((lun == NULL)
10136          || (lun->be_lun->lun_type != T_PROCESSOR))
10137                 inq_ptr->flags |= SID_CmdQue;
10138         /*
10139          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10140          * We have 8 bytes for the vendor name, and 16 bytes for the device
10141          * name and 4 bytes for the revision.
10142          */
10143         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10144             "vendor")) == NULL) {
10145                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10146         } else {
10147                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10148                 strncpy(inq_ptr->vendor, val,
10149                     min(sizeof(inq_ptr->vendor), strlen(val)));
10150         }
10151         if (lun == NULL) {
10152                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10153                     sizeof(inq_ptr->product));
10154         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10155                 switch (lun->be_lun->lun_type) {
10156                 case T_DIRECT:
10157                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10158                             sizeof(inq_ptr->product));
10159                         break;
10160                 case T_PROCESSOR:
10161                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10162                             sizeof(inq_ptr->product));
10163                         break;
10164                 default:
10165                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10166                             sizeof(inq_ptr->product));
10167                         break;
10168                 }
10169         } else {
10170                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10171                 strncpy(inq_ptr->product, val,
10172                     min(sizeof(inq_ptr->product), strlen(val)));
10173         }
10174
10175         /*
10176          * XXX make this a macro somewhere so it automatically gets
10177          * incremented when we make changes.
10178          */
10179         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10180             "revision")) == NULL) {
10181                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10182         } else {
10183                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10184                 strncpy(inq_ptr->revision, val,
10185                     min(sizeof(inq_ptr->revision), strlen(val)));
10186         }
10187
10188         /*
10189          * For parallel SCSI, we support double transition and single
10190          * transition clocking.  We also support QAS (Quick Arbitration
10191          * and Selection) and Information Unit transfers on both the
10192          * control and array devices.
10193          */
10194         if (port_type == CTL_PORT_SCSI)
10195                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10196                                     SID_SPI_IUS;
10197
10198         /* SAM-5 (no version claimed) */
10199         scsi_ulto2b(0x00A0, inq_ptr->version1);
10200         /* SPC-4 (no version claimed) */
10201         scsi_ulto2b(0x0460, inq_ptr->version2);
10202         if (port_type == CTL_PORT_FC) {
10203                 /* FCP-2 ANSI INCITS.350:2003 */
10204                 scsi_ulto2b(0x0917, inq_ptr->version3);
10205         } else if (port_type == CTL_PORT_SCSI) {
10206                 /* SPI-4 ANSI INCITS.362:200x */
10207                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10208         } else if (port_type == CTL_PORT_ISCSI) {
10209                 /* iSCSI (no version claimed) */
10210                 scsi_ulto2b(0x0960, inq_ptr->version3);
10211         } else if (port_type == CTL_PORT_SAS) {
10212                 /* SAS (no version claimed) */
10213                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10214         }
10215
10216         if (lun == NULL) {
10217                 /* SBC-4 (no version claimed) */
10218                 scsi_ulto2b(0x0600, inq_ptr->version4);
10219         } else {
10220                 switch (lun->be_lun->lun_type) {
10221                 case T_DIRECT:
10222                         /* SBC-4 (no version claimed) */
10223                         scsi_ulto2b(0x0600, inq_ptr->version4);
10224                         break;
10225                 case T_PROCESSOR:
10226                 default:
10227                         break;
10228                 }
10229         }
10230
10231         ctl_set_success(ctsio);
10232         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10233         ctsio->be_move_done = ctl_config_move_done;
10234         ctl_datamove((union ctl_io *)ctsio);
10235         return (CTL_RETVAL_COMPLETE);
10236 }
10237
10238 int
10239 ctl_inquiry(struct ctl_scsiio *ctsio)
10240 {
10241         struct scsi_inquiry *cdb;
10242         int retval;
10243
10244         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10245
10246         cdb = (struct scsi_inquiry *)ctsio->cdb;
10247         if (cdb->byte2 & SI_EVPD)
10248                 retval = ctl_inquiry_evpd(ctsio);
10249         else if (cdb->page_code == 0)
10250                 retval = ctl_inquiry_std(ctsio);
10251         else {
10252                 ctl_set_invalid_field(ctsio,
10253                                       /*sks_valid*/ 1,
10254                                       /*command*/ 1,
10255                                       /*field*/ 2,
10256                                       /*bit_valid*/ 0,
10257                                       /*bit*/ 0);
10258                 ctl_done((union ctl_io *)ctsio);
10259                 return (CTL_RETVAL_COMPLETE);
10260         }
10261
10262         return (retval);
10263 }
10264
10265 /*
10266  * For known CDB types, parse the LBA and length.
10267  */
10268 static int
10269 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10270 {
10271         if (io->io_hdr.io_type != CTL_IO_SCSI)
10272                 return (1);
10273
10274         switch (io->scsiio.cdb[0]) {
10275         case COMPARE_AND_WRITE: {
10276                 struct scsi_compare_and_write *cdb;
10277
10278                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10279
10280                 *lba = scsi_8btou64(cdb->addr);
10281                 *len = cdb->length;
10282                 break;
10283         }
10284         case READ_6:
10285         case WRITE_6: {
10286                 struct scsi_rw_6 *cdb;
10287
10288                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10289
10290                 *lba = scsi_3btoul(cdb->addr);
10291                 /* only 5 bits are valid in the most significant address byte */
10292                 *lba &= 0x1fffff;
10293                 *len = cdb->length;
10294                 break;
10295         }
10296         case READ_10:
10297         case WRITE_10: {
10298                 struct scsi_rw_10 *cdb;
10299
10300                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10301
10302                 *lba = scsi_4btoul(cdb->addr);
10303                 *len = scsi_2btoul(cdb->length);
10304                 break;
10305         }
10306         case WRITE_VERIFY_10: {
10307                 struct scsi_write_verify_10 *cdb;
10308
10309                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10310
10311                 *lba = scsi_4btoul(cdb->addr);
10312                 *len = scsi_2btoul(cdb->length);
10313                 break;
10314         }
10315         case READ_12:
10316         case WRITE_12: {
10317                 struct scsi_rw_12 *cdb;
10318
10319                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10320
10321                 *lba = scsi_4btoul(cdb->addr);
10322                 *len = scsi_4btoul(cdb->length);
10323                 break;
10324         }
10325         case WRITE_VERIFY_12: {
10326                 struct scsi_write_verify_12 *cdb;
10327
10328                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10329
10330                 *lba = scsi_4btoul(cdb->addr);
10331                 *len = scsi_4btoul(cdb->length);
10332                 break;
10333         }
10334         case READ_16:
10335         case WRITE_16:
10336         case WRITE_ATOMIC_16: {
10337                 struct scsi_rw_16 *cdb;
10338
10339                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10340
10341                 *lba = scsi_8btou64(cdb->addr);
10342                 *len = scsi_4btoul(cdb->length);
10343                 break;
10344         }
10345         case WRITE_VERIFY_16: {
10346                 struct scsi_write_verify_16 *cdb;
10347
10348                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10349
10350                 *lba = scsi_8btou64(cdb->addr);
10351                 *len = scsi_4btoul(cdb->length);
10352                 break;
10353         }
10354         case WRITE_SAME_10: {
10355                 struct scsi_write_same_10 *cdb;
10356
10357                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10358
10359                 *lba = scsi_4btoul(cdb->addr);
10360                 *len = scsi_2btoul(cdb->length);
10361                 break;
10362         }
10363         case WRITE_SAME_16: {
10364                 struct scsi_write_same_16 *cdb;
10365
10366                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10367
10368                 *lba = scsi_8btou64(cdb->addr);
10369                 *len = scsi_4btoul(cdb->length);
10370                 break;
10371         }
10372         case VERIFY_10: {
10373                 struct scsi_verify_10 *cdb;
10374
10375                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10376
10377                 *lba = scsi_4btoul(cdb->addr);
10378                 *len = scsi_2btoul(cdb->length);
10379                 break;
10380         }
10381         case VERIFY_12: {
10382                 struct scsi_verify_12 *cdb;
10383
10384                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10385
10386                 *lba = scsi_4btoul(cdb->addr);
10387                 *len = scsi_4btoul(cdb->length);
10388                 break;
10389         }
10390         case VERIFY_16: {
10391                 struct scsi_verify_16 *cdb;
10392
10393                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10394
10395                 *lba = scsi_8btou64(cdb->addr);
10396                 *len = scsi_4btoul(cdb->length);
10397                 break;
10398         }
10399         case UNMAP: {
10400                 *lba = 0;
10401                 *len = UINT64_MAX;
10402                 break;
10403         }
10404         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10405                 struct scsi_get_lba_status *cdb;
10406
10407                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10408                 *lba = scsi_8btou64(cdb->addr);
10409                 *len = UINT32_MAX;
10410                 break;
10411         }
10412         default:
10413                 return (1);
10414                 break; /* NOTREACHED */
10415         }
10416
10417         return (0);
10418 }
10419
10420 static ctl_action
10421 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10422     bool seq)
10423 {
10424         uint64_t endlba1, endlba2;
10425
10426         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10427         endlba2 = lba2 + len2 - 1;
10428
10429         if ((endlba1 < lba2) || (endlba2 < lba1))
10430                 return (CTL_ACTION_PASS);
10431         else
10432                 return (CTL_ACTION_BLOCK);
10433 }
10434
10435 static int
10436 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10437 {
10438         struct ctl_ptr_len_flags *ptrlen;
10439         struct scsi_unmap_desc *buf, *end, *range;
10440         uint64_t lba;
10441         uint32_t len;
10442
10443         /* If not UNMAP -- go other way. */
10444         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10445             io->scsiio.cdb[0] != UNMAP)
10446                 return (CTL_ACTION_ERROR);
10447
10448         /* If UNMAP without data -- block and wait for data. */
10449         ptrlen = (struct ctl_ptr_len_flags *)
10450             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10451         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10452             ptrlen->ptr == NULL)
10453                 return (CTL_ACTION_BLOCK);
10454
10455         /* UNMAP with data -- check for collision. */
10456         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10457         end = buf + ptrlen->len / sizeof(*buf);
10458         for (range = buf; range < end; range++) {
10459                 lba = scsi_8btou64(range->lba);
10460                 len = scsi_4btoul(range->length);
10461                 if ((lba < lba2 + len2) && (lba + len > lba2))
10462                         return (CTL_ACTION_BLOCK);
10463         }
10464         return (CTL_ACTION_PASS);
10465 }
10466
10467 static ctl_action
10468 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10469 {
10470         uint64_t lba1, lba2;
10471         uint64_t len1, len2;
10472         int retval;
10473
10474         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10475                 return (CTL_ACTION_ERROR);
10476
10477         retval = ctl_extent_check_unmap(io1, lba2, len2);
10478         if (retval != CTL_ACTION_ERROR)
10479                 return (retval);
10480
10481         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10482                 return (CTL_ACTION_ERROR);
10483
10484         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10485 }
10486
10487 static ctl_action
10488 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10489 {
10490         uint64_t lba1, lba2;
10491         uint64_t len1, len2;
10492
10493         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10494                 return (CTL_ACTION_ERROR);
10495         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10496                 return (CTL_ACTION_ERROR);
10497
10498         if (lba1 + len1 == lba2)
10499                 return (CTL_ACTION_BLOCK);
10500         return (CTL_ACTION_PASS);
10501 }
10502
10503 static ctl_action
10504 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10505     union ctl_io *ooa_io)
10506 {
10507         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10508         ctl_serialize_action *serialize_row;
10509
10510         /*
10511          * The initiator attempted multiple untagged commands at the same
10512          * time.  Can't do that.
10513          */
10514         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10515          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10516          && ((pending_io->io_hdr.nexus.targ_port ==
10517               ooa_io->io_hdr.nexus.targ_port)
10518           && (pending_io->io_hdr.nexus.initid ==
10519               ooa_io->io_hdr.nexus.initid))
10520          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10521               CTL_FLAG_STATUS_SENT)) == 0))
10522                 return (CTL_ACTION_OVERLAP);
10523
10524         /*
10525          * The initiator attempted to send multiple tagged commands with
10526          * the same ID.  (It's fine if different initiators have the same
10527          * tag ID.)
10528          *
10529          * Even if all of those conditions are true, we don't kill the I/O
10530          * if the command ahead of us has been aborted.  We won't end up
10531          * sending it to the FETD, and it's perfectly legal to resend a
10532          * command with the same tag number as long as the previous
10533          * instance of this tag number has been aborted somehow.
10534          */
10535         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10536          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10537          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10538          && ((pending_io->io_hdr.nexus.targ_port ==
10539               ooa_io->io_hdr.nexus.targ_port)
10540           && (pending_io->io_hdr.nexus.initid ==
10541               ooa_io->io_hdr.nexus.initid))
10542          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10543               CTL_FLAG_STATUS_SENT)) == 0))
10544                 return (CTL_ACTION_OVERLAP_TAG);
10545
10546         /*
10547          * If we get a head of queue tag, SAM-3 says that we should
10548          * immediately execute it.
10549          *
10550          * What happens if this command would normally block for some other
10551          * reason?  e.g. a request sense with a head of queue tag
10552          * immediately after a write.  Normally that would block, but this
10553          * will result in its getting executed immediately...
10554          *
10555          * We currently return "pass" instead of "skip", so we'll end up
10556          * going through the rest of the queue to check for overlapped tags.
10557          *
10558          * XXX KDM check for other types of blockage first??
10559          */
10560         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10561                 return (CTL_ACTION_PASS);
10562
10563         /*
10564          * Ordered tags have to block until all items ahead of them
10565          * have completed.  If we get called with an ordered tag, we always
10566          * block, if something else is ahead of us in the queue.
10567          */
10568         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10569                 return (CTL_ACTION_BLOCK);
10570
10571         /*
10572          * Simple tags get blocked until all head of queue and ordered tags
10573          * ahead of them have completed.  I'm lumping untagged commands in
10574          * with simple tags here.  XXX KDM is that the right thing to do?
10575          */
10576         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10577           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10578          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10579           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10580                 return (CTL_ACTION_BLOCK);
10581
10582         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10583         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10584
10585         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10586
10587         switch (serialize_row[pending_entry->seridx]) {
10588         case CTL_SER_BLOCK:
10589                 return (CTL_ACTION_BLOCK);
10590         case CTL_SER_EXTENT:
10591                 return (ctl_extent_check(ooa_io, pending_io,
10592                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10593         case CTL_SER_EXTENTOPT:
10594                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10595                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10596                         return (ctl_extent_check(ooa_io, pending_io,
10597                             (lun->be_lun &&
10598                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10599                 return (CTL_ACTION_PASS);
10600         case CTL_SER_EXTENTSEQ:
10601                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10602                         return (ctl_extent_check_seq(ooa_io, pending_io));
10603                 return (CTL_ACTION_PASS);
10604         case CTL_SER_PASS:
10605                 return (CTL_ACTION_PASS);
10606         case CTL_SER_BLOCKOPT:
10607                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10608                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10609                         return (CTL_ACTION_BLOCK);
10610                 return (CTL_ACTION_PASS);
10611         case CTL_SER_SKIP:
10612                 return (CTL_ACTION_SKIP);
10613         default:
10614                 panic("invalid serialization value %d",
10615                       serialize_row[pending_entry->seridx]);
10616         }
10617
10618         return (CTL_ACTION_ERROR);
10619 }
10620
10621 /*
10622  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10623  * Assumptions:
10624  * - pending_io is generally either incoming, or on the blocked queue
10625  * - starting I/O is the I/O we want to start the check with.
10626  */
10627 static ctl_action
10628 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10629               union ctl_io *starting_io)
10630 {
10631         union ctl_io *ooa_io;
10632         ctl_action action;
10633
10634         mtx_assert(&lun->lun_lock, MA_OWNED);
10635
10636         /*
10637          * Run back along the OOA queue, starting with the current
10638          * blocked I/O and going through every I/O before it on the
10639          * queue.  If starting_io is NULL, we'll just end up returning
10640          * CTL_ACTION_PASS.
10641          */
10642         for (ooa_io = starting_io; ooa_io != NULL;
10643              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10644              ooa_links)){
10645
10646                 /*
10647                  * This routine just checks to see whether
10648                  * cur_blocked is blocked by ooa_io, which is ahead
10649                  * of it in the queue.  It doesn't queue/dequeue
10650                  * cur_blocked.
10651                  */
10652                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10653                 switch (action) {
10654                 case CTL_ACTION_BLOCK:
10655                 case CTL_ACTION_OVERLAP:
10656                 case CTL_ACTION_OVERLAP_TAG:
10657                 case CTL_ACTION_SKIP:
10658                 case CTL_ACTION_ERROR:
10659                         return (action);
10660                         break; /* NOTREACHED */
10661                 case CTL_ACTION_PASS:
10662                         break;
10663                 default:
10664                         panic("invalid action %d", action);
10665                         break;  /* NOTREACHED */
10666                 }
10667         }
10668
10669         return (CTL_ACTION_PASS);
10670 }
10671
10672 /*
10673  * Assumptions:
10674  * - An I/O has just completed, and has been removed from the per-LUN OOA
10675  *   queue, so some items on the blocked queue may now be unblocked.
10676  */
10677 static int
10678 ctl_check_blocked(struct ctl_lun *lun)
10679 {
10680         struct ctl_softc *softc = lun->ctl_softc;
10681         union ctl_io *cur_blocked, *next_blocked;
10682
10683         mtx_assert(&lun->lun_lock, MA_OWNED);
10684
10685         /*
10686          * Run forward from the head of the blocked queue, checking each
10687          * entry against the I/Os prior to it on the OOA queue to see if
10688          * there is still any blockage.
10689          *
10690          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10691          * with our removing a variable on it while it is traversing the
10692          * list.
10693          */
10694         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10695              cur_blocked != NULL; cur_blocked = next_blocked) {
10696                 union ctl_io *prev_ooa;
10697                 ctl_action action;
10698
10699                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10700                                                           blocked_links);
10701
10702                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10703                                                       ctl_ooaq, ooa_links);
10704
10705                 /*
10706                  * If cur_blocked happens to be the first item in the OOA
10707                  * queue now, prev_ooa will be NULL, and the action
10708                  * returned will just be CTL_ACTION_PASS.
10709                  */
10710                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10711
10712                 switch (action) {
10713                 case CTL_ACTION_BLOCK:
10714                         /* Nothing to do here, still blocked */
10715                         break;
10716                 case CTL_ACTION_OVERLAP:
10717                 case CTL_ACTION_OVERLAP_TAG:
10718                         /*
10719                          * This shouldn't happen!  In theory we've already
10720                          * checked this command for overlap...
10721                          */
10722                         break;
10723                 case CTL_ACTION_PASS:
10724                 case CTL_ACTION_SKIP: {
10725                         const struct ctl_cmd_entry *entry;
10726
10727                         /*
10728                          * The skip case shouldn't happen, this transaction
10729                          * should have never made it onto the blocked queue.
10730                          */
10731                         /*
10732                          * This I/O is no longer blocked, we can remove it
10733                          * from the blocked queue.  Since this is a TAILQ
10734                          * (doubly linked list), we can do O(1) removals
10735                          * from any place on the list.
10736                          */
10737                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10738                                      blocked_links);
10739                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10740
10741                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
10742                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
10743                                 /*
10744                                  * Need to send IO back to original side to
10745                                  * run
10746                                  */
10747                                 union ctl_ha_msg msg_info;
10748
10749                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10750                                 msg_info.hdr.original_sc =
10751                                         cur_blocked->io_hdr.original_sc;
10752                                 msg_info.hdr.serializing_sc = cur_blocked;
10753                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10754                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10755                                     sizeof(msg_info.hdr), M_NOWAIT);
10756                                 break;
10757                         }
10758                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10759
10760                         /*
10761                          * Check this I/O for LUN state changes that may
10762                          * have happened while this command was blocked.
10763                          * The LUN state may have been changed by a command
10764                          * ahead of us in the queue, so we need to re-check
10765                          * for any states that can be caused by SCSI
10766                          * commands.
10767                          */
10768                         if (ctl_scsiio_lun_check(lun, entry,
10769                                                  &cur_blocked->scsiio) == 0) {
10770                                 cur_blocked->io_hdr.flags |=
10771                                                       CTL_FLAG_IS_WAS_ON_RTR;
10772                                 ctl_enqueue_rtr(cur_blocked);
10773                         } else
10774                                 ctl_done(cur_blocked);
10775                         break;
10776                 }
10777                 default:
10778                         /*
10779                          * This probably shouldn't happen -- we shouldn't
10780                          * get CTL_ACTION_ERROR, or anything else.
10781                          */
10782                         break;
10783                 }
10784         }
10785
10786         return (CTL_RETVAL_COMPLETE);
10787 }
10788
10789 /*
10790  * This routine (with one exception) checks LUN flags that can be set by
10791  * commands ahead of us in the OOA queue.  These flags have to be checked
10792  * when a command initially comes in, and when we pull a command off the
10793  * blocked queue and are preparing to execute it.  The reason we have to
10794  * check these flags for commands on the blocked queue is that the LUN
10795  * state may have been changed by a command ahead of us while we're on the
10796  * blocked queue.
10797  *
10798  * Ordering is somewhat important with these checks, so please pay
10799  * careful attention to the placement of any new checks.
10800  */
10801 static int
10802 ctl_scsiio_lun_check(struct ctl_lun *lun,
10803     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10804 {
10805         struct ctl_softc *softc = lun->ctl_softc;
10806         int retval;
10807         uint32_t residx;
10808
10809         retval = 0;
10810
10811         mtx_assert(&lun->lun_lock, MA_OWNED);
10812
10813         /*
10814          * If this shelf is a secondary shelf controller, we may have to
10815          * reject some commands disallowed by HA mode and link state.
10816          */
10817         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10818                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
10819                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10820                         ctl_set_lun_unavail(ctsio);
10821                         retval = 1;
10822                         goto bailout;
10823                 }
10824                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
10825                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10826                         ctl_set_lun_transit(ctsio);
10827                         retval = 1;
10828                         goto bailout;
10829                 }
10830                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
10831                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
10832                         ctl_set_lun_standby(ctsio);
10833                         retval = 1;
10834                         goto bailout;
10835                 }
10836
10837                 /* The rest of checks are only done on executing side */
10838                 if (softc->ha_mode == CTL_HA_MODE_XFER)
10839                         goto bailout;
10840         }
10841
10842         if (entry->pattern & CTL_LUN_PAT_WRITE) {
10843                 if (lun->be_lun &&
10844                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
10845                         ctl_set_sense(ctsio, /*current_error*/ 1,
10846                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
10847                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
10848                         retval = 1;
10849                         goto bailout;
10850                 }
10851                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10852                     .eca_and_aen & SCP_SWP) != 0) {
10853                         ctl_set_sense(ctsio, /*current_error*/ 1,
10854                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
10855                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10856                         retval = 1;
10857                         goto bailout;
10858                 }
10859         }
10860
10861         /*
10862          * Check for a reservation conflict.  If this command isn't allowed
10863          * even on reserved LUNs, and if this initiator isn't the one who
10864          * reserved us, reject the command with a reservation conflict.
10865          */
10866         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10867         if ((lun->flags & CTL_LUN_RESERVED)
10868          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10869                 if (lun->res_idx != residx) {
10870                         ctl_set_reservation_conflict(ctsio);
10871                         retval = 1;
10872                         goto bailout;
10873                 }
10874         }
10875
10876         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10877             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10878                 /* No reservation or command is allowed. */;
10879         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10880             (lun->res_type == SPR_TYPE_WR_EX ||
10881              lun->res_type == SPR_TYPE_WR_EX_RO ||
10882              lun->res_type == SPR_TYPE_WR_EX_AR)) {
10883                 /* The command is allowed for Write Exclusive resv. */;
10884         } else {
10885                 /*
10886                  * if we aren't registered or it's a res holder type
10887                  * reservation and this isn't the res holder then set a
10888                  * conflict.
10889                  */
10890                 if (ctl_get_prkey(lun, residx) == 0
10891                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10892                         ctl_set_reservation_conflict(ctsio);
10893                         retval = 1;
10894                         goto bailout;
10895                 }
10896         }
10897
10898         if ((lun->flags & CTL_LUN_OFFLINE)
10899          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
10900                 ctl_set_lun_not_ready(ctsio);
10901                 retval = 1;
10902                 goto bailout;
10903         }
10904
10905         if ((lun->flags & CTL_LUN_STOPPED)
10906          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10907                 /* "Logical unit not ready, initializing cmd. required" */
10908                 ctl_set_lun_stopped(ctsio);
10909                 retval = 1;
10910                 goto bailout;
10911         }
10912
10913         if ((lun->flags & CTL_LUN_INOPERABLE)
10914          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10915                 /* "Medium format corrupted" */
10916                 ctl_set_medium_format_corrupted(ctsio);
10917                 retval = 1;
10918                 goto bailout;
10919         }
10920
10921 bailout:
10922         return (retval);
10923 }
10924
10925 static void
10926 ctl_failover_io(union ctl_io *io, int have_lock)
10927 {
10928         ctl_set_busy(&io->scsiio);
10929         ctl_done(io);
10930 }
10931
10932 static void
10933 ctl_failover_lun(struct ctl_lun *lun)
10934 {
10935         struct ctl_softc *softc = lun->ctl_softc;
10936         struct ctl_io_hdr *io, *next_io;
10937
10938         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
10939         if (softc->ha_mode == CTL_HA_MODE_XFER) {
10940                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10941                         /* We are master */
10942                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10943                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
10944                                         io->flags |= CTL_FLAG_ABORT;
10945                                 } else { /* This can be only due to DATAMOVE */
10946                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
10947                                         io->flags |= CTL_FLAG_IO_ACTIVE;
10948                                         io->port_status = 31340;
10949                                         ctl_enqueue_isc((union ctl_io *)io);
10950                                 }
10951                         }
10952                         /* We are slave */
10953                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10954                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10955                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
10956                                         io->flags |= CTL_FLAG_FAILOVER;
10957                                 } else {
10958                                         ctl_set_busy(&((union ctl_io *)io)->
10959                                             scsiio);
10960                                         ctl_done((union ctl_io *)io);
10961                                 }
10962                         }
10963                 }
10964         } else { /* SERIALIZE modes */
10965                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
10966                     next_io) {
10967                         /* We are master */
10968                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10969                                 TAILQ_REMOVE(&lun->blocked_queue, io,
10970                                     blocked_links);
10971                                 io->flags &= ~CTL_FLAG_BLOCKED;
10972                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10973                                 ctl_free_io((union ctl_io *)io);
10974                         }
10975                 }
10976                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10977                         /* We are master */
10978                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10979                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10980                                 ctl_free_io((union ctl_io *)io);
10981                         }
10982                         /* We are slave */
10983                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10984                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10985                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
10986                                         ctl_set_busy(&((union ctl_io *)io)->
10987                                             scsiio);
10988                                         ctl_done((union ctl_io *)io);
10989                                 }
10990                         }
10991                 }
10992                 ctl_check_blocked(lun);
10993         }
10994 }
10995
10996 static int
10997 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
10998 {
10999         struct ctl_lun *lun;
11000         const struct ctl_cmd_entry *entry;
11001         uint32_t initidx, targ_lun;
11002         int retval;
11003
11004         retval = 0;
11005
11006         lun = NULL;
11007
11008         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11009         if ((targ_lun < CTL_MAX_LUNS)
11010          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11011                 /*
11012                  * If the LUN is invalid, pretend that it doesn't exist.
11013                  * It will go away as soon as all pending I/O has been
11014                  * completed.
11015                  */
11016                 mtx_lock(&lun->lun_lock);
11017                 if (lun->flags & CTL_LUN_DISABLED) {
11018                         mtx_unlock(&lun->lun_lock);
11019                         lun = NULL;
11020                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11021                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11022                 } else {
11023                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11024                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11025                                 lun->be_lun;
11026
11027                         /*
11028                          * Every I/O goes into the OOA queue for a
11029                          * particular LUN, and stays there until completion.
11030                          */
11031 #ifdef CTL_TIME_IO
11032                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11033                                 lun->idle_time += getsbinuptime() -
11034                                     lun->last_busy;
11035                         }
11036 #endif
11037                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11038                             ooa_links);
11039                 }
11040         } else {
11041                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11042                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11043         }
11044
11045         /* Get command entry and return error if it is unsuppotyed. */
11046         entry = ctl_validate_command(ctsio);
11047         if (entry == NULL) {
11048                 if (lun)
11049                         mtx_unlock(&lun->lun_lock);
11050                 return (retval);
11051         }
11052
11053         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11054         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11055
11056         /*
11057          * Check to see whether we can send this command to LUNs that don't
11058          * exist.  This should pretty much only be the case for inquiry
11059          * and request sense.  Further checks, below, really require having
11060          * a LUN, so we can't really check the command anymore.  Just put
11061          * it on the rtr queue.
11062          */
11063         if (lun == NULL) {
11064                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11065                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11066                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11067                         return (retval);
11068                 }
11069
11070                 ctl_set_unsupported_lun(ctsio);
11071                 ctl_done((union ctl_io *)ctsio);
11072                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11073                 return (retval);
11074         } else {
11075                 /*
11076                  * Make sure we support this particular command on this LUN.
11077                  * e.g., we don't support writes to the control LUN.
11078                  */
11079                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11080                         mtx_unlock(&lun->lun_lock);
11081                         ctl_set_invalid_opcode(ctsio);
11082                         ctl_done((union ctl_io *)ctsio);
11083                         return (retval);
11084                 }
11085         }
11086
11087         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11088
11089 #ifdef CTL_WITH_CA
11090         /*
11091          * If we've got a request sense, it'll clear the contingent
11092          * allegiance condition.  Otherwise, if we have a CA condition for
11093          * this initiator, clear it, because it sent down a command other
11094          * than request sense.
11095          */
11096         if ((ctsio->cdb[0] != REQUEST_SENSE)
11097          && (ctl_is_set(lun->have_ca, initidx)))
11098                 ctl_clear_mask(lun->have_ca, initidx);
11099 #endif
11100
11101         /*
11102          * If the command has this flag set, it handles its own unit
11103          * attention reporting, we shouldn't do anything.  Otherwise we
11104          * check for any pending unit attentions, and send them back to the
11105          * initiator.  We only do this when a command initially comes in,
11106          * not when we pull it off the blocked queue.
11107          *
11108          * According to SAM-3, section 5.3.2, the order that things get
11109          * presented back to the host is basically unit attentions caused
11110          * by some sort of reset event, busy status, reservation conflicts
11111          * or task set full, and finally any other status.
11112          *
11113          * One issue here is that some of the unit attentions we report
11114          * don't fall into the "reset" category (e.g. "reported luns data
11115          * has changed").  So reporting it here, before the reservation
11116          * check, may be technically wrong.  I guess the only thing to do
11117          * would be to check for and report the reset events here, and then
11118          * check for the other unit attention types after we check for a
11119          * reservation conflict.
11120          *
11121          * XXX KDM need to fix this
11122          */
11123         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11124                 ctl_ua_type ua_type;
11125                 scsi_sense_data_type sense_format;
11126
11127                 if (lun->flags & CTL_LUN_SENSE_DESC)
11128                         sense_format = SSD_TYPE_DESC;
11129                 else
11130                         sense_format = SSD_TYPE_FIXED;
11131
11132                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11133                     sense_format);
11134                 if (ua_type != CTL_UA_NONE) {
11135                         mtx_unlock(&lun->lun_lock);
11136                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11137                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11138                         ctsio->sense_len = SSD_FULL_SIZE;
11139                         ctl_done((union ctl_io *)ctsio);
11140                         return (retval);
11141                 }
11142         }
11143
11144
11145         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11146                 mtx_unlock(&lun->lun_lock);
11147                 ctl_done((union ctl_io *)ctsio);
11148                 return (retval);
11149         }
11150
11151         /*
11152          * XXX CHD this is where we want to send IO to other side if
11153          * this LUN is secondary on this SC. We will need to make a copy
11154          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11155          * the copy we send as FROM_OTHER.
11156          * We also need to stuff the address of the original IO so we can
11157          * find it easily. Something similar will need be done on the other
11158          * side so when we are done we can find the copy.
11159          */
11160         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11161             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0) {
11162                 union ctl_ha_msg msg_info;
11163                 int isc_retval;
11164
11165                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11166                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11167                 mtx_unlock(&lun->lun_lock);
11168
11169                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11170                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11171                 msg_info.hdr.serializing_sc = NULL;
11172                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11173                 msg_info.scsi.tag_num = ctsio->tag_num;
11174                 msg_info.scsi.tag_type = ctsio->tag_type;
11175                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11176                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11177
11178                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11179                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11180                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11181                         ctl_set_busy(ctsio);
11182                         ctl_done((union ctl_io *)ctsio);
11183                         return (retval);
11184                 }
11185                 return (retval);
11186         }
11187
11188         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11189                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11190                               ctl_ooaq, ooa_links))) {
11191         case CTL_ACTION_BLOCK:
11192                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11193                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11194                                   blocked_links);
11195                 mtx_unlock(&lun->lun_lock);
11196                 return (retval);
11197         case CTL_ACTION_PASS:
11198         case CTL_ACTION_SKIP:
11199                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11200                 mtx_unlock(&lun->lun_lock);
11201                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11202                 break;
11203         case CTL_ACTION_OVERLAP:
11204                 mtx_unlock(&lun->lun_lock);
11205                 ctl_set_overlapped_cmd(ctsio);
11206                 ctl_done((union ctl_io *)ctsio);
11207                 break;
11208         case CTL_ACTION_OVERLAP_TAG:
11209                 mtx_unlock(&lun->lun_lock);
11210                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11211                 ctl_done((union ctl_io *)ctsio);
11212                 break;
11213         case CTL_ACTION_ERROR:
11214         default:
11215                 mtx_unlock(&lun->lun_lock);
11216                 ctl_set_internal_failure(ctsio,
11217                                          /*sks_valid*/ 0,
11218                                          /*retry_count*/ 0);
11219                 ctl_done((union ctl_io *)ctsio);
11220                 break;
11221         }
11222         return (retval);
11223 }
11224
11225 const struct ctl_cmd_entry *
11226 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11227 {
11228         const struct ctl_cmd_entry *entry;
11229         int service_action;
11230
11231         entry = &ctl_cmd_table[ctsio->cdb[0]];
11232         if (sa)
11233                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11234         if (entry->flags & CTL_CMD_FLAG_SA5) {
11235                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11236                 entry = &((const struct ctl_cmd_entry *)
11237                     entry->execute)[service_action];
11238         }
11239         return (entry);
11240 }
11241
11242 const struct ctl_cmd_entry *
11243 ctl_validate_command(struct ctl_scsiio *ctsio)
11244 {
11245         const struct ctl_cmd_entry *entry;
11246         int i, sa;
11247         uint8_t diff;
11248
11249         entry = ctl_get_cmd_entry(ctsio, &sa);
11250         if (entry->execute == NULL) {
11251                 if (sa)
11252                         ctl_set_invalid_field(ctsio,
11253                                               /*sks_valid*/ 1,
11254                                               /*command*/ 1,
11255                                               /*field*/ 1,
11256                                               /*bit_valid*/ 1,
11257                                               /*bit*/ 4);
11258                 else
11259                         ctl_set_invalid_opcode(ctsio);
11260                 ctl_done((union ctl_io *)ctsio);
11261                 return (NULL);
11262         }
11263         KASSERT(entry->length > 0,
11264             ("Not defined length for command 0x%02x/0x%02x",
11265              ctsio->cdb[0], ctsio->cdb[1]));
11266         for (i = 1; i < entry->length; i++) {
11267                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11268                 if (diff == 0)
11269                         continue;
11270                 ctl_set_invalid_field(ctsio,
11271                                       /*sks_valid*/ 1,
11272                                       /*command*/ 1,
11273                                       /*field*/ i,
11274                                       /*bit_valid*/ 1,
11275                                       /*bit*/ fls(diff) - 1);
11276                 ctl_done((union ctl_io *)ctsio);
11277                 return (NULL);
11278         }
11279         return (entry);
11280 }
11281
11282 static int
11283 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11284 {
11285
11286         switch (lun_type) {
11287         case T_PROCESSOR:
11288                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11289                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11290                         return (0);
11291                 break;
11292         case T_DIRECT:
11293                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11294                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11295                         return (0);
11296                 break;
11297         default:
11298                 return (0);
11299         }
11300         return (1);
11301 }
11302
11303 static int
11304 ctl_scsiio(struct ctl_scsiio *ctsio)
11305 {
11306         int retval;
11307         const struct ctl_cmd_entry *entry;
11308
11309         retval = CTL_RETVAL_COMPLETE;
11310
11311         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11312
11313         entry = ctl_get_cmd_entry(ctsio, NULL);
11314
11315         /*
11316          * If this I/O has been aborted, just send it straight to
11317          * ctl_done() without executing it.
11318          */
11319         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11320                 ctl_done((union ctl_io *)ctsio);
11321                 goto bailout;
11322         }
11323
11324         /*
11325          * All the checks should have been handled by ctl_scsiio_precheck().
11326          * We should be clear now to just execute the I/O.
11327          */
11328         retval = entry->execute(ctsio);
11329
11330 bailout:
11331         return (retval);
11332 }
11333
11334 /*
11335  * Since we only implement one target right now, a bus reset simply resets
11336  * our single target.
11337  */
11338 static int
11339 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11340 {
11341         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11342 }
11343
11344 static int
11345 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11346                  ctl_ua_type ua_type)
11347 {
11348         struct ctl_port *port;
11349         struct ctl_lun *lun;
11350         int retval;
11351
11352         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11353                 union ctl_ha_msg msg_info;
11354
11355                 msg_info.hdr.nexus = io->io_hdr.nexus;
11356                 if (ua_type==CTL_UA_TARG_RESET)
11357                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11358                 else
11359                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11360                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11361                 msg_info.hdr.original_sc = NULL;
11362                 msg_info.hdr.serializing_sc = NULL;
11363                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11364                     sizeof(msg_info.task), M_WAITOK);
11365         }
11366         retval = 0;
11367
11368         mtx_lock(&softc->ctl_lock);
11369         port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11370         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11371                 if (port != NULL &&
11372                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11373                         continue;
11374                 retval += ctl_lun_reset(lun, io, ua_type);
11375         }
11376         mtx_unlock(&softc->ctl_lock);
11377
11378         return (retval);
11379 }
11380
11381 /*
11382  * The LUN should always be set.  The I/O is optional, and is used to
11383  * distinguish between I/Os sent by this initiator, and by other
11384  * initiators.  We set unit attention for initiators other than this one.
11385  * SAM-3 is vague on this point.  It does say that a unit attention should
11386  * be established for other initiators when a LUN is reset (see section
11387  * 5.7.3), but it doesn't specifically say that the unit attention should
11388  * be established for this particular initiator when a LUN is reset.  Here
11389  * is the relevant text, from SAM-3 rev 8:
11390  *
11391  * 5.7.2 When a SCSI initiator port aborts its own tasks
11392  *
11393  * When a SCSI initiator port causes its own task(s) to be aborted, no
11394  * notification that the task(s) have been aborted shall be returned to
11395  * the SCSI initiator port other than the completion response for the
11396  * command or task management function action that caused the task(s) to
11397  * be aborted and notification(s) associated with related effects of the
11398  * action (e.g., a reset unit attention condition).
11399  *
11400  * XXX KDM for now, we're setting unit attention for all initiators.
11401  */
11402 static int
11403 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11404 {
11405         union ctl_io *xio;
11406 #if 0
11407         uint32_t initidx;
11408 #endif
11409 #ifdef CTL_WITH_CA
11410         int i;
11411 #endif
11412
11413         mtx_lock(&lun->lun_lock);
11414         /*
11415          * Run through the OOA queue and abort each I/O.
11416          */
11417         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11418              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11419                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11420         }
11421
11422         /*
11423          * This version sets unit attention for every
11424          */
11425 #if 0
11426         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11427         ctl_est_ua_all(lun, initidx, ua_type);
11428 #else
11429         ctl_est_ua_all(lun, -1, ua_type);
11430 #endif
11431
11432         /*
11433          * A reset (any kind, really) clears reservations established with
11434          * RESERVE/RELEASE.  It does not clear reservations established
11435          * with PERSISTENT RESERVE OUT, but we don't support that at the
11436          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11437          * reservations made with the RESERVE/RELEASE commands, because
11438          * those commands are obsolete in SPC-3.
11439          */
11440         lun->flags &= ~CTL_LUN_RESERVED;
11441
11442 #ifdef CTL_WITH_CA
11443         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11444                 ctl_clear_mask(lun->have_ca, i);
11445 #endif
11446         mtx_unlock(&lun->lun_lock);
11447
11448         return (0);
11449 }
11450
11451 static void
11452 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11453     int other_sc)
11454 {
11455         union ctl_io *xio;
11456
11457         mtx_assert(&lun->lun_lock, MA_OWNED);
11458
11459         /*
11460          * Run through the OOA queue and attempt to find the given I/O.
11461          * The target port, initiator ID, tag type and tag number have to
11462          * match the values that we got from the initiator.  If we have an
11463          * untagged command to abort, simply abort the first untagged command
11464          * we come to.  We only allow one untagged command at a time of course.
11465          */
11466         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11467              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11468
11469                 if ((targ_port == UINT32_MAX ||
11470                      targ_port == xio->io_hdr.nexus.targ_port) &&
11471                     (init_id == UINT32_MAX ||
11472                      init_id == xio->io_hdr.nexus.initid)) {
11473                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11474                             init_id != xio->io_hdr.nexus.initid)
11475                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11476                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11477                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11478                                 union ctl_ha_msg msg_info;
11479
11480                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11481                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11482                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11483                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11484                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11485                                 msg_info.hdr.original_sc = NULL;
11486                                 msg_info.hdr.serializing_sc = NULL;
11487                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11488                                     sizeof(msg_info.task), M_NOWAIT);
11489                         }
11490                 }
11491         }
11492 }
11493
11494 static int
11495 ctl_abort_task_set(union ctl_io *io)
11496 {
11497         struct ctl_softc *softc = control_softc;
11498         struct ctl_lun *lun;
11499         uint32_t targ_lun;
11500
11501         /*
11502          * Look up the LUN.
11503          */
11504         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11505         mtx_lock(&softc->ctl_lock);
11506         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11507                 lun = softc->ctl_luns[targ_lun];
11508         else {
11509                 mtx_unlock(&softc->ctl_lock);
11510                 return (1);
11511         }
11512
11513         mtx_lock(&lun->lun_lock);
11514         mtx_unlock(&softc->ctl_lock);
11515         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11516                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11517                     io->io_hdr.nexus.initid,
11518                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11519         } else { /* CTL_TASK_CLEAR_TASK_SET */
11520                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11521                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11522         }
11523         mtx_unlock(&lun->lun_lock);
11524         return (0);
11525 }
11526
11527 static int
11528 ctl_i_t_nexus_reset(union ctl_io *io)
11529 {
11530         struct ctl_softc *softc = control_softc;
11531         struct ctl_lun *lun;
11532         uint32_t initidx;
11533
11534         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11535                 union ctl_ha_msg msg_info;
11536
11537                 msg_info.hdr.nexus = io->io_hdr.nexus;
11538                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11539                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11540                 msg_info.hdr.original_sc = NULL;
11541                 msg_info.hdr.serializing_sc = NULL;
11542                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11543                     sizeof(msg_info.task), M_WAITOK);
11544         }
11545
11546         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11547         mtx_lock(&softc->ctl_lock);
11548         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11549                 mtx_lock(&lun->lun_lock);
11550                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11551                     io->io_hdr.nexus.initid, 1);
11552 #ifdef CTL_WITH_CA
11553                 ctl_clear_mask(lun->have_ca, initidx);
11554 #endif
11555                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11556                         lun->flags &= ~CTL_LUN_RESERVED;
11557                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11558                 mtx_unlock(&lun->lun_lock);
11559         }
11560         mtx_unlock(&softc->ctl_lock);
11561         return (0);
11562 }
11563
11564 static int
11565 ctl_abort_task(union ctl_io *io)
11566 {
11567         union ctl_io *xio;
11568         struct ctl_lun *lun;
11569         struct ctl_softc *softc;
11570 #if 0
11571         struct sbuf sb;
11572         char printbuf[128];
11573 #endif
11574         int found;
11575         uint32_t targ_lun;
11576
11577         softc = control_softc;
11578         found = 0;
11579
11580         /*
11581          * Look up the LUN.
11582          */
11583         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11584         mtx_lock(&softc->ctl_lock);
11585         if ((targ_lun < CTL_MAX_LUNS)
11586          && (softc->ctl_luns[targ_lun] != NULL))
11587                 lun = softc->ctl_luns[targ_lun];
11588         else {
11589                 mtx_unlock(&softc->ctl_lock);
11590                 return (1);
11591         }
11592
11593 #if 0
11594         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11595                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11596 #endif
11597
11598         mtx_lock(&lun->lun_lock);
11599         mtx_unlock(&softc->ctl_lock);
11600         /*
11601          * Run through the OOA queue and attempt to find the given I/O.
11602          * The target port, initiator ID, tag type and tag number have to
11603          * match the values that we got from the initiator.  If we have an
11604          * untagged command to abort, simply abort the first untagged command
11605          * we come to.  We only allow one untagged command at a time of course.
11606          */
11607         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11608              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11609 #if 0
11610                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11611
11612                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11613                             lun->lun, xio->scsiio.tag_num,
11614                             xio->scsiio.tag_type,
11615                             (xio->io_hdr.blocked_links.tqe_prev
11616                             == NULL) ? "" : " BLOCKED",
11617                             (xio->io_hdr.flags &
11618                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11619                             (xio->io_hdr.flags &
11620                             CTL_FLAG_ABORT) ? " ABORT" : "",
11621                             (xio->io_hdr.flags &
11622                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11623                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11624                 sbuf_finish(&sb);
11625                 printf("%s\n", sbuf_data(&sb));
11626 #endif
11627
11628                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11629                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11630                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11631                         continue;
11632
11633                 /*
11634                  * If the abort says that the task is untagged, the
11635                  * task in the queue must be untagged.  Otherwise,
11636                  * we just check to see whether the tag numbers
11637                  * match.  This is because the QLogic firmware
11638                  * doesn't pass back the tag type in an abort
11639                  * request.
11640                  */
11641 #if 0
11642                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11643                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11644                  || (xio->scsiio.tag_num == io->taskio.tag_num))
11645 #endif
11646                 /*
11647                  * XXX KDM we've got problems with FC, because it
11648                  * doesn't send down a tag type with aborts.  So we
11649                  * can only really go by the tag number...
11650                  * This may cause problems with parallel SCSI.
11651                  * Need to figure that out!!
11652                  */
11653                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
11654                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11655                         found = 1;
11656                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11657                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11658                                 union ctl_ha_msg msg_info;
11659
11660                                 msg_info.hdr.nexus = io->io_hdr.nexus;
11661                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11662                                 msg_info.task.tag_num = io->taskio.tag_num;
11663                                 msg_info.task.tag_type = io->taskio.tag_type;
11664                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11665                                 msg_info.hdr.original_sc = NULL;
11666                                 msg_info.hdr.serializing_sc = NULL;
11667 #if 0
11668                                 printf("Sent Abort to other side\n");
11669 #endif
11670                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11671                                     sizeof(msg_info.task), M_NOWAIT);
11672                         }
11673 #if 0
11674                         printf("ctl_abort_task: found I/O to abort\n");
11675 #endif
11676                 }
11677         }
11678         mtx_unlock(&lun->lun_lock);
11679
11680         if (found == 0) {
11681                 /*
11682                  * This isn't really an error.  It's entirely possible for
11683                  * the abort and command completion to cross on the wire.
11684                  * This is more of an informative/diagnostic error.
11685                  */
11686 #if 0
11687                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11688                        "%u:%u:%u tag %d type %d\n",
11689                        io->io_hdr.nexus.initid,
11690                        io->io_hdr.nexus.targ_port,
11691                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11692                        io->taskio.tag_type);
11693 #endif
11694         }
11695         return (0);
11696 }
11697
11698 static void
11699 ctl_run_task(union ctl_io *io)
11700 {
11701         struct ctl_softc *softc = control_softc;
11702         int retval = 1;
11703         const char *task_desc;
11704
11705         CTL_DEBUG_PRINT(("ctl_run_task\n"));
11706
11707         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11708             ("ctl_run_task: Unextected io_type %d\n",
11709              io->io_hdr.io_type));
11710
11711         task_desc = ctl_scsi_task_string(&io->taskio);
11712         if (task_desc != NULL) {
11713 #ifdef NEEDTOPORT
11714                 csevent_log(CSC_CTL | CSC_SHELF_SW |
11715                             CTL_TASK_REPORT,
11716                             csevent_LogType_Trace,
11717                             csevent_Severity_Information,
11718                             csevent_AlertLevel_Green,
11719                             csevent_FRU_Firmware,
11720                             csevent_FRU_Unknown,
11721                             "CTL: received task: %s",task_desc);
11722 #endif
11723         } else {
11724 #ifdef NEEDTOPORT
11725                 csevent_log(CSC_CTL | CSC_SHELF_SW |
11726                             CTL_TASK_REPORT,
11727                             csevent_LogType_Trace,
11728                             csevent_Severity_Information,
11729                             csevent_AlertLevel_Green,
11730                             csevent_FRU_Firmware,
11731                             csevent_FRU_Unknown,
11732                             "CTL: received unknown task "
11733                             "type: %d (%#x)",
11734                             io->taskio.task_action,
11735                             io->taskio.task_action);
11736 #endif
11737         }
11738         switch (io->taskio.task_action) {
11739         case CTL_TASK_ABORT_TASK:
11740                 retval = ctl_abort_task(io);
11741                 break;
11742         case CTL_TASK_ABORT_TASK_SET:
11743         case CTL_TASK_CLEAR_TASK_SET:
11744                 retval = ctl_abort_task_set(io);
11745                 break;
11746         case CTL_TASK_CLEAR_ACA:
11747                 break;
11748         case CTL_TASK_I_T_NEXUS_RESET:
11749                 retval = ctl_i_t_nexus_reset(io);
11750                 break;
11751         case CTL_TASK_LUN_RESET: {
11752                 struct ctl_lun *lun;
11753                 uint32_t targ_lun;
11754
11755                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11756                 mtx_lock(&softc->ctl_lock);
11757                 if ((targ_lun < CTL_MAX_LUNS)
11758                  && (softc->ctl_luns[targ_lun] != NULL))
11759                         lun = softc->ctl_luns[targ_lun];
11760                 else {
11761                         mtx_unlock(&softc->ctl_lock);
11762                         retval = 1;
11763                         break;
11764                 }
11765                 retval = ctl_lun_reset(lun, io, CTL_UA_LUN_RESET);
11766                 mtx_unlock(&softc->ctl_lock);
11767
11768                 if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11769                         union ctl_ha_msg msg_info;
11770
11771                         msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11772                         msg_info.hdr.nexus = io->io_hdr.nexus;
11773                         msg_info.task.task_action = CTL_TASK_LUN_RESET;
11774                         msg_info.hdr.original_sc = NULL;
11775                         msg_info.hdr.serializing_sc = NULL;
11776                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11777                             sizeof(msg_info.task), M_WAITOK);
11778                 }
11779                 break;
11780         }
11781         case CTL_TASK_TARGET_RESET:
11782                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11783                 break;
11784         case CTL_TASK_BUS_RESET:
11785                 retval = ctl_bus_reset(softc, io);
11786                 break;
11787         case CTL_TASK_PORT_LOGIN:
11788                 break;
11789         case CTL_TASK_PORT_LOGOUT:
11790                 break;
11791         default:
11792                 printf("ctl_run_task: got unknown task management event %d\n",
11793                        io->taskio.task_action);
11794                 break;
11795         }
11796         if (retval == 0)
11797                 io->io_hdr.status = CTL_SUCCESS;
11798         else
11799                 io->io_hdr.status = CTL_ERROR;
11800         ctl_done(io);
11801 }
11802
11803 /*
11804  * For HA operation.  Handle commands that come in from the other
11805  * controller.
11806  */
11807 static void
11808 ctl_handle_isc(union ctl_io *io)
11809 {
11810         int free_io;
11811         struct ctl_lun *lun;
11812         struct ctl_softc *softc;
11813         uint32_t targ_lun;
11814
11815         softc = control_softc;
11816
11817         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11818         lun = softc->ctl_luns[targ_lun];
11819
11820         switch (io->io_hdr.msg_type) {
11821         case CTL_MSG_SERIALIZE:
11822                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11823                 break;
11824         case CTL_MSG_R2R: {
11825                 const struct ctl_cmd_entry *entry;
11826
11827                 /*
11828                  * This is only used in SER_ONLY mode.
11829                  */
11830                 free_io = 0;
11831                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11832                 mtx_lock(&lun->lun_lock);
11833                 if (ctl_scsiio_lun_check(lun,
11834                     entry, (struct ctl_scsiio *)io) != 0) {
11835                         mtx_unlock(&lun->lun_lock);
11836                         ctl_done(io);
11837                         break;
11838                 }
11839                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11840                 mtx_unlock(&lun->lun_lock);
11841                 ctl_enqueue_rtr(io);
11842                 break;
11843         }
11844         case CTL_MSG_FINISH_IO:
11845                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
11846                         free_io = 0;
11847                         ctl_done(io);
11848                 } else {
11849                         free_io = 1;
11850                         mtx_lock(&lun->lun_lock);
11851                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11852                                      ooa_links);
11853                         ctl_check_blocked(lun);
11854                         mtx_unlock(&lun->lun_lock);
11855                 }
11856                 break;
11857         case CTL_MSG_PERS_ACTION:
11858                 ctl_hndl_per_res_out_on_other_sc(
11859                         (union ctl_ha_msg *)&io->presio.pr_msg);
11860                 free_io = 1;
11861                 break;
11862         case CTL_MSG_BAD_JUJU:
11863                 free_io = 0;
11864                 ctl_done(io);
11865                 break;
11866         case CTL_MSG_DATAMOVE:
11867                 /* Only used in XFER mode */
11868                 free_io = 0;
11869                 ctl_datamove_remote(io);
11870                 break;
11871         case CTL_MSG_DATAMOVE_DONE:
11872                 /* Only used in XFER mode */
11873                 free_io = 0;
11874                 io->scsiio.be_move_done(io);
11875                 break;
11876         case CTL_MSG_FAILOVER:
11877                 mtx_lock(&lun->lun_lock);
11878                 ctl_failover_lun(lun);
11879                 mtx_unlock(&lun->lun_lock);
11880                 free_io = 1;
11881                 break;
11882         default:
11883                 free_io = 1;
11884                 printf("%s: Invalid message type %d\n",
11885                        __func__, io->io_hdr.msg_type);
11886                 break;
11887         }
11888         if (free_io)
11889                 ctl_free_io(io);
11890
11891 }
11892
11893
11894 /*
11895  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11896  * there is no match.
11897  */
11898 static ctl_lun_error_pattern
11899 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11900 {
11901         const struct ctl_cmd_entry *entry;
11902         ctl_lun_error_pattern filtered_pattern, pattern;
11903
11904         pattern = desc->error_pattern;
11905
11906         /*
11907          * XXX KDM we need more data passed into this function to match a
11908          * custom pattern, and we actually need to implement custom pattern
11909          * matching.
11910          */
11911         if (pattern & CTL_LUN_PAT_CMD)
11912                 return (CTL_LUN_PAT_CMD);
11913
11914         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11915                 return (CTL_LUN_PAT_ANY);
11916
11917         entry = ctl_get_cmd_entry(ctsio, NULL);
11918
11919         filtered_pattern = entry->pattern & pattern;
11920
11921         /*
11922          * If the user requested specific flags in the pattern (e.g.
11923          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11924          * flags.
11925          *
11926          * If the user did not specify any flags, it doesn't matter whether
11927          * or not the command supports the flags.
11928          */
11929         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11930              (pattern & ~CTL_LUN_PAT_MASK))
11931                 return (CTL_LUN_PAT_NONE);
11932
11933         /*
11934          * If the user asked for a range check, see if the requested LBA
11935          * range overlaps with this command's LBA range.
11936          */
11937         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
11938                 uint64_t lba1;
11939                 uint64_t len1;
11940                 ctl_action action;
11941                 int retval;
11942
11943                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
11944                 if (retval != 0)
11945                         return (CTL_LUN_PAT_NONE);
11946
11947                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
11948                                               desc->lba_range.len, FALSE);
11949                 /*
11950                  * A "pass" means that the LBA ranges don't overlap, so
11951                  * this doesn't match the user's range criteria.
11952                  */
11953                 if (action == CTL_ACTION_PASS)
11954                         return (CTL_LUN_PAT_NONE);
11955         }
11956
11957         return (filtered_pattern);
11958 }
11959
11960 static void
11961 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
11962 {
11963         struct ctl_error_desc *desc, *desc2;
11964
11965         mtx_assert(&lun->lun_lock, MA_OWNED);
11966
11967         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
11968                 ctl_lun_error_pattern pattern;
11969                 /*
11970                  * Check to see whether this particular command matches
11971                  * the pattern in the descriptor.
11972                  */
11973                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
11974                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
11975                         continue;
11976
11977                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
11978                 case CTL_LUN_INJ_ABORTED:
11979                         ctl_set_aborted(&io->scsiio);
11980                         break;
11981                 case CTL_LUN_INJ_MEDIUM_ERR:
11982                         ctl_set_medium_error(&io->scsiio);
11983                         break;
11984                 case CTL_LUN_INJ_UA:
11985                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
11986                          * OCCURRED */
11987                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
11988                         break;
11989                 case CTL_LUN_INJ_CUSTOM:
11990                         /*
11991                          * We're assuming the user knows what he is doing.
11992                          * Just copy the sense information without doing
11993                          * checks.
11994                          */
11995                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
11996                               MIN(sizeof(desc->custom_sense),
11997                                   sizeof(io->scsiio.sense_data)));
11998                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
11999                         io->scsiio.sense_len = SSD_FULL_SIZE;
12000                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12001                         break;
12002                 case CTL_LUN_INJ_NONE:
12003                 default:
12004                         /*
12005                          * If this is an error injection type we don't know
12006                          * about, clear the continuous flag (if it is set)
12007                          * so it will get deleted below.
12008                          */
12009                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12010                         break;
12011                 }
12012                 /*
12013                  * By default, each error injection action is a one-shot
12014                  */
12015                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12016                         continue;
12017
12018                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12019
12020                 free(desc, M_CTL);
12021         }
12022 }
12023
12024 #ifdef CTL_IO_DELAY
12025 static void
12026 ctl_datamove_timer_wakeup(void *arg)
12027 {
12028         union ctl_io *io;
12029
12030         io = (union ctl_io *)arg;
12031
12032         ctl_datamove(io);
12033 }
12034 #endif /* CTL_IO_DELAY */
12035
12036 void
12037 ctl_datamove(union ctl_io *io)
12038 {
12039         void (*fe_datamove)(union ctl_io *io);
12040
12041         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12042
12043         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12044
12045 #ifdef CTL_TIME_IO
12046         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12047                 char str[256];
12048                 char path_str[64];
12049                 struct sbuf sb;
12050
12051                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12052                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12053
12054                 sbuf_cat(&sb, path_str);
12055                 switch (io->io_hdr.io_type) {
12056                 case CTL_IO_SCSI:
12057                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12058                         sbuf_printf(&sb, "\n");
12059                         sbuf_cat(&sb, path_str);
12060                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12061                                     io->scsiio.tag_num, io->scsiio.tag_type);
12062                         break;
12063                 case CTL_IO_TASK:
12064                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12065                                     "Tag Type: %d\n", io->taskio.task_action,
12066                                     io->taskio.tag_num, io->taskio.tag_type);
12067                         break;
12068                 default:
12069                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12070                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12071                         break;
12072                 }
12073                 sbuf_cat(&sb, path_str);
12074                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12075                             (intmax_t)time_uptime - io->io_hdr.start_time);
12076                 sbuf_finish(&sb);
12077                 printf("%s", sbuf_data(&sb));
12078         }
12079 #endif /* CTL_TIME_IO */
12080
12081 #ifdef CTL_IO_DELAY
12082         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12083                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12084         } else {
12085                 struct ctl_lun *lun;
12086
12087                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12088                 if ((lun != NULL)
12089                  && (lun->delay_info.datamove_delay > 0)) {
12090
12091                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12092                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12093                         callout_reset(&io->io_hdr.delay_callout,
12094                                       lun->delay_info.datamove_delay * hz,
12095                                       ctl_datamove_timer_wakeup, io);
12096                         if (lun->delay_info.datamove_type ==
12097                             CTL_DELAY_TYPE_ONESHOT)
12098                                 lun->delay_info.datamove_delay = 0;
12099                         return;
12100                 }
12101         }
12102 #endif
12103
12104         /*
12105          * This command has been aborted.  Set the port status, so we fail
12106          * the data move.
12107          */
12108         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12109                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12110                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12111                        io->io_hdr.nexus.targ_port,
12112                        io->io_hdr.nexus.targ_lun);
12113                 io->io_hdr.port_status = 31337;
12114                 /*
12115                  * Note that the backend, in this case, will get the
12116                  * callback in its context.  In other cases it may get
12117                  * called in the frontend's interrupt thread context.
12118                  */
12119                 io->scsiio.be_move_done(io);
12120                 return;
12121         }
12122
12123         /* Don't confuse frontend with zero length data move. */
12124         if (io->scsiio.kern_data_len == 0) {
12125                 io->scsiio.be_move_done(io);
12126                 return;
12127         }
12128
12129         /*
12130          * If we're in XFER mode and this I/O is from the other shelf
12131          * controller, we need to send the DMA to the other side to
12132          * actually transfer the data to/from the host.  In serialize only
12133          * mode the transfer happens below CTL and ctl_datamove() is only
12134          * called on the machine that originally received the I/O.
12135          */
12136         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12137          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12138                 union ctl_ha_msg msg;
12139                 uint32_t sg_entries_sent;
12140                 int do_sg_copy;
12141                 int i;
12142
12143                 memset(&msg, 0, sizeof(msg));
12144                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12145                 msg.hdr.original_sc = io->io_hdr.original_sc;
12146                 msg.hdr.serializing_sc = io;
12147                 msg.hdr.nexus = io->io_hdr.nexus;
12148                 msg.dt.flags = io->io_hdr.flags;
12149                 /*
12150                  * We convert everything into a S/G list here.  We can't
12151                  * pass by reference, only by value between controllers.
12152                  * So we can't pass a pointer to the S/G list, only as many
12153                  * S/G entries as we can fit in here.  If it's possible for
12154                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12155                  * then we need to break this up into multiple transfers.
12156                  */
12157                 if (io->scsiio.kern_sg_entries == 0) {
12158                         msg.dt.kern_sg_entries = 1;
12159 #if 0
12160                         /*
12161                          * Convert to a physical address if this is a
12162                          * virtual address.
12163                          */
12164                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12165                                 msg.dt.sg_list[0].addr =
12166                                         io->scsiio.kern_data_ptr;
12167                         } else {
12168                                 /*
12169                                  * XXX KDM use busdma here!
12170                                  */
12171                                 msg.dt.sg_list[0].addr = (void *)
12172                                         vtophys(io->scsiio.kern_data_ptr);
12173                         }
12174 #else
12175                         KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12176                             ("HA does not support BUS_ADDR"));
12177                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12178 #endif
12179
12180                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12181                         do_sg_copy = 0;
12182                 } else {
12183                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12184                         do_sg_copy = 1;
12185                 }
12186
12187                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12188                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12189                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12190                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12191                 msg.dt.sg_sequence = 0;
12192
12193                 /*
12194                  * Loop until we've sent all of the S/G entries.  On the
12195                  * other end, we'll recompose these S/G entries into one
12196                  * contiguous list before passing it to the
12197                  */
12198                 for (sg_entries_sent = 0; sg_entries_sent <
12199                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12200                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12201                                 sizeof(msg.dt.sg_list[0])),
12202                                 msg.dt.kern_sg_entries - sg_entries_sent);
12203
12204                         if (do_sg_copy != 0) {
12205                                 struct ctl_sg_entry *sgl;
12206                                 int j;
12207
12208                                 sgl = (struct ctl_sg_entry *)
12209                                         io->scsiio.kern_data_ptr;
12210                                 /*
12211                                  * If this is in cached memory, flush the cache
12212                                  * before we send the DMA request to the other
12213                                  * controller.  We want to do this in either
12214                                  * the * read or the write case.  The read
12215                                  * case is straightforward.  In the write
12216                                  * case, we want to make sure nothing is
12217                                  * in the local cache that could overwrite
12218                                  * the DMAed data.
12219                                  */
12220
12221                                 for (i = sg_entries_sent, j = 0;
12222                                      i < msg.dt.cur_sg_entries; i++, j++) {
12223 #if 0
12224                                         if ((io->io_hdr.flags &
12225                                              CTL_FLAG_BUS_ADDR) == 0) {
12226                                                 /*
12227                                                  * XXX KDM use busdma.
12228                                                  */
12229                                                 msg.dt.sg_list[j].addr =(void *)
12230                                                        vtophys(sgl[i].addr);
12231                                         } else {
12232                                                 msg.dt.sg_list[j].addr =
12233                                                         sgl[i].addr;
12234                                         }
12235 #else
12236                                         KASSERT((io->io_hdr.flags &
12237                                             CTL_FLAG_BUS_ADDR) == 0,
12238                                             ("HA does not support BUS_ADDR"));
12239                                         msg.dt.sg_list[j].addr = sgl[i].addr;
12240 #endif
12241                                         msg.dt.sg_list[j].len = sgl[i].len;
12242                                 }
12243                         }
12244
12245                         sg_entries_sent += msg.dt.cur_sg_entries;
12246                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12247                                 msg.dt.sg_last = 1;
12248                         else
12249                                 msg.dt.sg_last = 0;
12250
12251                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12252                             sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12253                             sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12254                             M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12255                                 io->io_hdr.port_status = 31341;
12256                                 io->scsiio.be_move_done(io);
12257                                 return;
12258                         }
12259
12260                         msg.dt.sent_sg_entries = sg_entries_sent;
12261                 }
12262                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12263         } else {
12264
12265                 /*
12266                  * Lookup the fe_datamove() function for this particular
12267                  * front end.
12268                  */
12269                 fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12270
12271                 fe_datamove(io);
12272         }
12273 }
12274
12275 static void
12276 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12277 {
12278         union ctl_ha_msg msg;
12279
12280         memset(&msg, 0, sizeof(msg));
12281
12282         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12283         msg.hdr.original_sc = io;
12284         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12285         msg.hdr.nexus = io->io_hdr.nexus;
12286         msg.hdr.status = io->io_hdr.status;
12287         msg.scsi.tag_num = io->scsiio.tag_num;
12288         msg.scsi.tag_type = io->scsiio.tag_type;
12289         msg.scsi.scsi_status = io->scsiio.scsi_status;
12290         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12291                io->scsiio.sense_len);
12292         msg.scsi.sense_len = io->scsiio.sense_len;
12293         msg.scsi.sense_residual = io->scsiio.sense_residual;
12294         msg.scsi.fetd_status = io->io_hdr.port_status;
12295         msg.scsi.residual = io->scsiio.residual;
12296         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12297
12298         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12299                 ctl_failover_io(io, /*have_lock*/ have_lock);
12300                 return;
12301         }
12302
12303         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12304             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12305             msg.scsi.sense_len, M_WAITOK);
12306 }
12307
12308 /*
12309  * The DMA to the remote side is done, now we need to tell the other side
12310  * we're done so it can continue with its data movement.
12311  */
12312 static void
12313 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12314 {
12315         union ctl_io *io;
12316         int i;
12317
12318         io = rq->context;
12319
12320         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12321                 printf("%s: ISC DMA write failed with error %d", __func__,
12322                        rq->ret);
12323                 ctl_set_internal_failure(&io->scsiio,
12324                                          /*sks_valid*/ 1,
12325                                          /*retry_count*/ rq->ret);
12326         }
12327
12328         ctl_dt_req_free(rq);
12329
12330         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12331                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12332         free(io->io_hdr.remote_sglist, M_CTL);
12333         io->io_hdr.remote_sglist = NULL;
12334         io->io_hdr.local_sglist = NULL;
12335
12336         /*
12337          * The data is in local and remote memory, so now we need to send
12338          * status (good or back) back to the other side.
12339          */
12340         ctl_send_datamove_done(io, /*have_lock*/ 0);
12341 }
12342
12343 /*
12344  * We've moved the data from the host/controller into local memory.  Now we
12345  * need to push it over to the remote controller's memory.
12346  */
12347 static int
12348 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12349 {
12350         int retval;
12351
12352         retval = 0;
12353
12354         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12355                                           ctl_datamove_remote_write_cb);
12356
12357         return (retval);
12358 }
12359
12360 static void
12361 ctl_datamove_remote_write(union ctl_io *io)
12362 {
12363         int retval;
12364         void (*fe_datamove)(union ctl_io *io);
12365
12366         /*
12367          * - Get the data from the host/HBA into local memory.
12368          * - DMA memory from the local controller to the remote controller.
12369          * - Send status back to the remote controller.
12370          */
12371
12372         retval = ctl_datamove_remote_sgl_setup(io);
12373         if (retval != 0)
12374                 return;
12375
12376         /* Switch the pointer over so the FETD knows what to do */
12377         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12378
12379         /*
12380          * Use a custom move done callback, since we need to send completion
12381          * back to the other controller, not to the backend on this side.
12382          */
12383         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12384
12385         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12386
12387         fe_datamove(io);
12388
12389         return;
12390
12391 }
12392
12393 static int
12394 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12395 {
12396 #if 0
12397         char str[256];
12398         char path_str[64];
12399         struct sbuf sb;
12400 #endif
12401         int i;
12402
12403         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12404                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12405         free(io->io_hdr.remote_sglist, M_CTL);
12406         io->io_hdr.remote_sglist = NULL;
12407         io->io_hdr.local_sglist = NULL;
12408
12409 #if 0
12410         scsi_path_string(io, path_str, sizeof(path_str));
12411         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12412         sbuf_cat(&sb, path_str);
12413         scsi_command_string(&io->scsiio, NULL, &sb);
12414         sbuf_printf(&sb, "\n");
12415         sbuf_cat(&sb, path_str);
12416         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12417                     io->scsiio.tag_num, io->scsiio.tag_type);
12418         sbuf_cat(&sb, path_str);
12419         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12420                     io->io_hdr.flags, io->io_hdr.status);
12421         sbuf_finish(&sb);
12422         printk("%s", sbuf_data(&sb));
12423 #endif
12424
12425
12426         /*
12427          * The read is done, now we need to send status (good or bad) back
12428          * to the other side.
12429          */
12430         ctl_send_datamove_done(io, /*have_lock*/ 0);
12431
12432         return (0);
12433 }
12434
12435 static void
12436 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12437 {
12438         union ctl_io *io;
12439         void (*fe_datamove)(union ctl_io *io);
12440
12441         io = rq->context;
12442
12443         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12444                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12445                        rq->ret);
12446                 ctl_set_internal_failure(&io->scsiio,
12447                                          /*sks_valid*/ 1,
12448                                          /*retry_count*/ rq->ret);
12449         }
12450
12451         ctl_dt_req_free(rq);
12452
12453         /* Switch the pointer over so the FETD knows what to do */
12454         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12455
12456         /*
12457          * Use a custom move done callback, since we need to send completion
12458          * back to the other controller, not to the backend on this side.
12459          */
12460         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12461
12462         /* XXX KDM add checks like the ones in ctl_datamove? */
12463
12464         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12465
12466         fe_datamove(io);
12467 }
12468
12469 static int
12470 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12471 {
12472         struct ctl_sg_entry *local_sglist, *remote_sglist;
12473         struct ctl_softc *softc;
12474         uint32_t len_to_go;
12475         int retval;
12476         int i;
12477
12478         retval = 0;
12479         softc = control_softc;
12480         local_sglist = io->io_hdr.local_sglist;
12481         remote_sglist = io->io_hdr.remote_sglist;
12482         len_to_go = io->scsiio.kern_data_len;
12483
12484         /*
12485          * The difficult thing here is that the size of the various
12486          * S/G segments may be different than the size from the
12487          * remote controller.  That'll make it harder when DMAing
12488          * the data back to the other side.
12489          */
12490         for (i = 0; len_to_go > 0; i++) {
12491                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12492                 local_sglist[i].addr =
12493                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12494
12495                 len_to_go -= local_sglist[i].len;
12496         }
12497         /*
12498          * Reset the number of S/G entries accordingly.  The original
12499          * number of S/G entries is available in rem_sg_entries.
12500          */
12501         io->scsiio.kern_sg_entries = i;
12502
12503 #if 0
12504         printf("%s: kern_sg_entries = %d\n", __func__,
12505                io->scsiio.kern_sg_entries);
12506         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12507                 printf("%s: sg[%d] = %p, %d\n", __func__, i,
12508                        local_sglist[i].addr, local_sglist[i].len);
12509 #endif
12510
12511         return (retval);
12512 }
12513
12514 static int
12515 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12516                          ctl_ha_dt_cb callback)
12517 {
12518         struct ctl_ha_dt_req *rq;
12519         struct ctl_sg_entry *remote_sglist, *local_sglist;
12520         uint32_t local_used, remote_used, total_used;
12521         int i, j, isc_ret;
12522
12523         rq = ctl_dt_req_alloc();
12524
12525         /*
12526          * If we failed to allocate the request, and if the DMA didn't fail
12527          * anyway, set busy status.  This is just a resource allocation
12528          * failure.
12529          */
12530         if ((rq == NULL)
12531          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12532                 ctl_set_busy(&io->scsiio);
12533
12534         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12535
12536                 if (rq != NULL)
12537                         ctl_dt_req_free(rq);
12538
12539                 /*
12540                  * The data move failed.  We need to return status back
12541                  * to the other controller.  No point in trying to DMA
12542                  * data to the remote controller.
12543                  */
12544
12545                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12546
12547                 return (1);
12548         }
12549
12550         local_sglist = io->io_hdr.local_sglist;
12551         remote_sglist = io->io_hdr.remote_sglist;
12552         local_used = 0;
12553         remote_used = 0;
12554         total_used = 0;
12555
12556         /*
12557          * Pull/push the data over the wire from/to the other controller.
12558          * This takes into account the possibility that the local and
12559          * remote sglists may not be identical in terms of the size of
12560          * the elements and the number of elements.
12561          *
12562          * One fundamental assumption here is that the length allocated for
12563          * both the local and remote sglists is identical.  Otherwise, we've
12564          * essentially got a coding error of some sort.
12565          */
12566         isc_ret = CTL_HA_STATUS_SUCCESS;
12567         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12568                 uint32_t cur_len;
12569                 uint8_t *tmp_ptr;
12570
12571                 rq->command = command;
12572                 rq->context = io;
12573
12574                 /*
12575                  * Both pointers should be aligned.  But it is possible
12576                  * that the allocation length is not.  They should both
12577                  * also have enough slack left over at the end, though,
12578                  * to round up to the next 8 byte boundary.
12579                  */
12580                 cur_len = MIN(local_sglist[i].len - local_used,
12581                               remote_sglist[j].len - remote_used);
12582                 rq->size = cur_len;
12583
12584                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12585                 tmp_ptr += local_used;
12586
12587 #if 0
12588                 /* Use physical addresses when talking to ISC hardware */
12589                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12590                         /* XXX KDM use busdma */
12591                         rq->local = vtophys(tmp_ptr);
12592                 } else
12593                         rq->local = tmp_ptr;
12594 #else
12595                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12596                     ("HA does not support BUS_ADDR"));
12597                 rq->local = tmp_ptr;
12598 #endif
12599
12600                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12601                 tmp_ptr += remote_used;
12602                 rq->remote = tmp_ptr;
12603
12604                 rq->callback = NULL;
12605
12606                 local_used += cur_len;
12607                 if (local_used >= local_sglist[i].len) {
12608                         i++;
12609                         local_used = 0;
12610                 }
12611
12612                 remote_used += cur_len;
12613                 if (remote_used >= remote_sglist[j].len) {
12614                         j++;
12615                         remote_used = 0;
12616                 }
12617                 total_used += cur_len;
12618
12619                 if (total_used >= io->scsiio.kern_data_len)
12620                         rq->callback = callback;
12621
12622 #if 0
12623                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12624                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12625                        rq->local, rq->remote, rq->size);
12626 #endif
12627
12628                 isc_ret = ctl_dt_single(rq);
12629                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12630                         break;
12631         }
12632         if (isc_ret != CTL_HA_STATUS_WAIT) {
12633                 rq->ret = isc_ret;
12634                 callback(rq);
12635         }
12636
12637         return (0);
12638 }
12639
12640 static void
12641 ctl_datamove_remote_read(union ctl_io *io)
12642 {
12643         int retval;
12644         int i;
12645
12646         /*
12647          * This will send an error to the other controller in the case of a
12648          * failure.
12649          */
12650         retval = ctl_datamove_remote_sgl_setup(io);
12651         if (retval != 0)
12652                 return;
12653
12654         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12655                                           ctl_datamove_remote_read_cb);
12656         if (retval != 0) {
12657                 /*
12658                  * Make sure we free memory if there was an error..  The
12659                  * ctl_datamove_remote_xfer() function will send the
12660                  * datamove done message, or call the callback with an
12661                  * error if there is a problem.
12662                  */
12663                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12664                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12665                 free(io->io_hdr.remote_sglist, M_CTL);
12666                 io->io_hdr.remote_sglist = NULL;
12667                 io->io_hdr.local_sglist = NULL;
12668         }
12669
12670         return;
12671 }
12672
12673 /*
12674  * Process a datamove request from the other controller.  This is used for
12675  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12676  * first.  Once that is complete, the data gets DMAed into the remote
12677  * controller's memory.  For reads, we DMA from the remote controller's
12678  * memory into our memory first, and then move it out to the FETD.
12679  */
12680 static void
12681 ctl_datamove_remote(union ctl_io *io)
12682 {
12683
12684         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12685
12686         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12687                 ctl_failover_io(io, /*have_lock*/ 0);
12688                 return;
12689         }
12690
12691         /*
12692          * Note that we look for an aborted I/O here, but don't do some of
12693          * the other checks that ctl_datamove() normally does.
12694          * We don't need to run the datamove delay code, since that should
12695          * have been done if need be on the other controller.
12696          */
12697         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12698                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12699                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12700                        io->io_hdr.nexus.targ_port,
12701                        io->io_hdr.nexus.targ_lun);
12702                 io->io_hdr.port_status = 31338;
12703                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12704                 return;
12705         }
12706
12707         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12708                 ctl_datamove_remote_write(io);
12709         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12710                 ctl_datamove_remote_read(io);
12711         else {
12712                 io->io_hdr.port_status = 31339;
12713                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12714         }
12715 }
12716
12717 static int
12718 ctl_process_done(union ctl_io *io)
12719 {
12720         struct ctl_lun *lun;
12721         struct ctl_softc *softc = control_softc;
12722         void (*fe_done)(union ctl_io *io);
12723         union ctl_ha_msg msg;
12724         uint32_t targ_port = io->io_hdr.nexus.targ_port;
12725
12726         CTL_DEBUG_PRINT(("ctl_process_done\n"));
12727
12728         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
12729                 fe_done = softc->ctl_ports[targ_port]->fe_done;
12730         else
12731                 fe_done = NULL;
12732
12733 #ifdef CTL_TIME_IO
12734         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12735                 char str[256];
12736                 char path_str[64];
12737                 struct sbuf sb;
12738
12739                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12740                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12741
12742                 sbuf_cat(&sb, path_str);
12743                 switch (io->io_hdr.io_type) {
12744                 case CTL_IO_SCSI:
12745                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12746                         sbuf_printf(&sb, "\n");
12747                         sbuf_cat(&sb, path_str);
12748                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12749                                     io->scsiio.tag_num, io->scsiio.tag_type);
12750                         break;
12751                 case CTL_IO_TASK:
12752                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12753                                     "Tag Type: %d\n", io->taskio.task_action,
12754                                     io->taskio.tag_num, io->taskio.tag_type);
12755                         break;
12756                 default:
12757                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12758                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12759                         break;
12760                 }
12761                 sbuf_cat(&sb, path_str);
12762                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12763                             (intmax_t)time_uptime - io->io_hdr.start_time);
12764                 sbuf_finish(&sb);
12765                 printf("%s", sbuf_data(&sb));
12766         }
12767 #endif /* CTL_TIME_IO */
12768
12769         switch (io->io_hdr.io_type) {
12770         case CTL_IO_SCSI:
12771                 break;
12772         case CTL_IO_TASK:
12773                 if (ctl_debug & CTL_DEBUG_INFO)
12774                         ctl_io_error_print(io, NULL);
12775                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12776                         ctl_free_io(io);
12777                 else
12778                         fe_done(io);
12779                 return (CTL_RETVAL_COMPLETE);
12780         default:
12781                 panic("ctl_process_done: invalid io type %d\n",
12782                       io->io_hdr.io_type);
12783                 break; /* NOTREACHED */
12784         }
12785
12786         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12787         if (lun == NULL) {
12788                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12789                                  io->io_hdr.nexus.targ_mapped_lun));
12790                 goto bailout;
12791         }
12792
12793         mtx_lock(&lun->lun_lock);
12794
12795         /*
12796          * Check to see if we have any errors to inject here.  We only
12797          * inject errors for commands that don't already have errors set.
12798          */
12799         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
12800             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12801             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12802                 ctl_inject_error(lun, io);
12803
12804         /*
12805          * XXX KDM how do we treat commands that aren't completed
12806          * successfully?
12807          *
12808          * XXX KDM should we also track I/O latency?
12809          */
12810         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12811             io->io_hdr.io_type == CTL_IO_SCSI) {
12812 #ifdef CTL_TIME_IO
12813                 struct bintime cur_bt;
12814 #endif
12815                 int type;
12816
12817                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12818                     CTL_FLAG_DATA_IN)
12819                         type = CTL_STATS_READ;
12820                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12821                     CTL_FLAG_DATA_OUT)
12822                         type = CTL_STATS_WRITE;
12823                 else
12824                         type = CTL_STATS_NO_IO;
12825
12826                 lun->stats.ports[targ_port].bytes[type] +=
12827                     io->scsiio.kern_total_len;
12828                 lun->stats.ports[targ_port].operations[type]++;
12829 #ifdef CTL_TIME_IO
12830                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
12831                    &io->io_hdr.dma_bt);
12832                 lun->stats.ports[targ_port].num_dmas[type] +=
12833                     io->io_hdr.num_dmas;
12834                 getbintime(&cur_bt);
12835                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12836                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
12837 #endif
12838         }
12839
12840         /*
12841          * Remove this from the OOA queue.
12842          */
12843         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12844 #ifdef CTL_TIME_IO
12845         if (TAILQ_EMPTY(&lun->ooa_queue))
12846                 lun->last_busy = getsbinuptime();
12847 #endif
12848
12849         /*
12850          * Run through the blocked queue on this LUN and see if anything
12851          * has become unblocked, now that this transaction is done.
12852          */
12853         ctl_check_blocked(lun);
12854
12855         /*
12856          * If the LUN has been invalidated, free it if there is nothing
12857          * left on its OOA queue.
12858          */
12859         if ((lun->flags & CTL_LUN_INVALID)
12860          && TAILQ_EMPTY(&lun->ooa_queue)) {
12861                 mtx_unlock(&lun->lun_lock);
12862                 mtx_lock(&softc->ctl_lock);
12863                 ctl_free_lun(lun);
12864                 mtx_unlock(&softc->ctl_lock);
12865         } else
12866                 mtx_unlock(&lun->lun_lock);
12867
12868 bailout:
12869
12870         /*
12871          * If this command has been aborted, make sure we set the status
12872          * properly.  The FETD is responsible for freeing the I/O and doing
12873          * whatever it needs to do to clean up its state.
12874          */
12875         if (io->io_hdr.flags & CTL_FLAG_ABORT)
12876                 ctl_set_task_aborted(&io->scsiio);
12877
12878         /*
12879          * If enabled, print command error status.
12880          */
12881         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12882             (ctl_debug & CTL_DEBUG_INFO) != 0)
12883                 ctl_io_error_print(io, NULL);
12884
12885         /*
12886          * Tell the FETD or the other shelf controller we're done with this
12887          * command.  Note that only SCSI commands get to this point.  Task
12888          * management commands are completed above.
12889          */
12890         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
12891             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
12892                 memset(&msg, 0, sizeof(msg));
12893                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12894                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12895                 msg.hdr.nexus = io->io_hdr.nexus;
12896                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12897                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
12898                     M_WAITOK);
12899         }
12900         if ((softc->ha_mode == CTL_HA_MODE_XFER)
12901          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12902                 memset(&msg, 0, sizeof(msg));
12903                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12904                 msg.hdr.original_sc = io->io_hdr.original_sc;
12905                 msg.hdr.nexus = io->io_hdr.nexus;
12906                 msg.hdr.status = io->io_hdr.status;
12907                 msg.scsi.scsi_status = io->scsiio.scsi_status;
12908                 msg.scsi.tag_num = io->scsiio.tag_num;
12909                 msg.scsi.tag_type = io->scsiio.tag_type;
12910                 msg.scsi.sense_len = io->scsiio.sense_len;
12911                 msg.scsi.sense_residual = io->scsiio.sense_residual;
12912                 msg.scsi.residual = io->scsiio.residual;
12913                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12914                        io->scsiio.sense_len);
12915                 /*
12916                  * We copy this whether or not this is an I/O-related
12917                  * command.  Otherwise, we'd have to go and check to see
12918                  * whether it's a read/write command, and it really isn't
12919                  * worth it.
12920                  */
12921                 memcpy(&msg.scsi.lbalen,
12922                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
12923                        sizeof(msg.scsi.lbalen));
12924
12925                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12926                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12927                     msg.scsi.sense_len, M_WAITOK);
12928                 ctl_free_io(io);
12929         } else 
12930                 fe_done(io);
12931
12932         return (CTL_RETVAL_COMPLETE);
12933 }
12934
12935 #ifdef CTL_WITH_CA
12936 /*
12937  * Front end should call this if it doesn't do autosense.  When the request
12938  * sense comes back in from the initiator, we'll dequeue this and send it.
12939  */
12940 int
12941 ctl_queue_sense(union ctl_io *io)
12942 {
12943         struct ctl_lun *lun;
12944         struct ctl_port *port;
12945         struct ctl_softc *softc;
12946         uint32_t initidx, targ_lun;
12947
12948         softc = control_softc;
12949
12950         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
12951
12952         /*
12953          * LUN lookup will likely move to the ctl_work_thread() once we
12954          * have our new queueing infrastructure (that doesn't put things on
12955          * a per-LUN queue initially).  That is so that we can handle
12956          * things like an INQUIRY to a LUN that we don't have enabled.  We
12957          * can't deal with that right now.
12958          */
12959         mtx_lock(&softc->ctl_lock);
12960
12961         /*
12962          * If we don't have a LUN for this, just toss the sense
12963          * information.
12964          */
12965         port = ctl_io_port(&ctsio->io_hdr);
12966         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
12967         if ((targ_lun < CTL_MAX_LUNS)
12968          && (softc->ctl_luns[targ_lun] != NULL))
12969                 lun = softc->ctl_luns[targ_lun];
12970         else
12971                 goto bailout;
12972
12973         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12974
12975         mtx_lock(&lun->lun_lock);
12976         /*
12977          * Already have CA set for this LUN...toss the sense information.
12978          */
12979         if (ctl_is_set(lun->have_ca, initidx)) {
12980                 mtx_unlock(&lun->lun_lock);
12981                 goto bailout;
12982         }
12983
12984         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
12985                MIN(sizeof(lun->pending_sense[initidx]),
12986                sizeof(io->scsiio.sense_data)));
12987         ctl_set_mask(lun->have_ca, initidx);
12988         mtx_unlock(&lun->lun_lock);
12989
12990 bailout:
12991         mtx_unlock(&softc->ctl_lock);
12992
12993         ctl_free_io(io);
12994
12995         return (CTL_RETVAL_COMPLETE);
12996 }
12997 #endif
12998
12999 /*
13000  * Primary command inlet from frontend ports.  All SCSI and task I/O
13001  * requests must go through this function.
13002  */
13003 int
13004 ctl_queue(union ctl_io *io)
13005 {
13006         struct ctl_port *port;
13007
13008         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13009
13010 #ifdef CTL_TIME_IO
13011         io->io_hdr.start_time = time_uptime;
13012         getbintime(&io->io_hdr.start_bt);
13013 #endif /* CTL_TIME_IO */
13014
13015         /* Map FE-specific LUN ID into global one. */
13016         port = ctl_io_port(&io->io_hdr);
13017         io->io_hdr.nexus.targ_mapped_lun =
13018             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13019
13020         switch (io->io_hdr.io_type) {
13021         case CTL_IO_SCSI:
13022         case CTL_IO_TASK:
13023                 if (ctl_debug & CTL_DEBUG_CDB)
13024                         ctl_io_print(io);
13025                 ctl_enqueue_incoming(io);
13026                 break;
13027         default:
13028                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13029                 return (EINVAL);
13030         }
13031
13032         return (CTL_RETVAL_COMPLETE);
13033 }
13034
13035 #ifdef CTL_IO_DELAY
13036 static void
13037 ctl_done_timer_wakeup(void *arg)
13038 {
13039         union ctl_io *io;
13040
13041         io = (union ctl_io *)arg;
13042         ctl_done(io);
13043 }
13044 #endif /* CTL_IO_DELAY */
13045
13046 void
13047 ctl_done(union ctl_io *io)
13048 {
13049
13050         /*
13051          * Enable this to catch duplicate completion issues.
13052          */
13053 #if 0
13054         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13055                 printf("%s: type %d msg %d cdb %x iptl: "
13056                        "%u:%u:%u tag 0x%04x "
13057                        "flag %#x status %x\n",
13058                         __func__,
13059                         io->io_hdr.io_type,
13060                         io->io_hdr.msg_type,
13061                         io->scsiio.cdb[0],
13062                         io->io_hdr.nexus.initid,
13063                         io->io_hdr.nexus.targ_port,
13064                         io->io_hdr.nexus.targ_lun,
13065                         (io->io_hdr.io_type ==
13066                         CTL_IO_TASK) ?
13067                         io->taskio.tag_num :
13068                         io->scsiio.tag_num,
13069                         io->io_hdr.flags,
13070                         io->io_hdr.status);
13071         } else
13072                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13073 #endif
13074
13075         /*
13076          * This is an internal copy of an I/O, and should not go through
13077          * the normal done processing logic.
13078          */
13079         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13080                 return;
13081
13082 #ifdef CTL_IO_DELAY
13083         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13084                 struct ctl_lun *lun;
13085
13086                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13087
13088                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13089         } else {
13090                 struct ctl_lun *lun;
13091
13092                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13093
13094                 if ((lun != NULL)
13095                  && (lun->delay_info.done_delay > 0)) {
13096
13097                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13098                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13099                         callout_reset(&io->io_hdr.delay_callout,
13100                                       lun->delay_info.done_delay * hz,
13101                                       ctl_done_timer_wakeup, io);
13102                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13103                                 lun->delay_info.done_delay = 0;
13104                         return;
13105                 }
13106         }
13107 #endif /* CTL_IO_DELAY */
13108
13109         ctl_enqueue_done(io);
13110 }
13111
13112 static void
13113 ctl_work_thread(void *arg)
13114 {
13115         struct ctl_thread *thr = (struct ctl_thread *)arg;
13116         struct ctl_softc *softc = thr->ctl_softc;
13117         union ctl_io *io;
13118         int retval;
13119
13120         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13121
13122         for (;;) {
13123                 retval = 0;
13124
13125                 /*
13126                  * We handle the queues in this order:
13127                  * - ISC
13128                  * - done queue (to free up resources, unblock other commands)
13129                  * - RtR queue
13130                  * - incoming queue
13131                  *
13132                  * If those queues are empty, we break out of the loop and
13133                  * go to sleep.
13134                  */
13135                 mtx_lock(&thr->queue_lock);
13136                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13137                 if (io != NULL) {
13138                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13139                         mtx_unlock(&thr->queue_lock);
13140                         ctl_handle_isc(io);
13141                         continue;
13142                 }
13143                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13144                 if (io != NULL) {
13145                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13146                         /* clear any blocked commands, call fe_done */
13147                         mtx_unlock(&thr->queue_lock);
13148                         retval = ctl_process_done(io);
13149                         continue;
13150                 }
13151                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13152                 if (io != NULL) {
13153                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13154                         mtx_unlock(&thr->queue_lock);
13155                         if (io->io_hdr.io_type == CTL_IO_TASK)
13156                                 ctl_run_task(io);
13157                         else
13158                                 ctl_scsiio_precheck(softc, &io->scsiio);
13159                         continue;
13160                 }
13161                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13162                 if (io != NULL) {
13163                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13164                         mtx_unlock(&thr->queue_lock);
13165                         retval = ctl_scsiio(&io->scsiio);
13166                         if (retval != CTL_RETVAL_COMPLETE)
13167                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13168                         continue;
13169                 }
13170
13171                 /* Sleep until we have something to do. */
13172                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13173         }
13174 }
13175
13176 static void
13177 ctl_lun_thread(void *arg)
13178 {
13179         struct ctl_softc *softc = (struct ctl_softc *)arg;
13180         struct ctl_be_lun *be_lun;
13181         int retval;
13182
13183         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13184
13185         for (;;) {
13186                 retval = 0;
13187                 mtx_lock(&softc->ctl_lock);
13188                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13189                 if (be_lun != NULL) {
13190                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13191                         mtx_unlock(&softc->ctl_lock);
13192                         ctl_create_lun(be_lun);
13193                         continue;
13194                 }
13195
13196                 /* Sleep until we have something to do. */
13197                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13198                     PDROP | PRIBIO, "-", 0);
13199         }
13200 }
13201
13202 static void
13203 ctl_thresh_thread(void *arg)
13204 {
13205         struct ctl_softc *softc = (struct ctl_softc *)arg;
13206         struct ctl_lun *lun;
13207         struct ctl_be_lun *be_lun;
13208         struct scsi_da_rw_recovery_page *rwpage;
13209         struct ctl_logical_block_provisioning_page *page;
13210         const char *attr;
13211         union ctl_ha_msg msg;
13212         uint64_t thres, val;
13213         int i, e, set;
13214
13215         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13216
13217         for (;;) {
13218                 mtx_lock(&softc->ctl_lock);
13219                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13220                         be_lun = lun->be_lun;
13221                         if ((lun->flags & CTL_LUN_DISABLED) ||
13222                             (lun->flags & CTL_LUN_OFFLINE) ||
13223                             lun->backend->lun_attr == NULL)
13224                                 continue;
13225                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13226                             softc->ha_mode == CTL_HA_MODE_XFER)
13227                                 continue;
13228                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13229                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13230                                 continue;
13231                         e = 0;
13232                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13233                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13234                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13235                                         continue;
13236                                 thres = scsi_4btoul(page->descr[i].count);
13237                                 thres <<= CTL_LBP_EXPONENT;
13238                                 switch (page->descr[i].resource) {
13239                                 case 0x01:
13240                                         attr = "blocksavail";
13241                                         break;
13242                                 case 0x02:
13243                                         attr = "blocksused";
13244                                         break;
13245                                 case 0xf1:
13246                                         attr = "poolblocksavail";
13247                                         break;
13248                                 case 0xf2:
13249                                         attr = "poolblocksused";
13250                                         break;
13251                                 default:
13252                                         continue;
13253                                 }
13254                                 mtx_unlock(&softc->ctl_lock); // XXX
13255                                 val = lun->backend->lun_attr(
13256                                     lun->be_lun->be_lun, attr);
13257                                 mtx_lock(&softc->ctl_lock);
13258                                 if (val == UINT64_MAX)
13259                                         continue;
13260                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13261                                     == SLBPPD_ARMING_INC)
13262                                         e |= (val >= thres);
13263                                 else
13264                                         e |= (val <= thres);
13265                         }
13266                         mtx_lock(&lun->lun_lock);
13267                         if (e) {
13268                                 if (lun->lasttpt == 0 ||
13269                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13270                                         lun->lasttpt = time_uptime;
13271                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13272                                         set = 1;
13273                                 } else
13274                                         set = 0;
13275                         } else {
13276                                 lun->lasttpt = 0;
13277                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13278                                 set = -1;
13279                         }
13280                         mtx_unlock(&lun->lun_lock);
13281                         if (set != 0 &&
13282                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13283                                 /* Send msg to other side. */
13284                                 bzero(&msg.ua, sizeof(msg.ua));
13285                                 msg.hdr.msg_type = CTL_MSG_UA;
13286                                 msg.hdr.nexus.initid = -1;
13287                                 msg.hdr.nexus.targ_port = -1;
13288                                 msg.hdr.nexus.targ_lun = lun->lun;
13289                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13290                                 msg.ua.ua_all = 1;
13291                                 msg.ua.ua_set = (set > 0);
13292                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13293                                 mtx_unlock(&softc->ctl_lock); // XXX
13294                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13295                                     sizeof(msg.ua), M_WAITOK);
13296                                 mtx_lock(&softc->ctl_lock);
13297                         }
13298                 }
13299                 mtx_unlock(&softc->ctl_lock);
13300                 pause("-", CTL_LBP_PERIOD * hz);
13301         }
13302 }
13303
13304 static void
13305 ctl_enqueue_incoming(union ctl_io *io)
13306 {
13307         struct ctl_softc *softc = control_softc;
13308         struct ctl_thread *thr;
13309         u_int idx;
13310
13311         idx = (io->io_hdr.nexus.targ_port * 127 +
13312                io->io_hdr.nexus.initid) % worker_threads;
13313         thr = &softc->threads[idx];
13314         mtx_lock(&thr->queue_lock);
13315         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13316         mtx_unlock(&thr->queue_lock);
13317         wakeup(thr);
13318 }
13319
13320 static void
13321 ctl_enqueue_rtr(union ctl_io *io)
13322 {
13323         struct ctl_softc *softc = control_softc;
13324         struct ctl_thread *thr;
13325
13326         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13327         mtx_lock(&thr->queue_lock);
13328         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13329         mtx_unlock(&thr->queue_lock);
13330         wakeup(thr);
13331 }
13332
13333 static void
13334 ctl_enqueue_done(union ctl_io *io)
13335 {
13336         struct ctl_softc *softc = control_softc;
13337         struct ctl_thread *thr;
13338
13339         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13340         mtx_lock(&thr->queue_lock);
13341         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13342         mtx_unlock(&thr->queue_lock);
13343         wakeup(thr);
13344 }
13345
13346 static void
13347 ctl_enqueue_isc(union ctl_io *io)
13348 {
13349         struct ctl_softc *softc = control_softc;
13350         struct ctl_thread *thr;
13351
13352         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13353         mtx_lock(&thr->queue_lock);
13354         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13355         mtx_unlock(&thr->queue_lock);
13356         wakeup(thr);
13357 }
13358
13359 /*
13360  *  vim: ts=8
13361  */