]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r287940: Replicate initiators WWPNs and names between HA peers.
[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_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
418                          ctl_ua_type ua_type);
419 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
420 static int ctl_abort_task(union ctl_io *io);
421 static int ctl_abort_task_set(union ctl_io *io);
422 static int ctl_query_task(union ctl_io *io, int task_set);
423 static int ctl_i_t_nexus_reset(union ctl_io *io);
424 static int ctl_query_async_event(union ctl_io *io);
425 static void ctl_run_task(union ctl_io *io);
426 #ifdef CTL_IO_DELAY
427 static void ctl_datamove_timer_wakeup(void *arg);
428 static void ctl_done_timer_wakeup(void *arg);
429 #endif /* CTL_IO_DELAY */
430
431 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
432 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
433 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
434 static void ctl_datamove_remote_write(union ctl_io *io);
435 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
436 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
437 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
438 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
439                                     ctl_ha_dt_cb callback);
440 static void ctl_datamove_remote_read(union ctl_io *io);
441 static void ctl_datamove_remote(union ctl_io *io);
442 static int ctl_process_done(union ctl_io *io);
443 static void ctl_lun_thread(void *arg);
444 static void ctl_thresh_thread(void *arg);
445 static void ctl_work_thread(void *arg);
446 static void ctl_enqueue_incoming(union ctl_io *io);
447 static void ctl_enqueue_rtr(union ctl_io *io);
448 static void ctl_enqueue_done(union ctl_io *io);
449 static void ctl_enqueue_isc(union ctl_io *io);
450 static const struct ctl_cmd_entry *
451     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
452 static const struct ctl_cmd_entry *
453     ctl_validate_command(struct ctl_scsiio *ctsio);
454 static int ctl_cmd_applicable(uint8_t lun_type,
455     const struct ctl_cmd_entry *entry);
456
457 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
458 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
459 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
460 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
461
462 /*
463  * Load the serialization table.  This isn't very pretty, but is probably
464  * the easiest way to do it.
465  */
466 #include "ctl_ser_table.c"
467
468 /*
469  * We only need to define open, close and ioctl routines for this driver.
470  */
471 static struct cdevsw ctl_cdevsw = {
472         .d_version =    D_VERSION,
473         .d_flags =      0,
474         .d_open =       ctl_open,
475         .d_close =      ctl_close,
476         .d_ioctl =      ctl_ioctl,
477         .d_name =       "ctl",
478 };
479
480
481 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
482
483 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
484
485 static moduledata_t ctl_moduledata = {
486         "ctl",
487         ctl_module_event_handler,
488         NULL
489 };
490
491 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
492 MODULE_VERSION(ctl, 1);
493
494 static struct ctl_frontend ha_frontend =
495 {
496         .name = "ha",
497 };
498
499 static void
500 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
501                             union ctl_ha_msg *msg_info)
502 {
503         struct ctl_scsiio *ctsio;
504
505         if (msg_info->hdr.original_sc == NULL) {
506                 printf("%s: original_sc == NULL!\n", __func__);
507                 /* XXX KDM now what? */
508                 return;
509         }
510
511         ctsio = &msg_info->hdr.original_sc->scsiio;
512         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
513         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
514         ctsio->io_hdr.status = msg_info->hdr.status;
515         ctsio->scsi_status = msg_info->scsi.scsi_status;
516         ctsio->sense_len = msg_info->scsi.sense_len;
517         ctsio->sense_residual = msg_info->scsi.sense_residual;
518         ctsio->residual = msg_info->scsi.residual;
519         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
520                msg_info->scsi.sense_len);
521         ctl_enqueue_isc((union ctl_io *)ctsio);
522 }
523
524 static void
525 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
526                                 union ctl_ha_msg *msg_info)
527 {
528         struct ctl_scsiio *ctsio;
529
530         if (msg_info->hdr.serializing_sc == NULL) {
531                 printf("%s: serializing_sc == NULL!\n", __func__);
532                 /* XXX KDM now what? */
533                 return;
534         }
535
536         ctsio = &msg_info->hdr.serializing_sc->scsiio;
537         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
538         ctl_enqueue_isc((union ctl_io *)ctsio);
539 }
540
541 void
542 ctl_isc_announce_lun(struct ctl_lun *lun)
543 {
544         struct ctl_softc *softc = lun->ctl_softc;
545         union ctl_ha_msg *msg;
546         struct ctl_ha_msg_lun_pr_key pr_key;
547         int i, k;
548
549         if (softc->ha_link != CTL_HA_LINK_ONLINE)
550                 return;
551         mtx_lock(&lun->lun_lock);
552         i = sizeof(msg->lun);
553         if (lun->lun_devid)
554                 i += lun->lun_devid->len;
555         i += sizeof(pr_key) * lun->pr_key_count;
556 alloc:
557         mtx_unlock(&lun->lun_lock);
558         msg = malloc(i, M_CTL, M_WAITOK);
559         mtx_lock(&lun->lun_lock);
560         k = sizeof(msg->lun);
561         if (lun->lun_devid)
562                 k += lun->lun_devid->len;
563         k += sizeof(pr_key) * lun->pr_key_count;
564         if (i < k) {
565                 free(msg, M_CTL);
566                 i = k;
567                 goto alloc;
568         }
569         bzero(&msg->lun, sizeof(msg->lun));
570         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
571         msg->hdr.nexus.targ_lun = lun->lun;
572         msg->hdr.nexus.targ_mapped_lun = lun->lun;
573         msg->lun.flags = lun->flags;
574         msg->lun.pr_generation = lun->PRGeneration;
575         msg->lun.pr_res_idx = lun->pr_res_idx;
576         msg->lun.pr_res_type = lun->res_type;
577         msg->lun.pr_key_count = lun->pr_key_count;
578         i = 0;
579         if (lun->lun_devid) {
580                 msg->lun.lun_devid_len = lun->lun_devid->len;
581                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
582                     msg->lun.lun_devid_len);
583                 i += msg->lun.lun_devid_len;
584         }
585         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
586                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
587                         continue;
588                 pr_key.pr_iid = k;
589                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
590                 i += sizeof(pr_key);
591         }
592         mtx_unlock(&lun->lun_lock);
593         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
594             M_WAITOK);
595         free(msg, M_CTL);
596 }
597
598 void
599 ctl_isc_announce_port(struct ctl_port *port)
600 {
601         struct ctl_softc *softc = control_softc;
602         union ctl_ha_msg *msg;
603         int i;
604
605         if (port->targ_port < softc->port_min ||
606             port->targ_port >= softc->port_max ||
607             softc->ha_link != CTL_HA_LINK_ONLINE)
608                 return;
609         i = sizeof(msg->port) + strlen(port->port_name) + 1;
610         if (port->lun_map)
611                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
612         if (port->port_devid)
613                 i += port->port_devid->len;
614         if (port->target_devid)
615                 i += port->target_devid->len;
616         if (port->init_devid)
617                 i += port->init_devid->len;
618         msg = malloc(i, M_CTL, M_WAITOK);
619         bzero(&msg->port, sizeof(msg->port));
620         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
621         msg->hdr.nexus.targ_port = port->targ_port;
622         msg->port.port_type = port->port_type;
623         msg->port.physical_port = port->physical_port;
624         msg->port.virtual_port = port->virtual_port;
625         msg->port.status = port->status;
626         i = 0;
627         msg->port.name_len = sprintf(&msg->port.data[i],
628             "%d:%s", softc->ha_id, port->port_name) + 1;
629         i += msg->port.name_len;
630         if (port->lun_map) {
631                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
632                 memcpy(&msg->port.data[i], port->lun_map,
633                     msg->port.lun_map_len);
634                 i += msg->port.lun_map_len;
635         }
636         if (port->port_devid) {
637                 msg->port.port_devid_len = port->port_devid->len;
638                 memcpy(&msg->port.data[i], port->port_devid->data,
639                     msg->port.port_devid_len);
640                 i += msg->port.port_devid_len;
641         }
642         if (port->target_devid) {
643                 msg->port.target_devid_len = port->target_devid->len;
644                 memcpy(&msg->port.data[i], port->target_devid->data,
645                     msg->port.target_devid_len);
646                 i += msg->port.target_devid_len;
647         }
648         if (port->init_devid) {
649                 msg->port.init_devid_len = port->init_devid->len;
650                 memcpy(&msg->port.data[i], port->init_devid->data,
651                     msg->port.init_devid_len);
652                 i += msg->port.init_devid_len;
653         }
654         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
655             M_WAITOK);
656         free(msg, M_CTL);
657 }
658
659 void
660 ctl_isc_announce_iid(struct ctl_port *port, int iid)
661 {
662         struct ctl_softc *softc = control_softc;
663         union ctl_ha_msg *msg;
664         int i, l;
665
666         if (port->targ_port < softc->port_min ||
667             port->targ_port >= softc->port_max ||
668             softc->ha_link != CTL_HA_LINK_ONLINE)
669                 return;
670         mtx_lock(&softc->ctl_lock);
671         i = sizeof(msg->iid);
672         l = 0;
673         if (port->wwpn_iid[iid].name)
674                 l = strlen(port->wwpn_iid[iid].name) + 1;
675         i += l;
676         msg = malloc(i, M_CTL, M_NOWAIT);
677         if (msg == NULL) {
678                 mtx_unlock(&softc->ctl_lock);
679                 return;
680         }
681         bzero(&msg->iid, sizeof(msg->iid));
682         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
683         msg->hdr.nexus.targ_port = port->targ_port;
684         msg->hdr.nexus.initid = iid;
685         msg->iid.in_use = port->wwpn_iid[iid].in_use;
686         msg->iid.name_len = l;
687         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
688         if (port->wwpn_iid[iid].name)
689                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
690         mtx_unlock(&softc->ctl_lock);
691         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
692         free(msg, M_CTL);
693 }
694
695 static void
696 ctl_isc_ha_link_up(struct ctl_softc *softc)
697 {
698         struct ctl_port *port;
699         struct ctl_lun *lun;
700         int i;
701
702         STAILQ_FOREACH(port, &softc->port_list, links) {
703                 ctl_isc_announce_port(port);
704                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
705                         if (port->wwpn_iid[i].in_use)
706                                 ctl_isc_announce_iid(port, i);
707                 }
708         }
709         STAILQ_FOREACH(lun, &softc->lun_list, links)
710                 ctl_isc_announce_lun(lun);
711 }
712
713 static void
714 ctl_isc_ha_link_down(struct ctl_softc *softc)
715 {
716         struct ctl_port *port;
717         struct ctl_lun *lun;
718         union ctl_io *io;
719         int i;
720
721         mtx_lock(&softc->ctl_lock);
722         STAILQ_FOREACH(lun, &softc->lun_list, links) {
723                 mtx_lock(&lun->lun_lock);
724                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
725                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
726                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
727                 }
728                 mtx_unlock(&lun->lun_lock);
729
730                 mtx_unlock(&softc->ctl_lock);
731                 io = ctl_alloc_io(softc->othersc_pool);
732                 mtx_lock(&softc->ctl_lock);
733                 ctl_zero_io(io);
734                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
735                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
736                 ctl_enqueue_isc(io);
737         }
738
739         STAILQ_FOREACH(port, &softc->port_list, links) {
740                 if (port->targ_port >= softc->port_min &&
741                     port->targ_port < softc->port_max)
742                         continue;
743                 port->status &= ~CTL_PORT_STATUS_ONLINE;
744                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
745                         port->wwpn_iid[i].in_use = 0;
746                         free(port->wwpn_iid[i].name, M_CTL);
747                         port->wwpn_iid[i].name = NULL;
748                 }
749         }
750         mtx_unlock(&softc->ctl_lock);
751 }
752
753 static void
754 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
755 {
756         struct ctl_lun *lun;
757         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
758
759         mtx_lock(&softc->ctl_lock);
760         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
761             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
762                 mtx_lock(&lun->lun_lock);
763                 mtx_unlock(&softc->ctl_lock);
764                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
765                     msg->ua.ua_set)
766                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
767                 if (msg->ua.ua_all) {
768                         if (msg->ua.ua_set)
769                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
770                         else
771                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
772                 } else {
773                         if (msg->ua.ua_set)
774                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
775                         else
776                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
777                 }
778                 mtx_unlock(&lun->lun_lock);
779         } else
780                 mtx_unlock(&softc->ctl_lock);
781 }
782
783 static void
784 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
785 {
786         struct ctl_lun *lun;
787         struct ctl_ha_msg_lun_pr_key pr_key;
788         int i, k;
789         ctl_lun_flags oflags;
790         uint32_t targ_lun;
791
792         targ_lun = msg->hdr.nexus.targ_mapped_lun;
793         mtx_lock(&softc->ctl_lock);
794         if ((targ_lun >= CTL_MAX_LUNS) ||
795             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
796                 mtx_unlock(&softc->ctl_lock);
797                 return;
798         }
799         mtx_lock(&lun->lun_lock);
800         mtx_unlock(&softc->ctl_lock);
801         if (lun->flags & CTL_LUN_DISABLED) {
802                 mtx_unlock(&lun->lun_lock);
803                 return;
804         }
805         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
806         if (msg->lun.lun_devid_len != i || (i > 0 &&
807             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
808                 mtx_unlock(&lun->lun_lock);
809                 printf("%s: Received conflicting HA LUN %d\n",
810                     __func__, msg->hdr.nexus.targ_lun);
811                 return;
812         } else {
813                 /* Record whether peer is primary. */
814                 oflags = lun->flags;
815                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
816                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
817                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
818                 else
819                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
820                 if (oflags != lun->flags)
821                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
822
823                 /* If peer is primary and we are not -- use data */
824                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
825                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
826                         lun->PRGeneration = msg->lun.pr_generation;
827                         lun->pr_res_idx = msg->lun.pr_res_idx;
828                         lun->res_type = msg->lun.pr_res_type;
829                         lun->pr_key_count = msg->lun.pr_key_count;
830                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
831                                 ctl_clr_prkey(lun, k);
832                         for (k = 0; k < msg->lun.pr_key_count; k++) {
833                                 memcpy(&pr_key, &msg->lun.data[i],
834                                     sizeof(pr_key));
835                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
836                                 ctl_set_prkey(lun, pr_key.pr_iid,
837                                     pr_key.pr_key);
838                                 i += sizeof(pr_key);
839                         }
840                 }
841
842                 mtx_unlock(&lun->lun_lock);
843                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
844                     __func__, msg->hdr.nexus.targ_lun,
845                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
846                     "primary" : "secondary"));
847
848                 /* If we are primary but peer doesn't know -- notify */
849                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
850                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
851                         ctl_isc_announce_lun(lun);
852         }
853 }
854
855 static void
856 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
857 {
858         struct ctl_port *port;
859         struct ctl_lun *lun;
860         int i, new;
861
862         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
863         if (port == NULL) {
864                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
865                     msg->hdr.nexus.targ_port));
866                 new = 1;
867                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
868                 port->frontend = &ha_frontend;
869                 port->targ_port = msg->hdr.nexus.targ_port;
870         } else if (port->frontend == &ha_frontend) {
871                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
872                     msg->hdr.nexus.targ_port));
873                 new = 0;
874         } else {
875                 printf("%s: Received conflicting HA port %d\n",
876                     __func__, msg->hdr.nexus.targ_port);
877                 return;
878         }
879         port->port_type = msg->port.port_type;
880         port->physical_port = msg->port.physical_port;
881         port->virtual_port = msg->port.virtual_port;
882         port->status = msg->port.status;
883         i = 0;
884         free(port->port_name, M_CTL);
885         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
886             M_CTL);
887         i += msg->port.name_len;
888         if (msg->port.lun_map_len != 0) {
889                 if (port->lun_map == NULL)
890                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
891                             M_CTL, M_WAITOK);
892                 memcpy(port->lun_map, &msg->port.data[i],
893                     sizeof(uint32_t) * CTL_MAX_LUNS);
894                 i += msg->port.lun_map_len;
895         } else {
896                 free(port->lun_map, M_CTL);
897                 port->lun_map = NULL;
898         }
899         if (msg->port.port_devid_len != 0) {
900                 if (port->port_devid == NULL ||
901                     port->port_devid->len != msg->port.port_devid_len) {
902                         free(port->port_devid, M_CTL);
903                         port->port_devid = malloc(sizeof(struct ctl_devid) +
904                             msg->port.port_devid_len, M_CTL, M_WAITOK);
905                 }
906                 memcpy(port->port_devid->data, &msg->port.data[i],
907                     msg->port.port_devid_len);
908                 port->port_devid->len = msg->port.port_devid_len;
909                 i += msg->port.port_devid_len;
910         } else {
911                 free(port->port_devid, M_CTL);
912                 port->port_devid = NULL;
913         }
914         if (msg->port.target_devid_len != 0) {
915                 if (port->target_devid == NULL ||
916                     port->target_devid->len != msg->port.target_devid_len) {
917                         free(port->target_devid, M_CTL);
918                         port->target_devid = malloc(sizeof(struct ctl_devid) +
919                             msg->port.target_devid_len, M_CTL, M_WAITOK);
920                 }
921                 memcpy(port->target_devid->data, &msg->port.data[i],
922                     msg->port.target_devid_len);
923                 port->target_devid->len = msg->port.target_devid_len;
924                 i += msg->port.target_devid_len;
925         } else {
926                 free(port->target_devid, M_CTL);
927                 port->target_devid = NULL;
928         }
929         if (msg->port.init_devid_len != 0) {
930                 if (port->init_devid == NULL ||
931                     port->init_devid->len != msg->port.init_devid_len) {
932                         free(port->init_devid, M_CTL);
933                         port->init_devid = malloc(sizeof(struct ctl_devid) +
934                             msg->port.init_devid_len, M_CTL, M_WAITOK);
935                 }
936                 memcpy(port->init_devid->data, &msg->port.data[i],
937                     msg->port.init_devid_len);
938                 port->init_devid->len = msg->port.init_devid_len;
939                 i += msg->port.init_devid_len;
940         } else {
941                 free(port->init_devid, M_CTL);
942                 port->init_devid = NULL;
943         }
944         if (new) {
945                 if (ctl_port_register(port) != 0) {
946                         printf("%s: ctl_port_register() failed with error\n",
947                             __func__);
948                 }
949         }
950         mtx_lock(&softc->ctl_lock);
951         STAILQ_FOREACH(lun, &softc->lun_list, links) {
952                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
953                         continue;
954                 mtx_lock(&lun->lun_lock);
955                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
956                 mtx_unlock(&lun->lun_lock);
957         }
958         mtx_unlock(&softc->ctl_lock);
959 }
960
961 static void
962 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
963 {
964         struct ctl_port *port;
965         int iid;
966
967         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
968         if (port == NULL) {
969                 printf("%s: Received IID for unknown port %d\n",
970                     __func__, msg->hdr.nexus.targ_port);
971                 return;
972         }
973         iid = msg->hdr.nexus.initid;
974         port->wwpn_iid[iid].in_use = msg->iid.in_use;
975         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
976         free(port->wwpn_iid[iid].name, M_CTL);
977         if (msg->iid.name_len) {
978                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
979                     msg->iid.name_len, M_CTL);
980         } else
981                 port->wwpn_iid[iid].name = NULL;
982 }
983
984 /*
985  * ISC (Inter Shelf Communication) event handler.  Events from the HA
986  * subsystem come in here.
987  */
988 static void
989 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
990 {
991         struct ctl_softc *softc;
992         union ctl_io *io;
993         struct ctl_prio *presio;
994         ctl_ha_status isc_status;
995
996         softc = control_softc;
997         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
998         if (event == CTL_HA_EVT_MSG_RECV) {
999                 union ctl_ha_msg *msg, msgbuf;
1000
1001                 if (param > sizeof(msgbuf))
1002                         msg = malloc(param, M_CTL, M_WAITOK);
1003                 else
1004                         msg = &msgbuf;
1005                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1006                     M_WAITOK);
1007                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1008                         printf("%s: Error receiving message: %d\n",
1009                             __func__, isc_status);
1010                         if (msg != &msgbuf)
1011                                 free(msg, M_CTL);
1012                         return;
1013                 }
1014
1015                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1016                 switch (msg->hdr.msg_type) {
1017                 case CTL_MSG_SERIALIZE:
1018                         io = ctl_alloc_io(softc->othersc_pool);
1019                         ctl_zero_io(io);
1020                         // populate ctsio from msg
1021                         io->io_hdr.io_type = CTL_IO_SCSI;
1022                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1023                         io->io_hdr.original_sc = msg->hdr.original_sc;
1024                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1025                                             CTL_FLAG_IO_ACTIVE;
1026                         /*
1027                          * If we're in serialization-only mode, we don't
1028                          * want to go through full done processing.  Thus
1029                          * the COPY flag.
1030                          *
1031                          * XXX KDM add another flag that is more specific.
1032                          */
1033                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1034                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1035                         io->io_hdr.nexus = msg->hdr.nexus;
1036 #if 0
1037                         printf("port %u, iid %u, lun %u\n",
1038                                io->io_hdr.nexus.targ_port,
1039                                io->io_hdr.nexus.initid,
1040                                io->io_hdr.nexus.targ_lun);
1041 #endif
1042                         io->scsiio.tag_num = msg->scsi.tag_num;
1043                         io->scsiio.tag_type = msg->scsi.tag_type;
1044 #ifdef CTL_TIME_IO
1045                         io->io_hdr.start_time = time_uptime;
1046                         getbintime(&io->io_hdr.start_bt);
1047 #endif /* CTL_TIME_IO */
1048                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1049                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1050                                CTL_MAX_CDBLEN);
1051                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1052                                 const struct ctl_cmd_entry *entry;
1053
1054                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1055                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1056                                 io->io_hdr.flags |=
1057                                         entry->flags & CTL_FLAG_DATA_MASK;
1058                         }
1059                         ctl_enqueue_isc(io);
1060                         break;
1061
1062                 /* Performed on the Originating SC, XFER mode only */
1063                 case CTL_MSG_DATAMOVE: {
1064                         struct ctl_sg_entry *sgl;
1065                         int i, j;
1066
1067                         io = msg->hdr.original_sc;
1068                         if (io == NULL) {
1069                                 printf("%s: original_sc == NULL!\n", __func__);
1070                                 /* XXX KDM do something here */
1071                                 break;
1072                         }
1073                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1074                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1075                         /*
1076                          * Keep track of this, we need to send it back over
1077                          * when the datamove is complete.
1078                          */
1079                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1080                         if (msg->hdr.status == CTL_SUCCESS)
1081                                 io->io_hdr.status = msg->hdr.status;
1082
1083                         if (msg->dt.sg_sequence == 0) {
1084                                 i = msg->dt.kern_sg_entries +
1085                                     io->scsiio.kern_data_len /
1086                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1087                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1088                                     M_WAITOK | M_ZERO);
1089                                 io->io_hdr.remote_sglist = sgl;
1090                                 io->io_hdr.local_sglist =
1091                                     &sgl[msg->dt.kern_sg_entries];
1092
1093                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1094
1095                                 io->scsiio.kern_sg_entries =
1096                                         msg->dt.kern_sg_entries;
1097                                 io->scsiio.rem_sg_entries =
1098                                         msg->dt.kern_sg_entries;
1099                                 io->scsiio.kern_data_len =
1100                                         msg->dt.kern_data_len;
1101                                 io->scsiio.kern_total_len =
1102                                         msg->dt.kern_total_len;
1103                                 io->scsiio.kern_data_resid =
1104                                         msg->dt.kern_data_resid;
1105                                 io->scsiio.kern_rel_offset =
1106                                         msg->dt.kern_rel_offset;
1107                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1108                                 io->io_hdr.flags |= msg->dt.flags &
1109                                     CTL_FLAG_BUS_ADDR;
1110                         } else
1111                                 sgl = (struct ctl_sg_entry *)
1112                                         io->scsiio.kern_data_ptr;
1113
1114                         for (i = msg->dt.sent_sg_entries, j = 0;
1115                              i < (msg->dt.sent_sg_entries +
1116                              msg->dt.cur_sg_entries); i++, j++) {
1117                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1118                                 sgl[i].len = msg->dt.sg_list[j].len;
1119
1120 #if 0
1121                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
1122                                        __func__,
1123                                        msg->dt.sg_list[j].addr,
1124                                        msg->dt.sg_list[j].len,
1125                                        sgl[i].addr, sgl[i].len, j, i);
1126 #endif
1127                         }
1128
1129                         /*
1130                          * If this is the last piece of the I/O, we've got
1131                          * the full S/G list.  Queue processing in the thread.
1132                          * Otherwise wait for the next piece.
1133                          */
1134                         if (msg->dt.sg_last != 0)
1135                                 ctl_enqueue_isc(io);
1136                         break;
1137                 }
1138                 /* Performed on the Serializing (primary) SC, XFER mode only */
1139                 case CTL_MSG_DATAMOVE_DONE: {
1140                         if (msg->hdr.serializing_sc == NULL) {
1141                                 printf("%s: serializing_sc == NULL!\n",
1142                                        __func__);
1143                                 /* XXX KDM now what? */
1144                                 break;
1145                         }
1146                         /*
1147                          * We grab the sense information here in case
1148                          * there was a failure, so we can return status
1149                          * back to the initiator.
1150                          */
1151                         io = msg->hdr.serializing_sc;
1152                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1153                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1154                         io->io_hdr.port_status = msg->scsi.fetd_status;
1155                         io->scsiio.residual = msg->scsi.residual;
1156                         if (msg->hdr.status != CTL_STATUS_NONE) {
1157                                 io->io_hdr.status = msg->hdr.status;
1158                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1159                                 io->scsiio.sense_len = msg->scsi.sense_len;
1160                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1161                                 memcpy(&io->scsiio.sense_data,
1162                                     &msg->scsi.sense_data,
1163                                     msg->scsi.sense_len);
1164                                 if (msg->hdr.status == CTL_SUCCESS)
1165                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1166                         }
1167                         ctl_enqueue_isc(io);
1168                         break;
1169                 }
1170
1171                 /* Preformed on Originating SC, SER_ONLY mode */
1172                 case CTL_MSG_R2R:
1173                         io = msg->hdr.original_sc;
1174                         if (io == NULL) {
1175                                 printf("%s: original_sc == NULL!\n",
1176                                     __func__);
1177                                 break;
1178                         }
1179                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1180                         io->io_hdr.msg_type = CTL_MSG_R2R;
1181                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1182                         ctl_enqueue_isc(io);
1183                         break;
1184
1185                 /*
1186                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1187                  * mode.
1188                  * Performed on the Originating (i.e. secondary) SC in XFER
1189                  * mode
1190                  */
1191                 case CTL_MSG_FINISH_IO:
1192                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1193                                 ctl_isc_handler_finish_xfer(softc, msg);
1194                         else
1195                                 ctl_isc_handler_finish_ser_only(softc, msg);
1196                         break;
1197
1198                 /* Preformed on Originating SC */
1199                 case CTL_MSG_BAD_JUJU:
1200                         io = msg->hdr.original_sc;
1201                         if (io == NULL) {
1202                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1203                                        __func__);
1204                                 break;
1205                         }
1206                         ctl_copy_sense_data(msg, io);
1207                         /*
1208                          * IO should have already been cleaned up on other
1209                          * SC so clear this flag so we won't send a message
1210                          * back to finish the IO there.
1211                          */
1212                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1213                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1214
1215                         /* io = msg->hdr.serializing_sc; */
1216                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1217                         ctl_enqueue_isc(io);
1218                         break;
1219
1220                 /* Handle resets sent from the other side */
1221                 case CTL_MSG_MANAGE_TASKS: {
1222                         struct ctl_taskio *taskio;
1223                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1224                             softc->othersc_pool);
1225                         ctl_zero_io((union ctl_io *)taskio);
1226                         taskio->io_hdr.io_type = CTL_IO_TASK;
1227                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1228                         taskio->io_hdr.nexus = msg->hdr.nexus;
1229                         taskio->task_action = msg->task.task_action;
1230                         taskio->tag_num = msg->task.tag_num;
1231                         taskio->tag_type = msg->task.tag_type;
1232 #ifdef CTL_TIME_IO
1233                         taskio->io_hdr.start_time = time_uptime;
1234                         getbintime(&taskio->io_hdr.start_bt);
1235 #endif /* CTL_TIME_IO */
1236                         ctl_run_task((union ctl_io *)taskio);
1237                         break;
1238                 }
1239                 /* Persistent Reserve action which needs attention */
1240                 case CTL_MSG_PERS_ACTION:
1241                         presio = (struct ctl_prio *)ctl_alloc_io(
1242                             softc->othersc_pool);
1243                         ctl_zero_io((union ctl_io *)presio);
1244                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1245                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1246                         presio->io_hdr.nexus = msg->hdr.nexus;
1247                         presio->pr_msg = msg->pr;
1248                         ctl_enqueue_isc((union ctl_io *)presio);
1249                         break;
1250                 case CTL_MSG_UA:
1251                         ctl_isc_ua(softc, msg, param);
1252                         break;
1253                 case CTL_MSG_PORT_SYNC:
1254                         ctl_isc_port_sync(softc, msg, param);
1255                         break;
1256                 case CTL_MSG_LUN_SYNC:
1257                         ctl_isc_lun_sync(softc, msg, param);
1258                         break;
1259                 case CTL_MSG_IID_SYNC:
1260                         ctl_isc_iid_sync(softc, msg, param);
1261                         break;
1262                 default:
1263                         printf("Received HA message of unknown type %d\n",
1264                             msg->hdr.msg_type);
1265                         break;
1266                 }
1267                 if (msg != &msgbuf)
1268                         free(msg, M_CTL);
1269         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1270                 printf("CTL: HA link status changed from %d to %d\n",
1271                     softc->ha_link, param);
1272                 if (param == softc->ha_link)
1273                         return;
1274                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1275                         softc->ha_link = param;
1276                         ctl_isc_ha_link_down(softc);
1277                 } else {
1278                         softc->ha_link = param;
1279                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1280                                 ctl_isc_ha_link_up(softc);
1281                 }
1282                 return;
1283         } else {
1284                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1285                 return;
1286         }
1287 }
1288
1289 static void
1290 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1291 {
1292
1293         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1294             src->scsi.sense_len);
1295         dest->scsiio.scsi_status = src->scsi.scsi_status;
1296         dest->scsiio.sense_len = src->scsi.sense_len;
1297         dest->io_hdr.status = src->hdr.status;
1298 }
1299
1300 static void
1301 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1302 {
1303
1304         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1305             src->scsiio.sense_len);
1306         dest->scsi.scsi_status = src->scsiio.scsi_status;
1307         dest->scsi.sense_len = src->scsiio.sense_len;
1308         dest->hdr.status = src->io_hdr.status;
1309 }
1310
1311 void
1312 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1313 {
1314         struct ctl_softc *softc = lun->ctl_softc;
1315         ctl_ua_type *pu;
1316
1317         if (initidx < softc->init_min || initidx >= softc->init_max)
1318                 return;
1319         mtx_assert(&lun->lun_lock, MA_OWNED);
1320         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1321         if (pu == NULL)
1322                 return;
1323         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1324 }
1325
1326 void
1327 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1328 {
1329         int i;
1330
1331         mtx_assert(&lun->lun_lock, MA_OWNED);
1332         if (lun->pending_ua[port] == NULL)
1333                 return;
1334         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1335                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1336                         continue;
1337                 lun->pending_ua[port][i] |= ua;
1338         }
1339 }
1340
1341 void
1342 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1343 {
1344         struct ctl_softc *softc = lun->ctl_softc;
1345         int i;
1346
1347         mtx_assert(&lun->lun_lock, MA_OWNED);
1348         for (i = softc->port_min; i < softc->port_max; i++)
1349                 ctl_est_ua_port(lun, i, except, ua);
1350 }
1351
1352 void
1353 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1354 {
1355         struct ctl_softc *softc = lun->ctl_softc;
1356         ctl_ua_type *pu;
1357
1358         if (initidx < softc->init_min || initidx >= softc->init_max)
1359                 return;
1360         mtx_assert(&lun->lun_lock, MA_OWNED);
1361         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1362         if (pu == NULL)
1363                 return;
1364         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1365 }
1366
1367 void
1368 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1369 {
1370         struct ctl_softc *softc = lun->ctl_softc;
1371         int i, j;
1372
1373         mtx_assert(&lun->lun_lock, MA_OWNED);
1374         for (i = softc->port_min; i < softc->port_max; i++) {
1375                 if (lun->pending_ua[i] == NULL)
1376                         continue;
1377                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1378                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1379                                 continue;
1380                         lun->pending_ua[i][j] &= ~ua;
1381                 }
1382         }
1383 }
1384
1385 void
1386 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1387     ctl_ua_type ua_type)
1388 {
1389         struct ctl_lun *lun;
1390
1391         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1392         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1393                 mtx_lock(&lun->lun_lock);
1394                 ctl_clr_ua(lun, initidx, ua_type);
1395                 mtx_unlock(&lun->lun_lock);
1396         }
1397 }
1398
1399 static int
1400 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1401 {
1402         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1403         struct ctl_lun *lun;
1404         struct ctl_lun_req ireq;
1405         int error, value;
1406
1407         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1408         error = sysctl_handle_int(oidp, &value, 0, req);
1409         if ((error != 0) || (req->newptr == NULL))
1410                 return (error);
1411
1412         mtx_lock(&softc->ctl_lock);
1413         if (value == 0)
1414                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1415         else
1416                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1417         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1418                 mtx_unlock(&softc->ctl_lock);
1419                 bzero(&ireq, sizeof(ireq));
1420                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1421                 ireq.reqdata.modify.lun_id = lun->lun;
1422                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1423                     curthread);
1424                 if (ireq.status != CTL_LUN_OK) {
1425                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1426                             __func__, ireq.status, ireq.error_str);
1427                 }
1428                 mtx_lock(&softc->ctl_lock);
1429         }
1430         mtx_unlock(&softc->ctl_lock);
1431         return (0);
1432 }
1433
1434 static int
1435 ctl_init(void)
1436 {
1437         struct ctl_softc *softc;
1438         void *other_pool;
1439         int i, error, retval;
1440
1441         retval = 0;
1442         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1443                                M_WAITOK | M_ZERO);
1444         softc = control_softc;
1445
1446         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1447                               "cam/ctl");
1448
1449         softc->dev->si_drv1 = softc;
1450
1451         sysctl_ctx_init(&softc->sysctl_ctx);
1452         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1453                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1454                 CTLFLAG_RD, 0, "CAM Target Layer");
1455
1456         if (softc->sysctl_tree == NULL) {
1457                 printf("%s: unable to allocate sysctl tree\n", __func__);
1458                 destroy_dev(softc->dev);
1459                 free(control_softc, M_DEVBUF);
1460                 control_softc = NULL;
1461                 return (ENOMEM);
1462         }
1463
1464         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1465         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1466             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1467         softc->open_count = 0;
1468
1469         /*
1470          * Default to actually sending a SYNCHRONIZE CACHE command down to
1471          * the drive.
1472          */
1473         softc->flags = CTL_FLAG_REAL_SYNC;
1474
1475         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1476             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1477             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1478
1479         /*
1480          * In Copan's HA scheme, the "master" and "slave" roles are
1481          * figured out through the slot the controller is in.  Although it
1482          * is an active/active system, someone has to be in charge.
1483          */
1484         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1485             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1486             "HA head ID (0 - no HA)");
1487         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1488                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1489                 softc->is_single = 1;
1490                 softc->port_cnt = CTL_MAX_PORTS;
1491                 softc->port_min = 0;
1492         } else {
1493                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1494                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1495         }
1496         softc->port_max = softc->port_min + softc->port_cnt;
1497         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1498         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1499
1500         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1501             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1502             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1503
1504         STAILQ_INIT(&softc->lun_list);
1505         STAILQ_INIT(&softc->pending_lun_queue);
1506         STAILQ_INIT(&softc->fe_list);
1507         STAILQ_INIT(&softc->port_list);
1508         STAILQ_INIT(&softc->be_list);
1509         ctl_tpc_init(softc);
1510
1511         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1512                             &other_pool) != 0)
1513         {
1514                 printf("ctl: can't allocate %d entry other SC pool, "
1515                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1516                 return (ENOMEM);
1517         }
1518         softc->othersc_pool = other_pool;
1519
1520         if (worker_threads <= 0)
1521                 worker_threads = max(1, mp_ncpus / 4);
1522         if (worker_threads > CTL_MAX_THREADS)
1523                 worker_threads = CTL_MAX_THREADS;
1524
1525         for (i = 0; i < worker_threads; i++) {
1526                 struct ctl_thread *thr = &softc->threads[i];
1527
1528                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1529                 thr->ctl_softc = softc;
1530                 STAILQ_INIT(&thr->incoming_queue);
1531                 STAILQ_INIT(&thr->rtr_queue);
1532                 STAILQ_INIT(&thr->done_queue);
1533                 STAILQ_INIT(&thr->isc_queue);
1534
1535                 error = kproc_kthread_add(ctl_work_thread, thr,
1536                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1537                 if (error != 0) {
1538                         printf("error creating CTL work thread!\n");
1539                         ctl_pool_free(other_pool);
1540                         return (error);
1541                 }
1542         }
1543         error = kproc_kthread_add(ctl_lun_thread, softc,
1544             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1545         if (error != 0) {
1546                 printf("error creating CTL lun thread!\n");
1547                 ctl_pool_free(other_pool);
1548                 return (error);
1549         }
1550         error = kproc_kthread_add(ctl_thresh_thread, softc,
1551             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1552         if (error != 0) {
1553                 printf("error creating CTL threshold thread!\n");
1554                 ctl_pool_free(other_pool);
1555                 return (error);
1556         }
1557
1558         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1559             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1560             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1561
1562         if (softc->is_single == 0) {
1563                 ctl_frontend_register(&ha_frontend);
1564                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1565                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1566                         softc->is_single = 1;
1567                 } else
1568                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1569                     != CTL_HA_STATUS_SUCCESS) {
1570                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1571                         softc->is_single = 1;
1572                 }
1573         }
1574         return (0);
1575 }
1576
1577 void
1578 ctl_shutdown(void)
1579 {
1580         struct ctl_softc *softc;
1581         struct ctl_lun *lun, *next_lun;
1582
1583         softc = (struct ctl_softc *)control_softc;
1584
1585         if (softc->is_single == 0) {
1586                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1587                     != CTL_HA_STATUS_SUCCESS) {
1588                         printf("ctl_shutdown: ctl_ha_msg_deregister failed.\n");
1589                 }
1590                 if (ctl_ha_msg_shutdown(softc) != CTL_HA_STATUS_SUCCESS) {
1591                         printf("ctl_shutdown: ctl_ha_msg_shutdown failed.\n");
1592                 }
1593                 ctl_frontend_deregister(&ha_frontend);
1594         }
1595
1596         mtx_lock(&softc->ctl_lock);
1597
1598         /*
1599          * Free up each LUN.
1600          */
1601         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1602                 next_lun = STAILQ_NEXT(lun, links);
1603                 ctl_free_lun(lun);
1604         }
1605
1606         mtx_unlock(&softc->ctl_lock);
1607
1608 #if 0
1609         ctl_shutdown_thread(softc->work_thread);
1610         mtx_destroy(&softc->queue_lock);
1611 #endif
1612
1613         ctl_tpc_shutdown(softc);
1614         uma_zdestroy(softc->io_zone);
1615         mtx_destroy(&softc->ctl_lock);
1616
1617         destroy_dev(softc->dev);
1618
1619         sysctl_ctx_free(&softc->sysctl_ctx);
1620
1621         free(control_softc, M_DEVBUF);
1622         control_softc = NULL;
1623 }
1624
1625 static int
1626 ctl_module_event_handler(module_t mod, int what, void *arg)
1627 {
1628
1629         switch (what) {
1630         case MOD_LOAD:
1631                 return (ctl_init());
1632         case MOD_UNLOAD:
1633                 return (EBUSY);
1634         default:
1635                 return (EOPNOTSUPP);
1636         }
1637 }
1638
1639 /*
1640  * XXX KDM should we do some access checks here?  Bump a reference count to
1641  * prevent a CTL module from being unloaded while someone has it open?
1642  */
1643 static int
1644 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1645 {
1646         return (0);
1647 }
1648
1649 static int
1650 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1651 {
1652         return (0);
1653 }
1654
1655 /*
1656  * Remove an initiator by port number and initiator ID.
1657  * Returns 0 for success, -1 for failure.
1658  */
1659 int
1660 ctl_remove_initiator(struct ctl_port *port, int iid)
1661 {
1662         struct ctl_softc *softc = control_softc;
1663
1664         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1665
1666         if (iid > CTL_MAX_INIT_PER_PORT) {
1667                 printf("%s: initiator ID %u > maximun %u!\n",
1668                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1669                 return (-1);
1670         }
1671
1672         mtx_lock(&softc->ctl_lock);
1673         port->wwpn_iid[iid].in_use--;
1674         port->wwpn_iid[iid].last_use = time_uptime;
1675         mtx_unlock(&softc->ctl_lock);
1676         ctl_isc_announce_iid(port, iid);
1677
1678         return (0);
1679 }
1680
1681 /*
1682  * Add an initiator to the initiator map.
1683  * Returns iid for success, < 0 for failure.
1684  */
1685 int
1686 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1687 {
1688         struct ctl_softc *softc = control_softc;
1689         time_t best_time;
1690         int i, best;
1691
1692         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1693
1694         if (iid >= CTL_MAX_INIT_PER_PORT) {
1695                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1696                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1697                 free(name, M_CTL);
1698                 return (-1);
1699         }
1700
1701         mtx_lock(&softc->ctl_lock);
1702
1703         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1704                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1705                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1706                                 iid = i;
1707                                 break;
1708                         }
1709                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1710                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1711                                 iid = i;
1712                                 break;
1713                         }
1714                 }
1715         }
1716
1717         if (iid < 0) {
1718                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1719                         if (port->wwpn_iid[i].in_use == 0 &&
1720                             port->wwpn_iid[i].wwpn == 0 &&
1721                             port->wwpn_iid[i].name == NULL) {
1722                                 iid = i;
1723                                 break;
1724                         }
1725                 }
1726         }
1727
1728         if (iid < 0) {
1729                 best = -1;
1730                 best_time = INT32_MAX;
1731                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1732                         if (port->wwpn_iid[i].in_use == 0) {
1733                                 if (port->wwpn_iid[i].last_use < best_time) {
1734                                         best = i;
1735                                         best_time = port->wwpn_iid[i].last_use;
1736                                 }
1737                         }
1738                 }
1739                 iid = best;
1740         }
1741
1742         if (iid < 0) {
1743                 mtx_unlock(&softc->ctl_lock);
1744                 free(name, M_CTL);
1745                 return (-2);
1746         }
1747
1748         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1749                 /*
1750                  * This is not an error yet.
1751                  */
1752                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1753 #if 0
1754                         printf("%s: port %d iid %u WWPN %#jx arrived"
1755                             " again\n", __func__, port->targ_port,
1756                             iid, (uintmax_t)wwpn);
1757 #endif
1758                         goto take;
1759                 }
1760                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1761                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1762 #if 0
1763                         printf("%s: port %d iid %u name '%s' arrived"
1764                             " again\n", __func__, port->targ_port,
1765                             iid, name);
1766 #endif
1767                         goto take;
1768                 }
1769
1770                 /*
1771                  * This is an error, but what do we do about it?  The
1772                  * driver is telling us we have a new WWPN for this
1773                  * initiator ID, so we pretty much need to use it.
1774                  */
1775                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1776                     " but WWPN %#jx '%s' is still at that address\n",
1777                     __func__, port->targ_port, iid, wwpn, name,
1778                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1779                     port->wwpn_iid[iid].name);
1780
1781                 /*
1782                  * XXX KDM clear have_ca and ua_pending on each LUN for
1783                  * this initiator.
1784                  */
1785         }
1786 take:
1787         free(port->wwpn_iid[iid].name, M_CTL);
1788         port->wwpn_iid[iid].name = name;
1789         port->wwpn_iid[iid].wwpn = wwpn;
1790         port->wwpn_iid[iid].in_use++;
1791         mtx_unlock(&softc->ctl_lock);
1792         ctl_isc_announce_iid(port, iid);
1793
1794         return (iid);
1795 }
1796
1797 static int
1798 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1799 {
1800         int len;
1801
1802         switch (port->port_type) {
1803         case CTL_PORT_FC:
1804         {
1805                 struct scsi_transportid_fcp *id =
1806                     (struct scsi_transportid_fcp *)buf;
1807                 if (port->wwpn_iid[iid].wwpn == 0)
1808                         return (0);
1809                 memset(id, 0, sizeof(*id));
1810                 id->format_protocol = SCSI_PROTO_FC;
1811                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1812                 return (sizeof(*id));
1813         }
1814         case CTL_PORT_ISCSI:
1815         {
1816                 struct scsi_transportid_iscsi_port *id =
1817                     (struct scsi_transportid_iscsi_port *)buf;
1818                 if (port->wwpn_iid[iid].name == NULL)
1819                         return (0);
1820                 memset(id, 0, 256);
1821                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1822                     SCSI_PROTO_ISCSI;
1823                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1824                 len = roundup2(min(len, 252), 4);
1825                 scsi_ulto2b(len, id->additional_length);
1826                 return (sizeof(*id) + len);
1827         }
1828         case CTL_PORT_SAS:
1829         {
1830                 struct scsi_transportid_sas *id =
1831                     (struct scsi_transportid_sas *)buf;
1832                 if (port->wwpn_iid[iid].wwpn == 0)
1833                         return (0);
1834                 memset(id, 0, sizeof(*id));
1835                 id->format_protocol = SCSI_PROTO_SAS;
1836                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1837                 return (sizeof(*id));
1838         }
1839         default:
1840         {
1841                 struct scsi_transportid_spi *id =
1842                     (struct scsi_transportid_spi *)buf;
1843                 memset(id, 0, sizeof(*id));
1844                 id->format_protocol = SCSI_PROTO_SPI;
1845                 scsi_ulto2b(iid, id->scsi_addr);
1846                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1847                 return (sizeof(*id));
1848         }
1849         }
1850 }
1851
1852 /*
1853  * Serialize a command that went down the "wrong" side, and so was sent to
1854  * this controller for execution.  The logic is a little different than the
1855  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1856  * sent back to the other side, but in the success case, we execute the
1857  * command on this side (XFER mode) or tell the other side to execute it
1858  * (SER_ONLY mode).
1859  */
1860 static int
1861 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1862 {
1863         struct ctl_softc *softc;
1864         union ctl_ha_msg msg_info;
1865         struct ctl_lun *lun;
1866         const struct ctl_cmd_entry *entry;
1867         int retval = 0;
1868         uint32_t targ_lun;
1869
1870         softc = control_softc;
1871
1872         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1873         mtx_lock(&softc->ctl_lock);
1874         if ((targ_lun < CTL_MAX_LUNS) &&
1875             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
1876                 mtx_lock(&lun->lun_lock);
1877                 mtx_unlock(&softc->ctl_lock);
1878                 /*
1879                  * If the LUN is invalid, pretend that it doesn't exist.
1880                  * It will go away as soon as all pending I/O has been
1881                  * completed.
1882                  */
1883                 if (lun->flags & CTL_LUN_DISABLED) {
1884                         mtx_unlock(&lun->lun_lock);
1885                         lun = NULL;
1886                 }
1887         } else {
1888                 mtx_unlock(&softc->ctl_lock);
1889                 lun = NULL;
1890         }
1891         if (lun == NULL) {
1892                 /*
1893                  * The other node would not send this request to us unless
1894                  * received announce that we are primary node for this LUN.
1895                  * If this LUN does not exist now, it is probably result of
1896                  * a race, so respond to initiator in the most opaque way.
1897                  */
1898                 ctl_set_busy(ctsio);
1899                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1900                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1901                 msg_info.hdr.serializing_sc = NULL;
1902                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1903                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1904                     sizeof(msg_info.scsi), M_WAITOK);
1905                 return(1);
1906         }
1907
1908         entry = ctl_get_cmd_entry(ctsio, NULL);
1909         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
1910                 mtx_unlock(&lun->lun_lock);
1911                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1912                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1913                 msg_info.hdr.serializing_sc = NULL;
1914                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1915                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1916                     sizeof(msg_info.scsi), M_WAITOK);
1917                 return(1);
1918         }
1919
1920         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
1921         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
1922
1923         /*
1924          * Every I/O goes into the OOA queue for a
1925          * particular LUN, and stays there until completion.
1926          */
1927 #ifdef CTL_TIME_IO
1928         if (TAILQ_EMPTY(&lun->ooa_queue))
1929                 lun->idle_time += getsbinuptime() - lun->last_busy;
1930 #endif
1931         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1932
1933         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1934                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1935                  ooa_links))) {
1936         case CTL_ACTION_BLOCK:
1937                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1938                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1939                                   blocked_links);
1940                 mtx_unlock(&lun->lun_lock);
1941                 break;
1942         case CTL_ACTION_PASS:
1943         case CTL_ACTION_SKIP:
1944                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1945                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1946                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1947                         mtx_unlock(&lun->lun_lock);
1948                 } else {
1949                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
1950                         mtx_unlock(&lun->lun_lock);
1951
1952                         /* send msg back to other side */
1953                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1954                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1955                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1956                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1957                             sizeof(msg_info.hdr), M_WAITOK);
1958                 }
1959                 break;
1960         case CTL_ACTION_OVERLAP:
1961                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1962                 mtx_unlock(&lun->lun_lock);
1963                 retval = 1;
1964
1965                 ctl_set_overlapped_cmd(ctsio);
1966                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1967                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1968                 msg_info.hdr.serializing_sc = NULL;
1969                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1970                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1971                     sizeof(msg_info.scsi), M_WAITOK);
1972                 break;
1973         case CTL_ACTION_OVERLAP_TAG:
1974                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1975                 mtx_unlock(&lun->lun_lock);
1976                 retval = 1;
1977                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
1978                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1979                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1980                 msg_info.hdr.serializing_sc = NULL;
1981                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1982                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1983                     sizeof(msg_info.scsi), M_WAITOK);
1984                 break;
1985         case CTL_ACTION_ERROR:
1986         default:
1987                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1988                 mtx_unlock(&lun->lun_lock);
1989                 retval = 1;
1990
1991                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
1992                                          /*retry_count*/ 0);
1993                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1994                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1995                 msg_info.hdr.serializing_sc = NULL;
1996                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1997                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1998                     sizeof(msg_info.scsi), M_WAITOK);
1999                 break;
2000         }
2001         return (retval);
2002 }
2003
2004 /*
2005  * Returns 0 for success, errno for failure.
2006  */
2007 static int
2008 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2009                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2010 {
2011         union ctl_io *io;
2012         int retval;
2013
2014         retval = 0;
2015
2016         mtx_lock(&lun->lun_lock);
2017         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2018              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2019              ooa_links)) {
2020                 struct ctl_ooa_entry *entry;
2021
2022                 /*
2023                  * If we've got more than we can fit, just count the
2024                  * remaining entries.
2025                  */
2026                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2027                         continue;
2028
2029                 entry = &kern_entries[*cur_fill_num];
2030
2031                 entry->tag_num = io->scsiio.tag_num;
2032                 entry->lun_num = lun->lun;
2033 #ifdef CTL_TIME_IO
2034                 entry->start_bt = io->io_hdr.start_bt;
2035 #endif
2036                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2037                 entry->cdb_len = io->scsiio.cdb_len;
2038                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2039                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2040
2041                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2042                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2043
2044                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2045                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2046
2047                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2048                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2049
2050                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2051                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2052         }
2053         mtx_unlock(&lun->lun_lock);
2054
2055         return (retval);
2056 }
2057
2058 static void *
2059 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2060                  size_t error_str_len)
2061 {
2062         void *kptr;
2063
2064         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2065
2066         if (copyin(user_addr, kptr, len) != 0) {
2067                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2068                          "from user address %p to kernel address %p", len,
2069                          user_addr, kptr);
2070                 free(kptr, M_CTL);
2071                 return (NULL);
2072         }
2073
2074         return (kptr);
2075 }
2076
2077 static void
2078 ctl_free_args(int num_args, struct ctl_be_arg *args)
2079 {
2080         int i;
2081
2082         if (args == NULL)
2083                 return;
2084
2085         for (i = 0; i < num_args; i++) {
2086                 free(args[i].kname, M_CTL);
2087                 free(args[i].kvalue, M_CTL);
2088         }
2089
2090         free(args, M_CTL);
2091 }
2092
2093 static struct ctl_be_arg *
2094 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2095                 char *error_str, size_t error_str_len)
2096 {
2097         struct ctl_be_arg *args;
2098         int i;
2099
2100         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2101                                 error_str, error_str_len);
2102
2103         if (args == NULL)
2104                 goto bailout;
2105
2106         for (i = 0; i < num_args; i++) {
2107                 args[i].kname = NULL;
2108                 args[i].kvalue = NULL;
2109         }
2110
2111         for (i = 0; i < num_args; i++) {
2112                 uint8_t *tmpptr;
2113
2114                 args[i].kname = ctl_copyin_alloc(args[i].name,
2115                         args[i].namelen, error_str, error_str_len);
2116                 if (args[i].kname == NULL)
2117                         goto bailout;
2118
2119                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2120                         snprintf(error_str, error_str_len, "Argument %d "
2121                                  "name is not NUL-terminated", i);
2122                         goto bailout;
2123                 }
2124
2125                 if (args[i].flags & CTL_BEARG_RD) {
2126                         tmpptr = ctl_copyin_alloc(args[i].value,
2127                                 args[i].vallen, error_str, error_str_len);
2128                         if (tmpptr == NULL)
2129                                 goto bailout;
2130                         if ((args[i].flags & CTL_BEARG_ASCII)
2131                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2132                                 snprintf(error_str, error_str_len, "Argument "
2133                                     "%d value is not NUL-terminated", i);
2134                                 goto bailout;
2135                         }
2136                         args[i].kvalue = tmpptr;
2137                 } else {
2138                         args[i].kvalue = malloc(args[i].vallen,
2139                             M_CTL, M_WAITOK | M_ZERO);
2140                 }
2141         }
2142
2143         return (args);
2144 bailout:
2145
2146         ctl_free_args(num_args, args);
2147
2148         return (NULL);
2149 }
2150
2151 static void
2152 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2153 {
2154         int i;
2155
2156         for (i = 0; i < num_args; i++) {
2157                 if (args[i].flags & CTL_BEARG_WR)
2158                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2159         }
2160 }
2161
2162 /*
2163  * Escape characters that are illegal or not recommended in XML.
2164  */
2165 int
2166 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2167 {
2168         char *end = str + size;
2169         int retval;
2170
2171         retval = 0;
2172
2173         for (; *str && str < end; str++) {
2174                 switch (*str) {
2175                 case '&':
2176                         retval = sbuf_printf(sb, "&amp;");
2177                         break;
2178                 case '>':
2179                         retval = sbuf_printf(sb, "&gt;");
2180                         break;
2181                 case '<':
2182                         retval = sbuf_printf(sb, "&lt;");
2183                         break;
2184                 default:
2185                         retval = sbuf_putc(sb, *str);
2186                         break;
2187                 }
2188
2189                 if (retval != 0)
2190                         break;
2191
2192         }
2193
2194         return (retval);
2195 }
2196
2197 static void
2198 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2199 {
2200         struct scsi_vpd_id_descriptor *desc;
2201         int i;
2202
2203         if (id == NULL || id->len < 4)
2204                 return;
2205         desc = (struct scsi_vpd_id_descriptor *)id->data;
2206         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2207         case SVPD_ID_TYPE_T10:
2208                 sbuf_printf(sb, "t10.");
2209                 break;
2210         case SVPD_ID_TYPE_EUI64:
2211                 sbuf_printf(sb, "eui.");
2212                 break;
2213         case SVPD_ID_TYPE_NAA:
2214                 sbuf_printf(sb, "naa.");
2215                 break;
2216         case SVPD_ID_TYPE_SCSI_NAME:
2217                 break;
2218         }
2219         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2220         case SVPD_ID_CODESET_BINARY:
2221                 for (i = 0; i < desc->length; i++)
2222                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2223                 break;
2224         case SVPD_ID_CODESET_ASCII:
2225                 sbuf_printf(sb, "%.*s", (int)desc->length,
2226                     (char *)desc->identifier);
2227                 break;
2228         case SVPD_ID_CODESET_UTF8:
2229                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2230                 break;
2231         }
2232 }
2233
2234 static int
2235 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2236           struct thread *td)
2237 {
2238         struct ctl_softc *softc;
2239         struct ctl_lun *lun;
2240         int retval;
2241
2242         softc = control_softc;
2243
2244         retval = 0;
2245
2246         switch (cmd) {
2247         case CTL_IO:
2248                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2249                 break;
2250         case CTL_ENABLE_PORT:
2251         case CTL_DISABLE_PORT:
2252         case CTL_SET_PORT_WWNS: {
2253                 struct ctl_port *port;
2254                 struct ctl_port_entry *entry;
2255
2256                 entry = (struct ctl_port_entry *)addr;
2257                 
2258                 mtx_lock(&softc->ctl_lock);
2259                 STAILQ_FOREACH(port, &softc->port_list, links) {
2260                         int action, done;
2261
2262                         if (port->targ_port < softc->port_min ||
2263                             port->targ_port >= softc->port_max)
2264                                 continue;
2265
2266                         action = 0;
2267                         done = 0;
2268                         if ((entry->port_type == CTL_PORT_NONE)
2269                          && (entry->targ_port == port->targ_port)) {
2270                                 /*
2271                                  * If the user only wants to enable or
2272                                  * disable or set WWNs on a specific port,
2273                                  * do the operation and we're done.
2274                                  */
2275                                 action = 1;
2276                                 done = 1;
2277                         } else if (entry->port_type & port->port_type) {
2278                                 /*
2279                                  * Compare the user's type mask with the
2280                                  * particular frontend type to see if we
2281                                  * have a match.
2282                                  */
2283                                 action = 1;
2284                                 done = 0;
2285
2286                                 /*
2287                                  * Make sure the user isn't trying to set
2288                                  * WWNs on multiple ports at the same time.
2289                                  */
2290                                 if (cmd == CTL_SET_PORT_WWNS) {
2291                                         printf("%s: Can't set WWNs on "
2292                                                "multiple ports\n", __func__);
2293                                         retval = EINVAL;
2294                                         break;
2295                                 }
2296                         }
2297                         if (action == 0)
2298                                 continue;
2299
2300                         /*
2301                          * XXX KDM we have to drop the lock here, because
2302                          * the online/offline operations can potentially
2303                          * block.  We need to reference count the frontends
2304                          * so they can't go away,
2305                          */
2306                         if (cmd == CTL_ENABLE_PORT) {
2307                                 mtx_unlock(&softc->ctl_lock);
2308                                 ctl_port_online(port);
2309                                 mtx_lock(&softc->ctl_lock);
2310                         } else if (cmd == CTL_DISABLE_PORT) {
2311                                 mtx_unlock(&softc->ctl_lock);
2312                                 ctl_port_offline(port);
2313                                 mtx_lock(&softc->ctl_lock);
2314                         } else if (cmd == CTL_SET_PORT_WWNS) {
2315                                 ctl_port_set_wwns(port,
2316                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2317                                     1 : 0, entry->wwnn,
2318                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2319                                     1 : 0, entry->wwpn);
2320                         }
2321                         if (done != 0)
2322                                 break;
2323                 }
2324                 mtx_unlock(&softc->ctl_lock);
2325                 break;
2326         }
2327         case CTL_GET_PORT_LIST: {
2328                 struct ctl_port *port;
2329                 struct ctl_port_list *list;
2330                 int i;
2331
2332                 list = (struct ctl_port_list *)addr;
2333
2334                 if (list->alloc_len != (list->alloc_num *
2335                     sizeof(struct ctl_port_entry))) {
2336                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2337                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2338                                "%zu\n", __func__, list->alloc_len,
2339                                list->alloc_num, sizeof(struct ctl_port_entry));
2340                         retval = EINVAL;
2341                         break;
2342                 }
2343                 list->fill_len = 0;
2344                 list->fill_num = 0;
2345                 list->dropped_num = 0;
2346                 i = 0;
2347                 mtx_lock(&softc->ctl_lock);
2348                 STAILQ_FOREACH(port, &softc->port_list, links) {
2349                         struct ctl_port_entry entry, *list_entry;
2350
2351                         if (list->fill_num >= list->alloc_num) {
2352                                 list->dropped_num++;
2353                                 continue;
2354                         }
2355
2356                         entry.port_type = port->port_type;
2357                         strlcpy(entry.port_name, port->port_name,
2358                                 sizeof(entry.port_name));
2359                         entry.targ_port = port->targ_port;
2360                         entry.physical_port = port->physical_port;
2361                         entry.virtual_port = port->virtual_port;
2362                         entry.wwnn = port->wwnn;
2363                         entry.wwpn = port->wwpn;
2364                         if (port->status & CTL_PORT_STATUS_ONLINE)
2365                                 entry.online = 1;
2366                         else
2367                                 entry.online = 0;
2368
2369                         list_entry = &list->entries[i];
2370
2371                         retval = copyout(&entry, list_entry, sizeof(entry));
2372                         if (retval != 0) {
2373                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2374                                        "returned %d\n", __func__, retval);
2375                                 break;
2376                         }
2377                         i++;
2378                         list->fill_num++;
2379                         list->fill_len += sizeof(entry);
2380                 }
2381                 mtx_unlock(&softc->ctl_lock);
2382
2383                 /*
2384                  * If this is non-zero, we had a copyout fault, so there's
2385                  * probably no point in attempting to set the status inside
2386                  * the structure.
2387                  */
2388                 if (retval != 0)
2389                         break;
2390
2391                 if (list->dropped_num > 0)
2392                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2393                 else
2394                         list->status = CTL_PORT_LIST_OK;
2395                 break;
2396         }
2397         case CTL_DUMP_OOA: {
2398                 union ctl_io *io;
2399                 char printbuf[128];
2400                 struct sbuf sb;
2401
2402                 mtx_lock(&softc->ctl_lock);
2403                 printf("Dumping OOA queues:\n");
2404                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2405                         mtx_lock(&lun->lun_lock);
2406                         for (io = (union ctl_io *)TAILQ_FIRST(
2407                              &lun->ooa_queue); io != NULL;
2408                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2409                              ooa_links)) {
2410                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2411                                          SBUF_FIXEDLEN);
2412                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2413                                             (intmax_t)lun->lun,
2414                                             io->scsiio.tag_num,
2415                                             (io->io_hdr.flags &
2416                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2417                                             (io->io_hdr.flags &
2418                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2419                                             (io->io_hdr.flags &
2420                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2421                                             (io->io_hdr.flags &
2422                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2423                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2424                                 sbuf_finish(&sb);
2425                                 printf("%s\n", sbuf_data(&sb));
2426                         }
2427                         mtx_unlock(&lun->lun_lock);
2428                 }
2429                 printf("OOA queues dump done\n");
2430                 mtx_unlock(&softc->ctl_lock);
2431                 break;
2432         }
2433         case CTL_GET_OOA: {
2434                 struct ctl_ooa *ooa_hdr;
2435                 struct ctl_ooa_entry *entries;
2436                 uint32_t cur_fill_num;
2437
2438                 ooa_hdr = (struct ctl_ooa *)addr;
2439
2440                 if ((ooa_hdr->alloc_len == 0)
2441                  || (ooa_hdr->alloc_num == 0)) {
2442                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2443                                "must be non-zero\n", __func__,
2444                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2445                         retval = EINVAL;
2446                         break;
2447                 }
2448
2449                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2450                     sizeof(struct ctl_ooa_entry))) {
2451                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2452                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2453                                __func__, ooa_hdr->alloc_len,
2454                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2455                         retval = EINVAL;
2456                         break;
2457                 }
2458
2459                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2460                 if (entries == NULL) {
2461                         printf("%s: could not allocate %d bytes for OOA "
2462                                "dump\n", __func__, ooa_hdr->alloc_len);
2463                         retval = ENOMEM;
2464                         break;
2465                 }
2466
2467                 mtx_lock(&softc->ctl_lock);
2468                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2469                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2470                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2471                         mtx_unlock(&softc->ctl_lock);
2472                         free(entries, M_CTL);
2473                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2474                                __func__, (uintmax_t)ooa_hdr->lun_num);
2475                         retval = EINVAL;
2476                         break;
2477                 }
2478
2479                 cur_fill_num = 0;
2480
2481                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2482                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2483                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2484                                         ooa_hdr, entries);
2485                                 if (retval != 0)
2486                                         break;
2487                         }
2488                         if (retval != 0) {
2489                                 mtx_unlock(&softc->ctl_lock);
2490                                 free(entries, M_CTL);
2491                                 break;
2492                         }
2493                 } else {
2494                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2495
2496                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2497                                                     entries);
2498                 }
2499                 mtx_unlock(&softc->ctl_lock);
2500
2501                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2502                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2503                         sizeof(struct ctl_ooa_entry);
2504                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2505                 if (retval != 0) {
2506                         printf("%s: error copying out %d bytes for OOA dump\n", 
2507                                __func__, ooa_hdr->fill_len);
2508                 }
2509
2510                 getbintime(&ooa_hdr->cur_bt);
2511
2512                 if (cur_fill_num > ooa_hdr->alloc_num) {
2513                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2514                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2515                 } else {
2516                         ooa_hdr->dropped_num = 0;
2517                         ooa_hdr->status = CTL_OOA_OK;
2518                 }
2519
2520                 free(entries, M_CTL);
2521                 break;
2522         }
2523         case CTL_CHECK_OOA: {
2524                 union ctl_io *io;
2525                 struct ctl_ooa_info *ooa_info;
2526
2527
2528                 ooa_info = (struct ctl_ooa_info *)addr;
2529
2530                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2531                         ooa_info->status = CTL_OOA_INVALID_LUN;
2532                         break;
2533                 }
2534                 mtx_lock(&softc->ctl_lock);
2535                 lun = softc->ctl_luns[ooa_info->lun_id];
2536                 if (lun == NULL) {
2537                         mtx_unlock(&softc->ctl_lock);
2538                         ooa_info->status = CTL_OOA_INVALID_LUN;
2539                         break;
2540                 }
2541                 mtx_lock(&lun->lun_lock);
2542                 mtx_unlock(&softc->ctl_lock);
2543                 ooa_info->num_entries = 0;
2544                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2545                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2546                      &io->io_hdr, ooa_links)) {
2547                         ooa_info->num_entries++;
2548                 }
2549                 mtx_unlock(&lun->lun_lock);
2550
2551                 ooa_info->status = CTL_OOA_SUCCESS;
2552
2553                 break;
2554         }
2555         case CTL_DELAY_IO: {
2556                 struct ctl_io_delay_info *delay_info;
2557
2558                 delay_info = (struct ctl_io_delay_info *)addr;
2559
2560 #ifdef CTL_IO_DELAY
2561                 mtx_lock(&softc->ctl_lock);
2562
2563                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2564                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2565                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2566                 } else {
2567                         lun = softc->ctl_luns[delay_info->lun_id];
2568                         mtx_lock(&lun->lun_lock);
2569
2570                         delay_info->status = CTL_DELAY_STATUS_OK;
2571
2572                         switch (delay_info->delay_type) {
2573                         case CTL_DELAY_TYPE_CONT:
2574                                 break;
2575                         case CTL_DELAY_TYPE_ONESHOT:
2576                                 break;
2577                         default:
2578                                 delay_info->status =
2579                                         CTL_DELAY_STATUS_INVALID_TYPE;
2580                                 break;
2581                         }
2582
2583                         switch (delay_info->delay_loc) {
2584                         case CTL_DELAY_LOC_DATAMOVE:
2585                                 lun->delay_info.datamove_type =
2586                                         delay_info->delay_type;
2587                                 lun->delay_info.datamove_delay =
2588                                         delay_info->delay_secs;
2589                                 break;
2590                         case CTL_DELAY_LOC_DONE:
2591                                 lun->delay_info.done_type =
2592                                         delay_info->delay_type;
2593                                 lun->delay_info.done_delay =
2594                                         delay_info->delay_secs;
2595                                 break;
2596                         default:
2597                                 delay_info->status =
2598                                         CTL_DELAY_STATUS_INVALID_LOC;
2599                                 break;
2600                         }
2601                         mtx_unlock(&lun->lun_lock);
2602                 }
2603
2604                 mtx_unlock(&softc->ctl_lock);
2605 #else
2606                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2607 #endif /* CTL_IO_DELAY */
2608                 break;
2609         }
2610         case CTL_REALSYNC_SET: {
2611                 int *syncstate;
2612
2613                 syncstate = (int *)addr;
2614
2615                 mtx_lock(&softc->ctl_lock);
2616                 switch (*syncstate) {
2617                 case 0:
2618                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2619                         break;
2620                 case 1:
2621                         softc->flags |= CTL_FLAG_REAL_SYNC;
2622                         break;
2623                 default:
2624                         retval = EINVAL;
2625                         break;
2626                 }
2627                 mtx_unlock(&softc->ctl_lock);
2628                 break;
2629         }
2630         case CTL_REALSYNC_GET: {
2631                 int *syncstate;
2632
2633                 syncstate = (int*)addr;
2634
2635                 mtx_lock(&softc->ctl_lock);
2636                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2637                         *syncstate = 1;
2638                 else
2639                         *syncstate = 0;
2640                 mtx_unlock(&softc->ctl_lock);
2641
2642                 break;
2643         }
2644         case CTL_SETSYNC:
2645         case CTL_GETSYNC: {
2646                 struct ctl_sync_info *sync_info;
2647
2648                 sync_info = (struct ctl_sync_info *)addr;
2649
2650                 mtx_lock(&softc->ctl_lock);
2651                 lun = softc->ctl_luns[sync_info->lun_id];
2652                 if (lun == NULL) {
2653                         mtx_unlock(&softc->ctl_lock);
2654                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2655                         break;
2656                 }
2657                 /*
2658                  * Get or set the sync interval.  We're not bounds checking
2659                  * in the set case, hopefully the user won't do something
2660                  * silly.
2661                  */
2662                 mtx_lock(&lun->lun_lock);
2663                 mtx_unlock(&softc->ctl_lock);
2664                 if (cmd == CTL_GETSYNC)
2665                         sync_info->sync_interval = lun->sync_interval;
2666                 else
2667                         lun->sync_interval = sync_info->sync_interval;
2668                 mtx_unlock(&lun->lun_lock);
2669
2670                 sync_info->status = CTL_GS_SYNC_OK;
2671
2672                 break;
2673         }
2674         case CTL_GETSTATS: {
2675                 struct ctl_stats *stats;
2676                 int i;
2677
2678                 stats = (struct ctl_stats *)addr;
2679
2680                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2681                      stats->alloc_len) {
2682                         stats->status = CTL_SS_NEED_MORE_SPACE;
2683                         stats->num_luns = softc->num_luns;
2684                         break;
2685                 }
2686                 /*
2687                  * XXX KDM no locking here.  If the LUN list changes,
2688                  * things can blow up.
2689                  */
2690                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2691                      i++, lun = STAILQ_NEXT(lun, links)) {
2692                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2693                                          sizeof(lun->stats));
2694                         if (retval != 0)
2695                                 break;
2696                 }
2697                 stats->num_luns = softc->num_luns;
2698                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2699                                  softc->num_luns;
2700                 stats->status = CTL_SS_OK;
2701 #ifdef CTL_TIME_IO
2702                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2703 #else
2704                 stats->flags = CTL_STATS_FLAG_NONE;
2705 #endif
2706                 getnanouptime(&stats->timestamp);
2707                 break;
2708         }
2709         case CTL_ERROR_INJECT: {
2710                 struct ctl_error_desc *err_desc, *new_err_desc;
2711
2712                 err_desc = (struct ctl_error_desc *)addr;
2713
2714                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2715                                       M_WAITOK | M_ZERO);
2716                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2717
2718                 mtx_lock(&softc->ctl_lock);
2719                 lun = softc->ctl_luns[err_desc->lun_id];
2720                 if (lun == NULL) {
2721                         mtx_unlock(&softc->ctl_lock);
2722                         free(new_err_desc, M_CTL);
2723                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2724                                __func__, (uintmax_t)err_desc->lun_id);
2725                         retval = EINVAL;
2726                         break;
2727                 }
2728                 mtx_lock(&lun->lun_lock);
2729                 mtx_unlock(&softc->ctl_lock);
2730
2731                 /*
2732                  * We could do some checking here to verify the validity
2733                  * of the request, but given the complexity of error
2734                  * injection requests, the checking logic would be fairly
2735                  * complex.
2736                  *
2737                  * For now, if the request is invalid, it just won't get
2738                  * executed and might get deleted.
2739                  */
2740                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2741
2742                 /*
2743                  * XXX KDM check to make sure the serial number is unique,
2744                  * in case we somehow manage to wrap.  That shouldn't
2745                  * happen for a very long time, but it's the right thing to
2746                  * do.
2747                  */
2748                 new_err_desc->serial = lun->error_serial;
2749                 err_desc->serial = lun->error_serial;
2750                 lun->error_serial++;
2751
2752                 mtx_unlock(&lun->lun_lock);
2753                 break;
2754         }
2755         case CTL_ERROR_INJECT_DELETE: {
2756                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2757                 int delete_done;
2758
2759                 delete_desc = (struct ctl_error_desc *)addr;
2760                 delete_done = 0;
2761
2762                 mtx_lock(&softc->ctl_lock);
2763                 lun = softc->ctl_luns[delete_desc->lun_id];
2764                 if (lun == NULL) {
2765                         mtx_unlock(&softc->ctl_lock);
2766                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2767                                __func__, (uintmax_t)delete_desc->lun_id);
2768                         retval = EINVAL;
2769                         break;
2770                 }
2771                 mtx_lock(&lun->lun_lock);
2772                 mtx_unlock(&softc->ctl_lock);
2773                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2774                         if (desc->serial != delete_desc->serial)
2775                                 continue;
2776
2777                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2778                                       links);
2779                         free(desc, M_CTL);
2780                         delete_done = 1;
2781                 }
2782                 mtx_unlock(&lun->lun_lock);
2783                 if (delete_done == 0) {
2784                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2785                                "error serial %ju on LUN %u\n", __func__, 
2786                                delete_desc->serial, delete_desc->lun_id);
2787                         retval = EINVAL;
2788                         break;
2789                 }
2790                 break;
2791         }
2792         case CTL_DUMP_STRUCTS: {
2793                 int i, j, k;
2794                 struct ctl_port *port;
2795                 struct ctl_frontend *fe;
2796
2797                 mtx_lock(&softc->ctl_lock);
2798                 printf("CTL Persistent Reservation information start:\n");
2799                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2800                         lun = softc->ctl_luns[i];
2801
2802                         if ((lun == NULL)
2803                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2804                                 continue;
2805
2806                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2807                                 if (lun->pr_keys[j] == NULL)
2808                                         continue;
2809                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2810                                         if (lun->pr_keys[j][k] == 0)
2811                                                 continue;
2812                                         printf("  LUN %d port %d iid %d key "
2813                                                "%#jx\n", i, j, k,
2814                                                (uintmax_t)lun->pr_keys[j][k]);
2815                                 }
2816                         }
2817                 }
2818                 printf("CTL Persistent Reservation information end\n");
2819                 printf("CTL Ports:\n");
2820                 STAILQ_FOREACH(port, &softc->port_list, links) {
2821                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2822                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2823                                port->frontend->name, port->port_type,
2824                                port->physical_port, port->virtual_port,
2825                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2826                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2827                                 if (port->wwpn_iid[j].in_use == 0 &&
2828                                     port->wwpn_iid[j].wwpn == 0 &&
2829                                     port->wwpn_iid[j].name == NULL)
2830                                         continue;
2831
2832                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2833                                     j, port->wwpn_iid[j].in_use,
2834                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2835                                     port->wwpn_iid[j].name);
2836                         }
2837                 }
2838                 printf("CTL Port information end\n");
2839                 mtx_unlock(&softc->ctl_lock);
2840                 /*
2841                  * XXX KDM calling this without a lock.  We'd likely want
2842                  * to drop the lock before calling the frontend's dump
2843                  * routine anyway.
2844                  */
2845                 printf("CTL Frontends:\n");
2846                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2847                         printf("  Frontend '%s'\n", fe->name);
2848                         if (fe->fe_dump != NULL)
2849                                 fe->fe_dump();
2850                 }
2851                 printf("CTL Frontend information end\n");
2852                 break;
2853         }
2854         case CTL_LUN_REQ: {
2855                 struct ctl_lun_req *lun_req;
2856                 struct ctl_backend_driver *backend;
2857
2858                 lun_req = (struct ctl_lun_req *)addr;
2859
2860                 backend = ctl_backend_find(lun_req->backend);
2861                 if (backend == NULL) {
2862                         lun_req->status = CTL_LUN_ERROR;
2863                         snprintf(lun_req->error_str,
2864                                  sizeof(lun_req->error_str),
2865                                  "Backend \"%s\" not found.",
2866                                  lun_req->backend);
2867                         break;
2868                 }
2869                 if (lun_req->num_be_args > 0) {
2870                         lun_req->kern_be_args = ctl_copyin_args(
2871                                 lun_req->num_be_args,
2872                                 lun_req->be_args,
2873                                 lun_req->error_str,
2874                                 sizeof(lun_req->error_str));
2875                         if (lun_req->kern_be_args == NULL) {
2876                                 lun_req->status = CTL_LUN_ERROR;
2877                                 break;
2878                         }
2879                 }
2880
2881                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2882
2883                 if (lun_req->num_be_args > 0) {
2884                         ctl_copyout_args(lun_req->num_be_args,
2885                                       lun_req->kern_be_args);
2886                         ctl_free_args(lun_req->num_be_args,
2887                                       lun_req->kern_be_args);
2888                 }
2889                 break;
2890         }
2891         case CTL_LUN_LIST: {
2892                 struct sbuf *sb;
2893                 struct ctl_lun_list *list;
2894                 struct ctl_option *opt;
2895
2896                 list = (struct ctl_lun_list *)addr;
2897
2898                 /*
2899                  * Allocate a fixed length sbuf here, based on the length
2900                  * of the user's buffer.  We could allocate an auto-extending
2901                  * buffer, and then tell the user how much larger our
2902                  * amount of data is than his buffer, but that presents
2903                  * some problems:
2904                  *
2905                  * 1.  The sbuf(9) routines use a blocking malloc, and so
2906                  *     we can't hold a lock while calling them with an
2907                  *     auto-extending buffer.
2908                  *
2909                  * 2.  There is not currently a LUN reference counting
2910                  *     mechanism, outside of outstanding transactions on
2911                  *     the LUN's OOA queue.  So a LUN could go away on us
2912                  *     while we're getting the LUN number, backend-specific
2913                  *     information, etc.  Thus, given the way things
2914                  *     currently work, we need to hold the CTL lock while
2915                  *     grabbing LUN information.
2916                  *
2917                  * So, from the user's standpoint, the best thing to do is
2918                  * allocate what he thinks is a reasonable buffer length,
2919                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2920                  * double the buffer length and try again.  (And repeat
2921                  * that until he succeeds.)
2922                  */
2923                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2924                 if (sb == NULL) {
2925                         list->status = CTL_LUN_LIST_ERROR;
2926                         snprintf(list->error_str, sizeof(list->error_str),
2927                                  "Unable to allocate %d bytes for LUN list",
2928                                  list->alloc_len);
2929                         break;
2930                 }
2931
2932                 sbuf_printf(sb, "<ctllunlist>\n");
2933
2934                 mtx_lock(&softc->ctl_lock);
2935                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2936                         mtx_lock(&lun->lun_lock);
2937                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2938                                              (uintmax_t)lun->lun);
2939
2940                         /*
2941                          * Bail out as soon as we see that we've overfilled
2942                          * the buffer.
2943                          */
2944                         if (retval != 0)
2945                                 break;
2946
2947                         retval = sbuf_printf(sb, "\t<backend_type>%s"
2948                                              "</backend_type>\n",
2949                                              (lun->backend == NULL) ?  "none" :
2950                                              lun->backend->name);
2951
2952                         if (retval != 0)
2953                                 break;
2954
2955                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2956                                              lun->be_lun->lun_type);
2957
2958                         if (retval != 0)
2959                                 break;
2960
2961                         if (lun->backend == NULL) {
2962                                 retval = sbuf_printf(sb, "</lun>\n");
2963                                 if (retval != 0)
2964                                         break;
2965                                 continue;
2966                         }
2967
2968                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2969                                              (lun->be_lun->maxlba > 0) ?
2970                                              lun->be_lun->maxlba + 1 : 0);
2971
2972                         if (retval != 0)
2973                                 break;
2974
2975                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2976                                              lun->be_lun->blocksize);
2977
2978                         if (retval != 0)
2979                                 break;
2980
2981                         retval = sbuf_printf(sb, "\t<serial_number>");
2982
2983                         if (retval != 0)
2984                                 break;
2985
2986                         retval = ctl_sbuf_printf_esc(sb,
2987                             lun->be_lun->serial_num,
2988                             sizeof(lun->be_lun->serial_num));
2989
2990                         if (retval != 0)
2991                                 break;
2992
2993                         retval = sbuf_printf(sb, "</serial_number>\n");
2994                 
2995                         if (retval != 0)
2996                                 break;
2997
2998                         retval = sbuf_printf(sb, "\t<device_id>");
2999
3000                         if (retval != 0)
3001                                 break;
3002
3003                         retval = ctl_sbuf_printf_esc(sb,
3004                             lun->be_lun->device_id,
3005                             sizeof(lun->be_lun->device_id));
3006
3007                         if (retval != 0)
3008                                 break;
3009
3010                         retval = sbuf_printf(sb, "</device_id>\n");
3011
3012                         if (retval != 0)
3013                                 break;
3014
3015                         if (lun->backend->lun_info != NULL) {
3016                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3017                                 if (retval != 0)
3018                                         break;
3019                         }
3020                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3021                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3022                                     opt->name, opt->value, opt->name);
3023                                 if (retval != 0)
3024                                         break;
3025                         }
3026
3027                         retval = sbuf_printf(sb, "</lun>\n");
3028
3029                         if (retval != 0)
3030                                 break;
3031                         mtx_unlock(&lun->lun_lock);
3032                 }
3033                 if (lun != NULL)
3034                         mtx_unlock(&lun->lun_lock);
3035                 mtx_unlock(&softc->ctl_lock);
3036
3037                 if ((retval != 0)
3038                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3039                         retval = 0;
3040                         sbuf_delete(sb);
3041                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3042                         snprintf(list->error_str, sizeof(list->error_str),
3043                                  "Out of space, %d bytes is too small",
3044                                  list->alloc_len);
3045                         break;
3046                 }
3047
3048                 sbuf_finish(sb);
3049
3050                 retval = copyout(sbuf_data(sb), list->lun_xml,
3051                                  sbuf_len(sb) + 1);
3052
3053                 list->fill_len = sbuf_len(sb) + 1;
3054                 list->status = CTL_LUN_LIST_OK;
3055                 sbuf_delete(sb);
3056                 break;
3057         }
3058         case CTL_ISCSI: {
3059                 struct ctl_iscsi *ci;
3060                 struct ctl_frontend *fe;
3061
3062                 ci = (struct ctl_iscsi *)addr;
3063
3064                 fe = ctl_frontend_find("iscsi");
3065                 if (fe == NULL) {
3066                         ci->status = CTL_ISCSI_ERROR;
3067                         snprintf(ci->error_str, sizeof(ci->error_str),
3068                             "Frontend \"iscsi\" not found.");
3069                         break;
3070                 }
3071
3072                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3073                 break;
3074         }
3075         case CTL_PORT_REQ: {
3076                 struct ctl_req *req;
3077                 struct ctl_frontend *fe;
3078
3079                 req = (struct ctl_req *)addr;
3080
3081                 fe = ctl_frontend_find(req->driver);
3082                 if (fe == NULL) {
3083                         req->status = CTL_LUN_ERROR;
3084                         snprintf(req->error_str, sizeof(req->error_str),
3085                             "Frontend \"%s\" not found.", req->driver);
3086                         break;
3087                 }
3088                 if (req->num_args > 0) {
3089                         req->kern_args = ctl_copyin_args(req->num_args,
3090                             req->args, req->error_str, sizeof(req->error_str));
3091                         if (req->kern_args == NULL) {
3092                                 req->status = CTL_LUN_ERROR;
3093                                 break;
3094                         }
3095                 }
3096
3097                 if (fe->ioctl)
3098                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3099                 else
3100                         retval = ENODEV;
3101
3102                 if (req->num_args > 0) {
3103                         ctl_copyout_args(req->num_args, req->kern_args);
3104                         ctl_free_args(req->num_args, req->kern_args);
3105                 }
3106                 break;
3107         }
3108         case CTL_PORT_LIST: {
3109                 struct sbuf *sb;
3110                 struct ctl_port *port;
3111                 struct ctl_lun_list *list;
3112                 struct ctl_option *opt;
3113                 int j;
3114                 uint32_t plun;
3115
3116                 list = (struct ctl_lun_list *)addr;
3117
3118                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3119                 if (sb == NULL) {
3120                         list->status = CTL_LUN_LIST_ERROR;
3121                         snprintf(list->error_str, sizeof(list->error_str),
3122                                  "Unable to allocate %d bytes for LUN list",
3123                                  list->alloc_len);
3124                         break;
3125                 }
3126
3127                 sbuf_printf(sb, "<ctlportlist>\n");
3128
3129                 mtx_lock(&softc->ctl_lock);
3130                 STAILQ_FOREACH(port, &softc->port_list, links) {
3131                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3132                                              (uintmax_t)port->targ_port);
3133
3134                         /*
3135                          * Bail out as soon as we see that we've overfilled
3136                          * the buffer.
3137                          */
3138                         if (retval != 0)
3139                                 break;
3140
3141                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3142                             "</frontend_type>\n", port->frontend->name);
3143                         if (retval != 0)
3144                                 break;
3145
3146                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3147                                              port->port_type);
3148                         if (retval != 0)
3149                                 break;
3150
3151                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3152                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3153                         if (retval != 0)
3154                                 break;
3155
3156                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3157                             port->port_name);
3158                         if (retval != 0)
3159                                 break;
3160
3161                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3162                             port->physical_port);
3163                         if (retval != 0)
3164                                 break;
3165
3166                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3167                             port->virtual_port);
3168                         if (retval != 0)
3169                                 break;
3170
3171                         if (port->target_devid != NULL) {
3172                                 sbuf_printf(sb, "\t<target>");
3173                                 ctl_id_sbuf(port->target_devid, sb);
3174                                 sbuf_printf(sb, "</target>\n");
3175                         }
3176
3177                         if (port->port_devid != NULL) {
3178                                 sbuf_printf(sb, "\t<port>");
3179                                 ctl_id_sbuf(port->port_devid, sb);
3180                                 sbuf_printf(sb, "</port>\n");
3181                         }
3182
3183                         if (port->port_info != NULL) {
3184                                 retval = port->port_info(port->onoff_arg, sb);
3185                                 if (retval != 0)
3186                                         break;
3187                         }
3188                         STAILQ_FOREACH(opt, &port->options, links) {
3189                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3190                                     opt->name, opt->value, opt->name);
3191                                 if (retval != 0)
3192                                         break;
3193                         }
3194
3195                         if (port->lun_map != NULL) {
3196                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3197                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3198                                         plun = ctl_lun_map_from_port(port, j);
3199                                         if (plun >= CTL_MAX_LUNS)
3200                                                 continue;
3201                                         sbuf_printf(sb,
3202                                             "\t<lun id=\"%u\">%u</lun>\n",
3203                                             j, plun);
3204                                 }
3205                         }
3206
3207                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3208                                 if (port->wwpn_iid[j].in_use == 0 ||
3209                                     (port->wwpn_iid[j].wwpn == 0 &&
3210                                      port->wwpn_iid[j].name == NULL))
3211                                         continue;
3212
3213                                 if (port->wwpn_iid[j].name != NULL)
3214                                         retval = sbuf_printf(sb,
3215                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3216                                             j, port->wwpn_iid[j].name);
3217                                 else
3218                                         retval = sbuf_printf(sb,
3219                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3220                                             j, port->wwpn_iid[j].wwpn);
3221                                 if (retval != 0)
3222                                         break;
3223                         }
3224                         if (retval != 0)
3225                                 break;
3226
3227                         retval = sbuf_printf(sb, "</targ_port>\n");
3228                         if (retval != 0)
3229                                 break;
3230                 }
3231                 mtx_unlock(&softc->ctl_lock);
3232
3233                 if ((retval != 0)
3234                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3235                         retval = 0;
3236                         sbuf_delete(sb);
3237                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3238                         snprintf(list->error_str, sizeof(list->error_str),
3239                                  "Out of space, %d bytes is too small",
3240                                  list->alloc_len);
3241                         break;
3242                 }
3243
3244                 sbuf_finish(sb);
3245
3246                 retval = copyout(sbuf_data(sb), list->lun_xml,
3247                                  sbuf_len(sb) + 1);
3248
3249                 list->fill_len = sbuf_len(sb) + 1;
3250                 list->status = CTL_LUN_LIST_OK;
3251                 sbuf_delete(sb);
3252                 break;
3253         }
3254         case CTL_LUN_MAP: {
3255                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3256                 struct ctl_port *port;
3257
3258                 mtx_lock(&softc->ctl_lock);
3259                 if (lm->port < softc->port_min ||
3260                     lm->port >= softc->port_max ||
3261                     (port = softc->ctl_ports[lm->port]) == NULL) {
3262                         mtx_unlock(&softc->ctl_lock);
3263                         return (ENXIO);
3264                 }
3265                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3266                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3267                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3268                                     CTL_MAX_LUNS)
3269                                         continue;
3270                                 mtx_lock(&lun->lun_lock);
3271                                 ctl_est_ua_port(lun, lm->port, -1,
3272                                     CTL_UA_LUN_CHANGE);
3273                                 mtx_unlock(&lun->lun_lock);
3274                         }
3275                 }
3276                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3277                 if (lm->plun < CTL_MAX_LUNS) {
3278                         if (lm->lun == UINT32_MAX)
3279                                 retval = ctl_lun_map_unset(port, lm->plun);
3280                         else if (lm->lun < CTL_MAX_LUNS &&
3281                             softc->ctl_luns[lm->lun] != NULL)
3282                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3283                         else
3284                                 return (ENXIO);
3285                 } else if (lm->plun == UINT32_MAX) {
3286                         if (lm->lun == UINT32_MAX)
3287                                 retval = ctl_lun_map_deinit(port);
3288                         else
3289                                 retval = ctl_lun_map_init(port);
3290                 } else
3291                         return (ENXIO);
3292                 if (port->status & CTL_PORT_STATUS_ONLINE)
3293                         ctl_isc_announce_port(port);
3294                 break;
3295         }
3296         default: {
3297                 /* XXX KDM should we fix this? */
3298 #if 0
3299                 struct ctl_backend_driver *backend;
3300                 unsigned int type;
3301                 int found;
3302
3303                 found = 0;
3304
3305                 /*
3306                  * We encode the backend type as the ioctl type for backend
3307                  * ioctls.  So parse it out here, and then search for a
3308                  * backend of this type.
3309                  */
3310                 type = _IOC_TYPE(cmd);
3311
3312                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3313                         if (backend->type == type) {
3314                                 found = 1;
3315                                 break;
3316                         }
3317                 }
3318                 if (found == 0) {
3319                         printf("ctl: unknown ioctl command %#lx or backend "
3320                                "%d\n", cmd, type);
3321                         retval = EINVAL;
3322                         break;
3323                 }
3324                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3325 #endif
3326                 retval = ENOTTY;
3327                 break;
3328         }
3329         }
3330         return (retval);
3331 }
3332
3333 uint32_t
3334 ctl_get_initindex(struct ctl_nexus *nexus)
3335 {
3336         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3337 }
3338
3339 int
3340 ctl_lun_map_init(struct ctl_port *port)
3341 {
3342         struct ctl_softc *softc = control_softc;
3343         struct ctl_lun *lun;
3344         uint32_t i;
3345
3346         if (port->lun_map == NULL)
3347                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3348                     M_CTL, M_NOWAIT);
3349         if (port->lun_map == NULL)
3350                 return (ENOMEM);
3351         for (i = 0; i < CTL_MAX_LUNS; i++)
3352                 port->lun_map[i] = UINT32_MAX;
3353         if (port->status & CTL_PORT_STATUS_ONLINE) {
3354                 if (port->lun_disable != NULL) {
3355                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3356                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3357                 }
3358                 ctl_isc_announce_port(port);
3359         }
3360         return (0);
3361 }
3362
3363 int
3364 ctl_lun_map_deinit(struct ctl_port *port)
3365 {
3366         struct ctl_softc *softc = control_softc;
3367         struct ctl_lun *lun;
3368
3369         if (port->lun_map == NULL)
3370                 return (0);
3371         free(port->lun_map, M_CTL);
3372         port->lun_map = NULL;
3373         if (port->status & CTL_PORT_STATUS_ONLINE) {
3374                 if (port->lun_enable != NULL) {
3375                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3376                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3377                 }
3378                 ctl_isc_announce_port(port);
3379         }
3380         return (0);
3381 }
3382
3383 int
3384 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3385 {
3386         int status;
3387         uint32_t old;
3388
3389         if (port->lun_map == NULL) {
3390                 status = ctl_lun_map_init(port);
3391                 if (status != 0)
3392                         return (status);
3393         }
3394         old = port->lun_map[plun];
3395         port->lun_map[plun] = glun;
3396         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3397                 if (port->lun_enable != NULL)
3398                         port->lun_enable(port->targ_lun_arg, plun);
3399                 ctl_isc_announce_port(port);
3400         }
3401         return (0);
3402 }
3403
3404 int
3405 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3406 {
3407         uint32_t old;
3408
3409         if (port->lun_map == NULL)
3410                 return (0);
3411         old = port->lun_map[plun];
3412         port->lun_map[plun] = UINT32_MAX;
3413         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3414                 if (port->lun_disable != NULL)
3415                         port->lun_disable(port->targ_lun_arg, plun);
3416                 ctl_isc_announce_port(port);
3417         }
3418         return (0);
3419 }
3420
3421 uint32_t
3422 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3423 {
3424
3425         if (port == NULL)
3426                 return (UINT32_MAX);
3427         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3428                 return (lun_id);
3429         return (port->lun_map[lun_id]);
3430 }
3431
3432 uint32_t
3433 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3434 {
3435         uint32_t i;
3436
3437         if (port == NULL)
3438                 return (UINT32_MAX);
3439         if (port->lun_map == NULL)
3440                 return (lun_id);
3441         for (i = 0; i < CTL_MAX_LUNS; i++) {
3442                 if (port->lun_map[i] == lun_id)
3443                         return (i);
3444         }
3445         return (UINT32_MAX);
3446 }
3447
3448 static struct ctl_port *
3449 ctl_io_port(struct ctl_io_hdr *io_hdr)
3450 {
3451
3452         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3453 }
3454
3455 int
3456 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3457 {
3458         int i;
3459
3460         for (i = first; i < last; i++) {
3461                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3462                         return (i);
3463         }
3464         return (-1);
3465 }
3466
3467 int
3468 ctl_set_mask(uint32_t *mask, uint32_t bit)
3469 {
3470         uint32_t chunk, piece;
3471
3472         chunk = bit >> 5;
3473         piece = bit % (sizeof(uint32_t) * 8);
3474
3475         if ((mask[chunk] & (1 << piece)) != 0)
3476                 return (-1);
3477         else
3478                 mask[chunk] |= (1 << piece);
3479
3480         return (0);
3481 }
3482
3483 int
3484 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3485 {
3486         uint32_t chunk, piece;
3487
3488         chunk = bit >> 5;
3489         piece = bit % (sizeof(uint32_t) * 8);
3490
3491         if ((mask[chunk] & (1 << piece)) == 0)
3492                 return (-1);
3493         else
3494                 mask[chunk] &= ~(1 << piece);
3495
3496         return (0);
3497 }
3498
3499 int
3500 ctl_is_set(uint32_t *mask, uint32_t bit)
3501 {
3502         uint32_t chunk, piece;
3503
3504         chunk = bit >> 5;
3505         piece = bit % (sizeof(uint32_t) * 8);
3506
3507         if ((mask[chunk] & (1 << piece)) == 0)
3508                 return (0);
3509         else
3510                 return (1);
3511 }
3512
3513 static uint64_t
3514 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3515 {
3516         uint64_t *t;
3517
3518         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3519         if (t == NULL)
3520                 return (0);
3521         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3522 }
3523
3524 static void
3525 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3526 {
3527         uint64_t *t;
3528
3529         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3530         if (t == NULL)
3531                 return;
3532         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3533 }
3534
3535 static void
3536 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3537 {
3538         uint64_t *p;
3539         u_int i;
3540
3541         i = residx/CTL_MAX_INIT_PER_PORT;
3542         if (lun->pr_keys[i] != NULL)
3543                 return;
3544         mtx_unlock(&lun->lun_lock);
3545         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3546             M_WAITOK | M_ZERO);
3547         mtx_lock(&lun->lun_lock);
3548         if (lun->pr_keys[i] == NULL)
3549                 lun->pr_keys[i] = p;
3550         else
3551                 free(p, M_CTL);
3552 }
3553
3554 static void
3555 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3556 {
3557         uint64_t *t;
3558
3559         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3560         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3561         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3562 }
3563
3564 /*
3565  * ctl_softc, pool_name, total_ctl_io are passed in.
3566  * npool is passed out.
3567  */
3568 int
3569 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3570                 uint32_t total_ctl_io, void **npool)
3571 {
3572 #ifdef IO_POOLS
3573         struct ctl_io_pool *pool;
3574
3575         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3576                                             M_NOWAIT | M_ZERO);
3577         if (pool == NULL)
3578                 return (ENOMEM);
3579
3580         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3581         pool->ctl_softc = ctl_softc;
3582         pool->zone = uma_zsecond_create(pool->name, NULL,
3583             NULL, NULL, NULL, ctl_softc->io_zone);
3584         /* uma_prealloc(pool->zone, total_ctl_io); */
3585
3586         *npool = pool;
3587 #else
3588         *npool = ctl_softc->io_zone;
3589 #endif
3590         return (0);
3591 }
3592
3593 void
3594 ctl_pool_free(struct ctl_io_pool *pool)
3595 {
3596
3597         if (pool == NULL)
3598                 return;
3599
3600 #ifdef IO_POOLS
3601         uma_zdestroy(pool->zone);
3602         free(pool, M_CTL);
3603 #endif
3604 }
3605
3606 union ctl_io *
3607 ctl_alloc_io(void *pool_ref)
3608 {
3609         union ctl_io *io;
3610 #ifdef IO_POOLS
3611         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3612
3613         io = uma_zalloc(pool->zone, M_WAITOK);
3614 #else
3615         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3616 #endif
3617         if (io != NULL)
3618                 io->io_hdr.pool = pool_ref;
3619         return (io);
3620 }
3621
3622 union ctl_io *
3623 ctl_alloc_io_nowait(void *pool_ref)
3624 {
3625         union ctl_io *io;
3626 #ifdef IO_POOLS
3627         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3628
3629         io = uma_zalloc(pool->zone, M_NOWAIT);
3630 #else
3631         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3632 #endif
3633         if (io != NULL)
3634                 io->io_hdr.pool = pool_ref;
3635         return (io);
3636 }
3637
3638 void
3639 ctl_free_io(union ctl_io *io)
3640 {
3641 #ifdef IO_POOLS
3642         struct ctl_io_pool *pool;
3643 #endif
3644
3645         if (io == NULL)
3646                 return;
3647
3648 #ifdef IO_POOLS
3649         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3650         uma_zfree(pool->zone, io);
3651 #else
3652         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3653 #endif
3654 }
3655
3656 void
3657 ctl_zero_io(union ctl_io *io)
3658 {
3659         void *pool_ref;
3660
3661         if (io == NULL)
3662                 return;
3663
3664         /*
3665          * May need to preserve linked list pointers at some point too.
3666          */
3667         pool_ref = io->io_hdr.pool;
3668         memset(io, 0, sizeof(*io));
3669         io->io_hdr.pool = pool_ref;
3670 }
3671
3672 /*
3673  * This routine is currently used for internal copies of ctl_ios that need
3674  * to persist for some reason after we've already returned status to the
3675  * FETD.  (Thus the flag set.)
3676  *
3677  * XXX XXX
3678  * Note that this makes a blind copy of all fields in the ctl_io, except
3679  * for the pool reference.  This includes any memory that has been
3680  * allocated!  That memory will no longer be valid after done has been
3681  * called, so this would be VERY DANGEROUS for command that actually does
3682  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3683  * start and stop commands, which don't transfer any data, so this is not a
3684  * problem.  If it is used for anything else, the caller would also need to
3685  * allocate data buffer space and this routine would need to be modified to
3686  * copy the data buffer(s) as well.
3687  */
3688 void
3689 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3690 {
3691         void *pool_ref;
3692
3693         if ((src == NULL)
3694          || (dest == NULL))
3695                 return;
3696
3697         /*
3698          * May need to preserve linked list pointers at some point too.
3699          */
3700         pool_ref = dest->io_hdr.pool;
3701
3702         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3703
3704         dest->io_hdr.pool = pool_ref;
3705         /*
3706          * We need to know that this is an internal copy, and doesn't need
3707          * to get passed back to the FETD that allocated it.
3708          */
3709         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3710 }
3711
3712 int
3713 ctl_expand_number(const char *buf, uint64_t *num)
3714 {
3715         char *endptr;
3716         uint64_t number;
3717         unsigned shift;
3718
3719         number = strtoq(buf, &endptr, 0);
3720
3721         switch (tolower((unsigned char)*endptr)) {
3722         case 'e':
3723                 shift = 60;
3724                 break;
3725         case 'p':
3726                 shift = 50;
3727                 break;
3728         case 't':
3729                 shift = 40;
3730                 break;
3731         case 'g':
3732                 shift = 30;
3733                 break;
3734         case 'm':
3735                 shift = 20;
3736                 break;
3737         case 'k':
3738                 shift = 10;
3739                 break;
3740         case 'b':
3741         case '\0': /* No unit. */
3742                 *num = number;
3743                 return (0);
3744         default:
3745                 /* Unrecognized unit. */
3746                 return (-1);
3747         }
3748
3749         if ((number << shift) >> shift != number) {
3750                 /* Overflow */
3751                 return (-1);
3752         }
3753         *num = number << shift;
3754         return (0);
3755 }
3756
3757
3758 /*
3759  * This routine could be used in the future to load default and/or saved
3760  * mode page parameters for a particuar lun.
3761  */
3762 static int
3763 ctl_init_page_index(struct ctl_lun *lun)
3764 {
3765         int i;
3766         struct ctl_page_index *page_index;
3767         const char *value;
3768         uint64_t ival;
3769
3770         memcpy(&lun->mode_pages.index, page_index_template,
3771                sizeof(page_index_template));
3772
3773         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3774
3775                 page_index = &lun->mode_pages.index[i];
3776                 /*
3777                  * If this is a disk-only mode page, there's no point in
3778                  * setting it up.  For some pages, we have to have some
3779                  * basic information about the disk in order to calculate the
3780                  * mode page data.
3781                  */
3782                 if ((lun->be_lun->lun_type != T_DIRECT)
3783                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3784                         continue;
3785
3786                 switch (page_index->page_code & SMPH_PC_MASK) {
3787                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3788                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3789                                 panic("subpage is incorrect!");
3790                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3791                                &rw_er_page_default,
3792                                sizeof(rw_er_page_default));
3793                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3794                                &rw_er_page_changeable,
3795                                sizeof(rw_er_page_changeable));
3796                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3797                                &rw_er_page_default,
3798                                sizeof(rw_er_page_default));
3799                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3800                                &rw_er_page_default,
3801                                sizeof(rw_er_page_default));
3802                         page_index->page_data =
3803                                 (uint8_t *)lun->mode_pages.rw_er_page;
3804                         break;
3805                 }
3806                 case SMS_FORMAT_DEVICE_PAGE: {
3807                         struct scsi_format_page *format_page;
3808
3809                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3810                                 panic("subpage is incorrect!");
3811
3812                         /*
3813                          * Sectors per track are set above.  Bytes per
3814                          * sector need to be set here on a per-LUN basis.
3815                          */
3816                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3817                                &format_page_default,
3818                                sizeof(format_page_default));
3819                         memcpy(&lun->mode_pages.format_page[
3820                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3821                                sizeof(format_page_changeable));
3822                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3823                                &format_page_default,
3824                                sizeof(format_page_default));
3825                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3826                                &format_page_default,
3827                                sizeof(format_page_default));
3828
3829                         format_page = &lun->mode_pages.format_page[
3830                                 CTL_PAGE_CURRENT];
3831                         scsi_ulto2b(lun->be_lun->blocksize,
3832                                     format_page->bytes_per_sector);
3833
3834                         format_page = &lun->mode_pages.format_page[
3835                                 CTL_PAGE_DEFAULT];
3836                         scsi_ulto2b(lun->be_lun->blocksize,
3837                                     format_page->bytes_per_sector);
3838
3839                         format_page = &lun->mode_pages.format_page[
3840                                 CTL_PAGE_SAVED];
3841                         scsi_ulto2b(lun->be_lun->blocksize,
3842                                     format_page->bytes_per_sector);
3843
3844                         page_index->page_data =
3845                                 (uint8_t *)lun->mode_pages.format_page;
3846                         break;
3847                 }
3848                 case SMS_RIGID_DISK_PAGE: {
3849                         struct scsi_rigid_disk_page *rigid_disk_page;
3850                         uint32_t sectors_per_cylinder;
3851                         uint64_t cylinders;
3852 #ifndef __XSCALE__
3853                         int shift;
3854 #endif /* !__XSCALE__ */
3855
3856                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3857                                 panic("invalid subpage value %d",
3858                                       page_index->subpage);
3859
3860                         /*
3861                          * Rotation rate and sectors per track are set
3862                          * above.  We calculate the cylinders here based on
3863                          * capacity.  Due to the number of heads and
3864                          * sectors per track we're using, smaller arrays
3865                          * may turn out to have 0 cylinders.  Linux and
3866                          * FreeBSD don't pay attention to these mode pages
3867                          * to figure out capacity, but Solaris does.  It
3868                          * seems to deal with 0 cylinders just fine, and
3869                          * works out a fake geometry based on the capacity.
3870                          */
3871                         memcpy(&lun->mode_pages.rigid_disk_page[
3872                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3873                                sizeof(rigid_disk_page_default));
3874                         memcpy(&lun->mode_pages.rigid_disk_page[
3875                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3876                                sizeof(rigid_disk_page_changeable));
3877
3878                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3879                                 CTL_DEFAULT_HEADS;
3880
3881                         /*
3882                          * The divide method here will be more accurate,
3883                          * probably, but results in floating point being
3884                          * used in the kernel on i386 (__udivdi3()).  On the
3885                          * XScale, though, __udivdi3() is implemented in
3886                          * software.
3887                          *
3888                          * The shift method for cylinder calculation is
3889                          * accurate if sectors_per_cylinder is a power of
3890                          * 2.  Otherwise it might be slightly off -- you
3891                          * might have a bit of a truncation problem.
3892                          */
3893 #ifdef  __XSCALE__
3894                         cylinders = (lun->be_lun->maxlba + 1) /
3895                                 sectors_per_cylinder;
3896 #else
3897                         for (shift = 31; shift > 0; shift--) {
3898                                 if (sectors_per_cylinder & (1 << shift))
3899                                         break;
3900                         }
3901                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
3902 #endif
3903
3904                         /*
3905                          * We've basically got 3 bytes, or 24 bits for the
3906                          * cylinder size in the mode page.  If we're over,
3907                          * just round down to 2^24.
3908                          */
3909                         if (cylinders > 0xffffff)
3910                                 cylinders = 0xffffff;
3911
3912                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3913                                 CTL_PAGE_DEFAULT];
3914                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3915
3916                         if ((value = ctl_get_opt(&lun->be_lun->options,
3917                             "rpm")) != NULL) {
3918                                 scsi_ulto2b(strtol(value, NULL, 0),
3919                                      rigid_disk_page->rotation_rate);
3920                         }
3921
3922                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3923                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3924                                sizeof(rigid_disk_page_default));
3925                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3926                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3927                                sizeof(rigid_disk_page_default));
3928
3929                         page_index->page_data =
3930                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
3931                         break;
3932                 }
3933                 case SMS_CACHING_PAGE: {
3934                         struct scsi_caching_page *caching_page;
3935
3936                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3937                                 panic("invalid subpage value %d",
3938                                       page_index->subpage);
3939                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3940                                &caching_page_default,
3941                                sizeof(caching_page_default));
3942                         memcpy(&lun->mode_pages.caching_page[
3943                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3944                                sizeof(caching_page_changeable));
3945                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3946                                &caching_page_default,
3947                                sizeof(caching_page_default));
3948                         caching_page = &lun->mode_pages.caching_page[
3949                             CTL_PAGE_SAVED];
3950                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
3951                         if (value != NULL && strcmp(value, "off") == 0)
3952                                 caching_page->flags1 &= ~SCP_WCE;
3953                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
3954                         if (value != NULL && strcmp(value, "off") == 0)
3955                                 caching_page->flags1 |= SCP_RCD;
3956                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3957                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3958                                sizeof(caching_page_default));
3959                         page_index->page_data =
3960                                 (uint8_t *)lun->mode_pages.caching_page;
3961                         break;
3962                 }
3963                 case SMS_CONTROL_MODE_PAGE: {
3964                         struct scsi_control_page *control_page;
3965
3966                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3967                                 panic("invalid subpage value %d",
3968                                       page_index->subpage);
3969
3970                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
3971                                &control_page_default,
3972                                sizeof(control_page_default));
3973                         memcpy(&lun->mode_pages.control_page[
3974                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
3975                                sizeof(control_page_changeable));
3976                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
3977                                &control_page_default,
3978                                sizeof(control_page_default));
3979                         control_page = &lun->mode_pages.control_page[
3980                             CTL_PAGE_SAVED];
3981                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
3982                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
3983                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
3984                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
3985                         }
3986                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
3987                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
3988                                sizeof(control_page_default));
3989                         page_index->page_data =
3990                                 (uint8_t *)lun->mode_pages.control_page;
3991                         break;
3992
3993                 }
3994                 case SMS_INFO_EXCEPTIONS_PAGE: {
3995                         switch (page_index->subpage) {
3996                         case SMS_SUBPAGE_PAGE_0:
3997                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
3998                                        &ie_page_default,
3999                                        sizeof(ie_page_default));
4000                                 memcpy(&lun->mode_pages.ie_page[
4001                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4002                                        sizeof(ie_page_changeable));
4003                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4004                                        &ie_page_default,
4005                                        sizeof(ie_page_default));
4006                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4007                                        &ie_page_default,
4008                                        sizeof(ie_page_default));
4009                                 page_index->page_data =
4010                                         (uint8_t *)lun->mode_pages.ie_page;
4011                                 break;
4012                         case 0x02: {
4013                                 struct ctl_logical_block_provisioning_page *page;
4014
4015                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4016                                        &lbp_page_default,
4017                                        sizeof(lbp_page_default));
4018                                 memcpy(&lun->mode_pages.lbp_page[
4019                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4020                                        sizeof(lbp_page_changeable));
4021                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4022                                        &lbp_page_default,
4023                                        sizeof(lbp_page_default));
4024                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4025                                 value = ctl_get_opt(&lun->be_lun->options,
4026                                     "avail-threshold");
4027                                 if (value != NULL &&
4028                                     ctl_expand_number(value, &ival) == 0) {
4029                                         page->descr[0].flags |= SLBPPD_ENABLED |
4030                                             SLBPPD_ARMING_DEC;
4031                                         if (lun->be_lun->blocksize)
4032                                                 ival /= lun->be_lun->blocksize;
4033                                         else
4034                                                 ival /= 512;
4035                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4036                                             page->descr[0].count);
4037                                 }
4038                                 value = ctl_get_opt(&lun->be_lun->options,
4039                                     "used-threshold");
4040                                 if (value != NULL &&
4041                                     ctl_expand_number(value, &ival) == 0) {
4042                                         page->descr[1].flags |= SLBPPD_ENABLED |
4043                                             SLBPPD_ARMING_INC;
4044                                         if (lun->be_lun->blocksize)
4045                                                 ival /= lun->be_lun->blocksize;
4046                                         else
4047                                                 ival /= 512;
4048                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4049                                             page->descr[1].count);
4050                                 }
4051                                 value = ctl_get_opt(&lun->be_lun->options,
4052                                     "pool-avail-threshold");
4053                                 if (value != NULL &&
4054                                     ctl_expand_number(value, &ival) == 0) {
4055                                         page->descr[2].flags |= SLBPPD_ENABLED |
4056                                             SLBPPD_ARMING_DEC;
4057                                         if (lun->be_lun->blocksize)
4058                                                 ival /= lun->be_lun->blocksize;
4059                                         else
4060                                                 ival /= 512;
4061                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4062                                             page->descr[2].count);
4063                                 }
4064                                 value = ctl_get_opt(&lun->be_lun->options,
4065                                     "pool-used-threshold");
4066                                 if (value != NULL &&
4067                                     ctl_expand_number(value, &ival) == 0) {
4068                                         page->descr[3].flags |= SLBPPD_ENABLED |
4069                                             SLBPPD_ARMING_INC;
4070                                         if (lun->be_lun->blocksize)
4071                                                 ival /= lun->be_lun->blocksize;
4072                                         else
4073                                                 ival /= 512;
4074                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4075                                             page->descr[3].count);
4076                                 }
4077                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4078                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4079                                        sizeof(lbp_page_default));
4080                                 page_index->page_data =
4081                                         (uint8_t *)lun->mode_pages.lbp_page;
4082                         }}
4083                         break;
4084                 }
4085                 case SMS_VENDOR_SPECIFIC_PAGE:{
4086                         switch (page_index->subpage) {
4087                         case DBGCNF_SUBPAGE_CODE: {
4088                                 struct copan_debugconf_subpage *current_page,
4089                                                                *saved_page;
4090
4091                                 memcpy(&lun->mode_pages.debugconf_subpage[
4092                                        CTL_PAGE_CURRENT],
4093                                        &debugconf_page_default,
4094                                        sizeof(debugconf_page_default));
4095                                 memcpy(&lun->mode_pages.debugconf_subpage[
4096                                        CTL_PAGE_CHANGEABLE],
4097                                        &debugconf_page_changeable,
4098                                        sizeof(debugconf_page_changeable));
4099                                 memcpy(&lun->mode_pages.debugconf_subpage[
4100                                        CTL_PAGE_DEFAULT],
4101                                        &debugconf_page_default,
4102                                        sizeof(debugconf_page_default));
4103                                 memcpy(&lun->mode_pages.debugconf_subpage[
4104                                        CTL_PAGE_SAVED],
4105                                        &debugconf_page_default,
4106                                        sizeof(debugconf_page_default));
4107                                 page_index->page_data =
4108                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4109
4110                                 current_page = (struct copan_debugconf_subpage *)
4111                                         (page_index->page_data +
4112                                          (page_index->page_len *
4113                                           CTL_PAGE_CURRENT));
4114                                 saved_page = (struct copan_debugconf_subpage *)
4115                                         (page_index->page_data +
4116                                          (page_index->page_len *
4117                                           CTL_PAGE_SAVED));
4118                                 break;
4119                         }
4120                         default:
4121                                 panic("invalid subpage value %d",
4122                                       page_index->subpage);
4123                                 break;
4124                         }
4125                         break;
4126                 }
4127                 default:
4128                         panic("invalid page value %d",
4129                               page_index->page_code & SMPH_PC_MASK);
4130                         break;
4131         }
4132         }
4133
4134         return (CTL_RETVAL_COMPLETE);
4135 }
4136
4137 static int
4138 ctl_init_log_page_index(struct ctl_lun *lun)
4139 {
4140         struct ctl_page_index *page_index;
4141         int i, j, k, prev;
4142
4143         memcpy(&lun->log_pages.index, log_page_index_template,
4144                sizeof(log_page_index_template));
4145
4146         prev = -1;
4147         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4148
4149                 page_index = &lun->log_pages.index[i];
4150                 /*
4151                  * If this is a disk-only mode page, there's no point in
4152                  * setting it up.  For some pages, we have to have some
4153                  * basic information about the disk in order to calculate the
4154                  * mode page data.
4155                  */
4156                 if ((lun->be_lun->lun_type != T_DIRECT)
4157                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4158                         continue;
4159
4160                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4161                      lun->backend->lun_attr == NULL)
4162                         continue;
4163
4164                 if (page_index->page_code != prev) {
4165                         lun->log_pages.pages_page[j] = page_index->page_code;
4166                         prev = page_index->page_code;
4167                         j++;
4168                 }
4169                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4170                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4171                 k++;
4172         }
4173         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4174         lun->log_pages.index[0].page_len = j;
4175         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4176         lun->log_pages.index[1].page_len = k * 2;
4177         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4178         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4179         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4180         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4181
4182         return (CTL_RETVAL_COMPLETE);
4183 }
4184
4185 static int
4186 hex2bin(const char *str, uint8_t *buf, int buf_size)
4187 {
4188         int i;
4189         u_char c;
4190
4191         memset(buf, 0, buf_size);
4192         while (isspace(str[0]))
4193                 str++;
4194         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4195                 str += 2;
4196         buf_size *= 2;
4197         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4198                 c = str[i];
4199                 if (isdigit(c))
4200                         c -= '0';
4201                 else if (isalpha(c))
4202                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4203                 else
4204                         break;
4205                 if (c >= 16)
4206                         break;
4207                 if ((i & 1) == 0)
4208                         buf[i / 2] |= (c << 4);
4209                 else
4210                         buf[i / 2] |= c;
4211         }
4212         return ((i + 1) / 2);
4213 }
4214
4215 /*
4216  * LUN allocation.
4217  *
4218  * Requirements:
4219  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4220  *   wants us to allocate the LUN and he can block.
4221  * - ctl_softc is always set
4222  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4223  *
4224  * Returns 0 for success, non-zero (errno) for failure.
4225  */
4226 static int
4227 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4228               struct ctl_be_lun *const be_lun)
4229 {
4230         struct ctl_lun *nlun, *lun;
4231         struct scsi_vpd_id_descriptor *desc;
4232         struct scsi_vpd_id_t10 *t10id;
4233         const char *eui, *naa, *scsiname, *vendor;
4234         int lun_number, i, lun_malloced;
4235         int devidlen, idlen1, idlen2 = 0, len;
4236
4237         if (be_lun == NULL)
4238                 return (EINVAL);
4239
4240         /*
4241          * We currently only support Direct Access or Processor LUN types.
4242          */
4243         switch (be_lun->lun_type) {
4244         case T_DIRECT:
4245                 break;
4246         case T_PROCESSOR:
4247                 break;
4248         case T_SEQUENTIAL:
4249         case T_CHANGER:
4250         default:
4251                 be_lun->lun_config_status(be_lun->be_lun,
4252                                           CTL_LUN_CONFIG_FAILURE);
4253                 break;
4254         }
4255         if (ctl_lun == NULL) {
4256                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4257                 lun_malloced = 1;
4258         } else {
4259                 lun_malloced = 0;
4260                 lun = ctl_lun;
4261         }
4262
4263         memset(lun, 0, sizeof(*lun));
4264         if (lun_malloced)
4265                 lun->flags = CTL_LUN_MALLOCED;
4266
4267         /* Generate LUN ID. */
4268         devidlen = max(CTL_DEVID_MIN_LEN,
4269             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4270         idlen1 = sizeof(*t10id) + devidlen;
4271         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4272         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4273         if (scsiname != NULL) {
4274                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4275                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4276         }
4277         eui = ctl_get_opt(&be_lun->options, "eui");
4278         if (eui != NULL) {
4279                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4280         }
4281         naa = ctl_get_opt(&be_lun->options, "naa");
4282         if (naa != NULL) {
4283                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4284         }
4285         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4286             M_CTL, M_WAITOK | M_ZERO);
4287         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4288         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4289         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4290         desc->length = idlen1;
4291         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4292         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4293         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4294                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4295         } else {
4296                 strncpy(t10id->vendor, vendor,
4297                     min(sizeof(t10id->vendor), strlen(vendor)));
4298         }
4299         strncpy((char *)t10id->vendor_spec_id,
4300             (char *)be_lun->device_id, devidlen);
4301         if (scsiname != NULL) {
4302                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4303                     desc->length);
4304                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4305                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4306                     SVPD_ID_TYPE_SCSI_NAME;
4307                 desc->length = idlen2;
4308                 strlcpy(desc->identifier, scsiname, idlen2);
4309         }
4310         if (eui != NULL) {
4311                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4312                     desc->length);
4313                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4314                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4315                     SVPD_ID_TYPE_EUI64;
4316                 desc->length = hex2bin(eui, desc->identifier, 16);
4317                 desc->length = desc->length > 12 ? 16 :
4318                     (desc->length > 8 ? 12 : 8);
4319                 len -= 16 - desc->length;
4320         }
4321         if (naa != NULL) {
4322                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4323                     desc->length);
4324                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4325                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4326                     SVPD_ID_TYPE_NAA;
4327                 desc->length = hex2bin(naa, desc->identifier, 16);
4328                 desc->length = desc->length > 8 ? 16 : 8;
4329                 len -= 16 - desc->length;
4330         }
4331         lun->lun_devid->len = len;
4332
4333         mtx_lock(&ctl_softc->ctl_lock);
4334         /*
4335          * See if the caller requested a particular LUN number.  If so, see
4336          * if it is available.  Otherwise, allocate the first available LUN.
4337          */
4338         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4339                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4340                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4341                         mtx_unlock(&ctl_softc->ctl_lock);
4342                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4343                                 printf("ctl: requested LUN ID %d is higher "
4344                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4345                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4346                         } else {
4347                                 /*
4348                                  * XXX KDM return an error, or just assign
4349                                  * another LUN ID in this case??
4350                                  */
4351                                 printf("ctl: requested LUN ID %d is already "
4352                                        "in use\n", be_lun->req_lun_id);
4353                         }
4354                         if (lun->flags & CTL_LUN_MALLOCED)
4355                                 free(lun, M_CTL);
4356                         be_lun->lun_config_status(be_lun->be_lun,
4357                                                   CTL_LUN_CONFIG_FAILURE);
4358                         return (ENOSPC);
4359                 }
4360                 lun_number = be_lun->req_lun_id;
4361         } else {
4362                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4363                 if (lun_number == -1) {
4364                         mtx_unlock(&ctl_softc->ctl_lock);
4365                         printf("ctl: can't allocate LUN, out of LUNs\n");
4366                         if (lun->flags & CTL_LUN_MALLOCED)
4367                                 free(lun, M_CTL);
4368                         be_lun->lun_config_status(be_lun->be_lun,
4369                                                   CTL_LUN_CONFIG_FAILURE);
4370                         return (ENOSPC);
4371                 }
4372         }
4373         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4374
4375         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4376         lun->lun = lun_number;
4377         lun->be_lun = be_lun;
4378         /*
4379          * The processor LUN is always enabled.  Disk LUNs come on line
4380          * disabled, and must be enabled by the backend.
4381          */
4382         lun->flags |= CTL_LUN_DISABLED;
4383         lun->backend = be_lun->be;
4384         be_lun->ctl_lun = lun;
4385         be_lun->lun_id = lun_number;
4386         atomic_add_int(&be_lun->be->num_luns, 1);
4387         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4388                 lun->flags |= CTL_LUN_OFFLINE;
4389
4390         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4391                 lun->flags |= CTL_LUN_STOPPED;
4392
4393         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4394                 lun->flags |= CTL_LUN_INOPERABLE;
4395
4396         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4397                 lun->flags |= CTL_LUN_PRIMARY_SC;
4398
4399         lun->ctl_softc = ctl_softc;
4400 #ifdef CTL_TIME_IO
4401         lun->last_busy = getsbinuptime();
4402 #endif
4403         TAILQ_INIT(&lun->ooa_queue);
4404         TAILQ_INIT(&lun->blocked_queue);
4405         STAILQ_INIT(&lun->error_list);
4406         ctl_tpc_lun_init(lun);
4407
4408         /*
4409          * Initialize the mode and log page index.
4410          */
4411         ctl_init_page_index(lun);
4412         ctl_init_log_page_index(lun);
4413
4414         /*
4415          * Now, before we insert this lun on the lun list, set the lun
4416          * inventory changed UA for all other luns.
4417          */
4418         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4419                 mtx_lock(&nlun->lun_lock);
4420                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4421                 mtx_unlock(&nlun->lun_lock);
4422         }
4423
4424         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4425
4426         ctl_softc->ctl_luns[lun_number] = lun;
4427
4428         ctl_softc->num_luns++;
4429
4430         /* Setup statistics gathering */
4431         lun->stats.device_type = be_lun->lun_type;
4432         lun->stats.lun_number = lun_number;
4433         if (lun->stats.device_type == T_DIRECT)
4434                 lun->stats.blocksize = be_lun->blocksize;
4435         else
4436                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4437         for (i = 0;i < CTL_MAX_PORTS;i++)
4438                 lun->stats.ports[i].targ_port = i;
4439
4440         mtx_unlock(&ctl_softc->ctl_lock);
4441
4442         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4443         return (0);
4444 }
4445
4446 /*
4447  * Delete a LUN.
4448  * Assumptions:
4449  * - LUN has already been marked invalid and any pending I/O has been taken
4450  *   care of.
4451  */
4452 static int
4453 ctl_free_lun(struct ctl_lun *lun)
4454 {
4455         struct ctl_softc *softc;
4456         struct ctl_lun *nlun;
4457         int i;
4458
4459         softc = lun->ctl_softc;
4460
4461         mtx_assert(&softc->ctl_lock, MA_OWNED);
4462
4463         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4464
4465         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4466
4467         softc->ctl_luns[lun->lun] = NULL;
4468
4469         if (!TAILQ_EMPTY(&lun->ooa_queue))
4470                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4471
4472         softc->num_luns--;
4473
4474         /*
4475          * Tell the backend to free resources, if this LUN has a backend.
4476          */
4477         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4478         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4479
4480         ctl_tpc_lun_shutdown(lun);
4481         mtx_destroy(&lun->lun_lock);
4482         free(lun->lun_devid, M_CTL);
4483         for (i = 0; i < CTL_MAX_PORTS; i++)
4484                 free(lun->pending_ua[i], M_CTL);
4485         for (i = 0; i < CTL_MAX_PORTS; i++)
4486                 free(lun->pr_keys[i], M_CTL);
4487         free(lun->write_buffer, M_CTL);
4488         if (lun->flags & CTL_LUN_MALLOCED)
4489                 free(lun, M_CTL);
4490
4491         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4492                 mtx_lock(&nlun->lun_lock);
4493                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4494                 mtx_unlock(&nlun->lun_lock);
4495         }
4496
4497         return (0);
4498 }
4499
4500 static void
4501 ctl_create_lun(struct ctl_be_lun *be_lun)
4502 {
4503         struct ctl_softc *softc;
4504
4505         softc = control_softc;
4506
4507         /*
4508          * ctl_alloc_lun() should handle all potential failure cases.
4509          */
4510         ctl_alloc_lun(softc, NULL, be_lun);
4511 }
4512
4513 int
4514 ctl_add_lun(struct ctl_be_lun *be_lun)
4515 {
4516         struct ctl_softc *softc = control_softc;
4517
4518         mtx_lock(&softc->ctl_lock);
4519         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4520         mtx_unlock(&softc->ctl_lock);
4521         wakeup(&softc->pending_lun_queue);
4522
4523         return (0);
4524 }
4525
4526 int
4527 ctl_enable_lun(struct ctl_be_lun *be_lun)
4528 {
4529         struct ctl_softc *softc;
4530         struct ctl_port *port, *nport;
4531         struct ctl_lun *lun;
4532         int retval;
4533
4534         lun = (struct ctl_lun *)be_lun->ctl_lun;
4535         softc = lun->ctl_softc;
4536
4537         mtx_lock(&softc->ctl_lock);
4538         mtx_lock(&lun->lun_lock);
4539         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4540                 /*
4541                  * eh?  Why did we get called if the LUN is already
4542                  * enabled?
4543                  */
4544                 mtx_unlock(&lun->lun_lock);
4545                 mtx_unlock(&softc->ctl_lock);
4546                 return (0);
4547         }
4548         lun->flags &= ~CTL_LUN_DISABLED;
4549         mtx_unlock(&lun->lun_lock);
4550
4551         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4552                 nport = STAILQ_NEXT(port, links);
4553                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4554                     port->lun_map != NULL || port->lun_enable == NULL)
4555                         continue;
4556
4557                 /*
4558                  * Drop the lock while we call the FETD's enable routine.
4559                  * This can lead to a callback into CTL (at least in the
4560                  * case of the internal initiator frontend.
4561                  */
4562                 mtx_unlock(&softc->ctl_lock);
4563                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4564                 mtx_lock(&softc->ctl_lock);
4565                 if (retval != 0) {
4566                         printf("%s: FETD %s port %d returned error "
4567                                "%d for lun_enable on lun %jd\n",
4568                                __func__, port->port_name, port->targ_port,
4569                                retval, (intmax_t)lun->lun);
4570                 }
4571         }
4572
4573         mtx_unlock(&softc->ctl_lock);
4574         ctl_isc_announce_lun(lun);
4575
4576         return (0);
4577 }
4578
4579 int
4580 ctl_disable_lun(struct ctl_be_lun *be_lun)
4581 {
4582         struct ctl_softc *softc;
4583         struct ctl_port *port;
4584         struct ctl_lun *lun;
4585         int retval;
4586
4587         lun = (struct ctl_lun *)be_lun->ctl_lun;
4588         softc = lun->ctl_softc;
4589
4590         mtx_lock(&softc->ctl_lock);
4591         mtx_lock(&lun->lun_lock);
4592         if (lun->flags & CTL_LUN_DISABLED) {
4593                 mtx_unlock(&lun->lun_lock);
4594                 mtx_unlock(&softc->ctl_lock);
4595                 return (0);
4596         }
4597         lun->flags |= CTL_LUN_DISABLED;
4598         mtx_unlock(&lun->lun_lock);
4599
4600         STAILQ_FOREACH(port, &softc->port_list, links) {
4601                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4602                     port->lun_map != NULL || port->lun_disable == NULL)
4603                         continue;
4604
4605                 /*
4606                  * Drop the lock before we call the frontend's disable
4607                  * routine, to avoid lock order reversals.
4608                  *
4609                  * XXX KDM what happens if the frontend list changes while
4610                  * we're traversing it?  It's unlikely, but should be handled.
4611                  */
4612                 mtx_unlock(&softc->ctl_lock);
4613                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4614                 mtx_lock(&softc->ctl_lock);
4615                 if (retval != 0) {
4616                         printf("%s: FETD %s port %d returned error "
4617                                "%d for lun_disable on lun %jd\n",
4618                                __func__, port->port_name, port->targ_port,
4619                                retval, (intmax_t)lun->lun);
4620                 }
4621         }
4622
4623         mtx_unlock(&softc->ctl_lock);
4624         ctl_isc_announce_lun(lun);
4625
4626         return (0);
4627 }
4628
4629 int
4630 ctl_start_lun(struct ctl_be_lun *be_lun)
4631 {
4632         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4633
4634         mtx_lock(&lun->lun_lock);
4635         lun->flags &= ~CTL_LUN_STOPPED;
4636         mtx_unlock(&lun->lun_lock);
4637         return (0);
4638 }
4639
4640 int
4641 ctl_stop_lun(struct ctl_be_lun *be_lun)
4642 {
4643         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4644
4645         mtx_lock(&lun->lun_lock);
4646         lun->flags |= CTL_LUN_STOPPED;
4647         mtx_unlock(&lun->lun_lock);
4648         return (0);
4649 }
4650
4651 int
4652 ctl_lun_offline(struct ctl_be_lun *be_lun)
4653 {
4654         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4655
4656         mtx_lock(&lun->lun_lock);
4657         lun->flags |= CTL_LUN_OFFLINE;
4658         mtx_unlock(&lun->lun_lock);
4659         return (0);
4660 }
4661
4662 int
4663 ctl_lun_online(struct ctl_be_lun *be_lun)
4664 {
4665         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4666
4667         mtx_lock(&lun->lun_lock);
4668         lun->flags &= ~CTL_LUN_OFFLINE;
4669         mtx_unlock(&lun->lun_lock);
4670         return (0);
4671 }
4672
4673 int
4674 ctl_lun_primary(struct ctl_be_lun *be_lun)
4675 {
4676         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4677
4678         mtx_lock(&lun->lun_lock);
4679         lun->flags |= CTL_LUN_PRIMARY_SC;
4680         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4681         mtx_unlock(&lun->lun_lock);
4682         ctl_isc_announce_lun(lun);
4683         return (0);
4684 }
4685
4686 int
4687 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4688 {
4689         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4690
4691         mtx_lock(&lun->lun_lock);
4692         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4693         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4694         mtx_unlock(&lun->lun_lock);
4695         ctl_isc_announce_lun(lun);
4696         return (0);
4697 }
4698
4699 int
4700 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4701 {
4702         struct ctl_softc *softc;
4703         struct ctl_lun *lun;
4704
4705         lun = (struct ctl_lun *)be_lun->ctl_lun;
4706         softc = lun->ctl_softc;
4707
4708         mtx_lock(&lun->lun_lock);
4709
4710         /*
4711          * The LUN needs to be disabled before it can be marked invalid.
4712          */
4713         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4714                 mtx_unlock(&lun->lun_lock);
4715                 return (-1);
4716         }
4717         /*
4718          * Mark the LUN invalid.
4719          */
4720         lun->flags |= CTL_LUN_INVALID;
4721
4722         /*
4723          * If there is nothing in the OOA queue, go ahead and free the LUN.
4724          * If we have something in the OOA queue, we'll free it when the
4725          * last I/O completes.
4726          */
4727         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4728                 mtx_unlock(&lun->lun_lock);
4729                 mtx_lock(&softc->ctl_lock);
4730                 ctl_free_lun(lun);
4731                 mtx_unlock(&softc->ctl_lock);
4732         } else
4733                 mtx_unlock(&lun->lun_lock);
4734
4735         return (0);
4736 }
4737
4738 int
4739 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4740 {
4741         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4742
4743         mtx_lock(&lun->lun_lock);
4744         lun->flags |= CTL_LUN_INOPERABLE;
4745         mtx_unlock(&lun->lun_lock);
4746         return (0);
4747 }
4748
4749 int
4750 ctl_lun_operable(struct ctl_be_lun *be_lun)
4751 {
4752         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4753
4754         mtx_lock(&lun->lun_lock);
4755         lun->flags &= ~CTL_LUN_INOPERABLE;
4756         mtx_unlock(&lun->lun_lock);
4757         return (0);
4758 }
4759
4760 void
4761 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4762 {
4763         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4764         union ctl_ha_msg msg;
4765
4766         mtx_lock(&lun->lun_lock);
4767         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4768         mtx_unlock(&lun->lun_lock);
4769         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4770                 /* Send msg to other side. */
4771                 bzero(&msg.ua, sizeof(msg.ua));
4772                 msg.hdr.msg_type = CTL_MSG_UA;
4773                 msg.hdr.nexus.initid = -1;
4774                 msg.hdr.nexus.targ_port = -1;
4775                 msg.hdr.nexus.targ_lun = lun->lun;
4776                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4777                 msg.ua.ua_all = 1;
4778                 msg.ua.ua_set = 1;
4779                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4780                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4781                     M_WAITOK);
4782         }
4783 }
4784
4785 /*
4786  * Backend "memory move is complete" callback for requests that never
4787  * make it down to say RAIDCore's configuration code.
4788  */
4789 int
4790 ctl_config_move_done(union ctl_io *io)
4791 {
4792         int retval;
4793
4794         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4795         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4796             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4797
4798         if ((io->io_hdr.port_status != 0) &&
4799             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4800              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4801                 /*
4802                  * For hardware error sense keys, the sense key
4803                  * specific value is defined to be a retry count,
4804                  * but we use it to pass back an internal FETD
4805                  * error code.  XXX KDM  Hopefully the FETD is only
4806                  * using 16 bits for an error code, since that's
4807                  * all the space we have in the sks field.
4808                  */
4809                 ctl_set_internal_failure(&io->scsiio,
4810                                          /*sks_valid*/ 1,
4811                                          /*retry_count*/
4812                                          io->io_hdr.port_status);
4813         }
4814
4815         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4816                 ctl_data_print(io);
4817         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4818             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4819              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4820             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4821                 /*
4822                  * XXX KDM just assuming a single pointer here, and not a
4823                  * S/G list.  If we start using S/G lists for config data,
4824                  * we'll need to know how to clean them up here as well.
4825                  */
4826                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4827                         free(io->scsiio.kern_data_ptr, M_CTL);
4828                 ctl_done(io);
4829                 retval = CTL_RETVAL_COMPLETE;
4830         } else {
4831                 /*
4832                  * XXX KDM now we need to continue data movement.  Some
4833                  * options:
4834                  * - call ctl_scsiio() again?  We don't do this for data
4835                  *   writes, because for those at least we know ahead of
4836                  *   time where the write will go and how long it is.  For
4837                  *   config writes, though, that information is largely
4838                  *   contained within the write itself, thus we need to
4839                  *   parse out the data again.
4840                  *
4841                  * - Call some other function once the data is in?
4842                  */
4843
4844                 /*
4845                  * XXX KDM call ctl_scsiio() again for now, and check flag
4846                  * bits to see whether we're allocated or not.
4847                  */
4848                 retval = ctl_scsiio(&io->scsiio);
4849         }
4850         return (retval);
4851 }
4852
4853 /*
4854  * This gets called by a backend driver when it is done with a
4855  * data_submit method.
4856  */
4857 void
4858 ctl_data_submit_done(union ctl_io *io)
4859 {
4860         /*
4861          * If the IO_CONT flag is set, we need to call the supplied
4862          * function to continue processing the I/O, instead of completing
4863          * the I/O just yet.
4864          *
4865          * If there is an error, though, we don't want to keep processing.
4866          * Instead, just send status back to the initiator.
4867          */
4868         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4869             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4870             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4871              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4872                 io->scsiio.io_cont(io);
4873                 return;
4874         }
4875         ctl_done(io);
4876 }
4877
4878 /*
4879  * This gets called by a backend driver when it is done with a
4880  * configuration write.
4881  */
4882 void
4883 ctl_config_write_done(union ctl_io *io)
4884 {
4885         uint8_t *buf;
4886
4887         /*
4888          * If the IO_CONT flag is set, we need to call the supplied
4889          * function to continue processing the I/O, instead of completing
4890          * the I/O just yet.
4891          *
4892          * If there is an error, though, we don't want to keep processing.
4893          * Instead, just send status back to the initiator.
4894          */
4895         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4896             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4897             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4898              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4899                 io->scsiio.io_cont(io);
4900                 return;
4901         }
4902         /*
4903          * Since a configuration write can be done for commands that actually
4904          * have data allocated, like write buffer, and commands that have
4905          * no data, like start/stop unit, we need to check here.
4906          */
4907         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4908                 buf = io->scsiio.kern_data_ptr;
4909         else
4910                 buf = NULL;
4911         ctl_done(io);
4912         if (buf)
4913                 free(buf, M_CTL);
4914 }
4915
4916 void
4917 ctl_config_read_done(union ctl_io *io)
4918 {
4919         uint8_t *buf;
4920
4921         /*
4922          * If there is some error -- we are done, skip data transfer.
4923          */
4924         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4925             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4926              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4927                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4928                         buf = io->scsiio.kern_data_ptr;
4929                 else
4930                         buf = NULL;
4931                 ctl_done(io);
4932                 if (buf)
4933                         free(buf, M_CTL);
4934                 return;
4935         }
4936
4937         /*
4938          * If the IO_CONT flag is set, we need to call the supplied
4939          * function to continue processing the I/O, instead of completing
4940          * the I/O just yet.
4941          */
4942         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4943                 io->scsiio.io_cont(io);
4944                 return;
4945         }
4946
4947         ctl_datamove(io);
4948 }
4949
4950 /*
4951  * SCSI release command.
4952  */
4953 int
4954 ctl_scsi_release(struct ctl_scsiio *ctsio)
4955 {
4956         int length, longid, thirdparty_id, resv_id;
4957         struct ctl_lun *lun;
4958         uint32_t residx;
4959
4960         length = 0;
4961         resv_id = 0;
4962
4963         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4964
4965         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4966         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4967
4968         switch (ctsio->cdb[0]) {
4969         case RELEASE_10: {
4970                 struct scsi_release_10 *cdb;
4971
4972                 cdb = (struct scsi_release_10 *)ctsio->cdb;
4973
4974                 if (cdb->byte2 & SR10_LONGID)
4975                         longid = 1;
4976                 else
4977                         thirdparty_id = cdb->thirdparty_id;
4978
4979                 resv_id = cdb->resv_id;
4980                 length = scsi_2btoul(cdb->length);
4981                 break;
4982         }
4983         }
4984
4985
4986         /*
4987          * XXX KDM right now, we only support LUN reservation.  We don't
4988          * support 3rd party reservations, or extent reservations, which
4989          * might actually need the parameter list.  If we've gotten this
4990          * far, we've got a LUN reservation.  Anything else got kicked out
4991          * above.  So, according to SPC, ignore the length.
4992          */
4993         length = 0;
4994
4995         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4996          && (length > 0)) {
4997                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4998                 ctsio->kern_data_len = length;
4999                 ctsio->kern_total_len = length;
5000                 ctsio->kern_data_resid = 0;
5001                 ctsio->kern_rel_offset = 0;
5002                 ctsio->kern_sg_entries = 0;
5003                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5004                 ctsio->be_move_done = ctl_config_move_done;
5005                 ctl_datamove((union ctl_io *)ctsio);
5006
5007                 return (CTL_RETVAL_COMPLETE);
5008         }
5009
5010         if (length > 0)
5011                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5012
5013         mtx_lock(&lun->lun_lock);
5014
5015         /*
5016          * According to SPC, it is not an error for an intiator to attempt
5017          * to release a reservation on a LUN that isn't reserved, or that
5018          * is reserved by another initiator.  The reservation can only be
5019          * released, though, by the initiator who made it or by one of
5020          * several reset type events.
5021          */
5022         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5023                         lun->flags &= ~CTL_LUN_RESERVED;
5024
5025         mtx_unlock(&lun->lun_lock);
5026
5027         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5028                 free(ctsio->kern_data_ptr, M_CTL);
5029                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5030         }
5031
5032         ctl_set_success(ctsio);
5033         ctl_done((union ctl_io *)ctsio);
5034         return (CTL_RETVAL_COMPLETE);
5035 }
5036
5037 int
5038 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5039 {
5040         int extent, thirdparty, longid;
5041         int resv_id, length;
5042         uint64_t thirdparty_id;
5043         struct ctl_lun *lun;
5044         uint32_t residx;
5045
5046         extent = 0;
5047         thirdparty = 0;
5048         longid = 0;
5049         resv_id = 0;
5050         length = 0;
5051         thirdparty_id = 0;
5052
5053         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5054
5055         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5056         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5057
5058         switch (ctsio->cdb[0]) {
5059         case RESERVE_10: {
5060                 struct scsi_reserve_10 *cdb;
5061
5062                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5063
5064                 if (cdb->byte2 & SR10_LONGID)
5065                         longid = 1;
5066                 else
5067                         thirdparty_id = cdb->thirdparty_id;
5068
5069                 resv_id = cdb->resv_id;
5070                 length = scsi_2btoul(cdb->length);
5071                 break;
5072         }
5073         }
5074
5075         /*
5076          * XXX KDM right now, we only support LUN reservation.  We don't
5077          * support 3rd party reservations, or extent reservations, which
5078          * might actually need the parameter list.  If we've gotten this
5079          * far, we've got a LUN reservation.  Anything else got kicked out
5080          * above.  So, according to SPC, ignore the length.
5081          */
5082         length = 0;
5083
5084         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5085          && (length > 0)) {
5086                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5087                 ctsio->kern_data_len = length;
5088                 ctsio->kern_total_len = length;
5089                 ctsio->kern_data_resid = 0;
5090                 ctsio->kern_rel_offset = 0;
5091                 ctsio->kern_sg_entries = 0;
5092                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5093                 ctsio->be_move_done = ctl_config_move_done;
5094                 ctl_datamove((union ctl_io *)ctsio);
5095
5096                 return (CTL_RETVAL_COMPLETE);
5097         }
5098
5099         if (length > 0)
5100                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5101
5102         mtx_lock(&lun->lun_lock);
5103         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5104                 ctl_set_reservation_conflict(ctsio);
5105                 goto bailout;
5106         }
5107
5108         lun->flags |= CTL_LUN_RESERVED;
5109         lun->res_idx = residx;
5110
5111         ctl_set_success(ctsio);
5112
5113 bailout:
5114         mtx_unlock(&lun->lun_lock);
5115
5116         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5117                 free(ctsio->kern_data_ptr, M_CTL);
5118                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5119         }
5120
5121         ctl_done((union ctl_io *)ctsio);
5122         return (CTL_RETVAL_COMPLETE);
5123 }
5124
5125 int
5126 ctl_start_stop(struct ctl_scsiio *ctsio)
5127 {
5128         struct scsi_start_stop_unit *cdb;
5129         struct ctl_lun *lun;
5130         int retval;
5131
5132         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5133
5134         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5135         retval = 0;
5136
5137         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5138
5139         /*
5140          * XXX KDM
5141          * We don't support the immediate bit on a stop unit.  In order to
5142          * do that, we would need to code up a way to know that a stop is
5143          * pending, and hold off any new commands until it completes, one
5144          * way or another.  Then we could accept or reject those commands
5145          * depending on its status.  We would almost need to do the reverse
5146          * of what we do below for an immediate start -- return the copy of
5147          * the ctl_io to the FETD with status to send to the host (and to
5148          * free the copy!) and then free the original I/O once the stop
5149          * actually completes.  That way, the OOA queue mechanism can work
5150          * to block commands that shouldn't proceed.  Another alternative
5151          * would be to put the copy in the queue in place of the original,
5152          * and return the original back to the caller.  That could be
5153          * slightly safer..
5154          */
5155         if ((cdb->byte2 & SSS_IMMED)
5156          && ((cdb->how & SSS_START) == 0)) {
5157                 ctl_set_invalid_field(ctsio,
5158                                       /*sks_valid*/ 1,
5159                                       /*command*/ 1,
5160                                       /*field*/ 1,
5161                                       /*bit_valid*/ 1,
5162                                       /*bit*/ 0);
5163                 ctl_done((union ctl_io *)ctsio);
5164                 return (CTL_RETVAL_COMPLETE);
5165         }
5166
5167         if ((lun->flags & CTL_LUN_PR_RESERVED)
5168          && ((cdb->how & SSS_START)==0)) {
5169                 uint32_t residx;
5170
5171                 residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5172                 if (ctl_get_prkey(lun, residx) == 0
5173                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5174
5175                         ctl_set_reservation_conflict(ctsio);
5176                         ctl_done((union ctl_io *)ctsio);
5177                         return (CTL_RETVAL_COMPLETE);
5178                 }
5179         }
5180
5181         /*
5182          * If there is no backend on this device, we can't start or stop
5183          * it.  In theory we shouldn't get any start/stop commands in the
5184          * first place at this level if the LUN doesn't have a backend.
5185          * That should get stopped by the command decode code.
5186          */
5187         if (lun->backend == NULL) {
5188                 ctl_set_invalid_opcode(ctsio);
5189                 ctl_done((union ctl_io *)ctsio);
5190                 return (CTL_RETVAL_COMPLETE);
5191         }
5192
5193         /*
5194          * XXX KDM Copan-specific offline behavior.
5195          * Figure out a reasonable way to port this?
5196          */
5197 #ifdef NEEDTOPORT
5198         mtx_lock(&lun->lun_lock);
5199
5200         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5201          && (lun->flags & CTL_LUN_OFFLINE)) {
5202                 /*
5203                  * If the LUN is offline, and the on/offline bit isn't set,
5204                  * reject the start or stop.  Otherwise, let it through.
5205                  */
5206                 mtx_unlock(&lun->lun_lock);
5207                 ctl_set_lun_not_ready(ctsio);
5208                 ctl_done((union ctl_io *)ctsio);
5209         } else {
5210                 mtx_unlock(&lun->lun_lock);
5211 #endif /* NEEDTOPORT */
5212                 /*
5213                  * This could be a start or a stop when we're online,
5214                  * or a stop/offline or start/online.  A start or stop when
5215                  * we're offline is covered in the case above.
5216                  */
5217                 /*
5218                  * In the non-immediate case, we send the request to
5219                  * the backend and return status to the user when
5220                  * it is done.
5221                  *
5222                  * In the immediate case, we allocate a new ctl_io
5223                  * to hold a copy of the request, and send that to
5224                  * the backend.  We then set good status on the
5225                  * user's request and return it immediately.
5226                  */
5227                 if (cdb->byte2 & SSS_IMMED) {
5228                         union ctl_io *new_io;
5229
5230                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5231                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5232                         retval = lun->backend->config_write(new_io);
5233                         ctl_set_success(ctsio);
5234                         ctl_done((union ctl_io *)ctsio);
5235                 } else {
5236                         retval = lun->backend->config_write(
5237                                 (union ctl_io *)ctsio);
5238                 }
5239 #ifdef NEEDTOPORT
5240         }
5241 #endif
5242         return (retval);
5243 }
5244
5245 /*
5246  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5247  * we don't really do anything with the LBA and length fields if the user
5248  * passes them in.  Instead we'll just flush out the cache for the entire
5249  * LUN.
5250  */
5251 int
5252 ctl_sync_cache(struct ctl_scsiio *ctsio)
5253 {
5254         struct ctl_lun *lun;
5255         struct ctl_softc *softc;
5256         struct ctl_lba_len_flags *lbalen;
5257         uint64_t starting_lba;
5258         uint32_t block_count;
5259         int retval;
5260         uint8_t byte2;
5261
5262         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5263
5264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5265         softc = lun->ctl_softc;
5266         retval = 0;
5267
5268         switch (ctsio->cdb[0]) {
5269         case SYNCHRONIZE_CACHE: {
5270                 struct scsi_sync_cache *cdb;
5271                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5272
5273                 starting_lba = scsi_4btoul(cdb->begin_lba);
5274                 block_count = scsi_2btoul(cdb->lb_count);
5275                 byte2 = cdb->byte2;
5276                 break;
5277         }
5278         case SYNCHRONIZE_CACHE_16: {
5279                 struct scsi_sync_cache_16 *cdb;
5280                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5281
5282                 starting_lba = scsi_8btou64(cdb->begin_lba);
5283                 block_count = scsi_4btoul(cdb->lb_count);
5284                 byte2 = cdb->byte2;
5285                 break;
5286         }
5287         default:
5288                 ctl_set_invalid_opcode(ctsio);
5289                 ctl_done((union ctl_io *)ctsio);
5290                 goto bailout;
5291                 break; /* NOTREACHED */
5292         }
5293
5294         /*
5295          * We check the LBA and length, but don't do anything with them.
5296          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5297          * get flushed.  This check will just help satisfy anyone who wants
5298          * to see an error for an out of range LBA.
5299          */
5300         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5301                 ctl_set_lba_out_of_range(ctsio);
5302                 ctl_done((union ctl_io *)ctsio);
5303                 goto bailout;
5304         }
5305
5306         /*
5307          * If this LUN has no backend, we can't flush the cache anyway.
5308          */
5309         if (lun->backend == NULL) {
5310                 ctl_set_invalid_opcode(ctsio);
5311                 ctl_done((union ctl_io *)ctsio);
5312                 goto bailout;
5313         }
5314
5315         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5316         lbalen->lba = starting_lba;
5317         lbalen->len = block_count;
5318         lbalen->flags = byte2;
5319
5320         /*
5321          * Check to see whether we're configured to send the SYNCHRONIZE
5322          * CACHE command directly to the back end.
5323          */
5324         mtx_lock(&lun->lun_lock);
5325         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5326          && (++(lun->sync_count) >= lun->sync_interval)) {
5327                 lun->sync_count = 0;
5328                 mtx_unlock(&lun->lun_lock);
5329                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5330         } else {
5331                 mtx_unlock(&lun->lun_lock);
5332                 ctl_set_success(ctsio);
5333                 ctl_done((union ctl_io *)ctsio);
5334         }
5335
5336 bailout:
5337
5338         return (retval);
5339 }
5340
5341 int
5342 ctl_format(struct ctl_scsiio *ctsio)
5343 {
5344         struct scsi_format *cdb;
5345         struct ctl_lun *lun;
5346         int length, defect_list_len;
5347
5348         CTL_DEBUG_PRINT(("ctl_format\n"));
5349
5350         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5351
5352         cdb = (struct scsi_format *)ctsio->cdb;
5353
5354         length = 0;
5355         if (cdb->byte2 & SF_FMTDATA) {
5356                 if (cdb->byte2 & SF_LONGLIST)
5357                         length = sizeof(struct scsi_format_header_long);
5358                 else
5359                         length = sizeof(struct scsi_format_header_short);
5360         }
5361
5362         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5363          && (length > 0)) {
5364                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5365                 ctsio->kern_data_len = length;
5366                 ctsio->kern_total_len = length;
5367                 ctsio->kern_data_resid = 0;
5368                 ctsio->kern_rel_offset = 0;
5369                 ctsio->kern_sg_entries = 0;
5370                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5371                 ctsio->be_move_done = ctl_config_move_done;
5372                 ctl_datamove((union ctl_io *)ctsio);
5373
5374                 return (CTL_RETVAL_COMPLETE);
5375         }
5376
5377         defect_list_len = 0;
5378
5379         if (cdb->byte2 & SF_FMTDATA) {
5380                 if (cdb->byte2 & SF_LONGLIST) {
5381                         struct scsi_format_header_long *header;
5382
5383                         header = (struct scsi_format_header_long *)
5384                                 ctsio->kern_data_ptr;
5385
5386                         defect_list_len = scsi_4btoul(header->defect_list_len);
5387                         if (defect_list_len != 0) {
5388                                 ctl_set_invalid_field(ctsio,
5389                                                       /*sks_valid*/ 1,
5390                                                       /*command*/ 0,
5391                                                       /*field*/ 2,
5392                                                       /*bit_valid*/ 0,
5393                                                       /*bit*/ 0);
5394                                 goto bailout;
5395                         }
5396                 } else {
5397                         struct scsi_format_header_short *header;
5398
5399                         header = (struct scsi_format_header_short *)
5400                                 ctsio->kern_data_ptr;
5401
5402                         defect_list_len = scsi_2btoul(header->defect_list_len);
5403                         if (defect_list_len != 0) {
5404                                 ctl_set_invalid_field(ctsio,
5405                                                       /*sks_valid*/ 1,
5406                                                       /*command*/ 0,
5407                                                       /*field*/ 2,
5408                                                       /*bit_valid*/ 0,
5409                                                       /*bit*/ 0);
5410                                 goto bailout;
5411                         }
5412                 }
5413         }
5414
5415         /*
5416          * The format command will clear out the "Medium format corrupted"
5417          * status if set by the configuration code.  That status is really
5418          * just a way to notify the host that we have lost the media, and
5419          * get them to issue a command that will basically make them think
5420          * they're blowing away the media.
5421          */
5422         mtx_lock(&lun->lun_lock);
5423         lun->flags &= ~CTL_LUN_INOPERABLE;
5424         mtx_unlock(&lun->lun_lock);
5425
5426         ctl_set_success(ctsio);
5427 bailout:
5428
5429         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5430                 free(ctsio->kern_data_ptr, M_CTL);
5431                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5432         }
5433
5434         ctl_done((union ctl_io *)ctsio);
5435         return (CTL_RETVAL_COMPLETE);
5436 }
5437
5438 int
5439 ctl_read_buffer(struct ctl_scsiio *ctsio)
5440 {
5441         struct scsi_read_buffer *cdb;
5442         struct ctl_lun *lun;
5443         int buffer_offset, len;
5444         static uint8_t descr[4];
5445         static uint8_t echo_descr[4] = { 0 };
5446
5447         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5448
5449         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5450         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5451
5452         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5453             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5454             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5455                 ctl_set_invalid_field(ctsio,
5456                                       /*sks_valid*/ 1,
5457                                       /*command*/ 1,
5458                                       /*field*/ 1,
5459                                       /*bit_valid*/ 1,
5460                                       /*bit*/ 4);
5461                 ctl_done((union ctl_io *)ctsio);
5462                 return (CTL_RETVAL_COMPLETE);
5463         }
5464
5465         len = scsi_3btoul(cdb->length);
5466         buffer_offset = scsi_3btoul(cdb->offset);
5467
5468         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5469                 ctl_set_invalid_field(ctsio,
5470                                       /*sks_valid*/ 1,
5471                                       /*command*/ 1,
5472                                       /*field*/ 6,
5473                                       /*bit_valid*/ 0,
5474                                       /*bit*/ 0);
5475                 ctl_done((union ctl_io *)ctsio);
5476                 return (CTL_RETVAL_COMPLETE);
5477         }
5478
5479         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5480                 descr[0] = 0;
5481                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5482                 ctsio->kern_data_ptr = descr;
5483                 len = min(len, sizeof(descr));
5484         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5485                 ctsio->kern_data_ptr = echo_descr;
5486                 len = min(len, sizeof(echo_descr));
5487         } else {
5488                 if (lun->write_buffer == NULL) {
5489                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5490                             M_CTL, M_WAITOK);
5491                 }
5492                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5493         }
5494         ctsio->kern_data_len = len;
5495         ctsio->kern_total_len = len;
5496         ctsio->kern_data_resid = 0;
5497         ctsio->kern_rel_offset = 0;
5498         ctsio->kern_sg_entries = 0;
5499         ctl_set_success(ctsio);
5500         ctsio->be_move_done = ctl_config_move_done;
5501         ctl_datamove((union ctl_io *)ctsio);
5502         return (CTL_RETVAL_COMPLETE);
5503 }
5504
5505 int
5506 ctl_write_buffer(struct ctl_scsiio *ctsio)
5507 {
5508         struct scsi_write_buffer *cdb;
5509         struct ctl_lun *lun;
5510         int buffer_offset, len;
5511
5512         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5513
5514         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5515         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5516
5517         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5518                 ctl_set_invalid_field(ctsio,
5519                                       /*sks_valid*/ 1,
5520                                       /*command*/ 1,
5521                                       /*field*/ 1,
5522                                       /*bit_valid*/ 1,
5523                                       /*bit*/ 4);
5524                 ctl_done((union ctl_io *)ctsio);
5525                 return (CTL_RETVAL_COMPLETE);
5526         }
5527
5528         len = scsi_3btoul(cdb->length);
5529         buffer_offset = scsi_3btoul(cdb->offset);
5530
5531         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5532                 ctl_set_invalid_field(ctsio,
5533                                       /*sks_valid*/ 1,
5534                                       /*command*/ 1,
5535                                       /*field*/ 6,
5536                                       /*bit_valid*/ 0,
5537                                       /*bit*/ 0);
5538                 ctl_done((union ctl_io *)ctsio);
5539                 return (CTL_RETVAL_COMPLETE);
5540         }
5541
5542         /*
5543          * If we've got a kernel request that hasn't been malloced yet,
5544          * malloc it and tell the caller the data buffer is here.
5545          */
5546         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5547                 if (lun->write_buffer == NULL) {
5548                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5549                             M_CTL, M_WAITOK);
5550                 }
5551                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5552                 ctsio->kern_data_len = len;
5553                 ctsio->kern_total_len = len;
5554                 ctsio->kern_data_resid = 0;
5555                 ctsio->kern_rel_offset = 0;
5556                 ctsio->kern_sg_entries = 0;
5557                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5558                 ctsio->be_move_done = ctl_config_move_done;
5559                 ctl_datamove((union ctl_io *)ctsio);
5560
5561                 return (CTL_RETVAL_COMPLETE);
5562         }
5563
5564         ctl_set_success(ctsio);
5565         ctl_done((union ctl_io *)ctsio);
5566         return (CTL_RETVAL_COMPLETE);
5567 }
5568
5569 int
5570 ctl_write_same(struct ctl_scsiio *ctsio)
5571 {
5572         struct ctl_lun *lun;
5573         struct ctl_lba_len_flags *lbalen;
5574         uint64_t lba;
5575         uint32_t num_blocks;
5576         int len, retval;
5577         uint8_t byte2;
5578
5579         retval = CTL_RETVAL_COMPLETE;
5580
5581         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5582
5583         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5584
5585         switch (ctsio->cdb[0]) {
5586         case WRITE_SAME_10: {
5587                 struct scsi_write_same_10 *cdb;
5588
5589                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5590
5591                 lba = scsi_4btoul(cdb->addr);
5592                 num_blocks = scsi_2btoul(cdb->length);
5593                 byte2 = cdb->byte2;
5594                 break;
5595         }
5596         case WRITE_SAME_16: {
5597                 struct scsi_write_same_16 *cdb;
5598
5599                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5600
5601                 lba = scsi_8btou64(cdb->addr);
5602                 num_blocks = scsi_4btoul(cdb->length);
5603                 byte2 = cdb->byte2;
5604                 break;
5605         }
5606         default:
5607                 /*
5608                  * We got a command we don't support.  This shouldn't
5609                  * happen, commands should be filtered out above us.
5610                  */
5611                 ctl_set_invalid_opcode(ctsio);
5612                 ctl_done((union ctl_io *)ctsio);
5613
5614                 return (CTL_RETVAL_COMPLETE);
5615                 break; /* NOTREACHED */
5616         }
5617
5618         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5619         if ((byte2 & SWS_UNMAP) == 0 &&
5620             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5621                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5622                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5623                 ctl_done((union ctl_io *)ctsio);
5624                 return (CTL_RETVAL_COMPLETE);
5625         }
5626
5627         /*
5628          * The first check is to make sure we're in bounds, the second
5629          * check is to catch wrap-around problems.  If the lba + num blocks
5630          * is less than the lba, then we've wrapped around and the block
5631          * range is invalid anyway.
5632          */
5633         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5634          || ((lba + num_blocks) < lba)) {
5635                 ctl_set_lba_out_of_range(ctsio);
5636                 ctl_done((union ctl_io *)ctsio);
5637                 return (CTL_RETVAL_COMPLETE);
5638         }
5639
5640         /* Zero number of blocks means "to the last logical block" */
5641         if (num_blocks == 0) {
5642                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5643                         ctl_set_invalid_field(ctsio,
5644                                               /*sks_valid*/ 0,
5645                                               /*command*/ 1,
5646                                               /*field*/ 0,
5647                                               /*bit_valid*/ 0,
5648                                               /*bit*/ 0);
5649                         ctl_done((union ctl_io *)ctsio);
5650                         return (CTL_RETVAL_COMPLETE);
5651                 }
5652                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5653         }
5654
5655         len = lun->be_lun->blocksize;
5656
5657         /*
5658          * If we've got a kernel request that hasn't been malloced yet,
5659          * malloc it and tell the caller the data buffer is here.
5660          */
5661         if ((byte2 & SWS_NDOB) == 0 &&
5662             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5663                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5664                 ctsio->kern_data_len = len;
5665                 ctsio->kern_total_len = len;
5666                 ctsio->kern_data_resid = 0;
5667                 ctsio->kern_rel_offset = 0;
5668                 ctsio->kern_sg_entries = 0;
5669                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5670                 ctsio->be_move_done = ctl_config_move_done;
5671                 ctl_datamove((union ctl_io *)ctsio);
5672
5673                 return (CTL_RETVAL_COMPLETE);
5674         }
5675
5676         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5677         lbalen->lba = lba;
5678         lbalen->len = num_blocks;
5679         lbalen->flags = byte2;
5680         retval = lun->backend->config_write((union ctl_io *)ctsio);
5681
5682         return (retval);
5683 }
5684
5685 int
5686 ctl_unmap(struct ctl_scsiio *ctsio)
5687 {
5688         struct ctl_lun *lun;
5689         struct scsi_unmap *cdb;
5690         struct ctl_ptr_len_flags *ptrlen;
5691         struct scsi_unmap_header *hdr;
5692         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5693         uint64_t lba;
5694         uint32_t num_blocks;
5695         int len, retval;
5696         uint8_t byte2;
5697
5698         retval = CTL_RETVAL_COMPLETE;
5699
5700         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5701
5702         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5703         cdb = (struct scsi_unmap *)ctsio->cdb;
5704
5705         len = scsi_2btoul(cdb->length);
5706         byte2 = cdb->byte2;
5707
5708         /*
5709          * If we've got a kernel request that hasn't been malloced yet,
5710          * malloc it and tell the caller the data buffer is here.
5711          */
5712         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5713                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5714                 ctsio->kern_data_len = len;
5715                 ctsio->kern_total_len = len;
5716                 ctsio->kern_data_resid = 0;
5717                 ctsio->kern_rel_offset = 0;
5718                 ctsio->kern_sg_entries = 0;
5719                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5720                 ctsio->be_move_done = ctl_config_move_done;
5721                 ctl_datamove((union ctl_io *)ctsio);
5722
5723                 return (CTL_RETVAL_COMPLETE);
5724         }
5725
5726         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5727         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5728         if (len < sizeof (*hdr) ||
5729             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5730             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5731             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5732                 ctl_set_invalid_field(ctsio,
5733                                       /*sks_valid*/ 0,
5734                                       /*command*/ 0,
5735                                       /*field*/ 0,
5736                                       /*bit_valid*/ 0,
5737                                       /*bit*/ 0);
5738                 goto done;
5739         }
5740         len = scsi_2btoul(hdr->desc_length);
5741         buf = (struct scsi_unmap_desc *)(hdr + 1);
5742         end = buf + len / sizeof(*buf);
5743
5744         endnz = buf;
5745         for (range = buf; range < end; range++) {
5746                 lba = scsi_8btou64(range->lba);
5747                 num_blocks = scsi_4btoul(range->length);
5748                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5749                  || ((lba + num_blocks) < lba)) {
5750                         ctl_set_lba_out_of_range(ctsio);
5751                         ctl_done((union ctl_io *)ctsio);
5752                         return (CTL_RETVAL_COMPLETE);
5753                 }
5754                 if (num_blocks != 0)
5755                         endnz = range + 1;
5756         }
5757
5758         /*
5759          * Block backend can not handle zero last range.
5760          * Filter it out and return if there is nothing left.
5761          */
5762         len = (uint8_t *)endnz - (uint8_t *)buf;
5763         if (len == 0) {
5764                 ctl_set_success(ctsio);
5765                 goto done;
5766         }
5767
5768         mtx_lock(&lun->lun_lock);
5769         ptrlen = (struct ctl_ptr_len_flags *)
5770             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5771         ptrlen->ptr = (void *)buf;
5772         ptrlen->len = len;
5773         ptrlen->flags = byte2;
5774         ctl_check_blocked(lun);
5775         mtx_unlock(&lun->lun_lock);
5776
5777         retval = lun->backend->config_write((union ctl_io *)ctsio);
5778         return (retval);
5779
5780 done:
5781         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5782                 free(ctsio->kern_data_ptr, M_CTL);
5783                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5784         }
5785         ctl_done((union ctl_io *)ctsio);
5786         return (CTL_RETVAL_COMPLETE);
5787 }
5788
5789 /*
5790  * Note that this function currently doesn't actually do anything inside
5791  * CTL to enforce things if the DQue bit is turned on.
5792  *
5793  * Also note that this function can't be used in the default case, because
5794  * the DQue bit isn't set in the changeable mask for the control mode page
5795  * anyway.  This is just here as an example for how to implement a page
5796  * handler, and a placeholder in case we want to allow the user to turn
5797  * tagged queueing on and off.
5798  *
5799  * The D_SENSE bit handling is functional, however, and will turn
5800  * descriptor sense on and off for a given LUN.
5801  */
5802 int
5803 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5804                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5805 {
5806         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5807         struct ctl_lun *lun;
5808         int set_ua;
5809         uint32_t initidx;
5810
5811         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5812         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5813         set_ua = 0;
5814
5815         user_cp = (struct scsi_control_page *)page_ptr;
5816         current_cp = (struct scsi_control_page *)
5817                 (page_index->page_data + (page_index->page_len *
5818                 CTL_PAGE_CURRENT));
5819         saved_cp = (struct scsi_control_page *)
5820                 (page_index->page_data + (page_index->page_len *
5821                 CTL_PAGE_SAVED));
5822
5823         mtx_lock(&lun->lun_lock);
5824         if (((current_cp->rlec & SCP_DSENSE) == 0)
5825          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5826                 /*
5827                  * Descriptor sense is currently turned off and the user
5828                  * wants to turn it on.
5829                  */
5830                 current_cp->rlec |= SCP_DSENSE;
5831                 saved_cp->rlec |= SCP_DSENSE;
5832                 lun->flags |= CTL_LUN_SENSE_DESC;
5833                 set_ua = 1;
5834         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5835                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5836                 /*
5837                  * Descriptor sense is currently turned on, and the user
5838                  * wants to turn it off.
5839                  */
5840                 current_cp->rlec &= ~SCP_DSENSE;
5841                 saved_cp->rlec &= ~SCP_DSENSE;
5842                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5843                 set_ua = 1;
5844         }
5845         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5846             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5847                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5848                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5849                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5850                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5851                 set_ua = 1;
5852         }
5853         if ((current_cp->eca_and_aen & SCP_SWP) !=
5854             (user_cp->eca_and_aen & SCP_SWP)) {
5855                 current_cp->eca_and_aen &= ~SCP_SWP;
5856                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5857                 saved_cp->eca_and_aen &= ~SCP_SWP;
5858                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5859                 set_ua = 1;
5860         }
5861         if (set_ua != 0)
5862                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5863         mtx_unlock(&lun->lun_lock);
5864
5865         return (0);
5866 }
5867
5868 int
5869 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5870                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5871 {
5872         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5873         struct ctl_lun *lun;
5874         int set_ua;
5875         uint32_t initidx;
5876
5877         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5878         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5879         set_ua = 0;
5880
5881         user_cp = (struct scsi_caching_page *)page_ptr;
5882         current_cp = (struct scsi_caching_page *)
5883                 (page_index->page_data + (page_index->page_len *
5884                 CTL_PAGE_CURRENT));
5885         saved_cp = (struct scsi_caching_page *)
5886                 (page_index->page_data + (page_index->page_len *
5887                 CTL_PAGE_SAVED));
5888
5889         mtx_lock(&lun->lun_lock);
5890         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5891             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5892                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5893                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5894                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5895                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5896                 set_ua = 1;
5897         }
5898         if (set_ua != 0)
5899                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5900         mtx_unlock(&lun->lun_lock);
5901
5902         return (0);
5903 }
5904
5905 int
5906 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5907                                 struct ctl_page_index *page_index,
5908                                 uint8_t *page_ptr)
5909 {
5910         uint8_t *c;
5911         int i;
5912
5913         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5914         ctl_time_io_secs =
5915                 (c[0] << 8) |
5916                 (c[1] << 0) |
5917                 0;
5918         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5919         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5920         printf("page data:");
5921         for (i=0; i<8; i++)
5922                 printf(" %.2x",page_ptr[i]);
5923         printf("\n");
5924         return (0);
5925 }
5926
5927 int
5928 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5929                                struct ctl_page_index *page_index,
5930                                int pc)
5931 {
5932         struct copan_debugconf_subpage *page;
5933
5934         page = (struct copan_debugconf_subpage *)page_index->page_data +
5935                 (page_index->page_len * pc);
5936
5937         switch (pc) {
5938         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5939         case SMS_PAGE_CTRL_DEFAULT >> 6:
5940         case SMS_PAGE_CTRL_SAVED >> 6:
5941                 /*
5942                  * We don't update the changable or default bits for this page.
5943                  */
5944                 break;
5945         case SMS_PAGE_CTRL_CURRENT >> 6:
5946                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5947                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5948                 break;
5949         default:
5950 #ifdef NEEDTOPORT
5951                 EPRINT(0, "Invalid PC %d!!", pc);
5952 #endif /* NEEDTOPORT */
5953                 break;
5954         }
5955         return (0);
5956 }
5957
5958
5959 static int
5960 ctl_do_mode_select(union ctl_io *io)
5961 {
5962         struct scsi_mode_page_header *page_header;
5963         struct ctl_page_index *page_index;
5964         struct ctl_scsiio *ctsio;
5965         int control_dev, page_len;
5966         int page_len_offset, page_len_size;
5967         union ctl_modepage_info *modepage_info;
5968         struct ctl_lun *lun;
5969         int *len_left, *len_used;
5970         int retval, i;
5971
5972         ctsio = &io->scsiio;
5973         page_index = NULL;
5974         page_len = 0;
5975         retval = CTL_RETVAL_COMPLETE;
5976
5977         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5978
5979         if (lun->be_lun->lun_type != T_DIRECT)
5980                 control_dev = 1;
5981         else
5982                 control_dev = 0;
5983
5984         modepage_info = (union ctl_modepage_info *)
5985                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5986         len_left = &modepage_info->header.len_left;
5987         len_used = &modepage_info->header.len_used;
5988
5989 do_next_page:
5990
5991         page_header = (struct scsi_mode_page_header *)
5992                 (ctsio->kern_data_ptr + *len_used);
5993
5994         if (*len_left == 0) {
5995                 free(ctsio->kern_data_ptr, M_CTL);
5996                 ctl_set_success(ctsio);
5997                 ctl_done((union ctl_io *)ctsio);
5998                 return (CTL_RETVAL_COMPLETE);
5999         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6000
6001                 free(ctsio->kern_data_ptr, M_CTL);
6002                 ctl_set_param_len_error(ctsio);
6003                 ctl_done((union ctl_io *)ctsio);
6004                 return (CTL_RETVAL_COMPLETE);
6005
6006         } else if ((page_header->page_code & SMPH_SPF)
6007                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6008
6009                 free(ctsio->kern_data_ptr, M_CTL);
6010                 ctl_set_param_len_error(ctsio);
6011                 ctl_done((union ctl_io *)ctsio);
6012                 return (CTL_RETVAL_COMPLETE);
6013         }
6014
6015
6016         /*
6017          * XXX KDM should we do something with the block descriptor?
6018          */
6019         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6020
6021                 if ((control_dev != 0)
6022                  && (lun->mode_pages.index[i].page_flags &
6023                      CTL_PAGE_FLAG_DISK_ONLY))
6024                         continue;
6025
6026                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6027                     (page_header->page_code & SMPH_PC_MASK))
6028                         continue;
6029
6030                 /*
6031                  * If neither page has a subpage code, then we've got a
6032                  * match.
6033                  */
6034                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6035                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6036                         page_index = &lun->mode_pages.index[i];
6037                         page_len = page_header->page_length;
6038                         break;
6039                 }
6040
6041                 /*
6042                  * If both pages have subpages, then the subpage numbers
6043                  * have to match.
6044                  */
6045                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6046                   && (page_header->page_code & SMPH_SPF)) {
6047                         struct scsi_mode_page_header_sp *sph;
6048
6049                         sph = (struct scsi_mode_page_header_sp *)page_header;
6050
6051                         if (lun->mode_pages.index[i].subpage ==
6052                             sph->subpage) {
6053                                 page_index = &lun->mode_pages.index[i];
6054                                 page_len = scsi_2btoul(sph->page_length);
6055                                 break;
6056                         }
6057                 }
6058         }
6059
6060         /*
6061          * If we couldn't find the page, or if we don't have a mode select
6062          * handler for it, send back an error to the user.
6063          */
6064         if ((page_index == NULL)
6065          || (page_index->select_handler == NULL)) {
6066                 ctl_set_invalid_field(ctsio,
6067                                       /*sks_valid*/ 1,
6068                                       /*command*/ 0,
6069                                       /*field*/ *len_used,
6070                                       /*bit_valid*/ 0,
6071                                       /*bit*/ 0);
6072                 free(ctsio->kern_data_ptr, M_CTL);
6073                 ctl_done((union ctl_io *)ctsio);
6074                 return (CTL_RETVAL_COMPLETE);
6075         }
6076
6077         if (page_index->page_code & SMPH_SPF) {
6078                 page_len_offset = 2;
6079                 page_len_size = 2;
6080         } else {
6081                 page_len_size = 1;
6082                 page_len_offset = 1;
6083         }
6084
6085         /*
6086          * If the length the initiator gives us isn't the one we specify in
6087          * the mode page header, or if they didn't specify enough data in
6088          * the CDB to avoid truncating this page, kick out the request.
6089          */
6090         if ((page_len != (page_index->page_len - page_len_offset -
6091                           page_len_size))
6092          || (*len_left < page_index->page_len)) {
6093
6094
6095                 ctl_set_invalid_field(ctsio,
6096                                       /*sks_valid*/ 1,
6097                                       /*command*/ 0,
6098                                       /*field*/ *len_used + page_len_offset,
6099                                       /*bit_valid*/ 0,
6100                                       /*bit*/ 0);
6101                 free(ctsio->kern_data_ptr, M_CTL);
6102                 ctl_done((union ctl_io *)ctsio);
6103                 return (CTL_RETVAL_COMPLETE);
6104         }
6105
6106         /*
6107          * Run through the mode page, checking to make sure that the bits
6108          * the user changed are actually legal for him to change.
6109          */
6110         for (i = 0; i < page_index->page_len; i++) {
6111                 uint8_t *user_byte, *change_mask, *current_byte;
6112                 int bad_bit;
6113                 int j;
6114
6115                 user_byte = (uint8_t *)page_header + i;
6116                 change_mask = page_index->page_data +
6117                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6118                 current_byte = page_index->page_data +
6119                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6120
6121                 /*
6122                  * Check to see whether the user set any bits in this byte
6123                  * that he is not allowed to set.
6124                  */
6125                 if ((*user_byte & ~(*change_mask)) ==
6126                     (*current_byte & ~(*change_mask)))
6127                         continue;
6128
6129                 /*
6130                  * Go through bit by bit to determine which one is illegal.
6131                  */
6132                 bad_bit = 0;
6133                 for (j = 7; j >= 0; j--) {
6134                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6135                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6136                                 bad_bit = i;
6137                                 break;
6138                         }
6139                 }
6140                 ctl_set_invalid_field(ctsio,
6141                                       /*sks_valid*/ 1,
6142                                       /*command*/ 0,
6143                                       /*field*/ *len_used + i,
6144                                       /*bit_valid*/ 1,
6145                                       /*bit*/ bad_bit);
6146                 free(ctsio->kern_data_ptr, M_CTL);
6147                 ctl_done((union ctl_io *)ctsio);
6148                 return (CTL_RETVAL_COMPLETE);
6149         }
6150
6151         /*
6152          * Decrement these before we call the page handler, since we may
6153          * end up getting called back one way or another before the handler
6154          * returns to this context.
6155          */
6156         *len_left -= page_index->page_len;
6157         *len_used += page_index->page_len;
6158
6159         retval = page_index->select_handler(ctsio, page_index,
6160                                             (uint8_t *)page_header);
6161
6162         /*
6163          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6164          * wait until this queued command completes to finish processing
6165          * the mode page.  If it returns anything other than
6166          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6167          * already set the sense information, freed the data pointer, and
6168          * completed the io for us.
6169          */
6170         if (retval != CTL_RETVAL_COMPLETE)
6171                 goto bailout_no_done;
6172
6173         /*
6174          * If the initiator sent us more than one page, parse the next one.
6175          */
6176         if (*len_left > 0)
6177                 goto do_next_page;
6178
6179         ctl_set_success(ctsio);
6180         free(ctsio->kern_data_ptr, M_CTL);
6181         ctl_done((union ctl_io *)ctsio);
6182
6183 bailout_no_done:
6184
6185         return (CTL_RETVAL_COMPLETE);
6186
6187 }
6188
6189 int
6190 ctl_mode_select(struct ctl_scsiio *ctsio)
6191 {
6192         int param_len, pf, sp;
6193         int header_size, bd_len;
6194         int len_left, len_used;
6195         struct ctl_page_index *page_index;
6196         struct ctl_lun *lun;
6197         int control_dev, page_len;
6198         union ctl_modepage_info *modepage_info;
6199         int retval;
6200
6201         pf = 0;
6202         sp = 0;
6203         page_len = 0;
6204         len_used = 0;
6205         len_left = 0;
6206         retval = 0;
6207         bd_len = 0;
6208         page_index = NULL;
6209
6210         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6211
6212         if (lun->be_lun->lun_type != T_DIRECT)
6213                 control_dev = 1;
6214         else
6215                 control_dev = 0;
6216
6217         switch (ctsio->cdb[0]) {
6218         case MODE_SELECT_6: {
6219                 struct scsi_mode_select_6 *cdb;
6220
6221                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6222
6223                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6224                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6225
6226                 param_len = cdb->length;
6227                 header_size = sizeof(struct scsi_mode_header_6);
6228                 break;
6229         }
6230         case MODE_SELECT_10: {
6231                 struct scsi_mode_select_10 *cdb;
6232
6233                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6234
6235                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6236                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6237
6238                 param_len = scsi_2btoul(cdb->length);
6239                 header_size = sizeof(struct scsi_mode_header_10);
6240                 break;
6241         }
6242         default:
6243                 ctl_set_invalid_opcode(ctsio);
6244                 ctl_done((union ctl_io *)ctsio);
6245                 return (CTL_RETVAL_COMPLETE);
6246                 break; /* NOTREACHED */
6247         }
6248
6249         /*
6250          * From SPC-3:
6251          * "A parameter list length of zero indicates that the Data-Out Buffer
6252          * shall be empty. This condition shall not be considered as an error."
6253          */
6254         if (param_len == 0) {
6255                 ctl_set_success(ctsio);
6256                 ctl_done((union ctl_io *)ctsio);
6257                 return (CTL_RETVAL_COMPLETE);
6258         }
6259
6260         /*
6261          * Since we'll hit this the first time through, prior to
6262          * allocation, we don't need to free a data buffer here.
6263          */
6264         if (param_len < header_size) {
6265                 ctl_set_param_len_error(ctsio);
6266                 ctl_done((union ctl_io *)ctsio);
6267                 return (CTL_RETVAL_COMPLETE);
6268         }
6269
6270         /*
6271          * Allocate the data buffer and grab the user's data.  In theory,
6272          * we shouldn't have to sanity check the parameter list length here
6273          * because the maximum size is 64K.  We should be able to malloc
6274          * that much without too many problems.
6275          */
6276         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6277                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6278                 ctsio->kern_data_len = param_len;
6279                 ctsio->kern_total_len = param_len;
6280                 ctsio->kern_data_resid = 0;
6281                 ctsio->kern_rel_offset = 0;
6282                 ctsio->kern_sg_entries = 0;
6283                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6284                 ctsio->be_move_done = ctl_config_move_done;
6285                 ctl_datamove((union ctl_io *)ctsio);
6286
6287                 return (CTL_RETVAL_COMPLETE);
6288         }
6289
6290         switch (ctsio->cdb[0]) {
6291         case MODE_SELECT_6: {
6292                 struct scsi_mode_header_6 *mh6;
6293
6294                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6295                 bd_len = mh6->blk_desc_len;
6296                 break;
6297         }
6298         case MODE_SELECT_10: {
6299                 struct scsi_mode_header_10 *mh10;
6300
6301                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6302                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6303                 break;
6304         }
6305         default:
6306                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6307                 break;
6308         }
6309
6310         if (param_len < (header_size + bd_len)) {
6311                 free(ctsio->kern_data_ptr, M_CTL);
6312                 ctl_set_param_len_error(ctsio);
6313                 ctl_done((union ctl_io *)ctsio);
6314                 return (CTL_RETVAL_COMPLETE);
6315         }
6316
6317         /*
6318          * Set the IO_CONT flag, so that if this I/O gets passed to
6319          * ctl_config_write_done(), it'll get passed back to
6320          * ctl_do_mode_select() for further processing, or completion if
6321          * we're all done.
6322          */
6323         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6324         ctsio->io_cont = ctl_do_mode_select;
6325
6326         modepage_info = (union ctl_modepage_info *)
6327                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6328
6329         memset(modepage_info, 0, sizeof(*modepage_info));
6330
6331         len_left = param_len - header_size - bd_len;
6332         len_used = header_size + bd_len;
6333
6334         modepage_info->header.len_left = len_left;
6335         modepage_info->header.len_used = len_used;
6336
6337         return (ctl_do_mode_select((union ctl_io *)ctsio));
6338 }
6339
6340 int
6341 ctl_mode_sense(struct ctl_scsiio *ctsio)
6342 {
6343         struct ctl_lun *lun;
6344         int pc, page_code, dbd, llba, subpage;
6345         int alloc_len, page_len, header_len, total_len;
6346         struct scsi_mode_block_descr *block_desc;
6347         struct ctl_page_index *page_index;
6348         int control_dev;
6349
6350         dbd = 0;
6351         llba = 0;
6352         block_desc = NULL;
6353         page_index = NULL;
6354
6355         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6356
6357         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6358
6359         if (lun->be_lun->lun_type != T_DIRECT)
6360                 control_dev = 1;
6361         else
6362                 control_dev = 0;
6363
6364         switch (ctsio->cdb[0]) {
6365         case MODE_SENSE_6: {
6366                 struct scsi_mode_sense_6 *cdb;
6367
6368                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6369
6370                 header_len = sizeof(struct scsi_mode_hdr_6);
6371                 if (cdb->byte2 & SMS_DBD)
6372                         dbd = 1;
6373                 else
6374                         header_len += sizeof(struct scsi_mode_block_descr);
6375
6376                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6377                 page_code = cdb->page & SMS_PAGE_CODE;
6378                 subpage = cdb->subpage;
6379                 alloc_len = cdb->length;
6380                 break;
6381         }
6382         case MODE_SENSE_10: {
6383                 struct scsi_mode_sense_10 *cdb;
6384
6385                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6386
6387                 header_len = sizeof(struct scsi_mode_hdr_10);
6388
6389                 if (cdb->byte2 & SMS_DBD)
6390                         dbd = 1;
6391                 else
6392                         header_len += sizeof(struct scsi_mode_block_descr);
6393                 if (cdb->byte2 & SMS10_LLBAA)
6394                         llba = 1;
6395                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6396                 page_code = cdb->page & SMS_PAGE_CODE;
6397                 subpage = cdb->subpage;
6398                 alloc_len = scsi_2btoul(cdb->length);
6399                 break;
6400         }
6401         default:
6402                 ctl_set_invalid_opcode(ctsio);
6403                 ctl_done((union ctl_io *)ctsio);
6404                 return (CTL_RETVAL_COMPLETE);
6405                 break; /* NOTREACHED */
6406         }
6407
6408         /*
6409          * We have to make a first pass through to calculate the size of
6410          * the pages that match the user's query.  Then we allocate enough
6411          * memory to hold it, and actually copy the data into the buffer.
6412          */
6413         switch (page_code) {
6414         case SMS_ALL_PAGES_PAGE: {
6415                 int i;
6416
6417                 page_len = 0;
6418
6419                 /*
6420                  * At the moment, values other than 0 and 0xff here are
6421                  * reserved according to SPC-3.
6422                  */
6423                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6424                  && (subpage != SMS_SUBPAGE_ALL)) {
6425                         ctl_set_invalid_field(ctsio,
6426                                               /*sks_valid*/ 1,
6427                                               /*command*/ 1,
6428                                               /*field*/ 3,
6429                                               /*bit_valid*/ 0,
6430                                               /*bit*/ 0);
6431                         ctl_done((union ctl_io *)ctsio);
6432                         return (CTL_RETVAL_COMPLETE);
6433                 }
6434
6435                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6436                         if ((control_dev != 0)
6437                          && (lun->mode_pages.index[i].page_flags &
6438                              CTL_PAGE_FLAG_DISK_ONLY))
6439                                 continue;
6440
6441                         /*
6442                          * We don't use this subpage if the user didn't
6443                          * request all subpages.
6444                          */
6445                         if ((lun->mode_pages.index[i].subpage != 0)
6446                          && (subpage == SMS_SUBPAGE_PAGE_0))
6447                                 continue;
6448
6449 #if 0
6450                         printf("found page %#x len %d\n",
6451                                lun->mode_pages.index[i].page_code &
6452                                SMPH_PC_MASK,
6453                                lun->mode_pages.index[i].page_len);
6454 #endif
6455                         page_len += lun->mode_pages.index[i].page_len;
6456                 }
6457                 break;
6458         }
6459         default: {
6460                 int i;
6461
6462                 page_len = 0;
6463
6464                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6465                         /* Look for the right page code */
6466                         if ((lun->mode_pages.index[i].page_code &
6467                              SMPH_PC_MASK) != page_code)
6468                                 continue;
6469
6470                         /* Look for the right subpage or the subpage wildcard*/
6471                         if ((lun->mode_pages.index[i].subpage != subpage)
6472                          && (subpage != SMS_SUBPAGE_ALL))
6473                                 continue;
6474
6475                         /* Make sure the page is supported for this dev type */
6476                         if ((control_dev != 0)
6477                          && (lun->mode_pages.index[i].page_flags &
6478                              CTL_PAGE_FLAG_DISK_ONLY))
6479                                 continue;
6480
6481 #if 0
6482                         printf("found page %#x len %d\n",
6483                                lun->mode_pages.index[i].page_code &
6484                                SMPH_PC_MASK,
6485                                lun->mode_pages.index[i].page_len);
6486 #endif
6487
6488                         page_len += lun->mode_pages.index[i].page_len;
6489                 }
6490
6491                 if (page_len == 0) {
6492                         ctl_set_invalid_field(ctsio,
6493                                               /*sks_valid*/ 1,
6494                                               /*command*/ 1,
6495                                               /*field*/ 2,
6496                                               /*bit_valid*/ 1,
6497                                               /*bit*/ 5);
6498                         ctl_done((union ctl_io *)ctsio);
6499                         return (CTL_RETVAL_COMPLETE);
6500                 }
6501                 break;
6502         }
6503         }
6504
6505         total_len = header_len + page_len;
6506 #if 0
6507         printf("header_len = %d, page_len = %d, total_len = %d\n",
6508                header_len, page_len, total_len);
6509 #endif
6510
6511         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6512         ctsio->kern_sg_entries = 0;
6513         ctsio->kern_data_resid = 0;
6514         ctsio->kern_rel_offset = 0;
6515         if (total_len < alloc_len) {
6516                 ctsio->residual = alloc_len - total_len;
6517                 ctsio->kern_data_len = total_len;
6518                 ctsio->kern_total_len = total_len;
6519         } else {
6520                 ctsio->residual = 0;
6521                 ctsio->kern_data_len = alloc_len;
6522                 ctsio->kern_total_len = alloc_len;
6523         }
6524
6525         switch (ctsio->cdb[0]) {
6526         case MODE_SENSE_6: {
6527                 struct scsi_mode_hdr_6 *header;
6528
6529                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6530
6531                 header->datalen = MIN(total_len - 1, 254);
6532                 if (control_dev == 0) {
6533                         header->dev_specific = 0x10; /* DPOFUA */
6534                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6535                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6536                             .eca_and_aen & SCP_SWP) != 0)
6537                                     header->dev_specific |= 0x80; /* WP */
6538                 }
6539                 if (dbd)
6540                         header->block_descr_len = 0;
6541                 else
6542                         header->block_descr_len =
6543                                 sizeof(struct scsi_mode_block_descr);
6544                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6545                 break;
6546         }
6547         case MODE_SENSE_10: {
6548                 struct scsi_mode_hdr_10 *header;
6549                 int datalen;
6550
6551                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6552
6553                 datalen = MIN(total_len - 2, 65533);
6554                 scsi_ulto2b(datalen, header->datalen);
6555                 if (control_dev == 0) {
6556                         header->dev_specific = 0x10; /* DPOFUA */
6557                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6558                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6559                             .eca_and_aen & SCP_SWP) != 0)
6560                                     header->dev_specific |= 0x80; /* WP */
6561                 }
6562                 if (dbd)
6563                         scsi_ulto2b(0, header->block_descr_len);
6564                 else
6565                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6566                                     header->block_descr_len);
6567                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6568                 break;
6569         }
6570         default:
6571                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6572                 break; /* NOTREACHED */
6573         }
6574
6575         /*
6576          * If we've got a disk, use its blocksize in the block
6577          * descriptor.  Otherwise, just set it to 0.
6578          */
6579         if (dbd == 0) {
6580                 if (control_dev == 0)
6581                         scsi_ulto3b(lun->be_lun->blocksize,
6582                                     block_desc->block_len);
6583                 else
6584                         scsi_ulto3b(0, block_desc->block_len);
6585         }
6586
6587         switch (page_code) {
6588         case SMS_ALL_PAGES_PAGE: {
6589                 int i, data_used;
6590
6591                 data_used = header_len;
6592                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6593                         struct ctl_page_index *page_index;
6594
6595                         page_index = &lun->mode_pages.index[i];
6596
6597                         if ((control_dev != 0)
6598                          && (page_index->page_flags &
6599                             CTL_PAGE_FLAG_DISK_ONLY))
6600                                 continue;
6601
6602                         /*
6603                          * We don't use this subpage if the user didn't
6604                          * request all subpages.  We already checked (above)
6605                          * to make sure the user only specified a subpage
6606                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6607                          */
6608                         if ((page_index->subpage != 0)
6609                          && (subpage == SMS_SUBPAGE_PAGE_0))
6610                                 continue;
6611
6612                         /*
6613                          * Call the handler, if it exists, to update the
6614                          * page to the latest values.
6615                          */
6616                         if (page_index->sense_handler != NULL)
6617                                 page_index->sense_handler(ctsio, page_index,pc);
6618
6619                         memcpy(ctsio->kern_data_ptr + data_used,
6620                                page_index->page_data +
6621                                (page_index->page_len * pc),
6622                                page_index->page_len);
6623                         data_used += page_index->page_len;
6624                 }
6625                 break;
6626         }
6627         default: {
6628                 int i, data_used;
6629
6630                 data_used = header_len;
6631
6632                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6633                         struct ctl_page_index *page_index;
6634
6635                         page_index = &lun->mode_pages.index[i];
6636
6637                         /* Look for the right page code */
6638                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6639                                 continue;
6640
6641                         /* Look for the right subpage or the subpage wildcard*/
6642                         if ((page_index->subpage != subpage)
6643                          && (subpage != SMS_SUBPAGE_ALL))
6644                                 continue;
6645
6646                         /* Make sure the page is supported for this dev type */
6647                         if ((control_dev != 0)
6648                          && (page_index->page_flags &
6649                              CTL_PAGE_FLAG_DISK_ONLY))
6650                                 continue;
6651
6652                         /*
6653                          * Call the handler, if it exists, to update the
6654                          * page to the latest values.
6655                          */
6656                         if (page_index->sense_handler != NULL)
6657                                 page_index->sense_handler(ctsio, page_index,pc);
6658
6659                         memcpy(ctsio->kern_data_ptr + data_used,
6660                                page_index->page_data +
6661                                (page_index->page_len * pc),
6662                                page_index->page_len);
6663                         data_used += page_index->page_len;
6664                 }
6665                 break;
6666         }
6667         }
6668
6669         ctl_set_success(ctsio);
6670         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6671         ctsio->be_move_done = ctl_config_move_done;
6672         ctl_datamove((union ctl_io *)ctsio);
6673         return (CTL_RETVAL_COMPLETE);
6674 }
6675
6676 int
6677 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6678                                struct ctl_page_index *page_index,
6679                                int pc)
6680 {
6681         struct ctl_lun *lun;
6682         struct scsi_log_param_header *phdr;
6683         uint8_t *data;
6684         uint64_t val;
6685
6686         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6687         data = page_index->page_data;
6688
6689         if (lun->backend->lun_attr != NULL &&
6690             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6691              != UINT64_MAX) {
6692                 phdr = (struct scsi_log_param_header *)data;
6693                 scsi_ulto2b(0x0001, phdr->param_code);
6694                 phdr->param_control = SLP_LBIN | SLP_LP;
6695                 phdr->param_len = 8;
6696                 data = (uint8_t *)(phdr + 1);
6697                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6698                 data[4] = 0x02; /* per-pool */
6699                 data += phdr->param_len;
6700         }
6701
6702         if (lun->backend->lun_attr != NULL &&
6703             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6704              != UINT64_MAX) {
6705                 phdr = (struct scsi_log_param_header *)data;
6706                 scsi_ulto2b(0x0002, phdr->param_code);
6707                 phdr->param_control = SLP_LBIN | SLP_LP;
6708                 phdr->param_len = 8;
6709                 data = (uint8_t *)(phdr + 1);
6710                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6711                 data[4] = 0x01; /* per-LUN */
6712                 data += phdr->param_len;
6713         }
6714
6715         if (lun->backend->lun_attr != NULL &&
6716             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6717              != UINT64_MAX) {
6718                 phdr = (struct scsi_log_param_header *)data;
6719                 scsi_ulto2b(0x00f1, phdr->param_code);
6720                 phdr->param_control = SLP_LBIN | SLP_LP;
6721                 phdr->param_len = 8;
6722                 data = (uint8_t *)(phdr + 1);
6723                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6724                 data[4] = 0x02; /* per-pool */
6725                 data += phdr->param_len;
6726         }
6727
6728         if (lun->backend->lun_attr != NULL &&
6729             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6730              != UINT64_MAX) {
6731                 phdr = (struct scsi_log_param_header *)data;
6732                 scsi_ulto2b(0x00f2, phdr->param_code);
6733                 phdr->param_control = SLP_LBIN | SLP_LP;
6734                 phdr->param_len = 8;
6735                 data = (uint8_t *)(phdr + 1);
6736                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6737                 data[4] = 0x02; /* per-pool */
6738                 data += phdr->param_len;
6739         }
6740
6741         page_index->page_len = data - page_index->page_data;
6742         return (0);
6743 }
6744
6745 int
6746 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6747                                struct ctl_page_index *page_index,
6748                                int pc)
6749 {
6750         struct ctl_lun *lun;
6751         struct stat_page *data;
6752         uint64_t rn, wn, rb, wb;
6753         struct bintime rt, wt;
6754         int i;
6755
6756         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6757         data = (struct stat_page *)page_index->page_data;
6758
6759         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6760         data->sap.hdr.param_control = SLP_LBIN;
6761         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6762             sizeof(struct scsi_log_param_header);
6763         rn = wn = rb = wb = 0;
6764         bintime_clear(&rt);
6765         bintime_clear(&wt);
6766         for (i = 0; i < CTL_MAX_PORTS; i++) {
6767                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6768                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6769                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6770                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6771                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6772                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6773         }
6774         scsi_u64to8b(rn, data->sap.read_num);
6775         scsi_u64to8b(wn, data->sap.write_num);
6776         if (lun->stats.blocksize > 0) {
6777                 scsi_u64to8b(wb / lun->stats.blocksize,
6778                     data->sap.recvieved_lba);
6779                 scsi_u64to8b(rb / lun->stats.blocksize,
6780                     data->sap.transmitted_lba);
6781         }
6782         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6783             data->sap.read_int);
6784         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6785             data->sap.write_int);
6786         scsi_u64to8b(0, data->sap.weighted_num);
6787         scsi_u64to8b(0, data->sap.weighted_int);
6788         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6789         data->it.hdr.param_control = SLP_LBIN;
6790         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6791             sizeof(struct scsi_log_param_header);
6792 #ifdef CTL_TIME_IO
6793         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6794 #endif
6795         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6796         data->it.hdr.param_control = SLP_LBIN;
6797         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6798             sizeof(struct scsi_log_param_header);
6799         scsi_ulto4b(3, data->ti.exponent);
6800         scsi_ulto4b(1, data->ti.integer);
6801
6802         page_index->page_len = sizeof(*data);
6803         return (0);
6804 }
6805
6806 int
6807 ctl_log_sense(struct ctl_scsiio *ctsio)
6808 {
6809         struct ctl_lun *lun;
6810         int i, pc, page_code, subpage;
6811         int alloc_len, total_len;
6812         struct ctl_page_index *page_index;
6813         struct scsi_log_sense *cdb;
6814         struct scsi_log_header *header;
6815
6816         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6817
6818         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6819         cdb = (struct scsi_log_sense *)ctsio->cdb;
6820         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6821         page_code = cdb->page & SLS_PAGE_CODE;
6822         subpage = cdb->subpage;
6823         alloc_len = scsi_2btoul(cdb->length);
6824
6825         page_index = NULL;
6826         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6827                 page_index = &lun->log_pages.index[i];
6828
6829                 /* Look for the right page code */
6830                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6831                         continue;
6832
6833                 /* Look for the right subpage or the subpage wildcard*/
6834                 if (page_index->subpage != subpage)
6835                         continue;
6836
6837                 break;
6838         }
6839         if (i >= CTL_NUM_LOG_PAGES) {
6840                 ctl_set_invalid_field(ctsio,
6841                                       /*sks_valid*/ 1,
6842                                       /*command*/ 1,
6843                                       /*field*/ 2,
6844                                       /*bit_valid*/ 0,
6845                                       /*bit*/ 0);
6846                 ctl_done((union ctl_io *)ctsio);
6847                 return (CTL_RETVAL_COMPLETE);
6848         }
6849
6850         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6851
6852         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6853         ctsio->kern_sg_entries = 0;
6854         ctsio->kern_data_resid = 0;
6855         ctsio->kern_rel_offset = 0;
6856         if (total_len < alloc_len) {
6857                 ctsio->residual = alloc_len - total_len;
6858                 ctsio->kern_data_len = total_len;
6859                 ctsio->kern_total_len = total_len;
6860         } else {
6861                 ctsio->residual = 0;
6862                 ctsio->kern_data_len = alloc_len;
6863                 ctsio->kern_total_len = alloc_len;
6864         }
6865
6866         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6867         header->page = page_index->page_code;
6868         if (page_index->subpage) {
6869                 header->page |= SL_SPF;
6870                 header->subpage = page_index->subpage;
6871         }
6872         scsi_ulto2b(page_index->page_len, header->datalen);
6873
6874         /*
6875          * Call the handler, if it exists, to update the
6876          * page to the latest values.
6877          */
6878         if (page_index->sense_handler != NULL)
6879                 page_index->sense_handler(ctsio, page_index, pc);
6880
6881         memcpy(header + 1, page_index->page_data, page_index->page_len);
6882
6883         ctl_set_success(ctsio);
6884         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6885         ctsio->be_move_done = ctl_config_move_done;
6886         ctl_datamove((union ctl_io *)ctsio);
6887         return (CTL_RETVAL_COMPLETE);
6888 }
6889
6890 int
6891 ctl_read_capacity(struct ctl_scsiio *ctsio)
6892 {
6893         struct scsi_read_capacity *cdb;
6894         struct scsi_read_capacity_data *data;
6895         struct ctl_lun *lun;
6896         uint32_t lba;
6897
6898         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6899
6900         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6901
6902         lba = scsi_4btoul(cdb->addr);
6903         if (((cdb->pmi & SRC_PMI) == 0)
6904          && (lba != 0)) {
6905                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6906                                       /*sks_valid*/ 1,
6907                                       /*command*/ 1,
6908                                       /*field*/ 2,
6909                                       /*bit_valid*/ 0,
6910                                       /*bit*/ 0);
6911                 ctl_done((union ctl_io *)ctsio);
6912                 return (CTL_RETVAL_COMPLETE);
6913         }
6914
6915         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6916
6917         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6918         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6919         ctsio->residual = 0;
6920         ctsio->kern_data_len = sizeof(*data);
6921         ctsio->kern_total_len = sizeof(*data);
6922         ctsio->kern_data_resid = 0;
6923         ctsio->kern_rel_offset = 0;
6924         ctsio->kern_sg_entries = 0;
6925
6926         /*
6927          * If the maximum LBA is greater than 0xfffffffe, the user must
6928          * issue a SERVICE ACTION IN (16) command, with the read capacity
6929          * serivce action set.
6930          */
6931         if (lun->be_lun->maxlba > 0xfffffffe)
6932                 scsi_ulto4b(0xffffffff, data->addr);
6933         else
6934                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6935
6936         /*
6937          * XXX KDM this may not be 512 bytes...
6938          */
6939         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6940
6941         ctl_set_success(ctsio);
6942         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6943         ctsio->be_move_done = ctl_config_move_done;
6944         ctl_datamove((union ctl_io *)ctsio);
6945         return (CTL_RETVAL_COMPLETE);
6946 }
6947
6948 int
6949 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6950 {
6951         struct scsi_read_capacity_16 *cdb;
6952         struct scsi_read_capacity_data_long *data;
6953         struct ctl_lun *lun;
6954         uint64_t lba;
6955         uint32_t alloc_len;
6956
6957         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6958
6959         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6960
6961         alloc_len = scsi_4btoul(cdb->alloc_len);
6962         lba = scsi_8btou64(cdb->addr);
6963
6964         if ((cdb->reladr & SRC16_PMI)
6965          && (lba != 0)) {
6966                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6967                                       /*sks_valid*/ 1,
6968                                       /*command*/ 1,
6969                                       /*field*/ 2,
6970                                       /*bit_valid*/ 0,
6971                                       /*bit*/ 0);
6972                 ctl_done((union ctl_io *)ctsio);
6973                 return (CTL_RETVAL_COMPLETE);
6974         }
6975
6976         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6977
6978         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6979         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6980
6981         if (sizeof(*data) < alloc_len) {
6982                 ctsio->residual = alloc_len - sizeof(*data);
6983                 ctsio->kern_data_len = sizeof(*data);
6984                 ctsio->kern_total_len = sizeof(*data);
6985         } else {
6986                 ctsio->residual = 0;
6987                 ctsio->kern_data_len = alloc_len;
6988                 ctsio->kern_total_len = alloc_len;
6989         }
6990         ctsio->kern_data_resid = 0;
6991         ctsio->kern_rel_offset = 0;
6992         ctsio->kern_sg_entries = 0;
6993
6994         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6995         /* XXX KDM this may not be 512 bytes... */
6996         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6997         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6998         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6999         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7000                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7001
7002         ctl_set_success(ctsio);
7003         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7004         ctsio->be_move_done = ctl_config_move_done;
7005         ctl_datamove((union ctl_io *)ctsio);
7006         return (CTL_RETVAL_COMPLETE);
7007 }
7008
7009 int
7010 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7011 {
7012         struct scsi_get_lba_status *cdb;
7013         struct scsi_get_lba_status_data *data;
7014         struct ctl_lun *lun;
7015         struct ctl_lba_len_flags *lbalen;
7016         uint64_t lba;
7017         uint32_t alloc_len, total_len;
7018         int retval;
7019
7020         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7021
7022         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7023         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7024         lba = scsi_8btou64(cdb->addr);
7025         alloc_len = scsi_4btoul(cdb->alloc_len);
7026
7027         if (lba > lun->be_lun->maxlba) {
7028                 ctl_set_lba_out_of_range(ctsio);
7029                 ctl_done((union ctl_io *)ctsio);
7030                 return (CTL_RETVAL_COMPLETE);
7031         }
7032
7033         total_len = sizeof(*data) + sizeof(data->descr[0]);
7034         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7035         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7036
7037         if (total_len < alloc_len) {
7038                 ctsio->residual = alloc_len - total_len;
7039                 ctsio->kern_data_len = total_len;
7040                 ctsio->kern_total_len = total_len;
7041         } else {
7042                 ctsio->residual = 0;
7043                 ctsio->kern_data_len = alloc_len;
7044                 ctsio->kern_total_len = alloc_len;
7045         }
7046         ctsio->kern_data_resid = 0;
7047         ctsio->kern_rel_offset = 0;
7048         ctsio->kern_sg_entries = 0;
7049
7050         /* Fill dummy data in case backend can't tell anything. */
7051         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7052         scsi_u64to8b(lba, data->descr[0].addr);
7053         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7054             data->descr[0].length);
7055         data->descr[0].status = 0; /* Mapped or unknown. */
7056
7057         ctl_set_success(ctsio);
7058         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7059         ctsio->be_move_done = ctl_config_move_done;
7060
7061         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7062         lbalen->lba = lba;
7063         lbalen->len = total_len;
7064         lbalen->flags = 0;
7065         retval = lun->backend->config_read((union ctl_io *)ctsio);
7066         return (CTL_RETVAL_COMPLETE);
7067 }
7068
7069 int
7070 ctl_read_defect(struct ctl_scsiio *ctsio)
7071 {
7072         struct scsi_read_defect_data_10 *ccb10;
7073         struct scsi_read_defect_data_12 *ccb12;
7074         struct scsi_read_defect_data_hdr_10 *data10;
7075         struct scsi_read_defect_data_hdr_12 *data12;
7076         uint32_t alloc_len, data_len;
7077         uint8_t format;
7078
7079         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7080
7081         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7082                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7083                 format = ccb10->format;
7084                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7085                 data_len = sizeof(*data10);
7086         } else {
7087                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7088                 format = ccb12->format;
7089                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7090                 data_len = sizeof(*data12);
7091         }
7092         if (alloc_len == 0) {
7093                 ctl_set_success(ctsio);
7094                 ctl_done((union ctl_io *)ctsio);
7095                 return (CTL_RETVAL_COMPLETE);
7096         }
7097
7098         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7099         if (data_len < alloc_len) {
7100                 ctsio->residual = alloc_len - data_len;
7101                 ctsio->kern_data_len = data_len;
7102                 ctsio->kern_total_len = data_len;
7103         } else {
7104                 ctsio->residual = 0;
7105                 ctsio->kern_data_len = alloc_len;
7106                 ctsio->kern_total_len = alloc_len;
7107         }
7108         ctsio->kern_data_resid = 0;
7109         ctsio->kern_rel_offset = 0;
7110         ctsio->kern_sg_entries = 0;
7111
7112         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7113                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7114                     ctsio->kern_data_ptr;
7115                 data10->format = format;
7116                 scsi_ulto2b(0, data10->length);
7117         } else {
7118                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7119                     ctsio->kern_data_ptr;
7120                 data12->format = format;
7121                 scsi_ulto2b(0, data12->generation);
7122                 scsi_ulto4b(0, data12->length);
7123         }
7124
7125         ctl_set_success(ctsio);
7126         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7127         ctsio->be_move_done = ctl_config_move_done;
7128         ctl_datamove((union ctl_io *)ctsio);
7129         return (CTL_RETVAL_COMPLETE);
7130 }
7131
7132 int
7133 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7134 {
7135         struct scsi_maintenance_in *cdb;
7136         int retval;
7137         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7138         int num_target_port_groups, num_target_ports;
7139         struct ctl_lun *lun;
7140         struct ctl_softc *softc;
7141         struct ctl_port *port;
7142         struct scsi_target_group_data *rtg_ptr;
7143         struct scsi_target_group_data_extended *rtg_ext_ptr;
7144         struct scsi_target_port_group_descriptor *tpg_desc;
7145
7146         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7147
7148         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7149         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7150         softc = lun->ctl_softc;
7151
7152         retval = CTL_RETVAL_COMPLETE;
7153
7154         switch (cdb->byte2 & STG_PDF_MASK) {
7155         case STG_PDF_LENGTH:
7156                 ext = 0;
7157                 break;
7158         case STG_PDF_EXTENDED:
7159                 ext = 1;
7160                 break;
7161         default:
7162                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7163                                       /*sks_valid*/ 1,
7164                                       /*command*/ 1,
7165                                       /*field*/ 2,
7166                                       /*bit_valid*/ 1,
7167                                       /*bit*/ 5);
7168                 ctl_done((union ctl_io *)ctsio);
7169                 return(retval);
7170         }
7171
7172         if (softc->is_single)
7173                 num_target_port_groups = 1;
7174         else
7175                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7176         num_target_ports = 0;
7177         mtx_lock(&softc->ctl_lock);
7178         STAILQ_FOREACH(port, &softc->port_list, links) {
7179                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7180                         continue;
7181                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7182                         continue;
7183                 num_target_ports++;
7184         }
7185         mtx_unlock(&softc->ctl_lock);
7186
7187         if (ext)
7188                 total_len = sizeof(struct scsi_target_group_data_extended);
7189         else
7190                 total_len = sizeof(struct scsi_target_group_data);
7191         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7192                 num_target_port_groups +
7193             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7194
7195         alloc_len = scsi_4btoul(cdb->length);
7196
7197         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7198
7199         ctsio->kern_sg_entries = 0;
7200
7201         if (total_len < alloc_len) {
7202                 ctsio->residual = alloc_len - total_len;
7203                 ctsio->kern_data_len = total_len;
7204                 ctsio->kern_total_len = total_len;
7205         } else {
7206                 ctsio->residual = 0;
7207                 ctsio->kern_data_len = alloc_len;
7208                 ctsio->kern_total_len = alloc_len;
7209         }
7210         ctsio->kern_data_resid = 0;
7211         ctsio->kern_rel_offset = 0;
7212
7213         if (ext) {
7214                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7215                     ctsio->kern_data_ptr;
7216                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7217                 rtg_ext_ptr->format_type = 0x10;
7218                 rtg_ext_ptr->implicit_transition_time = 0;
7219                 tpg_desc = &rtg_ext_ptr->groups[0];
7220         } else {
7221                 rtg_ptr = (struct scsi_target_group_data *)
7222                     ctsio->kern_data_ptr;
7223                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7224                 tpg_desc = &rtg_ptr->groups[0];
7225         }
7226
7227         mtx_lock(&softc->ctl_lock);
7228         pg = softc->port_min / softc->port_cnt;
7229         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7230                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7231         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7232                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7233         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7234                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7235         else
7236                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7237         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7238                 os = gs;
7239                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7240         } else
7241                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7242         for (g = 0; g < num_target_port_groups; g++) {
7243                 tpg_desc->pref_state = (g == pg) ? gs : os;
7244                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7245                     TPG_U_SUP | TPG_T_SUP;
7246                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7247                 tpg_desc->status = TPG_IMPLICIT;
7248                 pc = 0;
7249                 STAILQ_FOREACH(port, &softc->port_list, links) {
7250                         if (port->targ_port < g * softc->port_cnt ||
7251                             port->targ_port >= (g + 1) * softc->port_cnt)
7252                                 continue;
7253                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7254                                 continue;
7255                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7256                                 continue;
7257                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7258                             relative_target_port_identifier);
7259                         pc++;
7260                 }
7261                 tpg_desc->target_port_count = pc;
7262                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7263                     &tpg_desc->descriptors[pc];
7264         }
7265         mtx_unlock(&softc->ctl_lock);
7266
7267         ctl_set_success(ctsio);
7268         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7269         ctsio->be_move_done = ctl_config_move_done;
7270         ctl_datamove((union ctl_io *)ctsio);
7271         return(retval);
7272 }
7273
7274 int
7275 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7276 {
7277         struct ctl_lun *lun;
7278         struct scsi_report_supported_opcodes *cdb;
7279         const struct ctl_cmd_entry *entry, *sentry;
7280         struct scsi_report_supported_opcodes_all *all;
7281         struct scsi_report_supported_opcodes_descr *descr;
7282         struct scsi_report_supported_opcodes_one *one;
7283         int retval;
7284         int alloc_len, total_len;
7285         int opcode, service_action, i, j, num;
7286
7287         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7288
7289         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7290         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7291
7292         retval = CTL_RETVAL_COMPLETE;
7293
7294         opcode = cdb->requested_opcode;
7295         service_action = scsi_2btoul(cdb->requested_service_action);
7296         switch (cdb->options & RSO_OPTIONS_MASK) {
7297         case RSO_OPTIONS_ALL:
7298                 num = 0;
7299                 for (i = 0; i < 256; i++) {
7300                         entry = &ctl_cmd_table[i];
7301                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7302                                 for (j = 0; j < 32; j++) {
7303                                         sentry = &((const struct ctl_cmd_entry *)
7304                                             entry->execute)[j];
7305                                         if (ctl_cmd_applicable(
7306                                             lun->be_lun->lun_type, sentry))
7307                                                 num++;
7308                                 }
7309                         } else {
7310                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7311                                     entry))
7312                                         num++;
7313                         }
7314                 }
7315                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7316                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7317                 break;
7318         case RSO_OPTIONS_OC:
7319                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7320                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7321                                               /*sks_valid*/ 1,
7322                                               /*command*/ 1,
7323                                               /*field*/ 2,
7324                                               /*bit_valid*/ 1,
7325                                               /*bit*/ 2);
7326                         ctl_done((union ctl_io *)ctsio);
7327                         return (CTL_RETVAL_COMPLETE);
7328                 }
7329                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7330                 break;
7331         case RSO_OPTIONS_OC_SA:
7332                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7333                     service_action >= 32) {
7334                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7335                                               /*sks_valid*/ 1,
7336                                               /*command*/ 1,
7337                                               /*field*/ 2,
7338                                               /*bit_valid*/ 1,
7339                                               /*bit*/ 2);
7340                         ctl_done((union ctl_io *)ctsio);
7341                         return (CTL_RETVAL_COMPLETE);
7342                 }
7343                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7344                 break;
7345         default:
7346                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7347                                       /*sks_valid*/ 1,
7348                                       /*command*/ 1,
7349                                       /*field*/ 2,
7350                                       /*bit_valid*/ 1,
7351                                       /*bit*/ 2);
7352                 ctl_done((union ctl_io *)ctsio);
7353                 return (CTL_RETVAL_COMPLETE);
7354         }
7355
7356         alloc_len = scsi_4btoul(cdb->length);
7357
7358         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7359
7360         ctsio->kern_sg_entries = 0;
7361
7362         if (total_len < alloc_len) {
7363                 ctsio->residual = alloc_len - total_len;
7364                 ctsio->kern_data_len = total_len;
7365                 ctsio->kern_total_len = total_len;
7366         } else {
7367                 ctsio->residual = 0;
7368                 ctsio->kern_data_len = alloc_len;
7369                 ctsio->kern_total_len = alloc_len;
7370         }
7371         ctsio->kern_data_resid = 0;
7372         ctsio->kern_rel_offset = 0;
7373
7374         switch (cdb->options & RSO_OPTIONS_MASK) {
7375         case RSO_OPTIONS_ALL:
7376                 all = (struct scsi_report_supported_opcodes_all *)
7377                     ctsio->kern_data_ptr;
7378                 num = 0;
7379                 for (i = 0; i < 256; i++) {
7380                         entry = &ctl_cmd_table[i];
7381                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7382                                 for (j = 0; j < 32; j++) {
7383                                         sentry = &((const struct ctl_cmd_entry *)
7384                                             entry->execute)[j];
7385                                         if (!ctl_cmd_applicable(
7386                                             lun->be_lun->lun_type, sentry))
7387                                                 continue;
7388                                         descr = &all->descr[num++];
7389                                         descr->opcode = i;
7390                                         scsi_ulto2b(j, descr->service_action);
7391                                         descr->flags = RSO_SERVACTV;
7392                                         scsi_ulto2b(sentry->length,
7393                                             descr->cdb_length);
7394                                 }
7395                         } else {
7396                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7397                                     entry))
7398                                         continue;
7399                                 descr = &all->descr[num++];
7400                                 descr->opcode = i;
7401                                 scsi_ulto2b(0, descr->service_action);
7402                                 descr->flags = 0;
7403                                 scsi_ulto2b(entry->length, descr->cdb_length);
7404                         }
7405                 }
7406                 scsi_ulto4b(
7407                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7408                     all->length);
7409                 break;
7410         case RSO_OPTIONS_OC:
7411                 one = (struct scsi_report_supported_opcodes_one *)
7412                     ctsio->kern_data_ptr;
7413                 entry = &ctl_cmd_table[opcode];
7414                 goto fill_one;
7415         case RSO_OPTIONS_OC_SA:
7416                 one = (struct scsi_report_supported_opcodes_one *)
7417                     ctsio->kern_data_ptr;
7418                 entry = &ctl_cmd_table[opcode];
7419                 entry = &((const struct ctl_cmd_entry *)
7420                     entry->execute)[service_action];
7421 fill_one:
7422                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7423                         one->support = 3;
7424                         scsi_ulto2b(entry->length, one->cdb_length);
7425                         one->cdb_usage[0] = opcode;
7426                         memcpy(&one->cdb_usage[1], entry->usage,
7427                             entry->length - 1);
7428                 } else
7429                         one->support = 1;
7430                 break;
7431         }
7432
7433         ctl_set_success(ctsio);
7434         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7435         ctsio->be_move_done = ctl_config_move_done;
7436         ctl_datamove((union ctl_io *)ctsio);
7437         return(retval);
7438 }
7439
7440 int
7441 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7442 {
7443         struct scsi_report_supported_tmf *cdb;
7444         struct scsi_report_supported_tmf_data *data;
7445         int retval;
7446         int alloc_len, total_len;
7447
7448         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7449
7450         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7451
7452         retval = CTL_RETVAL_COMPLETE;
7453
7454         total_len = sizeof(struct scsi_report_supported_tmf_data);
7455         alloc_len = scsi_4btoul(cdb->length);
7456
7457         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7458
7459         ctsio->kern_sg_entries = 0;
7460
7461         if (total_len < alloc_len) {
7462                 ctsio->residual = alloc_len - total_len;
7463                 ctsio->kern_data_len = total_len;
7464                 ctsio->kern_total_len = total_len;
7465         } else {
7466                 ctsio->residual = 0;
7467                 ctsio->kern_data_len = alloc_len;
7468                 ctsio->kern_total_len = alloc_len;
7469         }
7470         ctsio->kern_data_resid = 0;
7471         ctsio->kern_rel_offset = 0;
7472
7473         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7474         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7475             RST_TRS;
7476         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7477
7478         ctl_set_success(ctsio);
7479         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7480         ctsio->be_move_done = ctl_config_move_done;
7481         ctl_datamove((union ctl_io *)ctsio);
7482         return (retval);
7483 }
7484
7485 int
7486 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7487 {
7488         struct scsi_report_timestamp *cdb;
7489         struct scsi_report_timestamp_data *data;
7490         struct timeval tv;
7491         int64_t timestamp;
7492         int retval;
7493         int alloc_len, total_len;
7494
7495         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7496
7497         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7498
7499         retval = CTL_RETVAL_COMPLETE;
7500
7501         total_len = sizeof(struct scsi_report_timestamp_data);
7502         alloc_len = scsi_4btoul(cdb->length);
7503
7504         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7505
7506         ctsio->kern_sg_entries = 0;
7507
7508         if (total_len < alloc_len) {
7509                 ctsio->residual = alloc_len - total_len;
7510                 ctsio->kern_data_len = total_len;
7511                 ctsio->kern_total_len = total_len;
7512         } else {
7513                 ctsio->residual = 0;
7514                 ctsio->kern_data_len = alloc_len;
7515                 ctsio->kern_total_len = alloc_len;
7516         }
7517         ctsio->kern_data_resid = 0;
7518         ctsio->kern_rel_offset = 0;
7519
7520         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7521         scsi_ulto2b(sizeof(*data) - 2, data->length);
7522         data->origin = RTS_ORIG_OUTSIDE;
7523         getmicrotime(&tv);
7524         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7525         scsi_ulto4b(timestamp >> 16, data->timestamp);
7526         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7527
7528         ctl_set_success(ctsio);
7529         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7530         ctsio->be_move_done = ctl_config_move_done;
7531         ctl_datamove((union ctl_io *)ctsio);
7532         return (retval);
7533 }
7534
7535 int
7536 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7537 {
7538         struct scsi_per_res_in *cdb;
7539         int alloc_len, total_len = 0;
7540         /* struct scsi_per_res_in_rsrv in_data; */
7541         struct ctl_lun *lun;
7542         struct ctl_softc *softc;
7543         uint64_t key;
7544
7545         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7546
7547         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7548
7549         alloc_len = scsi_2btoul(cdb->length);
7550
7551         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7552         softc = lun->ctl_softc;
7553
7554 retry:
7555         mtx_lock(&lun->lun_lock);
7556         switch (cdb->action) {
7557         case SPRI_RK: /* read keys */
7558                 total_len = sizeof(struct scsi_per_res_in_keys) +
7559                         lun->pr_key_count *
7560                         sizeof(struct scsi_per_res_key);
7561                 break;
7562         case SPRI_RR: /* read reservation */
7563                 if (lun->flags & CTL_LUN_PR_RESERVED)
7564                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7565                 else
7566                         total_len = sizeof(struct scsi_per_res_in_header);
7567                 break;
7568         case SPRI_RC: /* report capabilities */
7569                 total_len = sizeof(struct scsi_per_res_cap);
7570                 break;
7571         case SPRI_RS: /* read full status */
7572                 total_len = sizeof(struct scsi_per_res_in_header) +
7573                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7574                     lun->pr_key_count;
7575                 break;
7576         default:
7577                 panic("Invalid PR type %x", cdb->action);
7578         }
7579         mtx_unlock(&lun->lun_lock);
7580
7581         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7582
7583         if (total_len < alloc_len) {
7584                 ctsio->residual = alloc_len - total_len;
7585                 ctsio->kern_data_len = total_len;
7586                 ctsio->kern_total_len = total_len;
7587         } else {
7588                 ctsio->residual = 0;
7589                 ctsio->kern_data_len = alloc_len;
7590                 ctsio->kern_total_len = alloc_len;
7591         }
7592
7593         ctsio->kern_data_resid = 0;
7594         ctsio->kern_rel_offset = 0;
7595         ctsio->kern_sg_entries = 0;
7596
7597         mtx_lock(&lun->lun_lock);
7598         switch (cdb->action) {
7599         case SPRI_RK: { // read keys
7600         struct scsi_per_res_in_keys *res_keys;
7601                 int i, key_count;
7602
7603                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7604
7605                 /*
7606                  * We had to drop the lock to allocate our buffer, which
7607                  * leaves time for someone to come in with another
7608                  * persistent reservation.  (That is unlikely, though,
7609                  * since this should be the only persistent reservation
7610                  * command active right now.)
7611                  */
7612                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7613                     (lun->pr_key_count *
7614                      sizeof(struct scsi_per_res_key)))){
7615                         mtx_unlock(&lun->lun_lock);
7616                         free(ctsio->kern_data_ptr, M_CTL);
7617                         printf("%s: reservation length changed, retrying\n",
7618                                __func__);
7619                         goto retry;
7620                 }
7621
7622                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7623
7624                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7625                              lun->pr_key_count, res_keys->header.length);
7626
7627                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7628                         if ((key = ctl_get_prkey(lun, i)) == 0)
7629                                 continue;
7630
7631                         /*
7632                          * We used lun->pr_key_count to calculate the
7633                          * size to allocate.  If it turns out the number of
7634                          * initiators with the registered flag set is
7635                          * larger than that (i.e. they haven't been kept in
7636                          * sync), we've got a problem.
7637                          */
7638                         if (key_count >= lun->pr_key_count) {
7639 #ifdef NEEDTOPORT
7640                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7641                                             CTL_PR_ERROR,
7642                                             csevent_LogType_Fault,
7643                                             csevent_AlertLevel_Yellow,
7644                                             csevent_FRU_ShelfController,
7645                                             csevent_FRU_Firmware,
7646                                         csevent_FRU_Unknown,
7647                                             "registered keys %d >= key "
7648                                             "count %d", key_count,
7649                                             lun->pr_key_count);
7650 #endif
7651                                 key_count++;
7652                                 continue;
7653                         }
7654                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7655                         key_count++;
7656                 }
7657                 break;
7658         }
7659         case SPRI_RR: { // read reservation
7660                 struct scsi_per_res_in_rsrv *res;
7661                 int tmp_len, header_only;
7662
7663                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7664
7665                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7666
7667                 if (lun->flags & CTL_LUN_PR_RESERVED)
7668                 {
7669                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7670                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7671                                     res->header.length);
7672                         header_only = 0;
7673                 } else {
7674                         tmp_len = sizeof(struct scsi_per_res_in_header);
7675                         scsi_ulto4b(0, res->header.length);
7676                         header_only = 1;
7677                 }
7678
7679                 /*
7680                  * We had to drop the lock to allocate our buffer, which
7681                  * leaves time for someone to come in with another
7682                  * persistent reservation.  (That is unlikely, though,
7683                  * since this should be the only persistent reservation
7684                  * command active right now.)
7685                  */
7686                 if (tmp_len != total_len) {
7687                         mtx_unlock(&lun->lun_lock);
7688                         free(ctsio->kern_data_ptr, M_CTL);
7689                         printf("%s: reservation status changed, retrying\n",
7690                                __func__);
7691                         goto retry;
7692                 }
7693
7694                 /*
7695                  * No reservation held, so we're done.
7696                  */
7697                 if (header_only != 0)
7698                         break;
7699
7700                 /*
7701                  * If the registration is an All Registrants type, the key
7702                  * is 0, since it doesn't really matter.
7703                  */
7704                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7705                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7706                             res->data.reservation);
7707                 }
7708                 res->data.scopetype = lun->res_type;
7709                 break;
7710         }
7711         case SPRI_RC:     //report capabilities
7712         {
7713                 struct scsi_per_res_cap *res_cap;
7714                 uint16_t type_mask;
7715
7716                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7717                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7718                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7719                 type_mask = SPRI_TM_WR_EX_AR |
7720                             SPRI_TM_EX_AC_RO |
7721                             SPRI_TM_WR_EX_RO |
7722                             SPRI_TM_EX_AC |
7723                             SPRI_TM_WR_EX |
7724                             SPRI_TM_EX_AC_AR;
7725                 scsi_ulto2b(type_mask, res_cap->type_mask);
7726                 break;
7727         }
7728         case SPRI_RS: { // read full status
7729                 struct scsi_per_res_in_full *res_status;
7730                 struct scsi_per_res_in_full_desc *res_desc;
7731                 struct ctl_port *port;
7732                 int i, len;
7733
7734                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7735
7736                 /*
7737                  * We had to drop the lock to allocate our buffer, which
7738                  * leaves time for someone to come in with another
7739                  * persistent reservation.  (That is unlikely, though,
7740                  * since this should be the only persistent reservation
7741                  * command active right now.)
7742                  */
7743                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7744                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7745                      lun->pr_key_count)){
7746                         mtx_unlock(&lun->lun_lock);
7747                         free(ctsio->kern_data_ptr, M_CTL);
7748                         printf("%s: reservation length changed, retrying\n",
7749                                __func__);
7750                         goto retry;
7751                 }
7752
7753                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7754
7755                 res_desc = &res_status->desc[0];
7756                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7757                         if ((key = ctl_get_prkey(lun, i)) == 0)
7758                                 continue;
7759
7760                         scsi_u64to8b(key, res_desc->res_key.key);
7761                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7762                             (lun->pr_res_idx == i ||
7763                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7764                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7765                                 res_desc->scopetype = lun->res_type;
7766                         }
7767                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7768                             res_desc->rel_trgt_port_id);
7769                         len = 0;
7770                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7771                         if (port != NULL)
7772                                 len = ctl_create_iid(port,
7773                                     i % CTL_MAX_INIT_PER_PORT,
7774                                     res_desc->transport_id);
7775                         scsi_ulto4b(len, res_desc->additional_length);
7776                         res_desc = (struct scsi_per_res_in_full_desc *)
7777                             &res_desc->transport_id[len];
7778                 }
7779                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7780                     res_status->header.length);
7781                 break;
7782         }
7783         default:
7784                 /*
7785                  * This is a bug, because we just checked for this above,
7786                  * and should have returned an error.
7787                  */
7788                 panic("Invalid PR type %x", cdb->action);
7789                 break; /* NOTREACHED */
7790         }
7791         mtx_unlock(&lun->lun_lock);
7792
7793         ctl_set_success(ctsio);
7794         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7795         ctsio->be_move_done = ctl_config_move_done;
7796         ctl_datamove((union ctl_io *)ctsio);
7797         return (CTL_RETVAL_COMPLETE);
7798 }
7799
7800 /*
7801  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7802  * it should return.
7803  */
7804 static int
7805 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7806                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7807                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7808                 struct scsi_per_res_out_parms* param)
7809 {
7810         union ctl_ha_msg persis_io;
7811         int i;
7812
7813         mtx_lock(&lun->lun_lock);
7814         if (sa_res_key == 0) {
7815                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7816                         /* validate scope and type */
7817                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7818                              SPR_LU_SCOPE) {
7819                                 mtx_unlock(&lun->lun_lock);
7820                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7821                                                       /*sks_valid*/ 1,
7822                                                       /*command*/ 1,
7823                                                       /*field*/ 2,
7824                                                       /*bit_valid*/ 1,
7825                                                       /*bit*/ 4);
7826                                 ctl_done((union ctl_io *)ctsio);
7827                                 return (1);
7828                         }
7829
7830                         if (type>8 || type==2 || type==4 || type==0) {
7831                                 mtx_unlock(&lun->lun_lock);
7832                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7833                                                       /*sks_valid*/ 1,
7834                                                       /*command*/ 1,
7835                                                       /*field*/ 2,
7836                                                       /*bit_valid*/ 1,
7837                                                       /*bit*/ 0);
7838                                 ctl_done((union ctl_io *)ctsio);
7839                                 return (1);
7840                         }
7841
7842                         /*
7843                          * Unregister everybody else and build UA for
7844                          * them
7845                          */
7846                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7847                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7848                                         continue;
7849
7850                                 ctl_clr_prkey(lun, i);
7851                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7852                         }
7853                         lun->pr_key_count = 1;
7854                         lun->res_type = type;
7855                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7856                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7857                                 lun->pr_res_idx = residx;
7858                         lun->PRGeneration++;
7859                         mtx_unlock(&lun->lun_lock);
7860
7861                         /* send msg to other side */
7862                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7863                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7864                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7865                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7866                         persis_io.pr.pr_info.res_type = type;
7867                         memcpy(persis_io.pr.pr_info.sa_res_key,
7868                                param->serv_act_res_key,
7869                                sizeof(param->serv_act_res_key));
7870                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7871                             sizeof(persis_io.pr), M_WAITOK);
7872                 } else {
7873                         /* not all registrants */
7874                         mtx_unlock(&lun->lun_lock);
7875                         free(ctsio->kern_data_ptr, M_CTL);
7876                         ctl_set_invalid_field(ctsio,
7877                                               /*sks_valid*/ 1,
7878                                               /*command*/ 0,
7879                                               /*field*/ 8,
7880                                               /*bit_valid*/ 0,
7881                                               /*bit*/ 0);
7882                         ctl_done((union ctl_io *)ctsio);
7883                         return (1);
7884                 }
7885         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7886                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7887                 int found = 0;
7888
7889                 if (res_key == sa_res_key) {
7890                         /* special case */
7891                         /*
7892                          * The spec implies this is not good but doesn't
7893                          * say what to do. There are two choices either
7894                          * generate a res conflict or check condition
7895                          * with illegal field in parameter data. Since
7896                          * that is what is done when the sa_res_key is
7897                          * zero I'll take that approach since this has
7898                          * to do with the sa_res_key.
7899                          */
7900                         mtx_unlock(&lun->lun_lock);
7901                         free(ctsio->kern_data_ptr, M_CTL);
7902                         ctl_set_invalid_field(ctsio,
7903                                               /*sks_valid*/ 1,
7904                                               /*command*/ 0,
7905                                               /*field*/ 8,
7906                                               /*bit_valid*/ 0,
7907                                               /*bit*/ 0);
7908                         ctl_done((union ctl_io *)ctsio);
7909                         return (1);
7910                 }
7911
7912                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7913                         if (ctl_get_prkey(lun, i) != sa_res_key)
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                 if (!found) {
7922                         mtx_unlock(&lun->lun_lock);
7923                         free(ctsio->kern_data_ptr, M_CTL);
7924                         ctl_set_reservation_conflict(ctsio);
7925                         ctl_done((union ctl_io *)ctsio);
7926                         return (CTL_RETVAL_COMPLETE);
7927                 }
7928                 lun->PRGeneration++;
7929                 mtx_unlock(&lun->lun_lock);
7930
7931                 /* send msg to other side */
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         } else {
7943                 /* Reserved but not all registrants */
7944                 /* sa_res_key is res holder */
7945                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7946                         /* validate scope and type */
7947                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7948                              SPR_LU_SCOPE) {
7949                                 mtx_unlock(&lun->lun_lock);
7950                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7951                                                       /*sks_valid*/ 1,
7952                                                       /*command*/ 1,
7953                                                       /*field*/ 2,
7954                                                       /*bit_valid*/ 1,
7955                                                       /*bit*/ 4);
7956                                 ctl_done((union ctl_io *)ctsio);
7957                                 return (1);
7958                         }
7959
7960                         if (type>8 || type==2 || type==4 || type==0) {
7961                                 mtx_unlock(&lun->lun_lock);
7962                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7963                                                       /*sks_valid*/ 1,
7964                                                       /*command*/ 1,
7965                                                       /*field*/ 2,
7966                                                       /*bit_valid*/ 1,
7967                                                       /*bit*/ 0);
7968                                 ctl_done((union ctl_io *)ctsio);
7969                                 return (1);
7970                         }
7971
7972                         /*
7973                          * Do the following:
7974                          * if sa_res_key != res_key remove all
7975                          * registrants w/sa_res_key and generate UA
7976                          * for these registrants(Registrations
7977                          * Preempted) if it wasn't an exclusive
7978                          * reservation generate UA(Reservations
7979                          * Preempted) for all other registered nexuses
7980                          * if the type has changed. Establish the new
7981                          * reservation and holder. If res_key and
7982                          * sa_res_key are the same do the above
7983                          * except don't unregister the res holder.
7984                          */
7985
7986                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7987                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7988                                         continue;
7989
7990                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7991                                         ctl_clr_prkey(lun, i);
7992                                         lun->pr_key_count--;
7993                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7994                                 } else if (type != lun->res_type
7995                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
7996                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7997                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7998                                 }
7999                         }
8000                         lun->res_type = type;
8001                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8002                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8003                                 lun->pr_res_idx = residx;
8004                         else
8005                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8006                         lun->PRGeneration++;
8007                         mtx_unlock(&lun->lun_lock);
8008
8009                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8010                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8011                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8012                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8013                         persis_io.pr.pr_info.res_type = type;
8014                         memcpy(persis_io.pr.pr_info.sa_res_key,
8015                                param->serv_act_res_key,
8016                                sizeof(param->serv_act_res_key));
8017                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8018                             sizeof(persis_io.pr), M_WAITOK);
8019                 } else {
8020                         /*
8021                          * sa_res_key is not the res holder just
8022                          * remove registrants
8023                          */
8024                         int found=0;
8025
8026                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8027                                 if (sa_res_key != ctl_get_prkey(lun, i))
8028                                         continue;
8029
8030                                 found = 1;
8031                                 ctl_clr_prkey(lun, i);
8032                                 lun->pr_key_count--;
8033                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8034                         }
8035
8036                         if (!found) {
8037                                 mtx_unlock(&lun->lun_lock);
8038                                 free(ctsio->kern_data_ptr, M_CTL);
8039                                 ctl_set_reservation_conflict(ctsio);
8040                                 ctl_done((union ctl_io *)ctsio);
8041                                 return (1);
8042                         }
8043                         lun->PRGeneration++;
8044                         mtx_unlock(&lun->lun_lock);
8045
8046                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8047                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8048                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8049                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8050                         persis_io.pr.pr_info.res_type = type;
8051                         memcpy(persis_io.pr.pr_info.sa_res_key,
8052                                param->serv_act_res_key,
8053                                sizeof(param->serv_act_res_key));
8054                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8055                             sizeof(persis_io.pr), M_WAITOK);
8056                 }
8057         }
8058         return (0);
8059 }
8060
8061 static void
8062 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8063 {
8064         uint64_t sa_res_key;
8065         int i;
8066
8067         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8068
8069         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8070          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8071          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8072                 if (sa_res_key == 0) {
8073                         /*
8074                          * Unregister everybody else and build UA for
8075                          * them
8076                          */
8077                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8078                                 if (i == msg->pr.pr_info.residx ||
8079                                     ctl_get_prkey(lun, i) == 0)
8080                                         continue;
8081
8082                                 ctl_clr_prkey(lun, i);
8083                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8084                         }
8085
8086                         lun->pr_key_count = 1;
8087                         lun->res_type = msg->pr.pr_info.res_type;
8088                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8089                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8090                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8091                 } else {
8092                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8093                                 if (sa_res_key == ctl_get_prkey(lun, i))
8094                                         continue;
8095
8096                                 ctl_clr_prkey(lun, i);
8097                                 lun->pr_key_count--;
8098                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8099                         }
8100                 }
8101         } else {
8102                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8103                         if (i == msg->pr.pr_info.residx ||
8104                             ctl_get_prkey(lun, i) == 0)
8105                                 continue;
8106
8107                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8108                                 ctl_clr_prkey(lun, i);
8109                                 lun->pr_key_count--;
8110                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8111                         } else if (msg->pr.pr_info.res_type != lun->res_type
8112                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8113                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8114                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8115                         }
8116                 }
8117                 lun->res_type = msg->pr.pr_info.res_type;
8118                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8119                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8120                         lun->pr_res_idx = msg->pr.pr_info.residx;
8121                 else
8122                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8123         }
8124         lun->PRGeneration++;
8125
8126 }
8127
8128
8129 int
8130 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8131 {
8132         int retval;
8133         u_int32_t param_len;
8134         struct scsi_per_res_out *cdb;
8135         struct ctl_lun *lun;
8136         struct scsi_per_res_out_parms* param;
8137         struct ctl_softc *softc;
8138         uint32_t residx;
8139         uint64_t res_key, sa_res_key, key;
8140         uint8_t type;
8141         union ctl_ha_msg persis_io;
8142         int    i;
8143
8144         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8145
8146         retval = CTL_RETVAL_COMPLETE;
8147
8148         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8149         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8150         softc = lun->ctl_softc;
8151
8152         /*
8153          * We only support whole-LUN scope.  The scope & type are ignored for
8154          * register, register and ignore existing key and clear.
8155          * We sometimes ignore scope and type on preempts too!!
8156          * Verify reservation type here as well.
8157          */
8158         type = cdb->scope_type & SPR_TYPE_MASK;
8159         if ((cdb->action == SPRO_RESERVE)
8160          || (cdb->action == SPRO_RELEASE)) {
8161                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8162                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8163                                               /*sks_valid*/ 1,
8164                                               /*command*/ 1,
8165                                               /*field*/ 2,
8166                                               /*bit_valid*/ 1,
8167                                               /*bit*/ 4);
8168                         ctl_done((union ctl_io *)ctsio);
8169                         return (CTL_RETVAL_COMPLETE);
8170                 }
8171
8172                 if (type>8 || type==2 || type==4 || type==0) {
8173                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8174                                               /*sks_valid*/ 1,
8175                                               /*command*/ 1,
8176                                               /*field*/ 2,
8177                                               /*bit_valid*/ 1,
8178                                               /*bit*/ 0);
8179                         ctl_done((union ctl_io *)ctsio);
8180                         return (CTL_RETVAL_COMPLETE);
8181                 }
8182         }
8183
8184         param_len = scsi_4btoul(cdb->length);
8185
8186         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8187                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8188                 ctsio->kern_data_len = param_len;
8189                 ctsio->kern_total_len = param_len;
8190                 ctsio->kern_data_resid = 0;
8191                 ctsio->kern_rel_offset = 0;
8192                 ctsio->kern_sg_entries = 0;
8193                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8194                 ctsio->be_move_done = ctl_config_move_done;
8195                 ctl_datamove((union ctl_io *)ctsio);
8196
8197                 return (CTL_RETVAL_COMPLETE);
8198         }
8199
8200         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8201
8202         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8203         res_key = scsi_8btou64(param->res_key.key);
8204         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8205
8206         /*
8207          * Validate the reservation key here except for SPRO_REG_IGNO
8208          * This must be done for all other service actions
8209          */
8210         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8211                 mtx_lock(&lun->lun_lock);
8212                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8213                         if (res_key != key) {
8214                                 /*
8215                                  * The current key passed in doesn't match
8216                                  * the one the initiator previously
8217                                  * registered.
8218                                  */
8219                                 mtx_unlock(&lun->lun_lock);
8220                                 free(ctsio->kern_data_ptr, M_CTL);
8221                                 ctl_set_reservation_conflict(ctsio);
8222                                 ctl_done((union ctl_io *)ctsio);
8223                                 return (CTL_RETVAL_COMPLETE);
8224                         }
8225                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8226                         /*
8227                          * We are not registered
8228                          */
8229                         mtx_unlock(&lun->lun_lock);
8230                         free(ctsio->kern_data_ptr, M_CTL);
8231                         ctl_set_reservation_conflict(ctsio);
8232                         ctl_done((union ctl_io *)ctsio);
8233                         return (CTL_RETVAL_COMPLETE);
8234                 } else if (res_key != 0) {
8235                         /*
8236                          * We are not registered and trying to register but
8237                          * the register key isn't zero.
8238                          */
8239                         mtx_unlock(&lun->lun_lock);
8240                         free(ctsio->kern_data_ptr, M_CTL);
8241                         ctl_set_reservation_conflict(ctsio);
8242                         ctl_done((union ctl_io *)ctsio);
8243                         return (CTL_RETVAL_COMPLETE);
8244                 }
8245                 mtx_unlock(&lun->lun_lock);
8246         }
8247
8248         switch (cdb->action & SPRO_ACTION_MASK) {
8249         case SPRO_REGISTER:
8250         case SPRO_REG_IGNO: {
8251
8252 #if 0
8253                 printf("Registration received\n");
8254 #endif
8255
8256                 /*
8257                  * We don't support any of these options, as we report in
8258                  * the read capabilities request (see
8259                  * ctl_persistent_reserve_in(), above).
8260                  */
8261                 if ((param->flags & SPR_SPEC_I_PT)
8262                  || (param->flags & SPR_ALL_TG_PT)
8263                  || (param->flags & SPR_APTPL)) {
8264                         int bit_ptr;
8265
8266                         if (param->flags & SPR_APTPL)
8267                                 bit_ptr = 0;
8268                         else if (param->flags & SPR_ALL_TG_PT)
8269                                 bit_ptr = 2;
8270                         else /* SPR_SPEC_I_PT */
8271                                 bit_ptr = 3;
8272
8273                         free(ctsio->kern_data_ptr, M_CTL);
8274                         ctl_set_invalid_field(ctsio,
8275                                               /*sks_valid*/ 1,
8276                                               /*command*/ 0,
8277                                               /*field*/ 20,
8278                                               /*bit_valid*/ 1,
8279                                               /*bit*/ bit_ptr);
8280                         ctl_done((union ctl_io *)ctsio);
8281                         return (CTL_RETVAL_COMPLETE);
8282                 }
8283
8284                 mtx_lock(&lun->lun_lock);
8285
8286                 /*
8287                  * The initiator wants to clear the
8288                  * key/unregister.
8289                  */
8290                 if (sa_res_key == 0) {
8291                         if ((res_key == 0
8292                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8293                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8294                           && ctl_get_prkey(lun, residx) == 0)) {
8295                                 mtx_unlock(&lun->lun_lock);
8296                                 goto done;
8297                         }
8298
8299                         ctl_clr_prkey(lun, residx);
8300                         lun->pr_key_count--;
8301
8302                         if (residx == lun->pr_res_idx) {
8303                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8304                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8305
8306                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8307                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8308                                  && lun->pr_key_count) {
8309                                         /*
8310                                          * If the reservation is a registrants
8311                                          * only type we need to generate a UA
8312                                          * for other registered inits.  The
8313                                          * sense code should be RESERVATIONS
8314                                          * RELEASED
8315                                          */
8316
8317                                         for (i = softc->init_min; i < softc->init_max; i++){
8318                                                 if (ctl_get_prkey(lun, i) == 0)
8319                                                         continue;
8320                                                 ctl_est_ua(lun, i,
8321                                                     CTL_UA_RES_RELEASE);
8322                                         }
8323                                 }
8324                                 lun->res_type = 0;
8325                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8326                                 if (lun->pr_key_count==0) {
8327                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8328                                         lun->res_type = 0;
8329                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8330                                 }
8331                         }
8332                         lun->PRGeneration++;
8333                         mtx_unlock(&lun->lun_lock);
8334
8335                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8336                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8337                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8338                         persis_io.pr.pr_info.residx = residx;
8339                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8340                             sizeof(persis_io.pr), M_WAITOK);
8341                 } else /* sa_res_key != 0 */ {
8342
8343                         /*
8344                          * If we aren't registered currently then increment
8345                          * the key count and set the registered flag.
8346                          */
8347                         ctl_alloc_prkey(lun, residx);
8348                         if (ctl_get_prkey(lun, residx) == 0)
8349                                 lun->pr_key_count++;
8350                         ctl_set_prkey(lun, residx, sa_res_key);
8351                         lun->PRGeneration++;
8352                         mtx_unlock(&lun->lun_lock);
8353
8354                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8355                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8356                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8357                         persis_io.pr.pr_info.residx = residx;
8358                         memcpy(persis_io.pr.pr_info.sa_res_key,
8359                                param->serv_act_res_key,
8360                                sizeof(param->serv_act_res_key));
8361                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8362                             sizeof(persis_io.pr), M_WAITOK);
8363                 }
8364
8365                 break;
8366         }
8367         case SPRO_RESERVE:
8368 #if 0
8369                 printf("Reserve executed type %d\n", type);
8370 #endif
8371                 mtx_lock(&lun->lun_lock);
8372                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8373                         /*
8374                          * if this isn't the reservation holder and it's
8375                          * not a "all registrants" type or if the type is
8376                          * different then we have a conflict
8377                          */
8378                         if ((lun->pr_res_idx != residx
8379                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8380                          || lun->res_type != type) {
8381                                 mtx_unlock(&lun->lun_lock);
8382                                 free(ctsio->kern_data_ptr, M_CTL);
8383                                 ctl_set_reservation_conflict(ctsio);
8384                                 ctl_done((union ctl_io *)ctsio);
8385                                 return (CTL_RETVAL_COMPLETE);
8386                         }
8387                         mtx_unlock(&lun->lun_lock);
8388                 } else /* create a reservation */ {
8389                         /*
8390                          * If it's not an "all registrants" type record
8391                          * reservation holder
8392                          */
8393                         if (type != SPR_TYPE_WR_EX_AR
8394                          && type != SPR_TYPE_EX_AC_AR)
8395                                 lun->pr_res_idx = residx; /* Res holder */
8396                         else
8397                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8398
8399                         lun->flags |= CTL_LUN_PR_RESERVED;
8400                         lun->res_type = type;
8401
8402                         mtx_unlock(&lun->lun_lock);
8403
8404                         /* send msg to other side */
8405                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8406                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8407                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8408                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8409                         persis_io.pr.pr_info.res_type = type;
8410                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8411                             sizeof(persis_io.pr), M_WAITOK);
8412                 }
8413                 break;
8414
8415         case SPRO_RELEASE:
8416                 mtx_lock(&lun->lun_lock);
8417                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8418                         /* No reservation exists return good status */
8419                         mtx_unlock(&lun->lun_lock);
8420                         goto done;
8421                 }
8422                 /*
8423                  * Is this nexus a reservation holder?
8424                  */
8425                 if (lun->pr_res_idx != residx
8426                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8427                         /*
8428                          * not a res holder return good status but
8429                          * do nothing
8430                          */
8431                         mtx_unlock(&lun->lun_lock);
8432                         goto done;
8433                 }
8434
8435                 if (lun->res_type != type) {
8436                         mtx_unlock(&lun->lun_lock);
8437                         free(ctsio->kern_data_ptr, M_CTL);
8438                         ctl_set_illegal_pr_release(ctsio);
8439                         ctl_done((union ctl_io *)ctsio);
8440                         return (CTL_RETVAL_COMPLETE);
8441                 }
8442
8443                 /* okay to release */
8444                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8445                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8446                 lun->res_type = 0;
8447
8448                 /*
8449                  * if this isn't an exclusive access
8450                  * res generate UA for all other
8451                  * registrants.
8452                  */
8453                 if (type != SPR_TYPE_EX_AC
8454                  && type != SPR_TYPE_WR_EX) {
8455                         for (i = softc->init_min; i < softc->init_max; i++) {
8456                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8457                                         continue;
8458                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8459                         }
8460                 }
8461                 mtx_unlock(&lun->lun_lock);
8462
8463                 /* Send msg to other side */
8464                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8465                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8466                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8467                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8468                      sizeof(persis_io.pr), M_WAITOK);
8469                 break;
8470
8471         case SPRO_CLEAR:
8472                 /* send msg to other side */
8473
8474                 mtx_lock(&lun->lun_lock);
8475                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8476                 lun->res_type = 0;
8477                 lun->pr_key_count = 0;
8478                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8479
8480                 ctl_clr_prkey(lun, residx);
8481                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8482                         if (ctl_get_prkey(lun, i) != 0) {
8483                                 ctl_clr_prkey(lun, i);
8484                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8485                         }
8486                 lun->PRGeneration++;
8487                 mtx_unlock(&lun->lun_lock);
8488
8489                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8490                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8491                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8492                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8493                      sizeof(persis_io.pr), M_WAITOK);
8494                 break;
8495
8496         case SPRO_PREEMPT:
8497         case SPRO_PRE_ABO: {
8498                 int nretval;
8499
8500                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8501                                           residx, ctsio, cdb, param);
8502                 if (nretval != 0)
8503                         return (CTL_RETVAL_COMPLETE);
8504                 break;
8505         }
8506         default:
8507                 panic("Invalid PR type %x", cdb->action);
8508         }
8509
8510 done:
8511         free(ctsio->kern_data_ptr, M_CTL);
8512         ctl_set_success(ctsio);
8513         ctl_done((union ctl_io *)ctsio);
8514
8515         return (retval);
8516 }
8517
8518 /*
8519  * This routine is for handling a message from the other SC pertaining to
8520  * persistent reserve out. All the error checking will have been done
8521  * so only perorming the action need be done here to keep the two
8522  * in sync.
8523  */
8524 static void
8525 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8526 {
8527         struct ctl_lun *lun;
8528         struct ctl_softc *softc;
8529         int i;
8530         uint32_t residx, targ_lun;
8531
8532         softc = control_softc;
8533         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8534         mtx_lock(&softc->ctl_lock);
8535         if ((targ_lun >= CTL_MAX_LUNS) ||
8536             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8537                 mtx_unlock(&softc->ctl_lock);
8538                 return;
8539         }
8540         mtx_lock(&lun->lun_lock);
8541         mtx_unlock(&softc->ctl_lock);
8542         if (lun->flags & CTL_LUN_DISABLED) {
8543                 mtx_unlock(&lun->lun_lock);
8544                 return;
8545         }
8546         residx = ctl_get_initindex(&msg->hdr.nexus);
8547         switch(msg->pr.pr_info.action) {
8548         case CTL_PR_REG_KEY:
8549                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8550                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8551                         lun->pr_key_count++;
8552                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8553                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8554                 lun->PRGeneration++;
8555                 break;
8556
8557         case CTL_PR_UNREG_KEY:
8558                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8559                 lun->pr_key_count--;
8560
8561                 /* XXX Need to see if the reservation has been released */
8562                 /* if so do we need to generate UA? */
8563                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8564                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8565                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8566
8567                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8568                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8569                          && lun->pr_key_count) {
8570                                 /*
8571                                  * If the reservation is a registrants
8572                                  * only type we need to generate a UA
8573                                  * for other registered inits.  The
8574                                  * sense code should be RESERVATIONS
8575                                  * RELEASED
8576                                  */
8577
8578                                 for (i = softc->init_min; i < softc->init_max; i++) {
8579                                         if (ctl_get_prkey(lun, i) == 0)
8580                                                 continue;
8581
8582                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8583                                 }
8584                         }
8585                         lun->res_type = 0;
8586                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8587                         if (lun->pr_key_count==0) {
8588                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8589                                 lun->res_type = 0;
8590                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8591                         }
8592                 }
8593                 lun->PRGeneration++;
8594                 break;
8595
8596         case CTL_PR_RESERVE:
8597                 lun->flags |= CTL_LUN_PR_RESERVED;
8598                 lun->res_type = msg->pr.pr_info.res_type;
8599                 lun->pr_res_idx = msg->pr.pr_info.residx;
8600
8601                 break;
8602
8603         case CTL_PR_RELEASE:
8604                 /*
8605                  * if this isn't an exclusive access res generate UA for all
8606                  * other registrants.
8607                  */
8608                 if (lun->res_type != SPR_TYPE_EX_AC
8609                  && lun->res_type != SPR_TYPE_WR_EX) {
8610                         for (i = softc->init_min; i < softc->init_max; i++)
8611                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8612                                         continue;
8613                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8614                 }
8615
8616                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8617                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8618                 lun->res_type = 0;
8619                 break;
8620
8621         case CTL_PR_PREEMPT:
8622                 ctl_pro_preempt_other(lun, msg);
8623                 break;
8624         case CTL_PR_CLEAR:
8625                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8626                 lun->res_type = 0;
8627                 lun->pr_key_count = 0;
8628                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8629
8630                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8631                         if (ctl_get_prkey(lun, i) == 0)
8632                                 continue;
8633                         ctl_clr_prkey(lun, i);
8634                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8635                 }
8636                 lun->PRGeneration++;
8637                 break;
8638         }
8639
8640         mtx_unlock(&lun->lun_lock);
8641 }
8642
8643 int
8644 ctl_read_write(struct ctl_scsiio *ctsio)
8645 {
8646         struct ctl_lun *lun;
8647         struct ctl_lba_len_flags *lbalen;
8648         uint64_t lba;
8649         uint32_t num_blocks;
8650         int flags, retval;
8651         int isread;
8652
8653         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8654
8655         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8656
8657         flags = 0;
8658         retval = CTL_RETVAL_COMPLETE;
8659
8660         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8661               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8662         switch (ctsio->cdb[0]) {
8663         case READ_6:
8664         case WRITE_6: {
8665                 struct scsi_rw_6 *cdb;
8666
8667                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8668
8669                 lba = scsi_3btoul(cdb->addr);
8670                 /* only 5 bits are valid in the most significant address byte */
8671                 lba &= 0x1fffff;
8672                 num_blocks = cdb->length;
8673                 /*
8674                  * This is correct according to SBC-2.
8675                  */
8676                 if (num_blocks == 0)
8677                         num_blocks = 256;
8678                 break;
8679         }
8680         case READ_10:
8681         case WRITE_10: {
8682                 struct scsi_rw_10 *cdb;
8683
8684                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8685                 if (cdb->byte2 & SRW10_FUA)
8686                         flags |= CTL_LLF_FUA;
8687                 if (cdb->byte2 & SRW10_DPO)
8688                         flags |= CTL_LLF_DPO;
8689                 lba = scsi_4btoul(cdb->addr);
8690                 num_blocks = scsi_2btoul(cdb->length);
8691                 break;
8692         }
8693         case WRITE_VERIFY_10: {
8694                 struct scsi_write_verify_10 *cdb;
8695
8696                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8697                 flags |= CTL_LLF_FUA;
8698                 if (cdb->byte2 & SWV_DPO)
8699                         flags |= CTL_LLF_DPO;
8700                 lba = scsi_4btoul(cdb->addr);
8701                 num_blocks = scsi_2btoul(cdb->length);
8702                 break;
8703         }
8704         case READ_12:
8705         case WRITE_12: {
8706                 struct scsi_rw_12 *cdb;
8707
8708                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8709                 if (cdb->byte2 & SRW12_FUA)
8710                         flags |= CTL_LLF_FUA;
8711                 if (cdb->byte2 & SRW12_DPO)
8712                         flags |= CTL_LLF_DPO;
8713                 lba = scsi_4btoul(cdb->addr);
8714                 num_blocks = scsi_4btoul(cdb->length);
8715                 break;
8716         }
8717         case WRITE_VERIFY_12: {
8718                 struct scsi_write_verify_12 *cdb;
8719
8720                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8721                 flags |= CTL_LLF_FUA;
8722                 if (cdb->byte2 & SWV_DPO)
8723                         flags |= CTL_LLF_DPO;
8724                 lba = scsi_4btoul(cdb->addr);
8725                 num_blocks = scsi_4btoul(cdb->length);
8726                 break;
8727         }
8728         case READ_16:
8729         case WRITE_16: {
8730                 struct scsi_rw_16 *cdb;
8731
8732                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8733                 if (cdb->byte2 & SRW12_FUA)
8734                         flags |= CTL_LLF_FUA;
8735                 if (cdb->byte2 & SRW12_DPO)
8736                         flags |= CTL_LLF_DPO;
8737                 lba = scsi_8btou64(cdb->addr);
8738                 num_blocks = scsi_4btoul(cdb->length);
8739                 break;
8740         }
8741         case WRITE_ATOMIC_16: {
8742                 struct scsi_rw_16 *cdb;
8743
8744                 if (lun->be_lun->atomicblock == 0) {
8745                         ctl_set_invalid_opcode(ctsio);
8746                         ctl_done((union ctl_io *)ctsio);
8747                         return (CTL_RETVAL_COMPLETE);
8748                 }
8749
8750                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8751                 if (cdb->byte2 & SRW12_FUA)
8752                         flags |= CTL_LLF_FUA;
8753                 if (cdb->byte2 & SRW12_DPO)
8754                         flags |= CTL_LLF_DPO;
8755                 lba = scsi_8btou64(cdb->addr);
8756                 num_blocks = scsi_4btoul(cdb->length);
8757                 if (num_blocks > lun->be_lun->atomicblock) {
8758                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8759                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8760                             /*bit*/ 0);
8761                         ctl_done((union ctl_io *)ctsio);
8762                         return (CTL_RETVAL_COMPLETE);
8763                 }
8764                 break;
8765         }
8766         case WRITE_VERIFY_16: {
8767                 struct scsi_write_verify_16 *cdb;
8768
8769                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8770                 flags |= CTL_LLF_FUA;
8771                 if (cdb->byte2 & SWV_DPO)
8772                         flags |= CTL_LLF_DPO;
8773                 lba = scsi_8btou64(cdb->addr);
8774                 num_blocks = scsi_4btoul(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          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8805          * translates to 256 blocks for those commands.
8806          */
8807         if (num_blocks == 0) {
8808                 ctl_set_success(ctsio);
8809                 ctl_done((union ctl_io *)ctsio);
8810                 return (CTL_RETVAL_COMPLETE);
8811         }
8812
8813         /* Set FUA and/or DPO if caches are disabled. */
8814         if (isread) {
8815                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8816                     SCP_RCD) != 0)
8817                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8818         } else {
8819                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8820                     SCP_WCE) == 0)
8821                         flags |= CTL_LLF_FUA;
8822         }
8823
8824         lbalen = (struct ctl_lba_len_flags *)
8825             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8826         lbalen->lba = lba;
8827         lbalen->len = num_blocks;
8828         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8829
8830         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8831         ctsio->kern_rel_offset = 0;
8832
8833         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8834
8835         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8836
8837         return (retval);
8838 }
8839
8840 static int
8841 ctl_cnw_cont(union ctl_io *io)
8842 {
8843         struct ctl_scsiio *ctsio;
8844         struct ctl_lun *lun;
8845         struct ctl_lba_len_flags *lbalen;
8846         int retval;
8847
8848         ctsio = &io->scsiio;
8849         ctsio->io_hdr.status = CTL_STATUS_NONE;
8850         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8851         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8852         lbalen = (struct ctl_lba_len_flags *)
8853             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8854         lbalen->flags &= ~CTL_LLF_COMPARE;
8855         lbalen->flags |= CTL_LLF_WRITE;
8856
8857         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8858         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8859         return (retval);
8860 }
8861
8862 int
8863 ctl_cnw(struct ctl_scsiio *ctsio)
8864 {
8865         struct ctl_lun *lun;
8866         struct ctl_lba_len_flags *lbalen;
8867         uint64_t lba;
8868         uint32_t num_blocks;
8869         int flags, retval;
8870
8871         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8872
8873         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8874
8875         flags = 0;
8876         retval = CTL_RETVAL_COMPLETE;
8877
8878         switch (ctsio->cdb[0]) {
8879         case COMPARE_AND_WRITE: {
8880                 struct scsi_compare_and_write *cdb;
8881
8882                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8883                 if (cdb->byte2 & SRW10_FUA)
8884                         flags |= CTL_LLF_FUA;
8885                 if (cdb->byte2 & SRW10_DPO)
8886                         flags |= CTL_LLF_DPO;
8887                 lba = scsi_8btou64(cdb->addr);
8888                 num_blocks = cdb->length;
8889                 break;
8890         }
8891         default:
8892                 /*
8893                  * We got a command we don't support.  This shouldn't
8894                  * happen, commands should be filtered out above us.
8895                  */
8896                 ctl_set_invalid_opcode(ctsio);
8897                 ctl_done((union ctl_io *)ctsio);
8898
8899                 return (CTL_RETVAL_COMPLETE);
8900                 break; /* NOTREACHED */
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         /* Set FUA if write cache is disabled. */
8926         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8927             SCP_WCE) == 0)
8928                 flags |= CTL_LLF_FUA;
8929
8930         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8931         ctsio->kern_rel_offset = 0;
8932
8933         /*
8934          * Set the IO_CONT flag, so that if this I/O gets passed to
8935          * ctl_data_submit_done(), it'll get passed back to
8936          * ctl_ctl_cnw_cont() for further processing.
8937          */
8938         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8939         ctsio->io_cont = ctl_cnw_cont;
8940
8941         lbalen = (struct ctl_lba_len_flags *)
8942             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8943         lbalen->lba = lba;
8944         lbalen->len = num_blocks;
8945         lbalen->flags = CTL_LLF_COMPARE | flags;
8946
8947         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8948         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8949         return (retval);
8950 }
8951
8952 int
8953 ctl_verify(struct ctl_scsiio *ctsio)
8954 {
8955         struct ctl_lun *lun;
8956         struct ctl_lba_len_flags *lbalen;
8957         uint64_t lba;
8958         uint32_t num_blocks;
8959         int bytchk, flags;
8960         int retval;
8961
8962         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8963
8964         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8965
8966         bytchk = 0;
8967         flags = CTL_LLF_FUA;
8968         retval = CTL_RETVAL_COMPLETE;
8969
8970         switch (ctsio->cdb[0]) {
8971         case VERIFY_10: {
8972                 struct scsi_verify_10 *cdb;
8973
8974                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8975                 if (cdb->byte2 & SVFY_BYTCHK)
8976                         bytchk = 1;
8977                 if (cdb->byte2 & SVFY_DPO)
8978                         flags |= CTL_LLF_DPO;
8979                 lba = scsi_4btoul(cdb->addr);
8980                 num_blocks = scsi_2btoul(cdb->length);
8981                 break;
8982         }
8983         case VERIFY_12: {
8984                 struct scsi_verify_12 *cdb;
8985
8986                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8987                 if (cdb->byte2 & SVFY_BYTCHK)
8988                         bytchk = 1;
8989                 if (cdb->byte2 & SVFY_DPO)
8990                         flags |= CTL_LLF_DPO;
8991                 lba = scsi_4btoul(cdb->addr);
8992                 num_blocks = scsi_4btoul(cdb->length);
8993                 break;
8994         }
8995         case VERIFY_16: {
8996                 struct scsi_rw_16 *cdb;
8997
8998                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8999                 if (cdb->byte2 & SVFY_BYTCHK)
9000                         bytchk = 1;
9001                 if (cdb->byte2 & SVFY_DPO)
9002                         flags |= CTL_LLF_DPO;
9003                 lba = scsi_8btou64(cdb->addr);
9004                 num_blocks = scsi_4btoul(cdb->length);
9005                 break;
9006         }
9007         default:
9008                 /*
9009                  * We got a command we don't support.  This shouldn't
9010                  * happen, commands should be filtered out above us.
9011                  */
9012                 ctl_set_invalid_opcode(ctsio);
9013                 ctl_done((union ctl_io *)ctsio);
9014                 return (CTL_RETVAL_COMPLETE);
9015         }
9016
9017         /*
9018          * The first check is to make sure we're in bounds, the second
9019          * check is to catch wrap-around problems.  If the lba + num blocks
9020          * is less than the lba, then we've wrapped around and the block
9021          * range is invalid anyway.
9022          */
9023         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9024          || ((lba + num_blocks) < lba)) {
9025                 ctl_set_lba_out_of_range(ctsio);
9026                 ctl_done((union ctl_io *)ctsio);
9027                 return (CTL_RETVAL_COMPLETE);
9028         }
9029
9030         /*
9031          * According to SBC-3, a transfer length of 0 is not an error.
9032          */
9033         if (num_blocks == 0) {
9034                 ctl_set_success(ctsio);
9035                 ctl_done((union ctl_io *)ctsio);
9036                 return (CTL_RETVAL_COMPLETE);
9037         }
9038
9039         lbalen = (struct ctl_lba_len_flags *)
9040             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9041         lbalen->lba = lba;
9042         lbalen->len = num_blocks;
9043         if (bytchk) {
9044                 lbalen->flags = CTL_LLF_COMPARE | flags;
9045                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9046         } else {
9047                 lbalen->flags = CTL_LLF_VERIFY | flags;
9048                 ctsio->kern_total_len = 0;
9049         }
9050         ctsio->kern_rel_offset = 0;
9051
9052         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9053         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9054         return (retval);
9055 }
9056
9057 int
9058 ctl_report_luns(struct ctl_scsiio *ctsio)
9059 {
9060         struct ctl_softc *softc = control_softc;
9061         struct scsi_report_luns *cdb;
9062         struct scsi_report_luns_data *lun_data;
9063         struct ctl_lun *lun, *request_lun;
9064         struct ctl_port *port;
9065         int num_luns, retval;
9066         uint32_t alloc_len, lun_datalen;
9067         int num_filled, well_known;
9068         uint32_t initidx, targ_lun_id, lun_id;
9069
9070         retval = CTL_RETVAL_COMPLETE;
9071         well_known = 0;
9072
9073         cdb = (struct scsi_report_luns *)ctsio->cdb;
9074         port = ctl_io_port(&ctsio->io_hdr);
9075
9076         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9077
9078         mtx_lock(&softc->ctl_lock);
9079         num_luns = 0;
9080         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9081                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9082                         num_luns++;
9083         }
9084         mtx_unlock(&softc->ctl_lock);
9085
9086         switch (cdb->select_report) {
9087         case RPL_REPORT_DEFAULT:
9088         case RPL_REPORT_ALL:
9089                 break;
9090         case RPL_REPORT_WELLKNOWN:
9091                 well_known = 1;
9092                 num_luns = 0;
9093                 break;
9094         default:
9095                 ctl_set_invalid_field(ctsio,
9096                                       /*sks_valid*/ 1,
9097                                       /*command*/ 1,
9098                                       /*field*/ 2,
9099                                       /*bit_valid*/ 0,
9100                                       /*bit*/ 0);
9101                 ctl_done((union ctl_io *)ctsio);
9102                 return (retval);
9103                 break; /* NOTREACHED */
9104         }
9105
9106         alloc_len = scsi_4btoul(cdb->length);
9107         /*
9108          * The initiator has to allocate at least 16 bytes for this request,
9109          * so he can at least get the header and the first LUN.  Otherwise
9110          * we reject the request (per SPC-3 rev 14, section 6.21).
9111          */
9112         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9113             sizeof(struct scsi_report_luns_lundata))) {
9114                 ctl_set_invalid_field(ctsio,
9115                                       /*sks_valid*/ 1,
9116                                       /*command*/ 1,
9117                                       /*field*/ 6,
9118                                       /*bit_valid*/ 0,
9119                                       /*bit*/ 0);
9120                 ctl_done((union ctl_io *)ctsio);
9121                 return (retval);
9122         }
9123
9124         request_lun = (struct ctl_lun *)
9125                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9126
9127         lun_datalen = sizeof(*lun_data) +
9128                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9129
9130         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9131         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9132         ctsio->kern_sg_entries = 0;
9133
9134         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9135
9136         mtx_lock(&softc->ctl_lock);
9137         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9138                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9139                 if (lun_id >= CTL_MAX_LUNS)
9140                         continue;
9141                 lun = softc->ctl_luns[lun_id];
9142                 if (lun == NULL)
9143                         continue;
9144
9145                 if (targ_lun_id <= 0xff) {
9146                         /*
9147                          * Peripheral addressing method, bus number 0.
9148                          */
9149                         lun_data->luns[num_filled].lundata[0] =
9150                                 RPL_LUNDATA_ATYP_PERIPH;
9151                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9152                         num_filled++;
9153                 } else if (targ_lun_id <= 0x3fff) {
9154                         /*
9155                          * Flat addressing method.
9156                          */
9157                         lun_data->luns[num_filled].lundata[0] =
9158                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9159                         lun_data->luns[num_filled].lundata[1] =
9160                                 (targ_lun_id & 0xff);
9161                         num_filled++;
9162                 } else if (targ_lun_id <= 0xffffff) {
9163                         /*
9164                          * Extended flat addressing method.
9165                          */
9166                         lun_data->luns[num_filled].lundata[0] =
9167                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9168                         scsi_ulto3b(targ_lun_id,
9169                             &lun_data->luns[num_filled].lundata[1]);
9170                         num_filled++;
9171                 } else {
9172                         printf("ctl_report_luns: bogus LUN number %jd, "
9173                                "skipping\n", (intmax_t)targ_lun_id);
9174                 }
9175                 /*
9176                  * According to SPC-3, rev 14 section 6.21:
9177                  *
9178                  * "The execution of a REPORT LUNS command to any valid and
9179                  * installed logical unit shall clear the REPORTED LUNS DATA
9180                  * HAS CHANGED unit attention condition for all logical
9181                  * units of that target with respect to the requesting
9182                  * initiator. A valid and installed logical unit is one
9183                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9184                  * INQUIRY data (see 6.4.2)."
9185                  *
9186                  * If request_lun is NULL, the LUN this report luns command
9187                  * was issued to is either disabled or doesn't exist. In that
9188                  * case, we shouldn't clear any pending lun change unit
9189                  * attention.
9190                  */
9191                 if (request_lun != NULL) {
9192                         mtx_lock(&lun->lun_lock);
9193                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9194                         mtx_unlock(&lun->lun_lock);
9195                 }
9196         }
9197         mtx_unlock(&softc->ctl_lock);
9198
9199         /*
9200          * It's quite possible that we've returned fewer LUNs than we allocated
9201          * space for.  Trim it.
9202          */
9203         lun_datalen = sizeof(*lun_data) +
9204                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9205
9206         if (lun_datalen < alloc_len) {
9207                 ctsio->residual = alloc_len - lun_datalen;
9208                 ctsio->kern_data_len = lun_datalen;
9209                 ctsio->kern_total_len = lun_datalen;
9210         } else {
9211                 ctsio->residual = 0;
9212                 ctsio->kern_data_len = alloc_len;
9213                 ctsio->kern_total_len = alloc_len;
9214         }
9215         ctsio->kern_data_resid = 0;
9216         ctsio->kern_rel_offset = 0;
9217         ctsio->kern_sg_entries = 0;
9218
9219         /*
9220          * We set this to the actual data length, regardless of how much
9221          * space we actually have to return results.  If the user looks at
9222          * this value, he'll know whether or not he allocated enough space
9223          * and reissue the command if necessary.  We don't support well
9224          * known logical units, so if the user asks for that, return none.
9225          */
9226         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9227
9228         /*
9229          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9230          * this request.
9231          */
9232         ctl_set_success(ctsio);
9233         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9234         ctsio->be_move_done = ctl_config_move_done;
9235         ctl_datamove((union ctl_io *)ctsio);
9236         return (retval);
9237 }
9238
9239 int
9240 ctl_request_sense(struct ctl_scsiio *ctsio)
9241 {
9242         struct scsi_request_sense *cdb;
9243         struct scsi_sense_data *sense_ptr;
9244         struct ctl_softc *ctl_softc;
9245         struct ctl_lun *lun;
9246         uint32_t initidx;
9247         int have_error;
9248         scsi_sense_data_type sense_format;
9249         ctl_ua_type ua_type;
9250
9251         cdb = (struct scsi_request_sense *)ctsio->cdb;
9252
9253         ctl_softc = control_softc;
9254         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9255
9256         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9257
9258         /*
9259          * Determine which sense format the user wants.
9260          */
9261         if (cdb->byte2 & SRS_DESC)
9262                 sense_format = SSD_TYPE_DESC;
9263         else
9264                 sense_format = SSD_TYPE_FIXED;
9265
9266         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9267         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9268         ctsio->kern_sg_entries = 0;
9269
9270         /*
9271          * struct scsi_sense_data, which is currently set to 256 bytes, is
9272          * larger than the largest allowed value for the length field in the
9273          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9274          */
9275         ctsio->residual = 0;
9276         ctsio->kern_data_len = cdb->length;
9277         ctsio->kern_total_len = cdb->length;
9278
9279         ctsio->kern_data_resid = 0;
9280         ctsio->kern_rel_offset = 0;
9281         ctsio->kern_sg_entries = 0;
9282
9283         /*
9284          * If we don't have a LUN, we don't have any pending sense.
9285          */
9286         if (lun == NULL)
9287                 goto no_sense;
9288
9289         have_error = 0;
9290         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9291         /*
9292          * Check for pending sense, and then for pending unit attentions.
9293          * Pending sense gets returned first, then pending unit attentions.
9294          */
9295         mtx_lock(&lun->lun_lock);
9296 #ifdef CTL_WITH_CA
9297         if (ctl_is_set(lun->have_ca, initidx)) {
9298                 scsi_sense_data_type stored_format;
9299
9300                 /*
9301                  * Check to see which sense format was used for the stored
9302                  * sense data.
9303                  */
9304                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9305
9306                 /*
9307                  * If the user requested a different sense format than the
9308                  * one we stored, then we need to convert it to the other
9309                  * format.  If we're going from descriptor to fixed format
9310                  * sense data, we may lose things in translation, depending
9311                  * on what options were used.
9312                  *
9313                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9314                  * for some reason we'll just copy it out as-is.
9315                  */
9316                 if ((stored_format == SSD_TYPE_FIXED)
9317                  && (sense_format == SSD_TYPE_DESC))
9318                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9319                             &lun->pending_sense[initidx],
9320                             (struct scsi_sense_data_desc *)sense_ptr);
9321                 else if ((stored_format == SSD_TYPE_DESC)
9322                       && (sense_format == SSD_TYPE_FIXED))
9323                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9324                             &lun->pending_sense[initidx],
9325                             (struct scsi_sense_data_fixed *)sense_ptr);
9326                 else
9327                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9328                                MIN(sizeof(*sense_ptr),
9329                                sizeof(lun->pending_sense[initidx])));
9330
9331                 ctl_clear_mask(lun->have_ca, initidx);
9332                 have_error = 1;
9333         } else
9334 #endif
9335         {
9336                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9337                 if (ua_type != CTL_UA_NONE)
9338                         have_error = 1;
9339                 if (ua_type == CTL_UA_LUN_CHANGE) {
9340                         mtx_unlock(&lun->lun_lock);
9341                         mtx_lock(&ctl_softc->ctl_lock);
9342                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9343                         mtx_unlock(&ctl_softc->ctl_lock);
9344                         mtx_lock(&lun->lun_lock);
9345                 }
9346
9347         }
9348         mtx_unlock(&lun->lun_lock);
9349
9350         /*
9351          * We already have a pending error, return it.
9352          */
9353         if (have_error != 0) {
9354                 /*
9355                  * We report the SCSI status as OK, since the status of the
9356                  * request sense command itself is OK.
9357                  * We report 0 for the sense length, because we aren't doing
9358                  * autosense in this case.  We're reporting sense as
9359                  * parameter data.
9360                  */
9361                 ctl_set_success(ctsio);
9362                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9363                 ctsio->be_move_done = ctl_config_move_done;
9364                 ctl_datamove((union ctl_io *)ctsio);
9365                 return (CTL_RETVAL_COMPLETE);
9366         }
9367
9368 no_sense:
9369
9370         /*
9371          * No sense information to report, so we report that everything is
9372          * okay.
9373          */
9374         ctl_set_sense_data(sense_ptr,
9375                            lun,
9376                            sense_format,
9377                            /*current_error*/ 1,
9378                            /*sense_key*/ SSD_KEY_NO_SENSE,
9379                            /*asc*/ 0x00,
9380                            /*ascq*/ 0x00,
9381                            SSD_ELEM_NONE);
9382
9383         /*
9384          * We report 0 for the sense length, because we aren't doing
9385          * autosense in this case.  We're reporting sense as parameter data.
9386          */
9387         ctl_set_success(ctsio);
9388         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9389         ctsio->be_move_done = ctl_config_move_done;
9390         ctl_datamove((union ctl_io *)ctsio);
9391         return (CTL_RETVAL_COMPLETE);
9392 }
9393
9394 int
9395 ctl_tur(struct ctl_scsiio *ctsio)
9396 {
9397
9398         CTL_DEBUG_PRINT(("ctl_tur\n"));
9399
9400         ctl_set_success(ctsio);
9401         ctl_done((union ctl_io *)ctsio);
9402
9403         return (CTL_RETVAL_COMPLETE);
9404 }
9405
9406 /*
9407  * SCSI VPD page 0x00, the Supported VPD Pages page.
9408  */
9409 static int
9410 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9411 {
9412         struct scsi_vpd_supported_pages *pages;
9413         int sup_page_size;
9414         struct ctl_lun *lun;
9415         int p;
9416
9417         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9418
9419         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9420             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9421         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9422         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9423         ctsio->kern_sg_entries = 0;
9424
9425         if (sup_page_size < alloc_len) {
9426                 ctsio->residual = alloc_len - sup_page_size;
9427                 ctsio->kern_data_len = sup_page_size;
9428                 ctsio->kern_total_len = sup_page_size;
9429         } else {
9430                 ctsio->residual = 0;
9431                 ctsio->kern_data_len = alloc_len;
9432                 ctsio->kern_total_len = alloc_len;
9433         }
9434         ctsio->kern_data_resid = 0;
9435         ctsio->kern_rel_offset = 0;
9436         ctsio->kern_sg_entries = 0;
9437
9438         /*
9439          * The control device is always connected.  The disk device, on the
9440          * other hand, may not be online all the time.  Need to change this
9441          * to figure out whether the disk device is actually online or not.
9442          */
9443         if (lun != NULL)
9444                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9445                                 lun->be_lun->lun_type;
9446         else
9447                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9448
9449         p = 0;
9450         /* Supported VPD pages */
9451         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9452         /* Serial Number */
9453         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9454         /* Device Identification */
9455         pages->page_list[p++] = SVPD_DEVICE_ID;
9456         /* Extended INQUIRY Data */
9457         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9458         /* Mode Page Policy */
9459         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9460         /* SCSI Ports */
9461         pages->page_list[p++] = SVPD_SCSI_PORTS;
9462         /* Third-party Copy */
9463         pages->page_list[p++] = SVPD_SCSI_TPC;
9464         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9465                 /* Block limits */
9466                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9467                 /* Block Device Characteristics */
9468                 pages->page_list[p++] = SVPD_BDC;
9469                 /* Logical Block Provisioning */
9470                 pages->page_list[p++] = SVPD_LBP;
9471         }
9472         pages->length = p;
9473
9474         ctl_set_success(ctsio);
9475         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9476         ctsio->be_move_done = ctl_config_move_done;
9477         ctl_datamove((union ctl_io *)ctsio);
9478         return (CTL_RETVAL_COMPLETE);
9479 }
9480
9481 /*
9482  * SCSI VPD page 0x80, the Unit Serial Number page.
9483  */
9484 static int
9485 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9486 {
9487         struct scsi_vpd_unit_serial_number *sn_ptr;
9488         struct ctl_lun *lun;
9489         int data_len;
9490
9491         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9492
9493         data_len = 4 + CTL_SN_LEN;
9494         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9495         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9496         if (data_len < alloc_len) {
9497                 ctsio->residual = alloc_len - data_len;
9498                 ctsio->kern_data_len = data_len;
9499                 ctsio->kern_total_len = data_len;
9500         } else {
9501                 ctsio->residual = 0;
9502                 ctsio->kern_data_len = alloc_len;
9503                 ctsio->kern_total_len = alloc_len;
9504         }
9505         ctsio->kern_data_resid = 0;
9506         ctsio->kern_rel_offset = 0;
9507         ctsio->kern_sg_entries = 0;
9508
9509         /*
9510          * The control device is always connected.  The disk device, on the
9511          * other hand, may not be online all the time.  Need to change this
9512          * to figure out whether the disk device is actually online or not.
9513          */
9514         if (lun != NULL)
9515                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9516                                   lun->be_lun->lun_type;
9517         else
9518                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9519
9520         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9521         sn_ptr->length = CTL_SN_LEN;
9522         /*
9523          * If we don't have a LUN, we just leave the serial number as
9524          * all spaces.
9525          */
9526         if (lun != NULL) {
9527                 strncpy((char *)sn_ptr->serial_num,
9528                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9529         } else
9530                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9531
9532         ctl_set_success(ctsio);
9533         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9534         ctsio->be_move_done = ctl_config_move_done;
9535         ctl_datamove((union ctl_io *)ctsio);
9536         return (CTL_RETVAL_COMPLETE);
9537 }
9538
9539
9540 /*
9541  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9542  */
9543 static int
9544 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9545 {
9546         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9547         struct ctl_lun *lun;
9548         int data_len;
9549
9550         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9551
9552         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9553         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9554         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9555         ctsio->kern_sg_entries = 0;
9556
9557         if (data_len < alloc_len) {
9558                 ctsio->residual = alloc_len - data_len;
9559                 ctsio->kern_data_len = data_len;
9560                 ctsio->kern_total_len = data_len;
9561         } else {
9562                 ctsio->residual = 0;
9563                 ctsio->kern_data_len = alloc_len;
9564                 ctsio->kern_total_len = alloc_len;
9565         }
9566         ctsio->kern_data_resid = 0;
9567         ctsio->kern_rel_offset = 0;
9568         ctsio->kern_sg_entries = 0;
9569
9570         /*
9571          * The control device is always connected.  The disk device, on the
9572          * other hand, may not be online all the time.
9573          */
9574         if (lun != NULL)
9575                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9576                                      lun->be_lun->lun_type;
9577         else
9578                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9579         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9580         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9581         /*
9582          * We support head of queue, ordered and simple tags.
9583          */
9584         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9585         /*
9586          * Volatile cache supported.
9587          */
9588         eid_ptr->flags3 = SVPD_EID_V_SUP;
9589
9590         /*
9591          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9592          * attention for a particular IT nexus on all LUNs once we report
9593          * it to that nexus once.  This bit is required as of SPC-4.
9594          */
9595         eid_ptr->flags4 = SVPD_EID_LUICLT;
9596
9597         /*
9598          * XXX KDM in order to correctly answer this, we would need
9599          * information from the SIM to determine how much sense data it
9600          * can send.  So this would really be a path inquiry field, most
9601          * likely.  This can be set to a maximum of 252 according to SPC-4,
9602          * but the hardware may or may not be able to support that much.
9603          * 0 just means that the maximum sense data length is not reported.
9604          */
9605         eid_ptr->max_sense_length = 0;
9606
9607         ctl_set_success(ctsio);
9608         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9609         ctsio->be_move_done = ctl_config_move_done;
9610         ctl_datamove((union ctl_io *)ctsio);
9611         return (CTL_RETVAL_COMPLETE);
9612 }
9613
9614 static int
9615 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9616 {
9617         struct scsi_vpd_mode_page_policy *mpp_ptr;
9618         struct ctl_lun *lun;
9619         int data_len;
9620
9621         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9622
9623         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9624             sizeof(struct scsi_vpd_mode_page_policy_descr);
9625
9626         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9627         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9628         ctsio->kern_sg_entries = 0;
9629
9630         if (data_len < alloc_len) {
9631                 ctsio->residual = alloc_len - data_len;
9632                 ctsio->kern_data_len = data_len;
9633                 ctsio->kern_total_len = data_len;
9634         } else {
9635                 ctsio->residual = 0;
9636                 ctsio->kern_data_len = alloc_len;
9637                 ctsio->kern_total_len = alloc_len;
9638         }
9639         ctsio->kern_data_resid = 0;
9640         ctsio->kern_rel_offset = 0;
9641         ctsio->kern_sg_entries = 0;
9642
9643         /*
9644          * The control device is always connected.  The disk device, on the
9645          * other hand, may not be online all the time.
9646          */
9647         if (lun != NULL)
9648                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9649                                      lun->be_lun->lun_type;
9650         else
9651                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9652         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9653         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9654         mpp_ptr->descr[0].page_code = 0x3f;
9655         mpp_ptr->descr[0].subpage_code = 0xff;
9656         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9657
9658         ctl_set_success(ctsio);
9659         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9660         ctsio->be_move_done = ctl_config_move_done;
9661         ctl_datamove((union ctl_io *)ctsio);
9662         return (CTL_RETVAL_COMPLETE);
9663 }
9664
9665 /*
9666  * SCSI VPD page 0x83, the Device Identification page.
9667  */
9668 static int
9669 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9670 {
9671         struct scsi_vpd_device_id *devid_ptr;
9672         struct scsi_vpd_id_descriptor *desc;
9673         struct ctl_softc *softc;
9674         struct ctl_lun *lun;
9675         struct ctl_port *port;
9676         int data_len;
9677         uint8_t proto;
9678
9679         softc = control_softc;
9680
9681         port = ctl_io_port(&ctsio->io_hdr);
9682         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9683
9684         data_len = sizeof(struct scsi_vpd_device_id) +
9685             sizeof(struct scsi_vpd_id_descriptor) +
9686                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9687             sizeof(struct scsi_vpd_id_descriptor) +
9688                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9689         if (lun && lun->lun_devid)
9690                 data_len += lun->lun_devid->len;
9691         if (port && port->port_devid)
9692                 data_len += port->port_devid->len;
9693         if (port && port->target_devid)
9694                 data_len += port->target_devid->len;
9695
9696         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9697         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9698         ctsio->kern_sg_entries = 0;
9699
9700         if (data_len < alloc_len) {
9701                 ctsio->residual = alloc_len - data_len;
9702                 ctsio->kern_data_len = data_len;
9703                 ctsio->kern_total_len = data_len;
9704         } else {
9705                 ctsio->residual = 0;
9706                 ctsio->kern_data_len = alloc_len;
9707                 ctsio->kern_total_len = alloc_len;
9708         }
9709         ctsio->kern_data_resid = 0;
9710         ctsio->kern_rel_offset = 0;
9711         ctsio->kern_sg_entries = 0;
9712
9713         /*
9714          * The control device is always connected.  The disk device, on the
9715          * other hand, may not be online all the time.
9716          */
9717         if (lun != NULL)
9718                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9719                                      lun->be_lun->lun_type;
9720         else
9721                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9722         devid_ptr->page_code = SVPD_DEVICE_ID;
9723         scsi_ulto2b(data_len - 4, devid_ptr->length);
9724
9725         if (port && port->port_type == CTL_PORT_FC)
9726                 proto = SCSI_PROTO_FC << 4;
9727         else if (port && port->port_type == CTL_PORT_ISCSI)
9728                 proto = SCSI_PROTO_ISCSI << 4;
9729         else
9730                 proto = SCSI_PROTO_SPI << 4;
9731         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9732
9733         /*
9734          * We're using a LUN association here.  i.e., this device ID is a
9735          * per-LUN identifier.
9736          */
9737         if (lun && lun->lun_devid) {
9738                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9739                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9740                     lun->lun_devid->len);
9741         }
9742
9743         /*
9744          * This is for the WWPN which is a port association.
9745          */
9746         if (port && port->port_devid) {
9747                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9748                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9749                     port->port_devid->len);
9750         }
9751
9752         /*
9753          * This is for the Relative Target Port(type 4h) identifier
9754          */
9755         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9756         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9757             SVPD_ID_TYPE_RELTARG;
9758         desc->length = 4;
9759         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9760         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9761             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9762
9763         /*
9764          * This is for the Target Port Group(type 5h) identifier
9765          */
9766         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9767         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9768             SVPD_ID_TYPE_TPORTGRP;
9769         desc->length = 4;
9770         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9771             &desc->identifier[2]);
9772         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9773             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9774
9775         /*
9776          * This is for the Target identifier
9777          */
9778         if (port && port->target_devid) {
9779                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9780         }
9781
9782         ctl_set_success(ctsio);
9783         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9784         ctsio->be_move_done = ctl_config_move_done;
9785         ctl_datamove((union ctl_io *)ctsio);
9786         return (CTL_RETVAL_COMPLETE);
9787 }
9788
9789 static int
9790 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9791 {
9792         struct ctl_softc *softc = control_softc;
9793         struct scsi_vpd_scsi_ports *sp;
9794         struct scsi_vpd_port_designation *pd;
9795         struct scsi_vpd_port_designation_cont *pdc;
9796         struct ctl_lun *lun;
9797         struct ctl_port *port;
9798         int data_len, num_target_ports, iid_len, id_len;
9799
9800         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9801
9802         num_target_ports = 0;
9803         iid_len = 0;
9804         id_len = 0;
9805         mtx_lock(&softc->ctl_lock);
9806         STAILQ_FOREACH(port, &softc->port_list, links) {
9807                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9808                         continue;
9809                 if (lun != NULL &&
9810                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9811                         continue;
9812                 num_target_ports++;
9813                 if (port->init_devid)
9814                         iid_len += port->init_devid->len;
9815                 if (port->port_devid)
9816                         id_len += port->port_devid->len;
9817         }
9818         mtx_unlock(&softc->ctl_lock);
9819
9820         data_len = sizeof(struct scsi_vpd_scsi_ports) +
9821             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9822              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9823         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9824         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9825         ctsio->kern_sg_entries = 0;
9826
9827         if (data_len < alloc_len) {
9828                 ctsio->residual = alloc_len - data_len;
9829                 ctsio->kern_data_len = data_len;
9830                 ctsio->kern_total_len = data_len;
9831         } else {
9832                 ctsio->residual = 0;
9833                 ctsio->kern_data_len = alloc_len;
9834                 ctsio->kern_total_len = alloc_len;
9835         }
9836         ctsio->kern_data_resid = 0;
9837         ctsio->kern_rel_offset = 0;
9838         ctsio->kern_sg_entries = 0;
9839
9840         /*
9841          * The control device is always connected.  The disk device, on the
9842          * other hand, may not be online all the time.  Need to change this
9843          * to figure out whether the disk device is actually online or not.
9844          */
9845         if (lun != NULL)
9846                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9847                                   lun->be_lun->lun_type;
9848         else
9849                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9850
9851         sp->page_code = SVPD_SCSI_PORTS;
9852         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9853             sp->page_length);
9854         pd = &sp->design[0];
9855
9856         mtx_lock(&softc->ctl_lock);
9857         STAILQ_FOREACH(port, &softc->port_list, links) {
9858                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9859                         continue;
9860                 if (lun != NULL &&
9861                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9862                         continue;
9863                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
9864                 if (port->init_devid) {
9865                         iid_len = port->init_devid->len;
9866                         memcpy(pd->initiator_transportid,
9867                             port->init_devid->data, port->init_devid->len);
9868                 } else
9869                         iid_len = 0;
9870                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9871                 pdc = (struct scsi_vpd_port_designation_cont *)
9872                     (&pd->initiator_transportid[iid_len]);
9873                 if (port->port_devid) {
9874                         id_len = port->port_devid->len;
9875                         memcpy(pdc->target_port_descriptors,
9876                             port->port_devid->data, port->port_devid->len);
9877                 } else
9878                         id_len = 0;
9879                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9880                 pd = (struct scsi_vpd_port_designation *)
9881                     ((uint8_t *)pdc->target_port_descriptors + id_len);
9882         }
9883         mtx_unlock(&softc->ctl_lock);
9884
9885         ctl_set_success(ctsio);
9886         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9887         ctsio->be_move_done = ctl_config_move_done;
9888         ctl_datamove((union ctl_io *)ctsio);
9889         return (CTL_RETVAL_COMPLETE);
9890 }
9891
9892 static int
9893 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9894 {
9895         struct scsi_vpd_block_limits *bl_ptr;
9896         struct ctl_lun *lun;
9897         int bs;
9898
9899         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9900
9901         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9902         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9903         ctsio->kern_sg_entries = 0;
9904
9905         if (sizeof(*bl_ptr) < alloc_len) {
9906                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9907                 ctsio->kern_data_len = sizeof(*bl_ptr);
9908                 ctsio->kern_total_len = sizeof(*bl_ptr);
9909         } else {
9910                 ctsio->residual = 0;
9911                 ctsio->kern_data_len = alloc_len;
9912                 ctsio->kern_total_len = alloc_len;
9913         }
9914         ctsio->kern_data_resid = 0;
9915         ctsio->kern_rel_offset = 0;
9916         ctsio->kern_sg_entries = 0;
9917
9918         /*
9919          * The control device is always connected.  The disk device, on the
9920          * other hand, may not be online all the time.  Need to change this
9921          * to figure out whether the disk device is actually online or not.
9922          */
9923         if (lun != NULL)
9924                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9925                                   lun->be_lun->lun_type;
9926         else
9927                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9928
9929         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9930         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9931         bl_ptr->max_cmp_write_len = 0xff;
9932         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9933         if (lun != NULL) {
9934                 bs = lun->be_lun->blocksize;
9935                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9936                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9937                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9938                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9939                         if (lun->be_lun->ublockexp != 0) {
9940                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9941                                     bl_ptr->opt_unmap_grain);
9942                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9943                                     bl_ptr->unmap_grain_align);
9944                         }
9945                 }
9946                 scsi_ulto4b(lun->be_lun->atomicblock,
9947                     bl_ptr->max_atomic_transfer_length);
9948                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9949                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9950         }
9951         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9952
9953         ctl_set_success(ctsio);
9954         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9955         ctsio->be_move_done = ctl_config_move_done;
9956         ctl_datamove((union ctl_io *)ctsio);
9957         return (CTL_RETVAL_COMPLETE);
9958 }
9959
9960 static int
9961 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9962 {
9963         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9964         struct ctl_lun *lun;
9965         const char *value;
9966         u_int i;
9967
9968         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9969
9970         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9971         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9972         ctsio->kern_sg_entries = 0;
9973
9974         if (sizeof(*bdc_ptr) < alloc_len) {
9975                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9976                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9977                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9978         } else {
9979                 ctsio->residual = 0;
9980                 ctsio->kern_data_len = alloc_len;
9981                 ctsio->kern_total_len = alloc_len;
9982         }
9983         ctsio->kern_data_resid = 0;
9984         ctsio->kern_rel_offset = 0;
9985         ctsio->kern_sg_entries = 0;
9986
9987         /*
9988          * The control device is always connected.  The disk device, on the
9989          * other hand, may not be online all the time.  Need to change this
9990          * to figure out whether the disk device is actually online or not.
9991          */
9992         if (lun != NULL)
9993                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9994                                   lun->be_lun->lun_type;
9995         else
9996                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9997         bdc_ptr->page_code = SVPD_BDC;
9998         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9999         if (lun != NULL &&
10000             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10001                 i = strtol(value, NULL, 0);
10002         else
10003                 i = CTL_DEFAULT_ROTATION_RATE;
10004         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10005         if (lun != NULL &&
10006             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10007                 i = strtol(value, NULL, 0);
10008         else
10009                 i = 0;
10010         bdc_ptr->wab_wac_ff = (i & 0x0f);
10011         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10012
10013         ctl_set_success(ctsio);
10014         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10015         ctsio->be_move_done = ctl_config_move_done;
10016         ctl_datamove((union ctl_io *)ctsio);
10017         return (CTL_RETVAL_COMPLETE);
10018 }
10019
10020 static int
10021 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10022 {
10023         struct scsi_vpd_logical_block_prov *lbp_ptr;
10024         struct ctl_lun *lun;
10025
10026         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10027
10028         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10029         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10030         ctsio->kern_sg_entries = 0;
10031
10032         if (sizeof(*lbp_ptr) < alloc_len) {
10033                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10034                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10035                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10036         } else {
10037                 ctsio->residual = 0;
10038                 ctsio->kern_data_len = alloc_len;
10039                 ctsio->kern_total_len = alloc_len;
10040         }
10041         ctsio->kern_data_resid = 0;
10042         ctsio->kern_rel_offset = 0;
10043         ctsio->kern_sg_entries = 0;
10044
10045         /*
10046          * The control device is always connected.  The disk device, on the
10047          * other hand, may not be online all the time.  Need to change this
10048          * to figure out whether the disk device is actually online or not.
10049          */
10050         if (lun != NULL)
10051                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10052                                   lun->be_lun->lun_type;
10053         else
10054                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10055
10056         lbp_ptr->page_code = SVPD_LBP;
10057         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10058         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10059         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10060                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10061                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10062                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10063         }
10064
10065         ctl_set_success(ctsio);
10066         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10067         ctsio->be_move_done = ctl_config_move_done;
10068         ctl_datamove((union ctl_io *)ctsio);
10069         return (CTL_RETVAL_COMPLETE);
10070 }
10071
10072 /*
10073  * INQUIRY with the EVPD bit set.
10074  */
10075 static int
10076 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10077 {
10078         struct ctl_lun *lun;
10079         struct scsi_inquiry *cdb;
10080         int alloc_len, retval;
10081
10082         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10083         cdb = (struct scsi_inquiry *)ctsio->cdb;
10084         alloc_len = scsi_2btoul(cdb->length);
10085
10086         switch (cdb->page_code) {
10087         case SVPD_SUPPORTED_PAGES:
10088                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10089                 break;
10090         case SVPD_UNIT_SERIAL_NUMBER:
10091                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10092                 break;
10093         case SVPD_DEVICE_ID:
10094                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10095                 break;
10096         case SVPD_EXTENDED_INQUIRY_DATA:
10097                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10098                 break;
10099         case SVPD_MODE_PAGE_POLICY:
10100                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10101                 break;
10102         case SVPD_SCSI_PORTS:
10103                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10104                 break;
10105         case SVPD_SCSI_TPC:
10106                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10107                 break;
10108         case SVPD_BLOCK_LIMITS:
10109                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10110                         goto err;
10111                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10112                 break;
10113         case SVPD_BDC:
10114                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10115                         goto err;
10116                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10117                 break;
10118         case SVPD_LBP:
10119                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10120                         goto err;
10121                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10122                 break;
10123         default:
10124 err:
10125                 ctl_set_invalid_field(ctsio,
10126                                       /*sks_valid*/ 1,
10127                                       /*command*/ 1,
10128                                       /*field*/ 2,
10129                                       /*bit_valid*/ 0,
10130                                       /*bit*/ 0);
10131                 ctl_done((union ctl_io *)ctsio);
10132                 retval = CTL_RETVAL_COMPLETE;
10133                 break;
10134         }
10135
10136         return (retval);
10137 }
10138
10139 /*
10140  * Standard INQUIRY data.
10141  */
10142 static int
10143 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10144 {
10145         struct scsi_inquiry_data *inq_ptr;
10146         struct scsi_inquiry *cdb;
10147         struct ctl_softc *softc;
10148         struct ctl_port *port;
10149         struct ctl_lun *lun;
10150         char *val;
10151         uint32_t alloc_len, data_len;
10152         ctl_port_type port_type;
10153
10154         softc = control_softc;
10155
10156         /*
10157          * Figure out whether we're talking to a Fibre Channel port or not.
10158          * We treat the ioctl front end, and any SCSI adapters, as packetized
10159          * SCSI front ends.
10160          */
10161         port = ctl_io_port(&ctsio->io_hdr);
10162         if (port != NULL)
10163                 port_type = port->port_type;
10164         else
10165                 port_type = CTL_PORT_SCSI;
10166         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10167                 port_type = CTL_PORT_SCSI;
10168
10169         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10170         cdb = (struct scsi_inquiry *)ctsio->cdb;
10171         alloc_len = scsi_2btoul(cdb->length);
10172
10173         /*
10174          * We malloc the full inquiry data size here and fill it
10175          * in.  If the user only asks for less, we'll give him
10176          * that much.
10177          */
10178         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10179         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10180         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10181         ctsio->kern_sg_entries = 0;
10182         ctsio->kern_data_resid = 0;
10183         ctsio->kern_rel_offset = 0;
10184
10185         if (data_len < alloc_len) {
10186                 ctsio->residual = alloc_len - data_len;
10187                 ctsio->kern_data_len = data_len;
10188                 ctsio->kern_total_len = data_len;
10189         } else {
10190                 ctsio->residual = 0;
10191                 ctsio->kern_data_len = alloc_len;
10192                 ctsio->kern_total_len = alloc_len;
10193         }
10194
10195         if (lun != NULL) {
10196                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10197                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10198                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10199                             lun->be_lun->lun_type;
10200                 } else {
10201                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10202                             lun->be_lun->lun_type;
10203                 }
10204         } else
10205                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10206
10207         /* RMB in byte 2 is 0 */
10208         inq_ptr->version = SCSI_REV_SPC4;
10209
10210         /*
10211          * According to SAM-3, even if a device only supports a single
10212          * level of LUN addressing, it should still set the HISUP bit:
10213          *
10214          * 4.9.1 Logical unit numbers overview
10215          *
10216          * All logical unit number formats described in this standard are
10217          * hierarchical in structure even when only a single level in that
10218          * hierarchy is used. The HISUP bit shall be set to one in the
10219          * standard INQUIRY data (see SPC-2) when any logical unit number
10220          * format described in this standard is used.  Non-hierarchical
10221          * formats are outside the scope of this standard.
10222          *
10223          * Therefore we set the HiSup bit here.
10224          *
10225          * The reponse format is 2, per SPC-3.
10226          */
10227         inq_ptr->response_format = SID_HiSup | 2;
10228
10229         inq_ptr->additional_length = data_len -
10230             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10231         CTL_DEBUG_PRINT(("additional_length = %d\n",
10232                          inq_ptr->additional_length));
10233
10234         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10235         /* 16 bit addressing */
10236         if (port_type == CTL_PORT_SCSI)
10237                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10238         /* XXX set the SID_MultiP bit here if we're actually going to
10239            respond on multiple ports */
10240         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10241
10242         /* 16 bit data bus, synchronous transfers */
10243         if (port_type == CTL_PORT_SCSI)
10244                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10245         /*
10246          * XXX KDM do we want to support tagged queueing on the control
10247          * device at all?
10248          */
10249         if ((lun == NULL)
10250          || (lun->be_lun->lun_type != T_PROCESSOR))
10251                 inq_ptr->flags |= SID_CmdQue;
10252         /*
10253          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10254          * We have 8 bytes for the vendor name, and 16 bytes for the device
10255          * name and 4 bytes for the revision.
10256          */
10257         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10258             "vendor")) == NULL) {
10259                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10260         } else {
10261                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10262                 strncpy(inq_ptr->vendor, val,
10263                     min(sizeof(inq_ptr->vendor), strlen(val)));
10264         }
10265         if (lun == NULL) {
10266                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10267                     sizeof(inq_ptr->product));
10268         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10269                 switch (lun->be_lun->lun_type) {
10270                 case T_DIRECT:
10271                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10272                             sizeof(inq_ptr->product));
10273                         break;
10274                 case T_PROCESSOR:
10275                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10276                             sizeof(inq_ptr->product));
10277                         break;
10278                 default:
10279                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10280                             sizeof(inq_ptr->product));
10281                         break;
10282                 }
10283         } else {
10284                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10285                 strncpy(inq_ptr->product, val,
10286                     min(sizeof(inq_ptr->product), strlen(val)));
10287         }
10288
10289         /*
10290          * XXX make this a macro somewhere so it automatically gets
10291          * incremented when we make changes.
10292          */
10293         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10294             "revision")) == NULL) {
10295                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10296         } else {
10297                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10298                 strncpy(inq_ptr->revision, val,
10299                     min(sizeof(inq_ptr->revision), strlen(val)));
10300         }
10301
10302         /*
10303          * For parallel SCSI, we support double transition and single
10304          * transition clocking.  We also support QAS (Quick Arbitration
10305          * and Selection) and Information Unit transfers on both the
10306          * control and array devices.
10307          */
10308         if (port_type == CTL_PORT_SCSI)
10309                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10310                                     SID_SPI_IUS;
10311
10312         /* SAM-5 (no version claimed) */
10313         scsi_ulto2b(0x00A0, inq_ptr->version1);
10314         /* SPC-4 (no version claimed) */
10315         scsi_ulto2b(0x0460, inq_ptr->version2);
10316         if (port_type == CTL_PORT_FC) {
10317                 /* FCP-2 ANSI INCITS.350:2003 */
10318                 scsi_ulto2b(0x0917, inq_ptr->version3);
10319         } else if (port_type == CTL_PORT_SCSI) {
10320                 /* SPI-4 ANSI INCITS.362:200x */
10321                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10322         } else if (port_type == CTL_PORT_ISCSI) {
10323                 /* iSCSI (no version claimed) */
10324                 scsi_ulto2b(0x0960, inq_ptr->version3);
10325         } else if (port_type == CTL_PORT_SAS) {
10326                 /* SAS (no version claimed) */
10327                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10328         }
10329
10330         if (lun == NULL) {
10331                 /* SBC-4 (no version claimed) */
10332                 scsi_ulto2b(0x0600, inq_ptr->version4);
10333         } else {
10334                 switch (lun->be_lun->lun_type) {
10335                 case T_DIRECT:
10336                         /* SBC-4 (no version claimed) */
10337                         scsi_ulto2b(0x0600, inq_ptr->version4);
10338                         break;
10339                 case T_PROCESSOR:
10340                 default:
10341                         break;
10342                 }
10343         }
10344
10345         ctl_set_success(ctsio);
10346         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10347         ctsio->be_move_done = ctl_config_move_done;
10348         ctl_datamove((union ctl_io *)ctsio);
10349         return (CTL_RETVAL_COMPLETE);
10350 }
10351
10352 int
10353 ctl_inquiry(struct ctl_scsiio *ctsio)
10354 {
10355         struct scsi_inquiry *cdb;
10356         int retval;
10357
10358         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10359
10360         cdb = (struct scsi_inquiry *)ctsio->cdb;
10361         if (cdb->byte2 & SI_EVPD)
10362                 retval = ctl_inquiry_evpd(ctsio);
10363         else if (cdb->page_code == 0)
10364                 retval = ctl_inquiry_std(ctsio);
10365         else {
10366                 ctl_set_invalid_field(ctsio,
10367                                       /*sks_valid*/ 1,
10368                                       /*command*/ 1,
10369                                       /*field*/ 2,
10370                                       /*bit_valid*/ 0,
10371                                       /*bit*/ 0);
10372                 ctl_done((union ctl_io *)ctsio);
10373                 return (CTL_RETVAL_COMPLETE);
10374         }
10375
10376         return (retval);
10377 }
10378
10379 /*
10380  * For known CDB types, parse the LBA and length.
10381  */
10382 static int
10383 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10384 {
10385         if (io->io_hdr.io_type != CTL_IO_SCSI)
10386                 return (1);
10387
10388         switch (io->scsiio.cdb[0]) {
10389         case COMPARE_AND_WRITE: {
10390                 struct scsi_compare_and_write *cdb;
10391
10392                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10393
10394                 *lba = scsi_8btou64(cdb->addr);
10395                 *len = cdb->length;
10396                 break;
10397         }
10398         case READ_6:
10399         case WRITE_6: {
10400                 struct scsi_rw_6 *cdb;
10401
10402                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10403
10404                 *lba = scsi_3btoul(cdb->addr);
10405                 /* only 5 bits are valid in the most significant address byte */
10406                 *lba &= 0x1fffff;
10407                 *len = cdb->length;
10408                 break;
10409         }
10410         case READ_10:
10411         case WRITE_10: {
10412                 struct scsi_rw_10 *cdb;
10413
10414                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10415
10416                 *lba = scsi_4btoul(cdb->addr);
10417                 *len = scsi_2btoul(cdb->length);
10418                 break;
10419         }
10420         case WRITE_VERIFY_10: {
10421                 struct scsi_write_verify_10 *cdb;
10422
10423                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10424
10425                 *lba = scsi_4btoul(cdb->addr);
10426                 *len = scsi_2btoul(cdb->length);
10427                 break;
10428         }
10429         case READ_12:
10430         case WRITE_12: {
10431                 struct scsi_rw_12 *cdb;
10432
10433                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10434
10435                 *lba = scsi_4btoul(cdb->addr);
10436                 *len = scsi_4btoul(cdb->length);
10437                 break;
10438         }
10439         case WRITE_VERIFY_12: {
10440                 struct scsi_write_verify_12 *cdb;
10441
10442                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10443
10444                 *lba = scsi_4btoul(cdb->addr);
10445                 *len = scsi_4btoul(cdb->length);
10446                 break;
10447         }
10448         case READ_16:
10449         case WRITE_16:
10450         case WRITE_ATOMIC_16: {
10451                 struct scsi_rw_16 *cdb;
10452
10453                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10454
10455                 *lba = scsi_8btou64(cdb->addr);
10456                 *len = scsi_4btoul(cdb->length);
10457                 break;
10458         }
10459         case WRITE_VERIFY_16: {
10460                 struct scsi_write_verify_16 *cdb;
10461
10462                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10463
10464                 *lba = scsi_8btou64(cdb->addr);
10465                 *len = scsi_4btoul(cdb->length);
10466                 break;
10467         }
10468         case WRITE_SAME_10: {
10469                 struct scsi_write_same_10 *cdb;
10470
10471                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10472
10473                 *lba = scsi_4btoul(cdb->addr);
10474                 *len = scsi_2btoul(cdb->length);
10475                 break;
10476         }
10477         case WRITE_SAME_16: {
10478                 struct scsi_write_same_16 *cdb;
10479
10480                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10481
10482                 *lba = scsi_8btou64(cdb->addr);
10483                 *len = scsi_4btoul(cdb->length);
10484                 break;
10485         }
10486         case VERIFY_10: {
10487                 struct scsi_verify_10 *cdb;
10488
10489                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10490
10491                 *lba = scsi_4btoul(cdb->addr);
10492                 *len = scsi_2btoul(cdb->length);
10493                 break;
10494         }
10495         case VERIFY_12: {
10496                 struct scsi_verify_12 *cdb;
10497
10498                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10499
10500                 *lba = scsi_4btoul(cdb->addr);
10501                 *len = scsi_4btoul(cdb->length);
10502                 break;
10503         }
10504         case VERIFY_16: {
10505                 struct scsi_verify_16 *cdb;
10506
10507                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10508
10509                 *lba = scsi_8btou64(cdb->addr);
10510                 *len = scsi_4btoul(cdb->length);
10511                 break;
10512         }
10513         case UNMAP: {
10514                 *lba = 0;
10515                 *len = UINT64_MAX;
10516                 break;
10517         }
10518         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10519                 struct scsi_get_lba_status *cdb;
10520
10521                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10522                 *lba = scsi_8btou64(cdb->addr);
10523                 *len = UINT32_MAX;
10524                 break;
10525         }
10526         default:
10527                 return (1);
10528                 break; /* NOTREACHED */
10529         }
10530
10531         return (0);
10532 }
10533
10534 static ctl_action
10535 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10536     bool seq)
10537 {
10538         uint64_t endlba1, endlba2;
10539
10540         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10541         endlba2 = lba2 + len2 - 1;
10542
10543         if ((endlba1 < lba2) || (endlba2 < lba1))
10544                 return (CTL_ACTION_PASS);
10545         else
10546                 return (CTL_ACTION_BLOCK);
10547 }
10548
10549 static int
10550 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10551 {
10552         struct ctl_ptr_len_flags *ptrlen;
10553         struct scsi_unmap_desc *buf, *end, *range;
10554         uint64_t lba;
10555         uint32_t len;
10556
10557         /* If not UNMAP -- go other way. */
10558         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10559             io->scsiio.cdb[0] != UNMAP)
10560                 return (CTL_ACTION_ERROR);
10561
10562         /* If UNMAP without data -- block and wait for data. */
10563         ptrlen = (struct ctl_ptr_len_flags *)
10564             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10565         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10566             ptrlen->ptr == NULL)
10567                 return (CTL_ACTION_BLOCK);
10568
10569         /* UNMAP with data -- check for collision. */
10570         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10571         end = buf + ptrlen->len / sizeof(*buf);
10572         for (range = buf; range < end; range++) {
10573                 lba = scsi_8btou64(range->lba);
10574                 len = scsi_4btoul(range->length);
10575                 if ((lba < lba2 + len2) && (lba + len > lba2))
10576                         return (CTL_ACTION_BLOCK);
10577         }
10578         return (CTL_ACTION_PASS);
10579 }
10580
10581 static ctl_action
10582 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10583 {
10584         uint64_t lba1, lba2;
10585         uint64_t len1, len2;
10586         int retval;
10587
10588         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10589                 return (CTL_ACTION_ERROR);
10590
10591         retval = ctl_extent_check_unmap(io1, lba2, len2);
10592         if (retval != CTL_ACTION_ERROR)
10593                 return (retval);
10594
10595         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10596                 return (CTL_ACTION_ERROR);
10597
10598         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10599 }
10600
10601 static ctl_action
10602 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10603 {
10604         uint64_t lba1, lba2;
10605         uint64_t len1, len2;
10606
10607         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10608                 return (CTL_ACTION_ERROR);
10609         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10610                 return (CTL_ACTION_ERROR);
10611
10612         if (lba1 + len1 == lba2)
10613                 return (CTL_ACTION_BLOCK);
10614         return (CTL_ACTION_PASS);
10615 }
10616
10617 static ctl_action
10618 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10619     union ctl_io *ooa_io)
10620 {
10621         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10622         ctl_serialize_action *serialize_row;
10623
10624         /*
10625          * The initiator attempted multiple untagged commands at the same
10626          * time.  Can't do that.
10627          */
10628         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10629          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10630          && ((pending_io->io_hdr.nexus.targ_port ==
10631               ooa_io->io_hdr.nexus.targ_port)
10632           && (pending_io->io_hdr.nexus.initid ==
10633               ooa_io->io_hdr.nexus.initid))
10634          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10635               CTL_FLAG_STATUS_SENT)) == 0))
10636                 return (CTL_ACTION_OVERLAP);
10637
10638         /*
10639          * The initiator attempted to send multiple tagged commands with
10640          * the same ID.  (It's fine if different initiators have the same
10641          * tag ID.)
10642          *
10643          * Even if all of those conditions are true, we don't kill the I/O
10644          * if the command ahead of us has been aborted.  We won't end up
10645          * sending it to the FETD, and it's perfectly legal to resend a
10646          * command with the same tag number as long as the previous
10647          * instance of this tag number has been aborted somehow.
10648          */
10649         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10650          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10651          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10652          && ((pending_io->io_hdr.nexus.targ_port ==
10653               ooa_io->io_hdr.nexus.targ_port)
10654           && (pending_io->io_hdr.nexus.initid ==
10655               ooa_io->io_hdr.nexus.initid))
10656          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10657               CTL_FLAG_STATUS_SENT)) == 0))
10658                 return (CTL_ACTION_OVERLAP_TAG);
10659
10660         /*
10661          * If we get a head of queue tag, SAM-3 says that we should
10662          * immediately execute it.
10663          *
10664          * What happens if this command would normally block for some other
10665          * reason?  e.g. a request sense with a head of queue tag
10666          * immediately after a write.  Normally that would block, but this
10667          * will result in its getting executed immediately...
10668          *
10669          * We currently return "pass" instead of "skip", so we'll end up
10670          * going through the rest of the queue to check for overlapped tags.
10671          *
10672          * XXX KDM check for other types of blockage first??
10673          */
10674         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10675                 return (CTL_ACTION_PASS);
10676
10677         /*
10678          * Ordered tags have to block until all items ahead of them
10679          * have completed.  If we get called with an ordered tag, we always
10680          * block, if something else is ahead of us in the queue.
10681          */
10682         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10683                 return (CTL_ACTION_BLOCK);
10684
10685         /*
10686          * Simple tags get blocked until all head of queue and ordered tags
10687          * ahead of them have completed.  I'm lumping untagged commands in
10688          * with simple tags here.  XXX KDM is that the right thing to do?
10689          */
10690         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10691           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10692          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10693           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10694                 return (CTL_ACTION_BLOCK);
10695
10696         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10697         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10698
10699         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10700
10701         switch (serialize_row[pending_entry->seridx]) {
10702         case CTL_SER_BLOCK:
10703                 return (CTL_ACTION_BLOCK);
10704         case CTL_SER_EXTENT:
10705                 return (ctl_extent_check(ooa_io, pending_io,
10706                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10707         case CTL_SER_EXTENTOPT:
10708                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10709                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10710                         return (ctl_extent_check(ooa_io, pending_io,
10711                             (lun->be_lun &&
10712                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10713                 return (CTL_ACTION_PASS);
10714         case CTL_SER_EXTENTSEQ:
10715                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10716                         return (ctl_extent_check_seq(ooa_io, pending_io));
10717                 return (CTL_ACTION_PASS);
10718         case CTL_SER_PASS:
10719                 return (CTL_ACTION_PASS);
10720         case CTL_SER_BLOCKOPT:
10721                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10722                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10723                         return (CTL_ACTION_BLOCK);
10724                 return (CTL_ACTION_PASS);
10725         case CTL_SER_SKIP:
10726                 return (CTL_ACTION_SKIP);
10727         default:
10728                 panic("invalid serialization value %d",
10729                       serialize_row[pending_entry->seridx]);
10730         }
10731
10732         return (CTL_ACTION_ERROR);
10733 }
10734
10735 /*
10736  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10737  * Assumptions:
10738  * - pending_io is generally either incoming, or on the blocked queue
10739  * - starting I/O is the I/O we want to start the check with.
10740  */
10741 static ctl_action
10742 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10743               union ctl_io *starting_io)
10744 {
10745         union ctl_io *ooa_io;
10746         ctl_action action;
10747
10748         mtx_assert(&lun->lun_lock, MA_OWNED);
10749
10750         /*
10751          * Run back along the OOA queue, starting with the current
10752          * blocked I/O and going through every I/O before it on the
10753          * queue.  If starting_io is NULL, we'll just end up returning
10754          * CTL_ACTION_PASS.
10755          */
10756         for (ooa_io = starting_io; ooa_io != NULL;
10757              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10758              ooa_links)){
10759
10760                 /*
10761                  * This routine just checks to see whether
10762                  * cur_blocked is blocked by ooa_io, which is ahead
10763                  * of it in the queue.  It doesn't queue/dequeue
10764                  * cur_blocked.
10765                  */
10766                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10767                 switch (action) {
10768                 case CTL_ACTION_BLOCK:
10769                 case CTL_ACTION_OVERLAP:
10770                 case CTL_ACTION_OVERLAP_TAG:
10771                 case CTL_ACTION_SKIP:
10772                 case CTL_ACTION_ERROR:
10773                         return (action);
10774                         break; /* NOTREACHED */
10775                 case CTL_ACTION_PASS:
10776                         break;
10777                 default:
10778                         panic("invalid action %d", action);
10779                         break;  /* NOTREACHED */
10780                 }
10781         }
10782
10783         return (CTL_ACTION_PASS);
10784 }
10785
10786 /*
10787  * Assumptions:
10788  * - An I/O has just completed, and has been removed from the per-LUN OOA
10789  *   queue, so some items on the blocked queue may now be unblocked.
10790  */
10791 static int
10792 ctl_check_blocked(struct ctl_lun *lun)
10793 {
10794         struct ctl_softc *softc = lun->ctl_softc;
10795         union ctl_io *cur_blocked, *next_blocked;
10796
10797         mtx_assert(&lun->lun_lock, MA_OWNED);
10798
10799         /*
10800          * Run forward from the head of the blocked queue, checking each
10801          * entry against the I/Os prior to it on the OOA queue to see if
10802          * there is still any blockage.
10803          *
10804          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10805          * with our removing a variable on it while it is traversing the
10806          * list.
10807          */
10808         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10809              cur_blocked != NULL; cur_blocked = next_blocked) {
10810                 union ctl_io *prev_ooa;
10811                 ctl_action action;
10812
10813                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10814                                                           blocked_links);
10815
10816                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10817                                                       ctl_ooaq, ooa_links);
10818
10819                 /*
10820                  * If cur_blocked happens to be the first item in the OOA
10821                  * queue now, prev_ooa will be NULL, and the action
10822                  * returned will just be CTL_ACTION_PASS.
10823                  */
10824                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10825
10826                 switch (action) {
10827                 case CTL_ACTION_BLOCK:
10828                         /* Nothing to do here, still blocked */
10829                         break;
10830                 case CTL_ACTION_OVERLAP:
10831                 case CTL_ACTION_OVERLAP_TAG:
10832                         /*
10833                          * This shouldn't happen!  In theory we've already
10834                          * checked this command for overlap...
10835                          */
10836                         break;
10837                 case CTL_ACTION_PASS:
10838                 case CTL_ACTION_SKIP: {
10839                         const struct ctl_cmd_entry *entry;
10840
10841                         /*
10842                          * The skip case shouldn't happen, this transaction
10843                          * should have never made it onto the blocked queue.
10844                          */
10845                         /*
10846                          * This I/O is no longer blocked, we can remove it
10847                          * from the blocked queue.  Since this is a TAILQ
10848                          * (doubly linked list), we can do O(1) removals
10849                          * from any place on the list.
10850                          */
10851                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10852                                      blocked_links);
10853                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10854
10855                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
10856                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
10857                                 /*
10858                                  * Need to send IO back to original side to
10859                                  * run
10860                                  */
10861                                 union ctl_ha_msg msg_info;
10862
10863                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10864                                 msg_info.hdr.original_sc =
10865                                         cur_blocked->io_hdr.original_sc;
10866                                 msg_info.hdr.serializing_sc = cur_blocked;
10867                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10868                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10869                                     sizeof(msg_info.hdr), M_NOWAIT);
10870                                 break;
10871                         }
10872                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10873
10874                         /*
10875                          * Check this I/O for LUN state changes that may
10876                          * have happened while this command was blocked.
10877                          * The LUN state may have been changed by a command
10878                          * ahead of us in the queue, so we need to re-check
10879                          * for any states that can be caused by SCSI
10880                          * commands.
10881                          */
10882                         if (ctl_scsiio_lun_check(lun, entry,
10883                                                  &cur_blocked->scsiio) == 0) {
10884                                 cur_blocked->io_hdr.flags |=
10885                                                       CTL_FLAG_IS_WAS_ON_RTR;
10886                                 ctl_enqueue_rtr(cur_blocked);
10887                         } else
10888                                 ctl_done(cur_blocked);
10889                         break;
10890                 }
10891                 default:
10892                         /*
10893                          * This probably shouldn't happen -- we shouldn't
10894                          * get CTL_ACTION_ERROR, or anything else.
10895                          */
10896                         break;
10897                 }
10898         }
10899
10900         return (CTL_RETVAL_COMPLETE);
10901 }
10902
10903 /*
10904  * This routine (with one exception) checks LUN flags that can be set by
10905  * commands ahead of us in the OOA queue.  These flags have to be checked
10906  * when a command initially comes in, and when we pull a command off the
10907  * blocked queue and are preparing to execute it.  The reason we have to
10908  * check these flags for commands on the blocked queue is that the LUN
10909  * state may have been changed by a command ahead of us while we're on the
10910  * blocked queue.
10911  *
10912  * Ordering is somewhat important with these checks, so please pay
10913  * careful attention to the placement of any new checks.
10914  */
10915 static int
10916 ctl_scsiio_lun_check(struct ctl_lun *lun,
10917     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10918 {
10919         struct ctl_softc *softc = lun->ctl_softc;
10920         int retval;
10921         uint32_t residx;
10922
10923         retval = 0;
10924
10925         mtx_assert(&lun->lun_lock, MA_OWNED);
10926
10927         /*
10928          * If this shelf is a secondary shelf controller, we may have to
10929          * reject some commands disallowed by HA mode and link state.
10930          */
10931         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10932                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
10933                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10934                         ctl_set_lun_unavail(ctsio);
10935                         retval = 1;
10936                         goto bailout;
10937                 }
10938                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
10939                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10940                         ctl_set_lun_transit(ctsio);
10941                         retval = 1;
10942                         goto bailout;
10943                 }
10944                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
10945                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
10946                         ctl_set_lun_standby(ctsio);
10947                         retval = 1;
10948                         goto bailout;
10949                 }
10950
10951                 /* The rest of checks are only done on executing side */
10952                 if (softc->ha_mode == CTL_HA_MODE_XFER)
10953                         goto bailout;
10954         }
10955
10956         if (entry->pattern & CTL_LUN_PAT_WRITE) {
10957                 if (lun->be_lun &&
10958                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
10959                         ctl_set_hw_write_protected(ctsio);
10960                         retval = 1;
10961                         goto bailout;
10962                 }
10963                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10964                     .eca_and_aen & SCP_SWP) != 0) {
10965                         ctl_set_sense(ctsio, /*current_error*/ 1,
10966                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
10967                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10968                         retval = 1;
10969                         goto bailout;
10970                 }
10971         }
10972
10973         /*
10974          * Check for a reservation conflict.  If this command isn't allowed
10975          * even on reserved LUNs, and if this initiator isn't the one who
10976          * reserved us, reject the command with a reservation conflict.
10977          */
10978         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10979         if ((lun->flags & CTL_LUN_RESERVED)
10980          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10981                 if (lun->res_idx != residx) {
10982                         ctl_set_reservation_conflict(ctsio);
10983                         retval = 1;
10984                         goto bailout;
10985                 }
10986         }
10987
10988         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10989             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10990                 /* No reservation or command is allowed. */;
10991         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10992             (lun->res_type == SPR_TYPE_WR_EX ||
10993              lun->res_type == SPR_TYPE_WR_EX_RO ||
10994              lun->res_type == SPR_TYPE_WR_EX_AR)) {
10995                 /* The command is allowed for Write Exclusive resv. */;
10996         } else {
10997                 /*
10998                  * if we aren't registered or it's a res holder type
10999                  * reservation and this isn't the res holder then set a
11000                  * conflict.
11001                  */
11002                 if (ctl_get_prkey(lun, residx) == 0
11003                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11004                         ctl_set_reservation_conflict(ctsio);
11005                         retval = 1;
11006                         goto bailout;
11007                 }
11008         }
11009
11010         if ((lun->flags & CTL_LUN_OFFLINE)
11011          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
11012                 ctl_set_lun_not_ready(ctsio);
11013                 retval = 1;
11014                 goto bailout;
11015         }
11016
11017         if ((lun->flags & CTL_LUN_STOPPED)
11018          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11019                 /* "Logical unit not ready, initializing cmd. required" */
11020                 ctl_set_lun_stopped(ctsio);
11021                 retval = 1;
11022                 goto bailout;
11023         }
11024
11025         if ((lun->flags & CTL_LUN_INOPERABLE)
11026          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11027                 /* "Medium format corrupted" */
11028                 ctl_set_medium_format_corrupted(ctsio);
11029                 retval = 1;
11030                 goto bailout;
11031         }
11032
11033 bailout:
11034         return (retval);
11035 }
11036
11037 static void
11038 ctl_failover_io(union ctl_io *io, int have_lock)
11039 {
11040         ctl_set_busy(&io->scsiio);
11041         ctl_done(io);
11042 }
11043
11044 static void
11045 ctl_failover_lun(struct ctl_lun *lun)
11046 {
11047         struct ctl_softc *softc = lun->ctl_softc;
11048         struct ctl_io_hdr *io, *next_io;
11049
11050         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
11051         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11052                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11053                         /* We are master */
11054                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11055                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11056                                         io->flags |= CTL_FLAG_ABORT;
11057                                         io->flags |= CTL_FLAG_FAILOVER;
11058                                 } else { /* This can be only due to DATAMOVE */
11059                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11060                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11061                                         io->port_status = 31340;
11062                                         ctl_enqueue_isc((union ctl_io *)io);
11063                                 }
11064                         }
11065                         /* We are slave */
11066                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11067                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11068                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11069                                         io->flags |= CTL_FLAG_FAILOVER;
11070                                 } else {
11071                                         ctl_set_busy(&((union ctl_io *)io)->
11072                                             scsiio);
11073                                         ctl_done((union ctl_io *)io);
11074                                 }
11075                         }
11076                 }
11077         } else { /* SERIALIZE modes */
11078                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11079                     next_io) {
11080                         /* We are master */
11081                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11082                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11083                                     blocked_links);
11084                                 io->flags &= ~CTL_FLAG_BLOCKED;
11085                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11086                                 ctl_free_io((union ctl_io *)io);
11087                         }
11088                 }
11089                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11090                         /* We are master */
11091                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11092                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11093                                 ctl_free_io((union ctl_io *)io);
11094                         }
11095                         /* We are slave */
11096                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11097                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11098                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11099                                         ctl_set_busy(&((union ctl_io *)io)->
11100                                             scsiio);
11101                                         ctl_done((union ctl_io *)io);
11102                                 }
11103                         }
11104                 }
11105                 ctl_check_blocked(lun);
11106         }
11107 }
11108
11109 static int
11110 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11111 {
11112         struct ctl_lun *lun;
11113         const struct ctl_cmd_entry *entry;
11114         uint32_t initidx, targ_lun;
11115         int retval;
11116
11117         retval = 0;
11118
11119         lun = NULL;
11120
11121         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11122         if ((targ_lun < CTL_MAX_LUNS)
11123          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11124                 /*
11125                  * If the LUN is invalid, pretend that it doesn't exist.
11126                  * It will go away as soon as all pending I/O has been
11127                  * completed.
11128                  */
11129                 mtx_lock(&lun->lun_lock);
11130                 if (lun->flags & CTL_LUN_DISABLED) {
11131                         mtx_unlock(&lun->lun_lock);
11132                         lun = NULL;
11133                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11134                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11135                 } else {
11136                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11137                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11138                                 lun->be_lun;
11139
11140                         /*
11141                          * Every I/O goes into the OOA queue for a
11142                          * particular LUN, and stays there until completion.
11143                          */
11144 #ifdef CTL_TIME_IO
11145                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11146                                 lun->idle_time += getsbinuptime() -
11147                                     lun->last_busy;
11148                         }
11149 #endif
11150                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11151                             ooa_links);
11152                 }
11153         } else {
11154                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11155                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11156         }
11157
11158         /* Get command entry and return error if it is unsuppotyed. */
11159         entry = ctl_validate_command(ctsio);
11160         if (entry == NULL) {
11161                 if (lun)
11162                         mtx_unlock(&lun->lun_lock);
11163                 return (retval);
11164         }
11165
11166         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11167         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11168
11169         /*
11170          * Check to see whether we can send this command to LUNs that don't
11171          * exist.  This should pretty much only be the case for inquiry
11172          * and request sense.  Further checks, below, really require having
11173          * a LUN, so we can't really check the command anymore.  Just put
11174          * it on the rtr queue.
11175          */
11176         if (lun == NULL) {
11177                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11178                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11179                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11180                         return (retval);
11181                 }
11182
11183                 ctl_set_unsupported_lun(ctsio);
11184                 ctl_done((union ctl_io *)ctsio);
11185                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11186                 return (retval);
11187         } else {
11188                 /*
11189                  * Make sure we support this particular command on this LUN.
11190                  * e.g., we don't support writes to the control LUN.
11191                  */
11192                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11193                         mtx_unlock(&lun->lun_lock);
11194                         ctl_set_invalid_opcode(ctsio);
11195                         ctl_done((union ctl_io *)ctsio);
11196                         return (retval);
11197                 }
11198         }
11199
11200         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11201
11202 #ifdef CTL_WITH_CA
11203         /*
11204          * If we've got a request sense, it'll clear the contingent
11205          * allegiance condition.  Otherwise, if we have a CA condition for
11206          * this initiator, clear it, because it sent down a command other
11207          * than request sense.
11208          */
11209         if ((ctsio->cdb[0] != REQUEST_SENSE)
11210          && (ctl_is_set(lun->have_ca, initidx)))
11211                 ctl_clear_mask(lun->have_ca, initidx);
11212 #endif
11213
11214         /*
11215          * If the command has this flag set, it handles its own unit
11216          * attention reporting, we shouldn't do anything.  Otherwise we
11217          * check for any pending unit attentions, and send them back to the
11218          * initiator.  We only do this when a command initially comes in,
11219          * not when we pull it off the blocked queue.
11220          *
11221          * According to SAM-3, section 5.3.2, the order that things get
11222          * presented back to the host is basically unit attentions caused
11223          * by some sort of reset event, busy status, reservation conflicts
11224          * or task set full, and finally any other status.
11225          *
11226          * One issue here is that some of the unit attentions we report
11227          * don't fall into the "reset" category (e.g. "reported luns data
11228          * has changed").  So reporting it here, before the reservation
11229          * check, may be technically wrong.  I guess the only thing to do
11230          * would be to check for and report the reset events here, and then
11231          * check for the other unit attention types after we check for a
11232          * reservation conflict.
11233          *
11234          * XXX KDM need to fix this
11235          */
11236         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11237                 ctl_ua_type ua_type;
11238
11239                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11240                     SSD_TYPE_NONE);
11241                 if (ua_type != CTL_UA_NONE) {
11242                         mtx_unlock(&lun->lun_lock);
11243                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11244                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11245                         ctsio->sense_len = SSD_FULL_SIZE;
11246                         ctl_done((union ctl_io *)ctsio);
11247                         return (retval);
11248                 }
11249         }
11250
11251
11252         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11253                 mtx_unlock(&lun->lun_lock);
11254                 ctl_done((union ctl_io *)ctsio);
11255                 return (retval);
11256         }
11257
11258         /*
11259          * XXX CHD this is where we want to send IO to other side if
11260          * this LUN is secondary on this SC. We will need to make a copy
11261          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11262          * the copy we send as FROM_OTHER.
11263          * We also need to stuff the address of the original IO so we can
11264          * find it easily. Something similar will need be done on the other
11265          * side so when we are done we can find the copy.
11266          */
11267         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11268             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0) {
11269                 union ctl_ha_msg msg_info;
11270                 int isc_retval;
11271
11272                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11273                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11274                 mtx_unlock(&lun->lun_lock);
11275
11276                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11277                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11278                 msg_info.hdr.serializing_sc = NULL;
11279                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11280                 msg_info.scsi.tag_num = ctsio->tag_num;
11281                 msg_info.scsi.tag_type = ctsio->tag_type;
11282                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11283                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11284
11285                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11286                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11287                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11288                         ctl_set_busy(ctsio);
11289                         ctl_done((union ctl_io *)ctsio);
11290                         return (retval);
11291                 }
11292                 return (retval);
11293         }
11294
11295         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11296                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11297                               ctl_ooaq, ooa_links))) {
11298         case CTL_ACTION_BLOCK:
11299                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11300                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11301                                   blocked_links);
11302                 mtx_unlock(&lun->lun_lock);
11303                 return (retval);
11304         case CTL_ACTION_PASS:
11305         case CTL_ACTION_SKIP:
11306                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11307                 mtx_unlock(&lun->lun_lock);
11308                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11309                 break;
11310         case CTL_ACTION_OVERLAP:
11311                 mtx_unlock(&lun->lun_lock);
11312                 ctl_set_overlapped_cmd(ctsio);
11313                 ctl_done((union ctl_io *)ctsio);
11314                 break;
11315         case CTL_ACTION_OVERLAP_TAG:
11316                 mtx_unlock(&lun->lun_lock);
11317                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11318                 ctl_done((union ctl_io *)ctsio);
11319                 break;
11320         case CTL_ACTION_ERROR:
11321         default:
11322                 mtx_unlock(&lun->lun_lock);
11323                 ctl_set_internal_failure(ctsio,
11324                                          /*sks_valid*/ 0,
11325                                          /*retry_count*/ 0);
11326                 ctl_done((union ctl_io *)ctsio);
11327                 break;
11328         }
11329         return (retval);
11330 }
11331
11332 const struct ctl_cmd_entry *
11333 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11334 {
11335         const struct ctl_cmd_entry *entry;
11336         int service_action;
11337
11338         entry = &ctl_cmd_table[ctsio->cdb[0]];
11339         if (sa)
11340                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11341         if (entry->flags & CTL_CMD_FLAG_SA5) {
11342                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11343                 entry = &((const struct ctl_cmd_entry *)
11344                     entry->execute)[service_action];
11345         }
11346         return (entry);
11347 }
11348
11349 const struct ctl_cmd_entry *
11350 ctl_validate_command(struct ctl_scsiio *ctsio)
11351 {
11352         const struct ctl_cmd_entry *entry;
11353         int i, sa;
11354         uint8_t diff;
11355
11356         entry = ctl_get_cmd_entry(ctsio, &sa);
11357         if (entry->execute == NULL) {
11358                 if (sa)
11359                         ctl_set_invalid_field(ctsio,
11360                                               /*sks_valid*/ 1,
11361                                               /*command*/ 1,
11362                                               /*field*/ 1,
11363                                               /*bit_valid*/ 1,
11364                                               /*bit*/ 4);
11365                 else
11366                         ctl_set_invalid_opcode(ctsio);
11367                 ctl_done((union ctl_io *)ctsio);
11368                 return (NULL);
11369         }
11370         KASSERT(entry->length > 0,
11371             ("Not defined length for command 0x%02x/0x%02x",
11372              ctsio->cdb[0], ctsio->cdb[1]));
11373         for (i = 1; i < entry->length; i++) {
11374                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11375                 if (diff == 0)
11376                         continue;
11377                 ctl_set_invalid_field(ctsio,
11378                                       /*sks_valid*/ 1,
11379                                       /*command*/ 1,
11380                                       /*field*/ i,
11381                                       /*bit_valid*/ 1,
11382                                       /*bit*/ fls(diff) - 1);
11383                 ctl_done((union ctl_io *)ctsio);
11384                 return (NULL);
11385         }
11386         return (entry);
11387 }
11388
11389 static int
11390 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11391 {
11392
11393         switch (lun_type) {
11394         case T_PROCESSOR:
11395                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11396                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11397                         return (0);
11398                 break;
11399         case T_DIRECT:
11400                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11401                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11402                         return (0);
11403                 break;
11404         default:
11405                 return (0);
11406         }
11407         return (1);
11408 }
11409
11410 static int
11411 ctl_scsiio(struct ctl_scsiio *ctsio)
11412 {
11413         int retval;
11414         const struct ctl_cmd_entry *entry;
11415
11416         retval = CTL_RETVAL_COMPLETE;
11417
11418         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11419
11420         entry = ctl_get_cmd_entry(ctsio, NULL);
11421
11422         /*
11423          * If this I/O has been aborted, just send it straight to
11424          * ctl_done() without executing it.
11425          */
11426         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11427                 ctl_done((union ctl_io *)ctsio);
11428                 goto bailout;
11429         }
11430
11431         /*
11432          * All the checks should have been handled by ctl_scsiio_precheck().
11433          * We should be clear now to just execute the I/O.
11434          */
11435         retval = entry->execute(ctsio);
11436
11437 bailout:
11438         return (retval);
11439 }
11440
11441 /*
11442  * Since we only implement one target right now, a bus reset simply resets
11443  * our single target.
11444  */
11445 static int
11446 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11447 {
11448         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11449 }
11450
11451 static int
11452 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11453                  ctl_ua_type ua_type)
11454 {
11455         struct ctl_port *port;
11456         struct ctl_lun *lun;
11457         int retval;
11458
11459         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11460                 union ctl_ha_msg msg_info;
11461
11462                 msg_info.hdr.nexus = io->io_hdr.nexus;
11463                 if (ua_type==CTL_UA_TARG_RESET)
11464                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11465                 else
11466                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11467                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11468                 msg_info.hdr.original_sc = NULL;
11469                 msg_info.hdr.serializing_sc = NULL;
11470                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11471                     sizeof(msg_info.task), M_WAITOK);
11472         }
11473         retval = 0;
11474
11475         mtx_lock(&softc->ctl_lock);
11476         port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11477         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11478                 if (port != NULL &&
11479                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11480                         continue;
11481                 retval += ctl_do_lun_reset(lun, io, ua_type);
11482         }
11483         mtx_unlock(&softc->ctl_lock);
11484         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11485         return (retval);
11486 }
11487
11488 /*
11489  * The LUN should always be set.  The I/O is optional, and is used to
11490  * distinguish between I/Os sent by this initiator, and by other
11491  * initiators.  We set unit attention for initiators other than this one.
11492  * SAM-3 is vague on this point.  It does say that a unit attention should
11493  * be established for other initiators when a LUN is reset (see section
11494  * 5.7.3), but it doesn't specifically say that the unit attention should
11495  * be established for this particular initiator when a LUN is reset.  Here
11496  * is the relevant text, from SAM-3 rev 8:
11497  *
11498  * 5.7.2 When a SCSI initiator port aborts its own tasks
11499  *
11500  * When a SCSI initiator port causes its own task(s) to be aborted, no
11501  * notification that the task(s) have been aborted shall be returned to
11502  * the SCSI initiator port other than the completion response for the
11503  * command or task management function action that caused the task(s) to
11504  * be aborted and notification(s) associated with related effects of the
11505  * action (e.g., a reset unit attention condition).
11506  *
11507  * XXX KDM for now, we're setting unit attention for all initiators.
11508  */
11509 static int
11510 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11511 {
11512         union ctl_io *xio;
11513 #if 0
11514         uint32_t initidx;
11515 #endif
11516 #ifdef CTL_WITH_CA
11517         int i;
11518 #endif
11519
11520         mtx_lock(&lun->lun_lock);
11521         /*
11522          * Run through the OOA queue and abort each I/O.
11523          */
11524         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11525              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11526                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11527         }
11528
11529         /*
11530          * This version sets unit attention for every
11531          */
11532 #if 0
11533         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11534         ctl_est_ua_all(lun, initidx, ua_type);
11535 #else
11536         ctl_est_ua_all(lun, -1, ua_type);
11537 #endif
11538
11539         /*
11540          * A reset (any kind, really) clears reservations established with
11541          * RESERVE/RELEASE.  It does not clear reservations established
11542          * with PERSISTENT RESERVE OUT, but we don't support that at the
11543          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11544          * reservations made with the RESERVE/RELEASE commands, because
11545          * those commands are obsolete in SPC-3.
11546          */
11547         lun->flags &= ~CTL_LUN_RESERVED;
11548
11549 #ifdef CTL_WITH_CA
11550         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11551                 ctl_clear_mask(lun->have_ca, i);
11552 #endif
11553         mtx_unlock(&lun->lun_lock);
11554
11555         return (0);
11556 }
11557
11558 static int
11559 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11560 {
11561         struct ctl_lun *lun;
11562         uint32_t targ_lun;
11563         int retval;
11564
11565         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11566         mtx_lock(&softc->ctl_lock);
11567         if ((targ_lun >= CTL_MAX_LUNS) ||
11568             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11569                 mtx_unlock(&softc->ctl_lock);
11570                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11571                 return (1);
11572         }
11573         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11574         mtx_unlock(&softc->ctl_lock);
11575         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11576
11577         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11578                 union ctl_ha_msg msg_info;
11579
11580                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11581                 msg_info.hdr.nexus = io->io_hdr.nexus;
11582                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11583                 msg_info.hdr.original_sc = NULL;
11584                 msg_info.hdr.serializing_sc = NULL;
11585                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11586                     sizeof(msg_info.task), M_WAITOK);
11587         }
11588         return (retval);
11589 }
11590
11591 static void
11592 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11593     int other_sc)
11594 {
11595         union ctl_io *xio;
11596
11597         mtx_assert(&lun->lun_lock, MA_OWNED);
11598
11599         /*
11600          * Run through the OOA queue and attempt to find the given I/O.
11601          * The target port, initiator ID, tag type and tag number have to
11602          * match the values that we got from the initiator.  If we have an
11603          * untagged command to abort, simply abort the first untagged command
11604          * we come to.  We only allow one untagged command at a time of course.
11605          */
11606         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11607              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11608
11609                 if ((targ_port == UINT32_MAX ||
11610                      targ_port == xio->io_hdr.nexus.targ_port) &&
11611                     (init_id == UINT32_MAX ||
11612                      init_id == xio->io_hdr.nexus.initid)) {
11613                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11614                             init_id != xio->io_hdr.nexus.initid)
11615                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11616                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11617                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11618                                 union ctl_ha_msg msg_info;
11619
11620                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11621                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11622                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11623                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11624                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11625                                 msg_info.hdr.original_sc = NULL;
11626                                 msg_info.hdr.serializing_sc = NULL;
11627                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11628                                     sizeof(msg_info.task), M_NOWAIT);
11629                         }
11630                 }
11631         }
11632 }
11633
11634 static int
11635 ctl_abort_task_set(union ctl_io *io)
11636 {
11637         struct ctl_softc *softc = control_softc;
11638         struct ctl_lun *lun;
11639         uint32_t targ_lun;
11640
11641         /*
11642          * Look up the LUN.
11643          */
11644         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11645         mtx_lock(&softc->ctl_lock);
11646         if ((targ_lun >= CTL_MAX_LUNS) ||
11647             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11648                 mtx_unlock(&softc->ctl_lock);
11649                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11650                 return (1);
11651         }
11652
11653         mtx_lock(&lun->lun_lock);
11654         mtx_unlock(&softc->ctl_lock);
11655         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11656                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11657                     io->io_hdr.nexus.initid,
11658                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11659         } else { /* CTL_TASK_CLEAR_TASK_SET */
11660                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11661                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11662         }
11663         mtx_unlock(&lun->lun_lock);
11664         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11665         return (0);
11666 }
11667
11668 static int
11669 ctl_i_t_nexus_reset(union ctl_io *io)
11670 {
11671         struct ctl_softc *softc = control_softc;
11672         struct ctl_lun *lun;
11673         uint32_t initidx;
11674
11675         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11676                 union ctl_ha_msg msg_info;
11677
11678                 msg_info.hdr.nexus = io->io_hdr.nexus;
11679                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11680                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11681                 msg_info.hdr.original_sc = NULL;
11682                 msg_info.hdr.serializing_sc = NULL;
11683                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11684                     sizeof(msg_info.task), M_WAITOK);
11685         }
11686
11687         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11688         mtx_lock(&softc->ctl_lock);
11689         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11690                 mtx_lock(&lun->lun_lock);
11691                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11692                     io->io_hdr.nexus.initid, 1);
11693 #ifdef CTL_WITH_CA
11694                 ctl_clear_mask(lun->have_ca, initidx);
11695 #endif
11696                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11697                         lun->flags &= ~CTL_LUN_RESERVED;
11698                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11699                 mtx_unlock(&lun->lun_lock);
11700         }
11701         mtx_unlock(&softc->ctl_lock);
11702         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11703         return (0);
11704 }
11705
11706 static int
11707 ctl_abort_task(union ctl_io *io)
11708 {
11709         union ctl_io *xio;
11710         struct ctl_lun *lun;
11711         struct ctl_softc *softc;
11712 #if 0
11713         struct sbuf sb;
11714         char printbuf[128];
11715 #endif
11716         int found;
11717         uint32_t targ_lun;
11718
11719         softc = control_softc;
11720         found = 0;
11721
11722         /*
11723          * Look up the LUN.
11724          */
11725         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11726         mtx_lock(&softc->ctl_lock);
11727         if ((targ_lun >= CTL_MAX_LUNS) ||
11728             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11729                 mtx_unlock(&softc->ctl_lock);
11730                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11731                 return (1);
11732         }
11733
11734 #if 0
11735         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11736                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11737 #endif
11738
11739         mtx_lock(&lun->lun_lock);
11740         mtx_unlock(&softc->ctl_lock);
11741         /*
11742          * Run through the OOA queue and attempt to find the given I/O.
11743          * The target port, initiator ID, tag type and tag number have to
11744          * match the values that we got from the initiator.  If we have an
11745          * untagged command to abort, simply abort the first untagged command
11746          * we come to.  We only allow one untagged command at a time of course.
11747          */
11748         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11749              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11750 #if 0
11751                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11752
11753                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11754                             lun->lun, xio->scsiio.tag_num,
11755                             xio->scsiio.tag_type,
11756                             (xio->io_hdr.blocked_links.tqe_prev
11757                             == NULL) ? "" : " BLOCKED",
11758                             (xio->io_hdr.flags &
11759                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11760                             (xio->io_hdr.flags &
11761                             CTL_FLAG_ABORT) ? " ABORT" : "",
11762                             (xio->io_hdr.flags &
11763                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11764                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11765                 sbuf_finish(&sb);
11766                 printf("%s\n", sbuf_data(&sb));
11767 #endif
11768
11769                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11770                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11771                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11772                         continue;
11773
11774                 /*
11775                  * If the abort says that the task is untagged, the
11776                  * task in the queue must be untagged.  Otherwise,
11777                  * we just check to see whether the tag numbers
11778                  * match.  This is because the QLogic firmware
11779                  * doesn't pass back the tag type in an abort
11780                  * request.
11781                  */
11782 #if 0
11783                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11784                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11785                  || (xio->scsiio.tag_num == io->taskio.tag_num))
11786 #endif
11787                 /*
11788                  * XXX KDM we've got problems with FC, because it
11789                  * doesn't send down a tag type with aborts.  So we
11790                  * can only really go by the tag number...
11791                  * This may cause problems with parallel SCSI.
11792                  * Need to figure that out!!
11793                  */
11794                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
11795                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11796                         found = 1;
11797                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11798                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11799                                 union ctl_ha_msg msg_info;
11800
11801                                 msg_info.hdr.nexus = io->io_hdr.nexus;
11802                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11803                                 msg_info.task.tag_num = io->taskio.tag_num;
11804                                 msg_info.task.tag_type = io->taskio.tag_type;
11805                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11806                                 msg_info.hdr.original_sc = NULL;
11807                                 msg_info.hdr.serializing_sc = NULL;
11808 #if 0
11809                                 printf("Sent Abort to other side\n");
11810 #endif
11811                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11812                                     sizeof(msg_info.task), M_NOWAIT);
11813                         }
11814 #if 0
11815                         printf("ctl_abort_task: found I/O to abort\n");
11816 #endif
11817                 }
11818         }
11819         mtx_unlock(&lun->lun_lock);
11820
11821         if (found == 0) {
11822                 /*
11823                  * This isn't really an error.  It's entirely possible for
11824                  * the abort and command completion to cross on the wire.
11825                  * This is more of an informative/diagnostic error.
11826                  */
11827 #if 0
11828                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11829                        "%u:%u:%u tag %d type %d\n",
11830                        io->io_hdr.nexus.initid,
11831                        io->io_hdr.nexus.targ_port,
11832                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11833                        io->taskio.tag_type);
11834 #endif
11835         }
11836         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11837         return (0);
11838 }
11839
11840 static int
11841 ctl_query_task(union ctl_io *io, int task_set)
11842 {
11843         union ctl_io *xio;
11844         struct ctl_lun *lun;
11845         struct ctl_softc *softc;
11846         int found = 0;
11847         uint32_t targ_lun;
11848
11849         softc = control_softc;
11850         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11851         mtx_lock(&softc->ctl_lock);
11852         if ((targ_lun >= CTL_MAX_LUNS) ||
11853             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11854                 mtx_unlock(&softc->ctl_lock);
11855                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11856                 return (1);
11857         }
11858         mtx_lock(&lun->lun_lock);
11859         mtx_unlock(&softc->ctl_lock);
11860         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11861              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11862
11863                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11864                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11865                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11866                         continue;
11867
11868                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11869                         found = 1;
11870                         break;
11871                 }
11872         }
11873         mtx_unlock(&lun->lun_lock);
11874         if (found)
11875                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11876         else
11877                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11878         return (0);
11879 }
11880
11881 static int
11882 ctl_query_async_event(union ctl_io *io)
11883 {
11884         struct ctl_lun *lun;
11885         struct ctl_softc *softc;
11886         ctl_ua_type ua;
11887         uint32_t targ_lun, initidx;
11888
11889         softc = control_softc;
11890         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11891         mtx_lock(&softc->ctl_lock);
11892         if ((targ_lun >= CTL_MAX_LUNS) ||
11893             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11894                 mtx_unlock(&softc->ctl_lock);
11895                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11896                 return (1);
11897         }
11898         mtx_lock(&lun->lun_lock);
11899         mtx_unlock(&softc->ctl_lock);
11900         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11901         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
11902         mtx_unlock(&lun->lun_lock);
11903         if (ua != CTL_UA_NONE)
11904                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11905         else
11906                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11907         return (0);
11908 }
11909
11910 static void
11911 ctl_run_task(union ctl_io *io)
11912 {
11913         struct ctl_softc *softc = control_softc;
11914         int retval = 1;
11915
11916         CTL_DEBUG_PRINT(("ctl_run_task\n"));
11917         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11918             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
11919         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
11920         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
11921         switch (io->taskio.task_action) {
11922         case CTL_TASK_ABORT_TASK:
11923                 retval = ctl_abort_task(io);
11924                 break;
11925         case CTL_TASK_ABORT_TASK_SET:
11926         case CTL_TASK_CLEAR_TASK_SET:
11927                 retval = ctl_abort_task_set(io);
11928                 break;
11929         case CTL_TASK_CLEAR_ACA:
11930                 break;
11931         case CTL_TASK_I_T_NEXUS_RESET:
11932                 retval = ctl_i_t_nexus_reset(io);
11933                 break;
11934         case CTL_TASK_LUN_RESET:
11935                 retval = ctl_lun_reset(softc, io);
11936                 break;
11937         case CTL_TASK_TARGET_RESET:
11938                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11939                 break;
11940         case CTL_TASK_BUS_RESET:
11941                 retval = ctl_bus_reset(softc, io);
11942                 break;
11943         case CTL_TASK_PORT_LOGIN:
11944                 break;
11945         case CTL_TASK_PORT_LOGOUT:
11946                 break;
11947         case CTL_TASK_QUERY_TASK:
11948                 retval = ctl_query_task(io, 0);
11949                 break;
11950         case CTL_TASK_QUERY_TASK_SET:
11951                 retval = ctl_query_task(io, 1);
11952                 break;
11953         case CTL_TASK_QUERY_ASYNC_EVENT:
11954                 retval = ctl_query_async_event(io);
11955                 break;
11956         default:
11957                 printf("%s: got unknown task management event %d\n",
11958                        __func__, io->taskio.task_action);
11959                 break;
11960         }
11961         if (retval == 0)
11962                 io->io_hdr.status = CTL_SUCCESS;
11963         else
11964                 io->io_hdr.status = CTL_ERROR;
11965         ctl_done(io);
11966 }
11967
11968 /*
11969  * For HA operation.  Handle commands that come in from the other
11970  * controller.
11971  */
11972 static void
11973 ctl_handle_isc(union ctl_io *io)
11974 {
11975         int free_io;
11976         struct ctl_lun *lun;
11977         struct ctl_softc *softc;
11978         uint32_t targ_lun;
11979
11980         softc = control_softc;
11981
11982         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11983         lun = softc->ctl_luns[targ_lun];
11984
11985         switch (io->io_hdr.msg_type) {
11986         case CTL_MSG_SERIALIZE:
11987                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11988                 break;
11989         case CTL_MSG_R2R: {
11990                 const struct ctl_cmd_entry *entry;
11991
11992                 /*
11993                  * This is only used in SER_ONLY mode.
11994                  */
11995                 free_io = 0;
11996                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11997                 mtx_lock(&lun->lun_lock);
11998                 if (ctl_scsiio_lun_check(lun,
11999                     entry, (struct ctl_scsiio *)io) != 0) {
12000                         mtx_unlock(&lun->lun_lock);
12001                         ctl_done(io);
12002                         break;
12003                 }
12004                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12005                 mtx_unlock(&lun->lun_lock);
12006                 ctl_enqueue_rtr(io);
12007                 break;
12008         }
12009         case CTL_MSG_FINISH_IO:
12010                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12011                         free_io = 0;
12012                         ctl_done(io);
12013                 } else {
12014                         free_io = 1;
12015                         mtx_lock(&lun->lun_lock);
12016                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12017                                      ooa_links);
12018                         ctl_check_blocked(lun);
12019                         mtx_unlock(&lun->lun_lock);
12020                 }
12021                 break;
12022         case CTL_MSG_PERS_ACTION:
12023                 ctl_hndl_per_res_out_on_other_sc(
12024                         (union ctl_ha_msg *)&io->presio.pr_msg);
12025                 free_io = 1;
12026                 break;
12027         case CTL_MSG_BAD_JUJU:
12028                 free_io = 0;
12029                 ctl_done(io);
12030                 break;
12031         case CTL_MSG_DATAMOVE:
12032                 /* Only used in XFER mode */
12033                 free_io = 0;
12034                 ctl_datamove_remote(io);
12035                 break;
12036         case CTL_MSG_DATAMOVE_DONE:
12037                 /* Only used in XFER mode */
12038                 free_io = 0;
12039                 io->scsiio.be_move_done(io);
12040                 break;
12041         case CTL_MSG_FAILOVER:
12042                 mtx_lock(&lun->lun_lock);
12043                 ctl_failover_lun(lun);
12044                 mtx_unlock(&lun->lun_lock);
12045                 free_io = 1;
12046                 break;
12047         default:
12048                 free_io = 1;
12049                 printf("%s: Invalid message type %d\n",
12050                        __func__, io->io_hdr.msg_type);
12051                 break;
12052         }
12053         if (free_io)
12054                 ctl_free_io(io);
12055
12056 }
12057
12058
12059 /*
12060  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12061  * there is no match.
12062  */
12063 static ctl_lun_error_pattern
12064 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12065 {
12066         const struct ctl_cmd_entry *entry;
12067         ctl_lun_error_pattern filtered_pattern, pattern;
12068
12069         pattern = desc->error_pattern;
12070
12071         /*
12072          * XXX KDM we need more data passed into this function to match a
12073          * custom pattern, and we actually need to implement custom pattern
12074          * matching.
12075          */
12076         if (pattern & CTL_LUN_PAT_CMD)
12077                 return (CTL_LUN_PAT_CMD);
12078
12079         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12080                 return (CTL_LUN_PAT_ANY);
12081
12082         entry = ctl_get_cmd_entry(ctsio, NULL);
12083
12084         filtered_pattern = entry->pattern & pattern;
12085
12086         /*
12087          * If the user requested specific flags in the pattern (e.g.
12088          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12089          * flags.
12090          *
12091          * If the user did not specify any flags, it doesn't matter whether
12092          * or not the command supports the flags.
12093          */
12094         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12095              (pattern & ~CTL_LUN_PAT_MASK))
12096                 return (CTL_LUN_PAT_NONE);
12097
12098         /*
12099          * If the user asked for a range check, see if the requested LBA
12100          * range overlaps with this command's LBA range.
12101          */
12102         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12103                 uint64_t lba1;
12104                 uint64_t len1;
12105                 ctl_action action;
12106                 int retval;
12107
12108                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12109                 if (retval != 0)
12110                         return (CTL_LUN_PAT_NONE);
12111
12112                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12113                                               desc->lba_range.len, FALSE);
12114                 /*
12115                  * A "pass" means that the LBA ranges don't overlap, so
12116                  * this doesn't match the user's range criteria.
12117                  */
12118                 if (action == CTL_ACTION_PASS)
12119                         return (CTL_LUN_PAT_NONE);
12120         }
12121
12122         return (filtered_pattern);
12123 }
12124
12125 static void
12126 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12127 {
12128         struct ctl_error_desc *desc, *desc2;
12129
12130         mtx_assert(&lun->lun_lock, MA_OWNED);
12131
12132         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12133                 ctl_lun_error_pattern pattern;
12134                 /*
12135                  * Check to see whether this particular command matches
12136                  * the pattern in the descriptor.
12137                  */
12138                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12139                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12140                         continue;
12141
12142                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12143                 case CTL_LUN_INJ_ABORTED:
12144                         ctl_set_aborted(&io->scsiio);
12145                         break;
12146                 case CTL_LUN_INJ_MEDIUM_ERR:
12147                         ctl_set_medium_error(&io->scsiio,
12148                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12149                              CTL_FLAG_DATA_OUT);
12150                         break;
12151                 case CTL_LUN_INJ_UA:
12152                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12153                          * OCCURRED */
12154                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12155                         break;
12156                 case CTL_LUN_INJ_CUSTOM:
12157                         /*
12158                          * We're assuming the user knows what he is doing.
12159                          * Just copy the sense information without doing
12160                          * checks.
12161                          */
12162                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12163                               MIN(sizeof(desc->custom_sense),
12164                                   sizeof(io->scsiio.sense_data)));
12165                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12166                         io->scsiio.sense_len = SSD_FULL_SIZE;
12167                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12168                         break;
12169                 case CTL_LUN_INJ_NONE:
12170                 default:
12171                         /*
12172                          * If this is an error injection type we don't know
12173                          * about, clear the continuous flag (if it is set)
12174                          * so it will get deleted below.
12175                          */
12176                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12177                         break;
12178                 }
12179                 /*
12180                  * By default, each error injection action is a one-shot
12181                  */
12182                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12183                         continue;
12184
12185                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12186
12187                 free(desc, M_CTL);
12188         }
12189 }
12190
12191 #ifdef CTL_IO_DELAY
12192 static void
12193 ctl_datamove_timer_wakeup(void *arg)
12194 {
12195         union ctl_io *io;
12196
12197         io = (union ctl_io *)arg;
12198
12199         ctl_datamove(io);
12200 }
12201 #endif /* CTL_IO_DELAY */
12202
12203 void
12204 ctl_datamove(union ctl_io *io)
12205 {
12206         struct ctl_lun *lun;
12207         void (*fe_datamove)(union ctl_io *io);
12208
12209         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12210
12211         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12212
12213         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12214 #ifdef CTL_TIME_IO
12215         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12216                 char str[256];
12217                 char path_str[64];
12218                 struct sbuf sb;
12219
12220                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12221                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12222
12223                 sbuf_cat(&sb, path_str);
12224                 switch (io->io_hdr.io_type) {
12225                 case CTL_IO_SCSI:
12226                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12227                         sbuf_printf(&sb, "\n");
12228                         sbuf_cat(&sb, path_str);
12229                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12230                                     io->scsiio.tag_num, io->scsiio.tag_type);
12231                         break;
12232                 case CTL_IO_TASK:
12233                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12234                                     "Tag Type: %d\n", io->taskio.task_action,
12235                                     io->taskio.tag_num, io->taskio.tag_type);
12236                         break;
12237                 default:
12238                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12239                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12240                         break;
12241                 }
12242                 sbuf_cat(&sb, path_str);
12243                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12244                             (intmax_t)time_uptime - io->io_hdr.start_time);
12245                 sbuf_finish(&sb);
12246                 printf("%s", sbuf_data(&sb));
12247         }
12248 #endif /* CTL_TIME_IO */
12249
12250 #ifdef CTL_IO_DELAY
12251         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12252                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12253         } else {
12254                 if ((lun != NULL)
12255                  && (lun->delay_info.datamove_delay > 0)) {
12256
12257                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12258                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12259                         callout_reset(&io->io_hdr.delay_callout,
12260                                       lun->delay_info.datamove_delay * hz,
12261                                       ctl_datamove_timer_wakeup, io);
12262                         if (lun->delay_info.datamove_type ==
12263                             CTL_DELAY_TYPE_ONESHOT)
12264                                 lun->delay_info.datamove_delay = 0;
12265                         return;
12266                 }
12267         }
12268 #endif
12269
12270         /*
12271          * This command has been aborted.  Set the port status, so we fail
12272          * the data move.
12273          */
12274         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12275                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12276                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12277                        io->io_hdr.nexus.targ_port,
12278                        io->io_hdr.nexus.targ_lun);
12279                 io->io_hdr.port_status = 31337;
12280                 /*
12281                  * Note that the backend, in this case, will get the
12282                  * callback in its context.  In other cases it may get
12283                  * called in the frontend's interrupt thread context.
12284                  */
12285                 io->scsiio.be_move_done(io);
12286                 return;
12287         }
12288
12289         /* Don't confuse frontend with zero length data move. */
12290         if (io->scsiio.kern_data_len == 0) {
12291                 io->scsiio.be_move_done(io);
12292                 return;
12293         }
12294
12295         /*
12296          * If we're in XFER mode and this I/O is from the other shelf
12297          * controller, we need to send the DMA to the other side to
12298          * actually transfer the data to/from the host.  In serialize only
12299          * mode the transfer happens below CTL and ctl_datamove() is only
12300          * called on the machine that originally received the I/O.
12301          */
12302         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12303          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12304                 union ctl_ha_msg msg;
12305                 uint32_t sg_entries_sent;
12306                 int do_sg_copy;
12307                 int i;
12308
12309                 memset(&msg, 0, sizeof(msg));
12310                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12311                 msg.hdr.original_sc = io->io_hdr.original_sc;
12312                 msg.hdr.serializing_sc = io;
12313                 msg.hdr.nexus = io->io_hdr.nexus;
12314                 msg.hdr.status = io->io_hdr.status;
12315                 msg.dt.flags = io->io_hdr.flags;
12316                 /*
12317                  * We convert everything into a S/G list here.  We can't
12318                  * pass by reference, only by value between controllers.
12319                  * So we can't pass a pointer to the S/G list, only as many
12320                  * S/G entries as we can fit in here.  If it's possible for
12321                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12322                  * then we need to break this up into multiple transfers.
12323                  */
12324                 if (io->scsiio.kern_sg_entries == 0) {
12325                         msg.dt.kern_sg_entries = 1;
12326 #if 0
12327                         /*
12328                          * Convert to a physical address if this is a
12329                          * virtual address.
12330                          */
12331                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12332                                 msg.dt.sg_list[0].addr =
12333                                         io->scsiio.kern_data_ptr;
12334                         } else {
12335                                 /*
12336                                  * XXX KDM use busdma here!
12337                                  */
12338                                 msg.dt.sg_list[0].addr = (void *)
12339                                         vtophys(io->scsiio.kern_data_ptr);
12340                         }
12341 #else
12342                         KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12343                             ("HA does not support BUS_ADDR"));
12344                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12345 #endif
12346
12347                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12348                         do_sg_copy = 0;
12349                 } else {
12350                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12351                         do_sg_copy = 1;
12352                 }
12353
12354                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12355                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12356                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12357                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12358                 msg.dt.sg_sequence = 0;
12359
12360                 /*
12361                  * Loop until we've sent all of the S/G entries.  On the
12362                  * other end, we'll recompose these S/G entries into one
12363                  * contiguous list before passing it to the
12364                  */
12365                 for (sg_entries_sent = 0; sg_entries_sent <
12366                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12367                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12368                                 sizeof(msg.dt.sg_list[0])),
12369                                 msg.dt.kern_sg_entries - sg_entries_sent);
12370
12371                         if (do_sg_copy != 0) {
12372                                 struct ctl_sg_entry *sgl;
12373                                 int j;
12374
12375                                 sgl = (struct ctl_sg_entry *)
12376                                         io->scsiio.kern_data_ptr;
12377                                 /*
12378                                  * If this is in cached memory, flush the cache
12379                                  * before we send the DMA request to the other
12380                                  * controller.  We want to do this in either
12381                                  * the * read or the write case.  The read
12382                                  * case is straightforward.  In the write
12383                                  * case, we want to make sure nothing is
12384                                  * in the local cache that could overwrite
12385                                  * the DMAed data.
12386                                  */
12387
12388                                 for (i = sg_entries_sent, j = 0;
12389                                      i < msg.dt.cur_sg_entries; i++, j++) {
12390 #if 0
12391                                         if ((io->io_hdr.flags &
12392                                              CTL_FLAG_BUS_ADDR) == 0) {
12393                                                 /*
12394                                                  * XXX KDM use busdma.
12395                                                  */
12396                                                 msg.dt.sg_list[j].addr =(void *)
12397                                                        vtophys(sgl[i].addr);
12398                                         } else {
12399                                                 msg.dt.sg_list[j].addr =
12400                                                         sgl[i].addr;
12401                                         }
12402 #else
12403                                         KASSERT((io->io_hdr.flags &
12404                                             CTL_FLAG_BUS_ADDR) == 0,
12405                                             ("HA does not support BUS_ADDR"));
12406                                         msg.dt.sg_list[j].addr = sgl[i].addr;
12407 #endif
12408                                         msg.dt.sg_list[j].len = sgl[i].len;
12409                                 }
12410                         }
12411
12412                         sg_entries_sent += msg.dt.cur_sg_entries;
12413                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12414                                 msg.dt.sg_last = 1;
12415                         else
12416                                 msg.dt.sg_last = 0;
12417
12418                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12419                             sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12420                             sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12421                             M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12422                                 io->io_hdr.port_status = 31341;
12423                                 io->scsiio.be_move_done(io);
12424                                 return;
12425                         }
12426
12427                         msg.dt.sent_sg_entries = sg_entries_sent;
12428                 }
12429
12430                 /*
12431                  * Officially handover the request from us to peer.
12432                  * If failover has just happened, then we must return error.
12433                  * If failover happen just after, then it is not our problem.
12434                  */
12435                 if (lun)
12436                         mtx_lock(&lun->lun_lock);
12437                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12438                         if (lun)
12439                                 mtx_unlock(&lun->lun_lock);
12440                         io->io_hdr.port_status = 31342;
12441                         io->scsiio.be_move_done(io);
12442                         return;
12443                 }
12444                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12445                 if (lun)
12446                         mtx_unlock(&lun->lun_lock);
12447         } else {
12448
12449                 /*
12450                  * Lookup the fe_datamove() function for this particular
12451                  * front end.
12452                  */
12453                 fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12454
12455                 fe_datamove(io);
12456         }
12457 }
12458
12459 static void
12460 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12461 {
12462         union ctl_ha_msg msg;
12463
12464         memset(&msg, 0, sizeof(msg));
12465
12466         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12467         msg.hdr.original_sc = io;
12468         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12469         msg.hdr.nexus = io->io_hdr.nexus;
12470         msg.hdr.status = io->io_hdr.status;
12471         msg.scsi.tag_num = io->scsiio.tag_num;
12472         msg.scsi.tag_type = io->scsiio.tag_type;
12473         msg.scsi.scsi_status = io->scsiio.scsi_status;
12474         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12475                io->scsiio.sense_len);
12476         msg.scsi.sense_len = io->scsiio.sense_len;
12477         msg.scsi.sense_residual = io->scsiio.sense_residual;
12478         msg.scsi.fetd_status = io->io_hdr.port_status;
12479         msg.scsi.residual = io->scsiio.residual;
12480         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12481
12482         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12483                 ctl_failover_io(io, /*have_lock*/ have_lock);
12484                 return;
12485         }
12486
12487         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12488             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12489             msg.scsi.sense_len, M_WAITOK);
12490 }
12491
12492 /*
12493  * The DMA to the remote side is done, now we need to tell the other side
12494  * we're done so it can continue with its data movement.
12495  */
12496 static void
12497 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12498 {
12499         union ctl_io *io;
12500         int i;
12501
12502         io = rq->context;
12503
12504         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12505                 printf("%s: ISC DMA write failed with error %d", __func__,
12506                        rq->ret);
12507                 ctl_set_internal_failure(&io->scsiio,
12508                                          /*sks_valid*/ 1,
12509                                          /*retry_count*/ rq->ret);
12510         }
12511
12512         ctl_dt_req_free(rq);
12513
12514         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12515                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12516         free(io->io_hdr.remote_sglist, M_CTL);
12517         io->io_hdr.remote_sglist = NULL;
12518         io->io_hdr.local_sglist = NULL;
12519
12520         /*
12521          * The data is in local and remote memory, so now we need to send
12522          * status (good or back) back to the other side.
12523          */
12524         ctl_send_datamove_done(io, /*have_lock*/ 0);
12525 }
12526
12527 /*
12528  * We've moved the data from the host/controller into local memory.  Now we
12529  * need to push it over to the remote controller's memory.
12530  */
12531 static int
12532 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12533 {
12534         int retval;
12535
12536         retval = 0;
12537
12538         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12539                                           ctl_datamove_remote_write_cb);
12540
12541         return (retval);
12542 }
12543
12544 static void
12545 ctl_datamove_remote_write(union ctl_io *io)
12546 {
12547         int retval;
12548         void (*fe_datamove)(union ctl_io *io);
12549
12550         /*
12551          * - Get the data from the host/HBA into local memory.
12552          * - DMA memory from the local controller to the remote controller.
12553          * - Send status back to the remote controller.
12554          */
12555
12556         retval = ctl_datamove_remote_sgl_setup(io);
12557         if (retval != 0)
12558                 return;
12559
12560         /* Switch the pointer over so the FETD knows what to do */
12561         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12562
12563         /*
12564          * Use a custom move done callback, since we need to send completion
12565          * back to the other controller, not to the backend on this side.
12566          */
12567         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12568
12569         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12570
12571         fe_datamove(io);
12572
12573         return;
12574
12575 }
12576
12577 static int
12578 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12579 {
12580 #if 0
12581         char str[256];
12582         char path_str[64];
12583         struct sbuf sb;
12584 #endif
12585         int i;
12586
12587         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12588                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12589         free(io->io_hdr.remote_sglist, M_CTL);
12590         io->io_hdr.remote_sglist = NULL;
12591         io->io_hdr.local_sglist = NULL;
12592
12593 #if 0
12594         scsi_path_string(io, path_str, sizeof(path_str));
12595         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12596         sbuf_cat(&sb, path_str);
12597         scsi_command_string(&io->scsiio, NULL, &sb);
12598         sbuf_printf(&sb, "\n");
12599         sbuf_cat(&sb, path_str);
12600         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12601                     io->scsiio.tag_num, io->scsiio.tag_type);
12602         sbuf_cat(&sb, path_str);
12603         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12604                     io->io_hdr.flags, io->io_hdr.status);
12605         sbuf_finish(&sb);
12606         printk("%s", sbuf_data(&sb));
12607 #endif
12608
12609
12610         /*
12611          * The read is done, now we need to send status (good or bad) back
12612          * to the other side.
12613          */
12614         ctl_send_datamove_done(io, /*have_lock*/ 0);
12615
12616         return (0);
12617 }
12618
12619 static void
12620 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12621 {
12622         union ctl_io *io;
12623         void (*fe_datamove)(union ctl_io *io);
12624
12625         io = rq->context;
12626
12627         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12628                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12629                        rq->ret);
12630                 ctl_set_internal_failure(&io->scsiio,
12631                                          /*sks_valid*/ 1,
12632                                          /*retry_count*/ rq->ret);
12633         }
12634
12635         ctl_dt_req_free(rq);
12636
12637         /* Switch the pointer over so the FETD knows what to do */
12638         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12639
12640         /*
12641          * Use a custom move done callback, since we need to send completion
12642          * back to the other controller, not to the backend on this side.
12643          */
12644         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12645
12646         /* XXX KDM add checks like the ones in ctl_datamove? */
12647
12648         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12649
12650         fe_datamove(io);
12651 }
12652
12653 static int
12654 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12655 {
12656         struct ctl_sg_entry *local_sglist, *remote_sglist;
12657         struct ctl_softc *softc;
12658         uint32_t len_to_go;
12659         int retval;
12660         int i;
12661
12662         retval = 0;
12663         softc = control_softc;
12664         local_sglist = io->io_hdr.local_sglist;
12665         remote_sglist = io->io_hdr.remote_sglist;
12666         len_to_go = io->scsiio.kern_data_len;
12667
12668         /*
12669          * The difficult thing here is that the size of the various
12670          * S/G segments may be different than the size from the
12671          * remote controller.  That'll make it harder when DMAing
12672          * the data back to the other side.
12673          */
12674         for (i = 0; len_to_go > 0; i++) {
12675                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12676                 local_sglist[i].addr =
12677                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12678
12679                 len_to_go -= local_sglist[i].len;
12680         }
12681         /*
12682          * Reset the number of S/G entries accordingly.  The original
12683          * number of S/G entries is available in rem_sg_entries.
12684          */
12685         io->scsiio.kern_sg_entries = i;
12686
12687 #if 0
12688         printf("%s: kern_sg_entries = %d\n", __func__,
12689                io->scsiio.kern_sg_entries);
12690         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12691                 printf("%s: sg[%d] = %p, %d\n", __func__, i,
12692                        local_sglist[i].addr, local_sglist[i].len);
12693 #endif
12694
12695         return (retval);
12696 }
12697
12698 static int
12699 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12700                          ctl_ha_dt_cb callback)
12701 {
12702         struct ctl_ha_dt_req *rq;
12703         struct ctl_sg_entry *remote_sglist, *local_sglist;
12704         uint32_t local_used, remote_used, total_used;
12705         int i, j, isc_ret;
12706
12707         rq = ctl_dt_req_alloc();
12708
12709         /*
12710          * If we failed to allocate the request, and if the DMA didn't fail
12711          * anyway, set busy status.  This is just a resource allocation
12712          * failure.
12713          */
12714         if ((rq == NULL)
12715          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12716              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12717                 ctl_set_busy(&io->scsiio);
12718
12719         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12720             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12721
12722                 if (rq != NULL)
12723                         ctl_dt_req_free(rq);
12724
12725                 /*
12726                  * The data move failed.  We need to return status back
12727                  * to the other controller.  No point in trying to DMA
12728                  * data to the remote controller.
12729                  */
12730
12731                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12732
12733                 return (1);
12734         }
12735
12736         local_sglist = io->io_hdr.local_sglist;
12737         remote_sglist = io->io_hdr.remote_sglist;
12738         local_used = 0;
12739         remote_used = 0;
12740         total_used = 0;
12741
12742         /*
12743          * Pull/push the data over the wire from/to the other controller.
12744          * This takes into account the possibility that the local and
12745          * remote sglists may not be identical in terms of the size of
12746          * the elements and the number of elements.
12747          *
12748          * One fundamental assumption here is that the length allocated for
12749          * both the local and remote sglists is identical.  Otherwise, we've
12750          * essentially got a coding error of some sort.
12751          */
12752         isc_ret = CTL_HA_STATUS_SUCCESS;
12753         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12754                 uint32_t cur_len;
12755                 uint8_t *tmp_ptr;
12756
12757                 rq->command = command;
12758                 rq->context = io;
12759
12760                 /*
12761                  * Both pointers should be aligned.  But it is possible
12762                  * that the allocation length is not.  They should both
12763                  * also have enough slack left over at the end, though,
12764                  * to round up to the next 8 byte boundary.
12765                  */
12766                 cur_len = MIN(local_sglist[i].len - local_used,
12767                               remote_sglist[j].len - remote_used);
12768                 rq->size = cur_len;
12769
12770                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12771                 tmp_ptr += local_used;
12772
12773 #if 0
12774                 /* Use physical addresses when talking to ISC hardware */
12775                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12776                         /* XXX KDM use busdma */
12777                         rq->local = vtophys(tmp_ptr);
12778                 } else
12779                         rq->local = tmp_ptr;
12780 #else
12781                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12782                     ("HA does not support BUS_ADDR"));
12783                 rq->local = tmp_ptr;
12784 #endif
12785
12786                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12787                 tmp_ptr += remote_used;
12788                 rq->remote = tmp_ptr;
12789
12790                 rq->callback = NULL;
12791
12792                 local_used += cur_len;
12793                 if (local_used >= local_sglist[i].len) {
12794                         i++;
12795                         local_used = 0;
12796                 }
12797
12798                 remote_used += cur_len;
12799                 if (remote_used >= remote_sglist[j].len) {
12800                         j++;
12801                         remote_used = 0;
12802                 }
12803                 total_used += cur_len;
12804
12805                 if (total_used >= io->scsiio.kern_data_len)
12806                         rq->callback = callback;
12807
12808 #if 0
12809                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12810                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12811                        rq->local, rq->remote, rq->size);
12812 #endif
12813
12814                 isc_ret = ctl_dt_single(rq);
12815                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12816                         break;
12817         }
12818         if (isc_ret != CTL_HA_STATUS_WAIT) {
12819                 rq->ret = isc_ret;
12820                 callback(rq);
12821         }
12822
12823         return (0);
12824 }
12825
12826 static void
12827 ctl_datamove_remote_read(union ctl_io *io)
12828 {
12829         int retval;
12830         int i;
12831
12832         /*
12833          * This will send an error to the other controller in the case of a
12834          * failure.
12835          */
12836         retval = ctl_datamove_remote_sgl_setup(io);
12837         if (retval != 0)
12838                 return;
12839
12840         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12841                                           ctl_datamove_remote_read_cb);
12842         if (retval != 0) {
12843                 /*
12844                  * Make sure we free memory if there was an error..  The
12845                  * ctl_datamove_remote_xfer() function will send the
12846                  * datamove done message, or call the callback with an
12847                  * error if there is a problem.
12848                  */
12849                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12850                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12851                 free(io->io_hdr.remote_sglist, M_CTL);
12852                 io->io_hdr.remote_sglist = NULL;
12853                 io->io_hdr.local_sglist = NULL;
12854         }
12855
12856         return;
12857 }
12858
12859 /*
12860  * Process a datamove request from the other controller.  This is used for
12861  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12862  * first.  Once that is complete, the data gets DMAed into the remote
12863  * controller's memory.  For reads, we DMA from the remote controller's
12864  * memory into our memory first, and then move it out to the FETD.
12865  */
12866 static void
12867 ctl_datamove_remote(union ctl_io *io)
12868 {
12869
12870         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12871
12872         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12873                 ctl_failover_io(io, /*have_lock*/ 0);
12874                 return;
12875         }
12876
12877         /*
12878          * Note that we look for an aborted I/O here, but don't do some of
12879          * the other checks that ctl_datamove() normally does.
12880          * We don't need to run the datamove delay code, since that should
12881          * have been done if need be on the other controller.
12882          */
12883         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12884                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12885                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12886                        io->io_hdr.nexus.targ_port,
12887                        io->io_hdr.nexus.targ_lun);
12888                 io->io_hdr.port_status = 31338;
12889                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12890                 return;
12891         }
12892
12893         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12894                 ctl_datamove_remote_write(io);
12895         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12896                 ctl_datamove_remote_read(io);
12897         else {
12898                 io->io_hdr.port_status = 31339;
12899                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12900         }
12901 }
12902
12903 static int
12904 ctl_process_done(union ctl_io *io)
12905 {
12906         struct ctl_lun *lun;
12907         struct ctl_softc *softc = control_softc;
12908         void (*fe_done)(union ctl_io *io);
12909         union ctl_ha_msg msg;
12910         uint32_t targ_port = io->io_hdr.nexus.targ_port;
12911
12912         CTL_DEBUG_PRINT(("ctl_process_done\n"));
12913
12914         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
12915                 fe_done = softc->ctl_ports[targ_port]->fe_done;
12916         else
12917                 fe_done = NULL;
12918
12919 #ifdef CTL_TIME_IO
12920         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12921                 char str[256];
12922                 char path_str[64];
12923                 struct sbuf sb;
12924
12925                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12926                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12927
12928                 sbuf_cat(&sb, path_str);
12929                 switch (io->io_hdr.io_type) {
12930                 case CTL_IO_SCSI:
12931                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12932                         sbuf_printf(&sb, "\n");
12933                         sbuf_cat(&sb, path_str);
12934                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12935                                     io->scsiio.tag_num, io->scsiio.tag_type);
12936                         break;
12937                 case CTL_IO_TASK:
12938                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12939                                     "Tag Type: %d\n", io->taskio.task_action,
12940                                     io->taskio.tag_num, io->taskio.tag_type);
12941                         break;
12942                 default:
12943                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12944                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12945                         break;
12946                 }
12947                 sbuf_cat(&sb, path_str);
12948                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12949                             (intmax_t)time_uptime - io->io_hdr.start_time);
12950                 sbuf_finish(&sb);
12951                 printf("%s", sbuf_data(&sb));
12952         }
12953 #endif /* CTL_TIME_IO */
12954
12955         switch (io->io_hdr.io_type) {
12956         case CTL_IO_SCSI:
12957                 break;
12958         case CTL_IO_TASK:
12959                 if (ctl_debug & CTL_DEBUG_INFO)
12960                         ctl_io_error_print(io, NULL);
12961                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12962                         ctl_free_io(io);
12963                 else
12964                         fe_done(io);
12965                 return (CTL_RETVAL_COMPLETE);
12966         default:
12967                 panic("ctl_process_done: invalid io type %d\n",
12968                       io->io_hdr.io_type);
12969                 break; /* NOTREACHED */
12970         }
12971
12972         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12973         if (lun == NULL) {
12974                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12975                                  io->io_hdr.nexus.targ_mapped_lun));
12976                 goto bailout;
12977         }
12978
12979         mtx_lock(&lun->lun_lock);
12980
12981         /*
12982          * Check to see if we have any errors to inject here.  We only
12983          * inject errors for commands that don't already have errors set.
12984          */
12985         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
12986             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12987             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12988                 ctl_inject_error(lun, io);
12989
12990         /*
12991          * XXX KDM how do we treat commands that aren't completed
12992          * successfully?
12993          *
12994          * XXX KDM should we also track I/O latency?
12995          */
12996         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12997             io->io_hdr.io_type == CTL_IO_SCSI) {
12998 #ifdef CTL_TIME_IO
12999                 struct bintime cur_bt;
13000 #endif
13001                 int type;
13002
13003                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13004                     CTL_FLAG_DATA_IN)
13005                         type = CTL_STATS_READ;
13006                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13007                     CTL_FLAG_DATA_OUT)
13008                         type = CTL_STATS_WRITE;
13009                 else
13010                         type = CTL_STATS_NO_IO;
13011
13012                 lun->stats.ports[targ_port].bytes[type] +=
13013                     io->scsiio.kern_total_len;
13014                 lun->stats.ports[targ_port].operations[type]++;
13015 #ifdef CTL_TIME_IO
13016                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13017                    &io->io_hdr.dma_bt);
13018                 lun->stats.ports[targ_port].num_dmas[type] +=
13019                     io->io_hdr.num_dmas;
13020                 getbintime(&cur_bt);
13021                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13022                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13023 #endif
13024         }
13025
13026         /*
13027          * Remove this from the OOA queue.
13028          */
13029         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13030 #ifdef CTL_TIME_IO
13031         if (TAILQ_EMPTY(&lun->ooa_queue))
13032                 lun->last_busy = getsbinuptime();
13033 #endif
13034
13035         /*
13036          * Run through the blocked queue on this LUN and see if anything
13037          * has become unblocked, now that this transaction is done.
13038          */
13039         ctl_check_blocked(lun);
13040
13041         /*
13042          * If the LUN has been invalidated, free it if there is nothing
13043          * left on its OOA queue.
13044          */
13045         if ((lun->flags & CTL_LUN_INVALID)
13046          && TAILQ_EMPTY(&lun->ooa_queue)) {
13047                 mtx_unlock(&lun->lun_lock);
13048                 mtx_lock(&softc->ctl_lock);
13049                 ctl_free_lun(lun);
13050                 mtx_unlock(&softc->ctl_lock);
13051         } else
13052                 mtx_unlock(&lun->lun_lock);
13053
13054 bailout:
13055
13056         /*
13057          * If this command has been aborted, make sure we set the status
13058          * properly.  The FETD is responsible for freeing the I/O and doing
13059          * whatever it needs to do to clean up its state.
13060          */
13061         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13062                 ctl_set_task_aborted(&io->scsiio);
13063
13064         /*
13065          * If enabled, print command error status.
13066          */
13067         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13068             (ctl_debug & CTL_DEBUG_INFO) != 0)
13069                 ctl_io_error_print(io, NULL);
13070
13071         /*
13072          * Tell the FETD or the other shelf controller we're done with this
13073          * command.  Note that only SCSI commands get to this point.  Task
13074          * management commands are completed above.
13075          */
13076         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13077             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13078                 memset(&msg, 0, sizeof(msg));
13079                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13080                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13081                 msg.hdr.nexus = io->io_hdr.nexus;
13082                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13083                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13084                     M_WAITOK);
13085         }
13086         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13087          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13088                 memset(&msg, 0, sizeof(msg));
13089                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13090                 msg.hdr.original_sc = io->io_hdr.original_sc;
13091                 msg.hdr.nexus = io->io_hdr.nexus;
13092                 msg.hdr.status = io->io_hdr.status;
13093                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13094                 msg.scsi.tag_num = io->scsiio.tag_num;
13095                 msg.scsi.tag_type = io->scsiio.tag_type;
13096                 msg.scsi.sense_len = io->scsiio.sense_len;
13097                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13098                 msg.scsi.residual = io->scsiio.residual;
13099                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13100                        io->scsiio.sense_len);
13101
13102                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13103                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
13104                     msg.scsi.sense_len, M_WAITOK);
13105                 ctl_free_io(io);
13106         } else 
13107                 fe_done(io);
13108
13109         return (CTL_RETVAL_COMPLETE);
13110 }
13111
13112 #ifdef CTL_WITH_CA
13113 /*
13114  * Front end should call this if it doesn't do autosense.  When the request
13115  * sense comes back in from the initiator, we'll dequeue this and send it.
13116  */
13117 int
13118 ctl_queue_sense(union ctl_io *io)
13119 {
13120         struct ctl_lun *lun;
13121         struct ctl_port *port;
13122         struct ctl_softc *softc;
13123         uint32_t initidx, targ_lun;
13124
13125         softc = control_softc;
13126
13127         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13128
13129         /*
13130          * LUN lookup will likely move to the ctl_work_thread() once we
13131          * have our new queueing infrastructure (that doesn't put things on
13132          * a per-LUN queue initially).  That is so that we can handle
13133          * things like an INQUIRY to a LUN that we don't have enabled.  We
13134          * can't deal with that right now.
13135          */
13136         mtx_lock(&softc->ctl_lock);
13137
13138         /*
13139          * If we don't have a LUN for this, just toss the sense
13140          * information.
13141          */
13142         port = ctl_io_port(&ctsio->io_hdr);
13143         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13144         if ((targ_lun < CTL_MAX_LUNS)
13145          && (softc->ctl_luns[targ_lun] != NULL))
13146                 lun = softc->ctl_luns[targ_lun];
13147         else
13148                 goto bailout;
13149
13150         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13151
13152         mtx_lock(&lun->lun_lock);
13153         /*
13154          * Already have CA set for this LUN...toss the sense information.
13155          */
13156         if (ctl_is_set(lun->have_ca, initidx)) {
13157                 mtx_unlock(&lun->lun_lock);
13158                 goto bailout;
13159         }
13160
13161         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13162                MIN(sizeof(lun->pending_sense[initidx]),
13163                sizeof(io->scsiio.sense_data)));
13164         ctl_set_mask(lun->have_ca, initidx);
13165         mtx_unlock(&lun->lun_lock);
13166
13167 bailout:
13168         mtx_unlock(&softc->ctl_lock);
13169
13170         ctl_free_io(io);
13171
13172         return (CTL_RETVAL_COMPLETE);
13173 }
13174 #endif
13175
13176 /*
13177  * Primary command inlet from frontend ports.  All SCSI and task I/O
13178  * requests must go through this function.
13179  */
13180 int
13181 ctl_queue(union ctl_io *io)
13182 {
13183         struct ctl_port *port;
13184
13185         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13186
13187 #ifdef CTL_TIME_IO
13188         io->io_hdr.start_time = time_uptime;
13189         getbintime(&io->io_hdr.start_bt);
13190 #endif /* CTL_TIME_IO */
13191
13192         /* Map FE-specific LUN ID into global one. */
13193         port = ctl_io_port(&io->io_hdr);
13194         io->io_hdr.nexus.targ_mapped_lun =
13195             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13196
13197         switch (io->io_hdr.io_type) {
13198         case CTL_IO_SCSI:
13199         case CTL_IO_TASK:
13200                 if (ctl_debug & CTL_DEBUG_CDB)
13201                         ctl_io_print(io);
13202                 ctl_enqueue_incoming(io);
13203                 break;
13204         default:
13205                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13206                 return (EINVAL);
13207         }
13208
13209         return (CTL_RETVAL_COMPLETE);
13210 }
13211
13212 #ifdef CTL_IO_DELAY
13213 static void
13214 ctl_done_timer_wakeup(void *arg)
13215 {
13216         union ctl_io *io;
13217
13218         io = (union ctl_io *)arg;
13219         ctl_done(io);
13220 }
13221 #endif /* CTL_IO_DELAY */
13222
13223 void
13224 ctl_done(union ctl_io *io)
13225 {
13226
13227         /*
13228          * Enable this to catch duplicate completion issues.
13229          */
13230 #if 0
13231         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13232                 printf("%s: type %d msg %d cdb %x iptl: "
13233                        "%u:%u:%u tag 0x%04x "
13234                        "flag %#x status %x\n",
13235                         __func__,
13236                         io->io_hdr.io_type,
13237                         io->io_hdr.msg_type,
13238                         io->scsiio.cdb[0],
13239                         io->io_hdr.nexus.initid,
13240                         io->io_hdr.nexus.targ_port,
13241                         io->io_hdr.nexus.targ_lun,
13242                         (io->io_hdr.io_type ==
13243                         CTL_IO_TASK) ?
13244                         io->taskio.tag_num :
13245                         io->scsiio.tag_num,
13246                         io->io_hdr.flags,
13247                         io->io_hdr.status);
13248         } else
13249                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13250 #endif
13251
13252         /*
13253          * This is an internal copy of an I/O, and should not go through
13254          * the normal done processing logic.
13255          */
13256         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13257                 return;
13258
13259 #ifdef CTL_IO_DELAY
13260         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13261                 struct ctl_lun *lun;
13262
13263                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13264
13265                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13266         } else {
13267                 struct ctl_lun *lun;
13268
13269                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13270
13271                 if ((lun != NULL)
13272                  && (lun->delay_info.done_delay > 0)) {
13273
13274                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13275                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13276                         callout_reset(&io->io_hdr.delay_callout,
13277                                       lun->delay_info.done_delay * hz,
13278                                       ctl_done_timer_wakeup, io);
13279                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13280                                 lun->delay_info.done_delay = 0;
13281                         return;
13282                 }
13283         }
13284 #endif /* CTL_IO_DELAY */
13285
13286         ctl_enqueue_done(io);
13287 }
13288
13289 static void
13290 ctl_work_thread(void *arg)
13291 {
13292         struct ctl_thread *thr = (struct ctl_thread *)arg;
13293         struct ctl_softc *softc = thr->ctl_softc;
13294         union ctl_io *io;
13295         int retval;
13296
13297         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13298
13299         for (;;) {
13300                 retval = 0;
13301
13302                 /*
13303                  * We handle the queues in this order:
13304                  * - ISC
13305                  * - done queue (to free up resources, unblock other commands)
13306                  * - RtR queue
13307                  * - incoming queue
13308                  *
13309                  * If those queues are empty, we break out of the loop and
13310                  * go to sleep.
13311                  */
13312                 mtx_lock(&thr->queue_lock);
13313                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13314                 if (io != NULL) {
13315                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13316                         mtx_unlock(&thr->queue_lock);
13317                         ctl_handle_isc(io);
13318                         continue;
13319                 }
13320                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13321                 if (io != NULL) {
13322                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13323                         /* clear any blocked commands, call fe_done */
13324                         mtx_unlock(&thr->queue_lock);
13325                         retval = ctl_process_done(io);
13326                         continue;
13327                 }
13328                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13329                 if (io != NULL) {
13330                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13331                         mtx_unlock(&thr->queue_lock);
13332                         if (io->io_hdr.io_type == CTL_IO_TASK)
13333                                 ctl_run_task(io);
13334                         else
13335                                 ctl_scsiio_precheck(softc, &io->scsiio);
13336                         continue;
13337                 }
13338                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13339                 if (io != NULL) {
13340                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13341                         mtx_unlock(&thr->queue_lock);
13342                         retval = ctl_scsiio(&io->scsiio);
13343                         if (retval != CTL_RETVAL_COMPLETE)
13344                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13345                         continue;
13346                 }
13347
13348                 /* Sleep until we have something to do. */
13349                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13350         }
13351 }
13352
13353 static void
13354 ctl_lun_thread(void *arg)
13355 {
13356         struct ctl_softc *softc = (struct ctl_softc *)arg;
13357         struct ctl_be_lun *be_lun;
13358         int retval;
13359
13360         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13361
13362         for (;;) {
13363                 retval = 0;
13364                 mtx_lock(&softc->ctl_lock);
13365                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13366                 if (be_lun != NULL) {
13367                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13368                         mtx_unlock(&softc->ctl_lock);
13369                         ctl_create_lun(be_lun);
13370                         continue;
13371                 }
13372
13373                 /* Sleep until we have something to do. */
13374                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13375                     PDROP | PRIBIO, "-", 0);
13376         }
13377 }
13378
13379 static void
13380 ctl_thresh_thread(void *arg)
13381 {
13382         struct ctl_softc *softc = (struct ctl_softc *)arg;
13383         struct ctl_lun *lun;
13384         struct ctl_be_lun *be_lun;
13385         struct scsi_da_rw_recovery_page *rwpage;
13386         struct ctl_logical_block_provisioning_page *page;
13387         const char *attr;
13388         union ctl_ha_msg msg;
13389         uint64_t thres, val;
13390         int i, e, set;
13391
13392         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13393
13394         for (;;) {
13395                 mtx_lock(&softc->ctl_lock);
13396                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13397                         be_lun = lun->be_lun;
13398                         if ((lun->flags & CTL_LUN_DISABLED) ||
13399                             (lun->flags & CTL_LUN_OFFLINE) ||
13400                             lun->backend->lun_attr == NULL)
13401                                 continue;
13402                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13403                             softc->ha_mode == CTL_HA_MODE_XFER)
13404                                 continue;
13405                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13406                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13407                                 continue;
13408                         e = 0;
13409                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13410                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13411                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13412                                         continue;
13413                                 thres = scsi_4btoul(page->descr[i].count);
13414                                 thres <<= CTL_LBP_EXPONENT;
13415                                 switch (page->descr[i].resource) {
13416                                 case 0x01:
13417                                         attr = "blocksavail";
13418                                         break;
13419                                 case 0x02:
13420                                         attr = "blocksused";
13421                                         break;
13422                                 case 0xf1:
13423                                         attr = "poolblocksavail";
13424                                         break;
13425                                 case 0xf2:
13426                                         attr = "poolblocksused";
13427                                         break;
13428                                 default:
13429                                         continue;
13430                                 }
13431                                 mtx_unlock(&softc->ctl_lock); // XXX
13432                                 val = lun->backend->lun_attr(
13433                                     lun->be_lun->be_lun, attr);
13434                                 mtx_lock(&softc->ctl_lock);
13435                                 if (val == UINT64_MAX)
13436                                         continue;
13437                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13438                                     == SLBPPD_ARMING_INC)
13439                                         e = (val >= thres);
13440                                 else
13441                                         e = (val <= thres);
13442                                 if (e)
13443                                         break;
13444                         }
13445                         mtx_lock(&lun->lun_lock);
13446                         if (e) {
13447                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13448                                     (uint8_t *)page, lun->ua_tpt_info);
13449                                 if (lun->lasttpt == 0 ||
13450                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13451                                         lun->lasttpt = time_uptime;
13452                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13453                                         set = 1;
13454                                 } else
13455                                         set = 0;
13456                         } else {
13457                                 lun->lasttpt = 0;
13458                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13459                                 set = -1;
13460                         }
13461                         mtx_unlock(&lun->lun_lock);
13462                         if (set != 0 &&
13463                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13464                                 /* Send msg to other side. */
13465                                 bzero(&msg.ua, sizeof(msg.ua));
13466                                 msg.hdr.msg_type = CTL_MSG_UA;
13467                                 msg.hdr.nexus.initid = -1;
13468                                 msg.hdr.nexus.targ_port = -1;
13469                                 msg.hdr.nexus.targ_lun = lun->lun;
13470                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13471                                 msg.ua.ua_all = 1;
13472                                 msg.ua.ua_set = (set > 0);
13473                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13474                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13475                                 mtx_unlock(&softc->ctl_lock); // XXX
13476                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13477                                     sizeof(msg.ua), M_WAITOK);
13478                                 mtx_lock(&softc->ctl_lock);
13479                         }
13480                 }
13481                 mtx_unlock(&softc->ctl_lock);
13482                 pause("-", CTL_LBP_PERIOD * hz);
13483         }
13484 }
13485
13486 static void
13487 ctl_enqueue_incoming(union ctl_io *io)
13488 {
13489         struct ctl_softc *softc = control_softc;
13490         struct ctl_thread *thr;
13491         u_int idx;
13492
13493         idx = (io->io_hdr.nexus.targ_port * 127 +
13494                io->io_hdr.nexus.initid) % worker_threads;
13495         thr = &softc->threads[idx];
13496         mtx_lock(&thr->queue_lock);
13497         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13498         mtx_unlock(&thr->queue_lock);
13499         wakeup(thr);
13500 }
13501
13502 static void
13503 ctl_enqueue_rtr(union ctl_io *io)
13504 {
13505         struct ctl_softc *softc = control_softc;
13506         struct ctl_thread *thr;
13507
13508         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13509         mtx_lock(&thr->queue_lock);
13510         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13511         mtx_unlock(&thr->queue_lock);
13512         wakeup(thr);
13513 }
13514
13515 static void
13516 ctl_enqueue_done(union ctl_io *io)
13517 {
13518         struct ctl_softc *softc = control_softc;
13519         struct ctl_thread *thr;
13520
13521         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13522         mtx_lock(&thr->queue_lock);
13523         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13524         mtx_unlock(&thr->queue_lock);
13525         wakeup(thr);
13526 }
13527
13528 static void
13529 ctl_enqueue_isc(union ctl_io *io)
13530 {
13531         struct ctl_softc *softc = control_softc;
13532         struct ctl_thread *thr;
13533
13534         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13535         mtx_lock(&thr->queue_lock);
13536         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13537         mtx_unlock(&thr->queue_lock);
13538         wakeup(thr);
13539 }
13540
13541 /*
13542  *  vim: ts=8
13543  */